Skip to content

Check for cancellation in the h3 array-expanding functions - #113924

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/h3-array-expansion-cancellation
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/h3-array-expansion-cancellation

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Check for cancellation in the h3 array-expanding functions

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 h3kRing, h3HexRing, h3Line and h3ToChildren ignoring max_execution_time and KILL QUERY while expanding a block of rows. The query is resolved from the executing thread rather than captured, so a call stored in a key, index or TTL is bounded by the query that runs it.

Description

Related: #112273

Each of these four functions expands every row of a block inside one executeImpl call, and the
pipeline evaluates max_execution_time and KILL QUERY only between blocks, so a cancelled query kept
a server thread busy until the whole block was done. Measured on a debug build against a one second
limit, unfixed: h3kRing 8.1s, h3HexRing 4.7s, h3Line 12.2s, h3ToChildren 8.1s. The per-row caps
these functions already have bound one row, not the sum over the block.

The fix polls the query's QueryStatus inside each expanding loop, throttled on accumulated output
items with every row counted as at least one, as in the merged fix for geohashesInBox. The element is
resolved per call from CurrentThread::tryGetQueryContext rather than captured in the constructor,
because these instances can live in table metadata and be run by unrelated later queries. Under break
checkTimeLimit returns false rather than throwing; that becomes a throw here, a half-built array being
a wrong value.

h3Line needs the check in both its loops: gridPathCellsSize walks the grid even for a distance
of zero, so at one item per row its sizing pass alone overshoots by 37.8x. h3HexRing's sizing loop is
6 * k arithmetic plus a cell validation and is left alone: reaching even 1.6x took eighty million rows.

Every other array-returning h3*/s2*/geohash* row loop was checked for the discriminator, whether
per-row output is driven by argument values. The seven left alone are not carriers, each row being
bounded by a library constant instead. Nullable and LowCardinality arguments are unwrapped before
executeImpl, so the checkpoint covers them.

Tests removed at review request, being timing based. They did validate on the previous head before
removal: Bugfix validation reported the bug reproduced on master HEAD and fixed here on
amd64,
aarch64
and unit tests.
The fix now ships without regression coverage.


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

`h3kRing`, `h3HexRing`, `h3Line` and `h3ToChildren` expand every row of a block
inside one `executeImpl` call, and the pipeline evaluates `max_execution_time`
and `KILL QUERY` only between blocks. Nothing could interrupt the expansion, so
a cancelled query kept a server thread busy until the whole block was done.
Measured against a one second limit on a debug build, and as the minimum of
seven runs each, unfixed: `h3kRing` 8.1x, `h3HexRing` 4.7x, `h3Line` 12.2x,
`h3ToChildren` 8.1x. The per-row caps these functions already have bound one
row, not the sum over the block, and `MemoryTracker::allocImpl` does not consult
the time limit either.

Poll the query's `QueryStatus` inside each expanding loop, throttled on
accumulated output items with every row counted as at least one, matching the
merged fix for `geohashesInBox`. The element is resolved per call from
`CurrentThread::tryGetQueryContext` rather than captured in the constructor,
because these instances can live in a key, index or TTL and be run by unrelated
later queries; `getProcessListElementSafe` returns an empty pointer where the
throwing accessor would raise a `LOGICAL_ERROR` on an expired weak pointer.
`checkTimeLimit` returns false rather than throwing under the `break` overflow
mode; that becomes a throw here, since a half-built `Array(UInt64)` is a wrong
value rather than a shorter one, and the pipeline absorbs it into a clean stop.

`h3Line` needs the check in both of its loops. Its sizing loop calls
`gridPathCellsSize`, which walks the grid and is not free even for a distance of
zero: isolated at one item per row it overshoots a deadline by 37.8x on its own,
so a uniform one-checkpoint-per-function change would have shipped that intact.
`h3HexRing`'s sizing loop is `6 * k` arithmetic plus a cell validation, and
reaching even 1.6x a one second deadline in it took eighty million rows, which
already needs more memory than a test may use, so it deliberately gets nothing.

The throttle is 100000 accumulated items, the constant `geohashesInBox` settled
on after 1000000 proved to be over three seconds of uninterruptible work on a
loaded sanitizer build. A `clock_gettime` is around 14.5ns here, so the added
cost is about 0.00004% of the loop's work.

The new test asserts a cancellation latency for each carrying loop under both
overflow modes, one `KILL QUERY ... SYNC`, a stored expression per function, and
liveness controls that would fail a change which simply always threw. What each
latency case bounds is the time the server itself reports having measured at the
checkpoint, so nothing the query does after stopping is counted, and the
allowance a bound gives is added to its deadline rather than multiplying it, so
shortening a deadline cannot tighten the assertion with it. Shapes are sized to
peak under 55% of the 5G `max_memory_usage` the CI profile sets: a shape sized
past memory measures the allocator instead.

These four have no observed hang in CI over 180 days, so this is a proactive fix
for the class rather than a report. One residual is left open and disclosed: a
per-row checkpoint bounds the block rather than a single row, and one
`h3ToChildren` row can still be `1 << 30` items, which would need chunking
inside the h3 library itself.

A block whose every row holds an invalid cell reaches a checkpoint only through
the rule that a row counts as one work unit, and no latency can assert that,
since such a block runs for under two seconds even at the largest size the
memory profile allows. A unit test pins it instead, by giving the query an
already expired deadline and asserting the throw, so the assertion is whether
the check fires at all rather than how long the block took.
The four array-expanding h3 functions throttle their in-loop cancellation
check on accumulated output items rather than on rows, because one row can
hold 300030001 items for h3kRing and 1073741824 for h3ToChildren. Nothing
asserted that weighting at any of its five sites: with the size term gone
the counter advances once per row, which every shape in the stateless test
still reaches because they all have millions of rows, so all of them pass on
a binary that counts rows alone.

Add five unit-test cases, one per weighting site, on valid cells sized so a
block has fewer rows than the 100000 threshold but more items than it. Only
the weighting can then reach the checkpoint, and the already expired deadline
makes reaching it observable without a wall clock. Each of the five mutation
arms, one per site, makes exactly its own case return instead of throwing.

h3Line has two weighting sites and needs a case for each. Its sizing pass is
pinned by a cell to itself, one item per row, where 66667 rows reach the
sizing checkpoint at row 50000 while the fill pass reaches only two thirds of
the threshold. Its fill pass is pinned by two rows of a 66411 item line,
where the sizing counter peaks at two thirds of the threshold and cannot fire
while the fill counter reaches a third above it. The zero-output-row case
pins neither weighting: it throws in the sizing pass, so the fill loop is
never entered, and at size zero the floor already yields the value the
mutant does.

Run the unit tests the way CI does, as the whole binary rather than under a
filter selecting only these cases. A filtered run cannot see that the
fixture collides with MainThreadStatus: ThreadStatus asserts that
current_thread is null, MainThreadStatus is a process-lifetime static that
leaves it set on the main thread, and three other test files in this binary
initialize it before these cases run. Every unit-test build in CI is a
sanitizer build, so that assertion aborts. Put the cases on a fixture that
saves, clears and restores the pointer, as the distributed query tests do.

Also note in the file comment that h3Line's two per-row floors are pinned
jointly rather than one each, since its sizing pass reaches the threshold one
pass before the fill pass and so removing either floor alone still stops the
block, and drop an unused scope_guard include.

Scope the stateless test's note about the memory peak at which the query
log's duration was compared against the reported elapsed time, which read as
a claim about the shipped shapes when it came from an arm deliberately forced
to hold that much live.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review, 5 rounds (4 blockers fixed, 3 findings disagreed with evidence)

An independent reviewer read the resulting code cold, without the author's evidence, and a second
model re-reviewed the change against the frozen PR description. Four rounds bounced back to the
implementer; this round is clean.

❌ The unit-test fixture aborted when the whole test binary runs. ThreadStatus's constructor
asserts current_thread is null (src/Common/ThreadStatus.cpp:120), and MainThreadStatus is a
process-lifetime static that leaves it set on the main thread. Nine other files in unit_tests_dbms
initialize it; by link order three precede this one. CI runs the binary on sanitizer builds, where that
assertion aborts. Every local run had used a filter selecting only the new suite, which is why it looked
green. Fixed with a fixture that saves, clears and restores the pointer, the pattern
gtest_filecache.cpp:350-351 and gtest_distributed_query.cpp:405-415 already use for the same
reason; re-verified by running the full binary, and by putting the cases back on unfixtured TEST to
confirm they then fail.

❌ One of the five item-weighting sites had no mutation arm. h3Line weights rows in both its
loops (:144 sizing, :162 fill). Only the sizing site had an arm, and four artifacts claimed the fill
site was covered by the zero-output-row case, which it is not: that case throws during sizing and never
enters the fill loop, and where output size is zero the weighted and unweighted expressions are equal.
An arm removing only :162 leaves every committed shape byte-identical. Fixed by adding that arm plus a
case whose block has fewer rows than the throttle threshold and more items than it, so only the fill
weighting can reach the checkpoint.

❌ The item weighting was unpinned at four of its five sites. Every latency shape has millions of
rows, so all of them reach the 100000 threshold on the row count alone and pass on a binary with no
weighting at all. Five cases now use fewer rows than the threshold and more items than it.

❌ The h3Line sizing loop needed its own checkpoint. gridPathCellsSize walks the grid even at
distance zero, so isolated at one item per row the sizing pass alone overshoots by 37.8x. A uniform
one-checkpoint-per-function change would have shipped that intact.

⚠️ "Four sibling functions still capture the definition-time query status" (raised as a blocker this
round). Refuted at the root: all four are already fixed upstream. The reviewing model read the working
tree, whose base is 655 commits behind master, and reported a defect that exists only on that stale
base. On origin/master, geohashesInBox, arrayFold, h3PolygonToCells and
h3PolygonToCellsWithContainment each score 0 for a constructor-captured process_list_element and 1
for CurrentThread::tryGetQueryContext, the exact migration the finding asks for; on this branch's base
the counts are reversed. git log -S tryGetQueryContext returns one commit for all four,
37a532be655467d "Resolve the query status per call in functions that check for cancellation"
(2026-08-05), which is not an ancestor of this base. The finding's second ask, stored-expression
regression coverage, is merged in that same commit as 04752_persisted_expression_cancellation.sh.
Independently, none of the four files is in this PR's diff.

⚠️ h3Line's fill-loop per-row floor is not pinned by a committed case. Agreed as a fact,
declined as a change, and re-derived from scratch this round rather than inherited. max(1, size) at
:162 differs from a bare size only when size == 0; such rows arise only from invalid cells; and
with all-invalid rows the sizing loop's own floor reaches the threshold first, at row 99999, so the fill
loop is never entered. Sweeping mixed invalid-and-valid shapes finds a discriminator only at a knife
edge: with 1261-item valid rows exactly 79 valid rows works, 78 and 80 do not, a margin of 619 items in
100000. The disjunction "at least one h3Line floor survives" is pinned, and this floor bounds nothing
the sizing floor does not, so a knife-edge case would be the flakiest assertion in the file for no
coverage gained.

⚠️ The test should carry no-parallel for its 5G memory pin. Declined on measurement: 5000000000
is exactly the CI profile's own 5G default, so it is a pin rather than a raise and cannot exceed what
the profile already permits one query; the per-user cap is 32G. Of the seven stateless tests setting
max_memory_usage >= 2e9, one is no-parallel, and the merged sibling 04648 is parallel too.

💡 Three countable claims corrected before the final gate. Two had gone stale across the fix
rounds: the unit-test case count (eight to nine, and "two per function" no longer describes the
grouping) and the mutant count (seventeen to eighteen, five weighting arms rather than four). The third
was a scope error: "None of the eleven" counted the functions with no cancellation check on the base
tree
, which includes the four fixed here, so a reader re-running the census on this head measures
seven. Both the description and the checklist comment now state the rebase-invariant form.

The fix itself was not in question in any round. Carriers were enumerated independently before the
author's plan was read: brace-matching getReturnTypeImpl over all 51 files registering an
h3*/s2*/geohash* function gives 14 array-returning functions, of which seven poll after this
change and seven bound each row by a library constant or have no per-row loop at all. Merges cleanly
onto current master, and all four modified files are byte-identical to master. Of 1917 open pull
requests, one touches the same four files: #112504 is a ColumnArray construction refactor scoring zero
on every symbol this change introduces and preserving both of h3Line's loops, so it is a textual
overlap rather than a competing fix.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand. SELECT h3kRing(materialize(644325529233966508), 1) FROM numbers(16000000) FORMAT Null SETTINGS max_block_size = 16000000, max_threads = 1, max_memory_usage = 5000000000, max_rows_to_read = 0, max_result_bytes = 0 with --max_execution_time 1 --timeout_overflow_mode throw. Unfixed 8115 / 8189 / 8210 / 8368 / 8409 ms over 5 reps against a 1000 ms limit; fixed 1000 / 1002 / 1004 / 1008 / 1027. Not a low-rate shape, and the spread is 2%.
b Root cause explained? Yes. Each function expands a whole block inside one executeImpl call and the pipeline evaluates max_execution_time and KILL QUERY only between blocks, so nothing observes the query's QueryStatus until the call returns. Per-row work is driven by argument values (maxGridDiskSize/gridDisk, 6 * k/gridRingUnsafe, gridPathCellsSize/gridPathCells, cellToChildrenSize/cellToChildren). The existing per-row caps bound one row, not the sum over the block; MemoryTracker::allocImpl does not consult the time limit either (0 occurrences of checkTimeLimit/is_killed in src/Common/MemoryTracker.cpp). Demonstrated directly: an 18000-row h3kRing shape runs 6415 ms in one block but 1046 ms split into eighteen, because the executor's own between-blocks check then bounds it.
c Fix matches root cause? Yes: a cancellation checkpoint inside the loop that cannot otherwise be interrupted. No widened bound, no lowered cap, no no-random-* tag, no defensive check at a crash site. Lowering max_k/MAX_ARRAY_SIZE was rejected as the wrong layer, since any cap still permits an unbounded block.
d Test intent preserved / new tests added? Two new tests, 37 assertions. 04818_h3_array_expansion_cancellation.sh has 28 (wc -l on its reference): 15 latency (grep -cE 'within|blocked|promptly|past') and 13 result. The latency ones are throw + break for each of the five carrying loops (10), one KILL ... SYNC, and one stored-expression case per function (4). The result ones are 4 documented-result liveness controls, 5 that cross the 100000-item throttle with no deadline set, and 4 degenerate-row controls. src/Functions/tests/gtest_h3_array_expansion_cancellation.cpp adds 9 more (grep -c '^TEST_F(H3ArrayExpansionCancellation, '), all under an already expired deadline and all asserting TIMEOUT_EXCEEDED: one per function for a 100000-row block whose every cell is invalid, which only the per-row work-unit floor can stop (4), and one per weighting site for a block of fewer rows than the throttle threshold but more items than it, which only the item weighting can stop (5, because h3Line weights in both its sizing and its fill pass). Those are the two things a latency cannot assert - the first because such a block runs under two seconds at any size the memory profile allows, the second because every latency shape has millions of rows and so reaches the threshold on the row count alone. The cases sit on a fixture that saves, clears and restores current_thread, because ThreadStatus asserts it is null while MainThreadStatus is a process-lifetime static that leaves it set, and three other files in unit_tests_dbms initialize it before these cases run; without the fixture all nine abort in every CI unit-test flavour, each of which is a sanitizer build. No existing test weakened. All 58 h3 stateless tests pass (a basename containing h3 with a runnable extension), as do the 11 other *cancellation* tests including 04648_geohashes_in_box_cancellation, 04408_array_fold_cancellation and 04650_replace_cancellation: 69 OK, 0 FAIL, 0 skipped. The 31 unit tests matching *Cancel*:*Cancellation*:H3* also pass, 31 verdict lines, 0 failed.
e Both directions demonstrated? Yes, on separate binaries with SELECT lower(buildId()) asserted equal to readelf -n before every verdict. BASE 0502ee8df849bfcb (the pristine master snapshot, confirmed pre-fix by 0 occurrences of items_since_check in all four files against a positive control of 2 in the merged geohashesInBox), FIX d028a7e4a8669726. Against the debug bound of 2500 ms, minimum unfixed over 7 reps against maximum fixed over 3: h3kRing 8115 -> 1027, h3HexRing 4730 -> 1002, h3Line 12175 -> 1026, h3Line sizing loop 37819 -> 1006, h3ToChildren 8054 -> 1004. The KILL ... SYNC case, re-measured this round on both servers with identity asserted, is 11117 / 11117 / 11222 ms unfixed against 102 / 102 / 102 fixed. Through the runner the test FAILS on BASE and PASSES on FIX, and all 15 differing lines are latency assertions while all 13 result assertions are byte-identical. For the 9 unit-test cases the two directions are the floor-removing and weighting-removing mutants: each makes exactly its own case return instead of throwing, on its own stated reason (<function> returned instead of reporting the expired deadline), and leaves the other eight passing. Every arm was run as the WHOLE binary the way CI runs it, --gtest_filter=-FunctionsStress.* plus the two suites that abort on unmodified trunk, with the verdict read from --gtest_output=json; the final tree is 27396 tests, 0 failures, 0 errors. 100 of 100 runs pass on the fix, 50 randomized and 50 not, counted from per-run verdict lines with --long-test-runs-ratio 1.0 (the test is long-tagged, which otherwise scales a batch to a tenth); the test carries no randomization opt-out, verified with the runner's own tag parser against three negative controls.
f Fix is general across code paths? Yes, and re-verified as a census. grep -ci 'checkTimeLimit|isKilled|isCancelled|getProcessListElement' is now 3/2/2/2 on h3kRing/h3HexRing/h3Line/h3ToChildren (positive control: geohashesInBox 3, arrayFold 3, h3PolygonToCells 2). Every other array-returning h3*/s2*/geohash* row loop was checked for the discriminator, which is whether per-row output is driven by argument values. Eleven such functions had 0 hits before this PR; the 7 that remain at 0 hits after it are not carriers, each bounding its row by a library constant instead, maxFaceCount (h3Index.c:1190-1195, 5 for a pentagon and 2 otherwise), pentagonCount (NUM_PENTAGONS = 12, constants.h:87), MAX_CELL_BNDRY_VERTS (10, h3api.h.in:134) for both boundary functions, a fixed std::array<H3Index, 6> of edges, and 4 neighbours. None is a carrier. h3GetRes0Indexes has no per-row loop at all: it calls res0CellCount() once and returns a const column. Within the four, h3Line needed the check in BOTH loops and h3HexRing in only its fill loop; that asymmetry was measured, not assumed.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable and LowCardinality arguments are ACCEPTED (not rejected before the loop, as one might expect), but neither useDefaultImplementationForNulls nor ...ForLowCardinality is overridden, so the wrapper is unwrapped before executeImpl and the single checkpoint covers it: fixed 1001/1025/1000 ms for plain/Nullable/LowCardinality against a negative control on BASE of 8466/11289/6301 ms. There is no second template instantiation to cover. Boundary values: k = 0 and distance 0 return 1 item, a 0-row block returns 0 rows, k = 10001 is Code: 12, h3ToChildren(<res-3 cell>, 15) is Code: 128 TOO_LARGE_ARRAY_SIZE, and an invalid cell under functions_h3_default_if_invalid = 1 returns an empty array (asserted by the degenerate-row controls, which are what exercise counting each row as at least one work unit).
h Backward compatible? (maintainer-approved exception only) Yes, and nothing to migrate: the diff adds 0 settings, 0 format or serialization changes and 0 SettingsChangesHistory lines, and touches only four self-contained anonymous-namespace classes in src/Functions/. No header, no shared type, no experimental gate. The only behaviour change is that a cancelled query now stops during the expansion instead of after it.
i Invariants and contracts preserved? Yes. The checkpoint is placed so every row passes through it, including the invalid-cell continue branches, and dst_offsets[row] is still written for every row on every path. In h3HexRing and h3Line the fill-loop checkpoint sits before gridRingUnsafe/gridPathCells, so it cannot leave current_offset and ptr inconsistent: a throw abandons the whole column. checkTimeLimit returning false under the break overflow mode becomes a throw rather than a short array, because a half-built Array(UInt64) is a wrong value rather than a smaller one, and the pipeline absorbs the throw into a clean error-free stop; the break cases assert exactly that. The INCORRECT_DATA throws already inside these loops are unaffected.

Mutation coverage: eighteen arms (19 MUTANTS entries, read by AST from .scratch/mutate.py, of which
M7 is superseded by M8c), each built as its own binary with the Build ID asserted to move and then,
after restore, to return byte-exactly. Five checkpoint arms each redden exactly their own loop's three
latency assertions. Four per-call-resolution arms, one per file, each redden exactly one assertion,
their own stored expression, which is the asymmetry that distinguishes the two designs and the reason
all four functions need a stored case rather than one of them. Four floor arms and five weighting arms,
one per site, each redden exactly their own unit-test case while the others and the whole stateless
test stay green. No arm survives.

The floor and weighting arms are why the unit test exists; neither property admits a latency oracle.
Removing the floor moves an all-invalid block from stopping at the deadline to running its whole 1.86 s,
which is inside the smallest bound the latency allowance permits, so a latency arm would be green on the
very mutants above. Even at 75% of the memory cap such a block reaches only 2496 ms; the loop costs
3-6.7 ns a row against ~19-30 B of it, so no size separates time from memory. Removing the weighting
leaves a counter that advances once per row, which every shape in the stateless test still reaches
because they all have millions of rows, so those stay green too; the weighting cases use a hundred to
sixty-seven thousand rows instead, below the threshold, each row carrying more items than it. Asserting
the throw under an already expired deadline has no wall clock in it at all.

For h3Line the floor is pinned jointly rather than per loop: its sizing pass reaches the threshold one
pass before the fill pass, so removing either floor alone still stops the block and only the arm that
removes both is observable. A case discriminating the fill floor alone exists only in a knife-edge
window, a margin of 619 items in 100000 with the valid-row count pinned to 77-79, which any change to
the throttle constant or the vendored library would silently vacate, and that floor bounds nothing the
sizing floor does not, so none was added and the limit is recorded rather than papered over.

Its two WEIGHTINGS, by contrast, are pinned one each, and the zero-output-row case pins neither: that
case throws in the sizing pass so the fill loop is never entered, and at size == 0 the floor already
yields the value the weighting-removing mutant does. The sizing site is discriminated by 66667 rows of a
one-item line, the fill site by 2 rows of a measured 66411-item line, where the sizing counter peaks at
66413 of the 100000 threshold and cannot fire while the fill counter reaches 132822. Both margins are a
third of the threshold, so unlike the floor case neither sits on a knife edge.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @PedroTadim, could you review this? These four h3 functions expand every row of a block inside one executeImpl call, so nothing evaluated max_execution_time or KILL QUERY until the whole block was done; the fix polls the query status inside each expanding loop, throttled on accumulated output items, the same shape as the merged geohashesInBox fix.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@PedroTadim PedroTadim self-assigned this Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b54955]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d) FAIL cidb
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04510_not_has_function_explain FAIL cidb
02156_storage_merge_prewhere NOT_FAILED cidb
02346_non_negative_derivative NOT_FAILED cidb
02402_merge_engine_with_view NOT_FAILED cidb
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
Check Results FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

This PR adds in-function cancellation polling to h3kRing, h3HexRing, h3Line, and h3ToChildren so block-wide H3 expansion can stop on max_execution_time and KILL QUERY instead of running to the end of the block. The four touched functions are improved, but two contract gaps still remain in the current code: stored H3 expressions still snapshot functions_h3_default_if_invalid from the storage-definition path, and the sibling polygon expanders still miss max_execution_time in timeout_overflow_mode = 'break'.

Findings

⚠️ Majors

  • [src/Functions/h3kRing.cpp:39-41, src/Functions/h3Common.cpp:20-21, src/Storages/StorageFactory.cpp:236-238, src/Storages/KeyDescription.cpp:155-182] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/113924#discussion_r3741326189] The patch correctly stops capturing QueryStatus in the constructor, but these persisted H3 expressions still capture functions_h3_default_if_invalid through the constructor-built H3Validator. Because storage key expressions are built with the global context, invalid-cell behavior in PARTITION BY / TTL / index expressions still depends on the server/profile default instead of the executing query. Suggested fix: resolve the setting per executeImpl, or make H3Validator read from CurrentThread::tryGetQueryContext() with a global-default fallback, so the same metadata-stored-function reasoning applies to both cancellation and invalid-input handling.
  • [src/Functions/h3PolygonToCells.cpp:176-177, src/Functions/h3PolygonToCellsWithContainment.cpp:250-251, src/Interpreters/CancellationChecker.cpp:43-46, src/Interpreters/ProcessList.cpp:670-675] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/113924#discussion_r3749549783] The PR description says the remaining array-returning h3* loops were audited and left alone only when each row is bounded by a library constant, but the two polygon expanders still only poll isKilled(). In timeout_overflow_mode = 'break', CancellationChecker calls checkTimeLimit() without setting is_killed, so these functions can still sit inside a single executeImpl() well past max_execution_time with no in-function stop. Suggested fix: switch both loops to the same checkTimeLimit() or makeCancellationCheck primitive as the four touched functions, or narrow the PR contract so it no longer claims the sibling expanders were proven safe.
Tests
  • ⚠️ After the timing-based tests were removed, there is no regression coverage left for the new CurrentThread and checkTimeLimit() wiring. A focused deterministic test that injects a cancelled or expired QueryStatus into one H3 expander path would prove the contract without depending on wall-clock timing.
Final Verdict

Request changes: the four touched functions are better, but the PR's stated invariant still fails for metadata-stored H3 settings and for the sibling polygon expanders in timeout_overflow_mode = 'break'.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 97/114 (85.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
Comment thread src/Functions/h3kRing.cpp

ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
/// Resolved from the executing thread rather than captured: this instance can be stored in table

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.

process_list_element is now resolved per executeImpl, but validator is still a member built from the constructor Context: H3Validator(context) snapshots functions_h3_default_if_invalid once in src/Functions/h3Common.cpp:20-21. For the persisted-expression case this comment is talking about, that means these functions still execute invalid cells according to the query that defined the PARTITION BY / TTL / index expression, not the query that later runs it. For example, create the table with functions_h3_default_if_invalid = 0, then INSERT ... SETTINGS functions_h3_default_if_invalid = 1 on an invalid cell: validateCell will still throw instead of returning the default empty array. If the goal is to bind metadata-stored functions to the executing query, the validator needs the same per-call resolution as process_list_element.

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.

I measured this, and the mechanism is not the one described. Full messages compared (not error codes), on the PR head (Build ID d028a7e4a866972653283911a16c91b4f27ffea5) and on a pristine-master control whose five h3 files are md5-identical to origin/master.

The carrier does not discriminate. Creating with functions_h3_default_if_invalid = 0 and then inserting with = 1 throws Invalid H3 cell index: 1, but so does the reverse (create 1, insert 0), and so does = 1 on both queries. Since the flipped-on-both arm still throws, the validator is not reading the defining query either.

What it does read is the server/profile default. With functions_h3_default_if_invalid set to 1 in <profiles><default> and query-level 0 on both the CREATE and the INSERT, the INSERT succeeds (3 rows); on that same server a direct SELECT h3kRing(1::UInt64, 1) with query-level 0 still throws. So query-level values are honoured on a direct call and invisible on the persisted path, whichever query wrote it.

That follows from construction rather than from caching: StorageFactory::Arguments::getContext() is chassert'ed to be the global context (src/Storages/StorageFactory.cpp:236), registerStorageMergeTree.cpp:530 passes exactly that into KeyDescription::getKeyFromAST, and H3Validator reads a user-level setting off it (h3Common.cpp:20-21). Every arm above reproduces identically on pristine master.

I am not widening this PR for it. src/Functions/h3Common.{cpp,h} are not in this diff and are byte-identical to origin/master; the population is the 26 h3 files holding a constructor-built H3Validator, not the four here; and this PR is scoped to cancellation. The two cases are also not symmetric: a stale QueryStatus turns a cancellation check into dead code, whereas a stale snapshot of this setting yields a defined value that the profile controls, which is what #97821 added it to do. I am not opening a follow-up either, since there is no wrong result, hang or crash and no report asking for per-query resolution of that setting.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8b54955b8 with master e1a4240e9 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dc2e00698; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.24 MiB 702.22 MiB -3.02 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

The throttle counts accumulated output items, but a row of h3kRing or
h3ToChildren carries work of its own beyond its items: it allocates a vector
for its output, which a sanitizer build instruments heavily. So a shape with
few items per row buys a large number of rows per interval, and the loop is
uninterruptible between checkpoints.

A row of seven items advances the counter by eight, the per-row floor plus its
items, so the old count bought 12500 rows per interval, measured at 2612-3119
ms on a sanitizer build. A query stops within its deadline plus one interval,
and the new test allows 1000 + 1500*2 there, so a single interval consumed the
whole 3000 ms of slack. That is what made it fail on amd_tsan and on
amd_asan_ubsan, where a contended runner is slower still. The same interval is
a multi-second window in which a user's own h3kRing(cell, 1) over a large block
cannot be cancelled, so the test was reporting a real defect rather than being
too strict.

Ten thousand items is 1250 rows in that shape, measured at 29-59 ms. The item
count still binds for large arrays, where it is what keeps a single row from
running unchecked: at 1261 items per row it fires after 8 rows. Overhead is
unmeasurable, as before: the worst case is one item per row, where 5M rows cost
1000 checks, and a check is a clock read and an uncontended lock. That measured
3820 ms against 3839 ms over five runs each, i.e. within scatter.

The same reason is why 3f0e190 lowered this count from a million to a
hundred thousand for geohashesInBox. Its rows carry no such per-row work, which
is why it can keep the larger count.

Three unit test cases counted rows against the old value and are rescaled with
it. The h3Line fill-pass case also needs a shorter line: with the lower count
its old 66411-item cell reaches the threshold in the sizing pass, so the case
would no longer test the fill pass at all. Its sizing counter finishes on 13284
rather than the 6643 its checkpoints see, because the sizing pass tests before
adding the row's own size while the fill pass tests after; the case is sound
because the block ends before a third checkpoint could see it.

The stateless test's header said every case runs at least four times its bound
unfixed. Measured, h3HexRing is about 4800 ms against a 2500 ms bound, so it is
four times the deadline rather than the bound.
The four row-loop cases asserted a wall clock, but `max_execution_time` fires on the wall
clock while a shared CI runner can deschedule the query thread for seconds, so the assertion
measured runner contention on top of the interval the fix controls. Measured on an unfixed
build with the server pinned to four cores: contention moved one shape's wall clock from
4786ms to 33512ms while its CPU time held at 4783ms, a 7x inflation against 0.1% drift. That
is why the test reported overshoots of 4096ms to 5714ms on sanitizer runners while stopping
at 1000ms to 1030ms on an idle box, and why raising the bound could not fix it: the fixed and
unfixed wall-clock ranges overlap, so any bound admitting the fixed binary under contention
also admits the unfixed one.

The row-loop cases now bound `UserTimeMicroseconds + SystemTimeMicroseconds` from the query
log, which a descheduled thread does not accumulate, so the allowance covers one throttle
unit instead of worst-case contention. Both modes share one oracle, which also removes the
break mode's dependence on `query_duration_ms` matching the reported elapsed. A missing query
log row or a missing counter is reported rather than compared, so an absent measurement
cannot read as a pass; the `KILL` oracle gets the same row guard, without which `max` over
zero rows returns 0 and reads as a prompt cancellation.

Measured with the fix on the sanitizer build class that was failing: CPU time 1007ms to
1248ms across all fourteen assertions against a 3000ms bound, and the same fourteen on the
unfixed build 5552ms to 78233ms, a 5.1x separation on the tightest shape. The debug build
passes ten consecutive runs pinned to four cores and four more under fivefold
oversubscription of those cores.

The `KILL ... SYNC` case still bounds a wall clock: it times a different query, floored by
its own poll loop and client round-trips rather than by the row loop. It keeps the contention
allowance and stays no tighter than the merged siblings `04648` and `04650`.
Comment thread src/Functions/h3kRing.cpp Resolved
Comment thread src/Functions/h3Line.cpp Resolved
`run_stored_case` pinned `max_insert_block_size` and `min_insert_block_size_rows`
but not `min_insert_block_size_bytes`, whose 268402944 default caps a UInt64
block at 33550368 rows. The `line` case asked for 50000000, so the squasher
flushed early, the pipeline's own between-blocks check bounded the INSERT, and
the row loop under test never received the block: measured `SelectedRows` was
33554817, and the arm's CPU time no longer separated the fix from master
(fixed 1054/1463/2110 ms vs unfixed 1122/1691/1620 ms). An h3-free INSERT of the
same shape costs 1241-1278 ms on its own, dominated by 787803 soft page faults,
which is what the 3952 ms overshoot on amd_tsan was measuring.

Pin the byte threshold to the size of the block being requested and bring the
case to 16000000 rows, which is under the cap on any build. The block is then
read whole (`SelectedRows` == 16000000) and the arm separates again: fixed
1055 ms against its 3000 ms bound versus 52918 ms unfixed, a factor of 50.

Verified with the binaries CI built for this head. On amd_tsan the test is
[ OK ] 6/6 with settings randomization off and 4/4 with it on, and [ FAIL ] on a
pristine master amd_tsan build whose four h3 sources are md5-identical to the
merge base. On amd_release it is [ OK ] 3/3 and still reaches the deadline with a
full block, so it cannot report a missing timeout. No bound was widened and no
case removed.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f2d6b8a

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
- no failed checks on this commit -

CI is fully finished on this head with zero failing checks. Config Workflow, Fast test and
Finish Workflow are all success; 157 of 175 check-runs concluded success and the 18
non-running ones each carry an explicit praktika reason (reused from cache, not affected by the changed files, not labeled with 'pr-performance', and similar); no job was dropped.
CIDB records 330426 test rows across 160 checks on this commit with 0 FAIL/ERROR.

For contrast, the previous heads on this branch were not clean: 02eb44da04b5 had 2 red rows
and 98c9015bf6ef had 11, so this is a real improvement on this head rather than a run that
simply never executed anything.

Session id: cron:our-pr-ci-monitor:20260810-063000

kring throw: stopped within bound
kring break: stopped within bound
hexring throw: stopped within bound
hexring break: stopped within bound

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.

remove both gtests and sql tests in this pr. It is going to be flaky

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 8b54955, both are gone: the stateless test 04818 with its reference, and the gtest. No dangling
references left and the source fix is byte-identical to the previous head.

One consequence worth flagging. This is a pr-bugfix PR with no test now, so New tests check falls
through to its last branch, which passes only on a CI report link in the description. I added the Bugfix
validation links from the previous head, where both halves did reproduce the bug on master HEAD and pass
here. That keeps the category honest and the check green, but the fix now ships without regression
coverage. If you would rather have some, a deterministic unit test with an already expired QueryStatus
carries no timing, or the category can change instead. Your call.

Requested in review: both the stateless test 04818 and the gtest are timing
based, so they are expected to be flaky in CI. Both halves did validate on the
previous head before removal (Bugfix validation reported the bug reproduced on
master HEAD and fixed here, on amd64, aarch64 and unit tests), so the source fix
is unchanged and now ships without regression coverage.

The PR body carries the validation report links, which is what the merge
blocking New tests check accepts as evidence for a bug fix PR that adds no test.
Comment thread src/Functions/h3kRing.cpp
/// half-built array is a wrong value rather than a shorter one, so it becomes a throw here too.
auto check_query_time_limit = [&]
{
if (process_list_element && !process_list_element->checkTimeLimit())

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 patch adopts checkTimeLimit() as the cancellation primitive, but the sibling H3 polygon expanders still only poll isKilled() (src/Functions/h3PolygonToCells.cpp:176, src/Functions/h3PolygonToCellsWithContainment.cpp:250). That is not equivalent for max_execution_time: in timeout_overflow_mode = 'break', CancellationChecker::cancelTask calls query->checkTimeLimit() instead of cancelQuery(), and QueryStatus::checkTimeLimit() does not set is_killed (src/Interpreters/CancellationChecker.cpp:43-46, src/Interpreters/ProcessList.cpp:669-674). So after this PR a large h3PolygonToCells* expansion can still sit inside one executeImpl() call past the deadline without any in-function stop. Can we switch those two loops to the same checkTimeLimit() helper as part of this bugfix?

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.

Verified on current master (ef9be387). Both polygon expanders do still poll only isKilled() at the cited lines, and the mechanism is as you describe: under timeout_overflow_mode = 'break', CancellationChecker::cancelTask calls checkTimeLimit() instead of cancelQuery(), and only cancelQuery sets is_killed, so an isKilled() poll cannot observe a deadline in that mode.

I measured it rather than reading it, max_execution_time = 1:

  • h3PolygonToCells([(-123,37),(-123,38),(-122,38),(-122,37)], 12): break mode 37.81 s and 37.25 s against an unbounded control of 38.92 s, so there is no in-function stop at all. Default throw mode on the same query stops at 18.4 s.
  • h3PolygonToCellsWithContainment at resolution 11 over 30 non-const rows: break 10.78 s, throw 1.26 s, unbounded control 8.34 s.
  • For contrast, the four functions this PR changes bound correctly in break mode: 1.07 s against a 15.79 s unbounded control.

So the finding is real. I am not taking it into this PR though. It is a pre-existing defect in two files this PR does not touch, it is a different concern from the missing checkpoint these four functions had, and the isKilled() poll there is the deliberate shape of #101042. Widening a source-only bugfix into another function's cancellation design, right after its own tests were removed at a maintainer's request, is the wrong direction. I will do the primitive swap separately.

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.

Retracting this: I said I would do the primitive swap separately, and I am not going to.

The two polygon expanders do still poll only isKilled(), and I re-measured the gap today on master
b0476972 (break mode 40.2 s against a 38.3 s unbounded control at max_execution_time = 1, so no
in-function stop). But the swap would be the same per-function shape this PR was closed for, and the
direction stated here is one check before IFunction::executeImpl instead. A two-file version of the
rejected shape is not worth reviewing, so I am leaving both sites alone rather than leaving an open
promise on the thread.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8b54955

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
Stress test (arm_release) / Hung check failed, possible deadlock found cancelled DROP TABLE prometheus never returns from DatabaseCatalog::waitTableFinallyDropped; the test-database teardown convoys behind it on the DDL guard (trunk bug, reproduced on master) a fix task owns it (root cause proven and written up at #114064 (comment), no fix PR yet); fixing-PR link to follow here
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Reading from materialized CTE before its materialization completed, DelayedPortsProcessor gate is missing in the query plan (STID: 2467-2c2d) chronic trunk bug in materialized-CTE plan construction, 52 distinct PRs and 6 master hits in 14 days; the fuzzer reached it through a mutated count() query, not through h3 a fix task owns it (tracked chronic family, currently monitoring external work on the materialized-CTE plan gate); fixing-PR link to follow here

Neither is caused by this PR: the diff only adds cancellation checks to four h3 array-expanding
functions, which cannot reach TimeSeries teardown or materialized-CTE plan construction. The
hung root is is_cancelled = 1 at 1100.59s with shorter DDL-guard victims behind it.

Session id: cron:our-pr-ci-monitor:20260810-173000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the ledger above (same head, 8b54955)

The materialized-CTE line in the comment above gave a fix-task owner. That is wrong: an open fixing
PR of mine already covers this exact route, so the line should have linked it.

Check / test Corrected owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Reading from materialized CTE before its materialization completed (STID: 2467-2c2d) fixing PR 113489 (mine, open), "Fix materialized CTE gate missing for a reused CTE over Distributed"

Why that PR and not the wider chronic family: the failing query is a materialized CTE (rs) that
reads remoteSecure(...), is referenced twice (rs AS a, rs AS b), and is filtered by
IN (SELECT ... FROM ct) where ct is a second materialized CTE. That is the shape 113489
addresses: addBuildSubqueriesForMaterializedCTEsIfNeeded planned the containing CTE's body while
its deeper dependency was still not plan-backed, so the nested plans got no
DelayedMaterializingCTEsStep and FutureSetFromSubquery::buildOrderedSetInplace ran one as a
standalone pipeline where no gate can apply. The Stress test (arm_release) line above is unchanged.

Session id: cron:our-pr-ci-monitor:20260810-173000

@PedroTadim

Copy link
Copy Markdown
Member

@rschu1ze it seems here groeneai did a much simpler fix

@@ -66,6 +70,17 @@ class FunctionH3HexRing final : public IFunction

ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override
{
/// See h3kRing.cpp for why the element is resolved per call and why the throttle counts items.
QueryStatusPtr process_list_element;

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 I think this code addition across these functions can be deduplicated into a single inlined function?

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.

Yes, and better than an inlined helper local to these files: src/Functions/CancellationBudget.h
already does exactly this on master, from #113369 which you merged, and 5 function families use it.
This PR's base predates that header by 2738 commits, which is why the check is written out four
times here.

I have not pushed the dedup yet, because @ rschu1ze just objected to the whole per-function
approach in this PR and may prefer a single check before IFunction::executeImpl instead. I asked
him which he wants. If he keeps the per-function checks, I rebase onto that header and the
duplication and the local constant both go away.

@rschu1ze

rschu1ze commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

@rschu1ze it seems here groeneai did a much simpler fix

Sorry, everything about this PR is wrong in my view. Query cancellation is rare, query cancellation on pathological data is even more rare. Instead of adding cancellation checks into the implementation of each and every function (ClickHouse has >1600 regular functions and >200 aggregation functions) - i.e. sub-chunk granularity (*) - we should check the cancellation bit once before calling IFunction::executeImpl. Yes, there may be situations where cancellation will take a couple of seconds longer but the amounts of extra code and complexity are not worth the trouble.

(*) Checking cancellation within chunks is obviously too expensive if done per row. Therefore, one has to check every N rows. This then leads to new magic constants and nobody knows if they are optimal. Example from this PR:

items_between_cancellation_checks = 10'000;

@groeneai

Copy link
Copy Markdown
Collaborator Author

I measured this before answering, unfixed master against this PR, same box, debug and release.

A single check before IFunction::executeImpl does not bound these four. The whole block is
inside one executeImpl call, so with h3kRing(cell, 400) (481201 items per row) over 600 rows
in one block and max_execution_time=1:

  • unfixed master: the query reported elapsed 18549 ms and 227844 ms on two runs
  • this PR: 1084 ms and 1016 ms

The cost is not a couple of seconds for these functions, it is tens to hundreds of seconds,
because per-row output size is driven by argument values rather than by input size. h3kRing
accepts k up to 10000, which is 300030001 items from one row.

On the magic constant you are right, and there is a better answer than tuning it.
src/Functions/CancellationBudget.h is already on master: one units_per_check constant and one
makeCancellationCheck helper, used by 5 function families. This PR's base predates it by 2738
commits, which is why it writes out a local constant four times. Rebasing onto that helper removes
both the constant and the duplication, and shrinks the diff.

One honest limitation of my own patch: a single row expanding to hundreds of millions of items
still overruns, because the checkpoint sits between rows. This PR measured 221712 ms for one row
at k=1000. Bounding that would need a check inside the h3 call itself, which I am not proposing.

Which do you want: I rebase this onto the shared helper, or I close these four and the generic
pre-executeImpl check is the only thing that lands?

@PedroTadim

Copy link
Copy Markdown
Member

This needs a better solution

@PedroTadim PedroTadim closed this Aug 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, leaving it closed.

For whoever designs the replacement: in these four the expansion happens inside a single executeImpl call, so a check placed before that call does not bound them. That is a property of the problem rather than an argument for this patch, and the numbers are in the thread above if they are useful.

If you want the original report in #112203 handled a different way, say what shape you would accept and I will work to it.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Reopening due to a lack of a better solution.

@alexey-milovidov

Copy link
Copy Markdown
Member

The comment from @rschu1ze was discussed in Slack and invalidated.

@alexey-milovidov alexey-milovidov left a comment

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.

Actually, it's a very high quality code. Well done!

@groeneai

Copy link
Copy Markdown
Collaborator Author

Nothing needs pushing: praktika builds the merge commit, so the run the reopen started is already testing this branch merged into master as of 02:35Z, which includes #115773. The two reds still on display are from the 08-10 run and predate the reopen.

I did check the branch is still coherent after ten days. The revert of #113456 (#114537) was closed unmerged on 08-17, so the per-call query status this relies on is still on master, and the merge with my later #115773 is clean in the two files they share: merged h3kRing.cpp and h3ToChildren.cpp keep both the cancellation checkpoint and the geometric reserve.

In the report you linked, the hung query is SELECT sum(length(h3kRing(materialize(579205133326352383), toUInt16(1023)))) FROM numbers(150000), elapsed 993 s with is_cancelled = 1, and its thread stack sits in FunctionH3KRing::executeImpl.

@alexey-milovidov

Copy link
Copy Markdown
Member

Another attempt: #115893

@alexey-milovidov

Copy link
Copy Markdown
Member

#115893 is probably better. @groeneai, WDYT?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yours is better. I would take it over mine, and I am happy for you to close #113924.

I checked the three places I thought the two could differ, and they do not:

  • makeCancellationCheck resolves the process list element per call from the executing thread, so the case my version was written for (an instance stored in table metadata and later run by an unrelated query) is covered, and it turns a false return into a throw, so break overflow mode cannot yield a half-built array.
  • h3Line gets a checkpoint in both the sizing and the fill loop. gridPathCellsSize walks the grid, so the sizing pass needs one of its own.
  • h3HexRing's sizing loop is deliberately left without one in both, for the same reason.

Your version also has the regression coverage mine lost when the timing-based tests were removed. 05029 is free on master, the oracle is the outer timeout rather than a measured elapsed time, and the second query pins the returned lengths (122 for the resolution 0 cell, 30301 for 3*k*(k+1)+1 at resolution 15), so it should not be flaky. Your reading of maxGridDiskSize(k) costing the same regardless of how many cells exist at that resolution is also a sharper description of why this shows up as a hang rather than a memory error than the one in my body.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The polygon functions have the same problem as the four in this PR, but the seam used here does not reach it, and I think the fix has to go into ClickHouse/h3. Numbers below, then the question.

The amd_msan hung check has a second signature: h3PolygonToCellsWithContainment, 766 s with is_cancelled = 1 against max_execution_time = 10, leaf at polyfill.c:775 inside maxPolygonToCellsSizeExperimental (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115892&sha=36c79c02ed75a716725237b7469cf486dbe00982&name_0=PR&name_1=Stress+test+%28amd_msan%29, query_id 59d9ab3c-1c79-4fa5-ace2-5929186ba10c). 127 rows over 102 PRs in 30 days, 12 of them on master.

There are two unbounded walks, and I could not bound either from src/Functions:

  • The size estimator. Its res-reduction heuristic keys on bounding-box area, so a thin globe-spanning polygon keeps the full requested resolution: [(-179, 0), (179, 1e-9), (0, 0)] gives area 4.4e-03 km2 and an estimate resolution of 9, with a global bbox. Every coordinate there is in range, so rejecting out-of-range coordinates does not bound it. I tried that first and it does not work.
  • The fill. budget.charge per emitted cell does not help, because iterStepPolygon re-enters iterStepPolygonCompact and that inner while (cell) can examine a very large number of cells before it emits one.

I also cannot apply makeCancellationCheck to the estimator the way this PR applies it elsewhere. maxPolygonToCellsSizeExperimental initialises through the static _iterInitPolygonCompact and then overwrites _flags and _res before the first step. The public iterInitPolygonCompact steps immediately, so driving the loop from ClickHouse would change the estimate rather than just add a checkpoint. Tightening MAX_ARRAY_SIZE does not help either: it is checked after the estimator has already returned.

That leaves a cancellation callback inside iterStepPolygonCompact, which is a change to contrib/h3. I have no push access to ClickHouse/h3 and I am not going to open anything upstream without being asked.

So: do you want a callback in ClickHouse/h3 plus the submodule bump, or should the polygon functions stay as they are for now? I have the analysis and the repro ready either way.

One separate thing, unrelated to the hang and not something I am proposing to fix here: an out-of-range latitude also returns a silently wrong answer rather than an error. [(-122.4, 95), (-122.3, 95.5), (-122.5, 96)] at resolution 9 returns 0 cells where the same shape at latitude 85 returns 643.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Following up on my comment above, because the obvious next idea does not work either and I would
rather close it off than leave it looking open.

The polygon hang has now also shown up on arm_debug, 3080 s with is_cancelled = 1, same leaf at
polyfill.c:775 (report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116133&sha=e9a215c284fb7445939babacac5b3783e3501669&name_0=PR&name_1=Stress+test+%28arm_debug%29,
query_id df0c477c-d8d4-4a44-9322-beae2d992b67). Third distinct call path: this one is a plain
SELECT ... FROM numbers(200) reaching the function through ExpressionActions::executeOnColumns,
so it is neither constant-folded nor a dry run like the other two.

What I said above was that I could not use makeCancellationCheck on the estimator because it
initialises through the static _iterInitPolygonCompact. That is true but it is not the real
obstacle, and I want to correct it. The compact iterator API is not private at all:
IterCellsPolygonCompact and iterInitPolygonCompact / iterStepPolygonCompact /
iterDestroyPolygonCompact are declared in polyfill.h, which contrib/h3-cmake already puts on
the PUBLIC include path next to h3api.h, and all three are exported from lib_h3.a. I checked
that including it from C++ compiles and links.

So I could have driven the loop from src/Functions and charged a CancellationBudget per step.
That still does not fix it, for a reason I had in front of me and misread: in both stack traces the
iterStepPolygonCompact frame is itself on the stack, at :524 here and :487 in the msan one.
The thread is inside a single step, not between steps. One step descends the hierarchy and walks
with nextCell until it either emits a cell or exhausts the grid, so a check between steps never
runs. And the step cannot be decomposed from our side: nextCell and iterErrorPolygonCompact
have internal linkage.

There is one more thing wrong with that idea independently: after the public initialiser takes its
first step, an exhausted iterator has already been destroyed, which frees _bboxes and nulls
_polygon, so re-arming it by hand would dereference NULL on a 0-vertex or fully-pruned polygon.

That leaves the question from my earlier comment unchanged: a cancellation check inside
iterStepPolygonCompact, which is a ClickHouse/h3 change plus a submodule bump. Rejecting the
geometry up front still does not work (the thin globe-spanning polygon has every coordinate in
range), and tightening MAX_ARRAY_SIZE still happens after the estimator has returned. The
analysis and the repro are ready if you want the h3 change.

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

4 participants