Skip to content

Check for timeouts and KILL QUERY while covering a polygon with H3 cells - #116335

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
Algunenano:h3-polygon-to-cells-cancellation
Aug 31, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
Algunenano:h3-polygon-to-cells-cancellation

Conversation

@Algunenano

@Algunenano Algunenano commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

A stress test hung on a fuzzed h3PolygonToCellsWithContainment query whose polygon had a vertex at latitude -1.7976931348623157e308. It spent about 45 minutes inside one H3 call, observing neither max_execution_time nor KILL QUERY: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116133&sha=e9a215c284fb7445939babacac5b3783e3501669&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

Two causes. H3 picks the coarse resolution for its size estimate by dividing the polygon's bounding box area by the average cell area, and a vertex off the sphere makes that area negative, so the reduction never triggers and the estimate counts every cell of a polygon covering much of the globe: 2.6e8 cells at resolution 9. And the cells of one polygon were filled inside a single H3 call, so the only cancellation checkpoint was between rows, which bounds nothing when one row runs for 45 minutes.

Vertices are now rejected unless longitude is in -180..180 and latitude in -90..90 degrees, and the cells are enumerated one at a time through H3's cell iterator, charging the shared CancellationBudget per cell. Both functions share one implementation now, which also drops the staging buffer the results were copied through.

h3PolygonToCells had the same shape, plus H3's legacy algorithm allocating two estimate-sized buffers outside the memory tracker, so a large estimate could be OOM-killed instead of raising MEMORY_LIMIT_EXCEEDED. It goes through the same iterator with CONTAINMENT_CENTER, the containment rule its own H3 source documents for itself; the two functions return the same cells at resolutions 5, 7, 9 and 11 in the added test.

Measured on a release build:

before after
fuzzed query from the report ~45 min, unkillable ARGUMENT_OUT_OF_BOUND immediately
valid 20000-vertex polygon, res 10, 1 s deadline 7.5 s (WithContainment), 29 s (h3PolygonToCells) stops at 1.1 s
20 by 20 degree box, res 9, h3PolygonToCells 47 s, 4.5 GB peak RSS 0.64 s, 1.35 GB, same 58823612 cells

Verified clean under MSan and TSan, where the deadline is still honored within a millisecond.

Related: #116133

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

Functions h3PolygonToCells and h3PolygonToCellsWithContainment now check for query timeouts and KILL QUERY while covering a polygon, and reject vertices whose longitude is outside -180..180 or latitude outside -90..90 degrees. Previously a polygon with such a vertex could keep a thread busy for tens of minutes, ignoring both.

Closes #116195


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

Version info

  • Merged into: 26.9.1.446-master (included in 26.9 and later)
  • Backported to: 26.8.11.8, 26.7.14.22

A stress test hung on a fuzzed `h3PolygonToCellsWithContainment` query whose
polygon had a vertex at latitude -1.7976931348623157e308. It spent about 45
minutes inside one H3 call, observing neither `max_execution_time` nor
`KILL QUERY`.

Two causes. H3 picks the coarse resolution for its size estimate by dividing
the polygon's bounding box area by the average cell area, and a vertex off the
sphere makes that area negative, so the reduction never triggers and the
estimate counts every cell of a polygon covering much of the globe: 2.6e8 cells
at resolution 9. And the cells of one polygon were filled inside a single H3
call, so the only cancellation checkpoint was between rows.

Vertices are now rejected unless longitude is in -180..180 and latitude in
-90..90 degrees, and the cells are enumerated one at a time through H3's cell
iterator, charging the shared `CancellationBudget` per cell. Both functions
share one implementation now, which also drops the staging buffer the results
were copied through.

`h3PolygonToCells` had the same shape, plus H3's legacy algorithm allocating
two estimate-sized buffers outside the memory tracker. It goes through the same
iterator with `CONTAINMENT_CENTER`, the containment rule its own H3 source
documents for itself. On a 20 by 20 degree box at resolution 9 it returns the
same 58823612 cells in 0.64 s instead of 47 s, with 1.35 GB of peak RSS instead
of 4.5 GB.

Measured on a release build: a valid 20000-vertex polygon at resolution 10 took
7.5 s per row for the first function and 29 s for the second, and both now stop
1.1 s after a 1 s deadline. Clean under MSan and TSan.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116133&sha=e9a215c284fb7445939babacac5b3783e3501669&name_0=PR&name_1=Stress%20test%20%28arm_debug%29
ClickHouse#116133

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe3cc3a]

Summary: ✅


AI Review

Summary

This PR moves both H3 polygon-covering functions onto a shared, checkpointed traversal so max_execution_time and KILL QUERY are observed mid-row, rejects out-of-sphere vertices before entering H3, and documents the now-unstable output order of h3PolygonToCells. I did not find a remaining correctness or compatibility issue in the current code; the two earlier bot findings are addressed by the candidate-level cancellation checks and the doc/example updates.

Missing context / blind spots
  • ⚠️ I could not run the affected H3 stateless tests locally from this checkout because there are no build artifacts here, so the verdict is based on code inspection, the checked-in tests, and the GitHub discussion state rather than a fresh local execution.
Final Verdict

No new findings.

LLVM Coverage Report

Measured on commit fe3cc3a.

Metric Baseline Current Δ
Lines 88.40% 88.50% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.80% +0.10%

Changed lines: Changed C/C++ lines covered: 220/230 (95.65%) · 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 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fe3cc3a27 with master 90144f901 (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
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.24 MiB -3.09 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.

Object file sizes

6 object files changed (-61.00 KiB total), 1 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/h3GeometryToCells.cpp.o new 182.89 KiB +182.89 KiB
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/h3PolygonToCellsWithContainment.cpp.o 628.70 KiB 505.98 KiB -122.71 KiB (-19.52%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/h3PolygonToCells.cpp.o 578.32 KiB 457.14 KiB -121.18 KiB (-20.95%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

9 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Functions/h3GeometryToCells.cpp: 5.6 s

Job report

`h3PolygonToCells` now enumerates the cells through H3's cell iterator, which
emits them in a different order than the legacy breadth-first algorithm. The
set is unchanged: sorting every array in the reference makes the old and new
outputs identical, and the test's own comparison against the expected cells,
which sorts, keeps passing on every line.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/h3GeometryToCells.cpp Resolved
Comment thread src/Functions/h3PolygonToCells.cpp Resolved
Algunenano and others added 2 commits August 27, 2026 14:47
H3 wraps its candidate walk in one call, and that call rejects millions of
candidates before it returns a cell, so charging the budget per returned cell
bounds nothing for a sliver polygon: the size estimate returns no cell at all,
and a needle whose bounding box covers much of the globe runs for minutes past
the deadline. The walk of `iterStepPolygonCompact` now runs here, over the same
H3 primitives so the cells and their order are unchanged, with a checkpoint per
candidate, and the size estimate goes through it too.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`h3PolygonToCells` enumerates the cells through H3's cell iterator now, which
emits them in a different order, so the example response is the new order. Both
functions document that the order is not guaranteed and that every vertex must
be on the sphere, and the missing anchor is added.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Algunenano
Algunenano added this pull request to the merge queue Aug 31, 2026
Merged via the queue into ClickHouse:master with commit 828b3cd Aug 31, 2026
353 of 355 checks passed
@Algunenano
Algunenano deleted the h3-polygon-to-cells-cancellation branch August 31, 2026 14:40
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 31, 2026
@nikitamikhaylov nikitamikhaylov self-assigned this Sep 14, 2026
@Algunenano

Copy link
Copy Markdown
Member Author

@alexbakharew Why do we need to backport this?

clickhouse-gh Bot added a commit that referenced this pull request Sep 21, 2026
Backport #116335 to 26.8: Check for timeouts and KILL QUERY while covering a polygon with H3 cells
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 23, 2026
Cherry pick #116335 to 26.7: Check for timeouts and KILL QUERY while covering a polygon with H3 cells
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 23, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 23, 2026
Backport #116335 to 26.7: Check for timeouts and KILL QUERY while covering a polygon with H3 cells
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 5, 2026
Revert backport of #116335 to 26.8: Check for timeouts and KILL QUERY while covering a polygon with H3 cells
clickhouse-gh Bot added a commit that referenced this pull request Oct 5, 2026
Revert backport of #116335 to 26.7: Check for timeouts and KILL QUERY while covering a polygon with H3 cells
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 5, 2026
…ond algorithm

ClickHouse#116335 moved `h3PolygonToCells` onto the compact walk, which starts at the 122 base cells and
descends level by level to the target resolution, and runs it twice (the size estimate, then the
fill). For a polygon smaller than a cell that fixed descent is the whole cost, so 9-point rings at
resolution 10 became about 5x slower than with H3's legacy `polygonToCells`.

Per review, replace the legacy fast path of the previous commits with two changes to the walk:

- For a polygon at most half as large as the cells of some resolution `r >= 2`, away from the
  poles and not crossing the antimeridian, the walk starts at the resolution-`r` cells whose
  bounding box of children overlaps the polygon's: the only cells the walk descends into at that
  resolution. They are taken from the cells within three steps of the first vertex's cell; they
  are connected and include that cell, so the set is complete unless one of them is three steps
  away, in which case the walk starts from the base cells as before. Subtrees of distinct cells of
  one resolution are disjoint, ascending ranges of the walk, so the cells and their order do not
  change. Every other polygon keeps the walk from the base cells.
- Every covering cell descends from one of these cells, so their number of children bounds the
  result and the estimate, and the estimate walk is skipped when that bound fits the array limit.

One algorithm, all checkpoints and all containment modes are kept. Base vs this commit, release
builds, every mode: the outputs (exact arrays, so order included) are byte-identical on 975827
random polygons (resolutions 0-15, including antimeridian-crossing ones) and on 345891 polygons
near pentagons, the poles, the antimeridian, latitude 80, with holes, empty holes, bowties,
degenerate rings and multipolygons; the 109 rows that throw do so identically.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexbakharew

Copy link
Copy Markdown
Contributor

@Algunenano as discussed, it should be reverted.

zvonand pushed a commit to zvonand/ClickHouse that referenced this pull request Oct 13, 2026
Since ClickHouse#116335, `h3PolygonToCells` and `h3PolygonToCellsWithContainment`
cover every polygon with an in-tree copy of H3's compact-hierarchy walk,
run twice: once for the size estimate (`estimateCellCount`) and once for
the fill. The walk starts at base cell 0 and, for every candidate coarser
than the target resolution whose children bbox overlaps the polygon,
evaluates its 7 children. A polygon smaller than a cell overlaps about 3
candidates per level, so each walk costs about 7 x 3 x res cell centers
whatever the polygon's size. Before ClickHouse#116335, `h3PolygonToCells` used H3's
`polygonToCells` (trace the edges with `latLngToCell`, flood-fill
inwards), whose cost grows with the vertices and the covered cells. On the
issue's 30000 9-point rings at resolution 10 (release builds): 0.56 s on
the parent of the ClickHouse#116335 merge, 4.04 s on the merge, on 26.8.17 and
master. Measured split on master: estimate walk ~66%, fill ~34%.

ClickHouse#116335 moved off `polygonToCells` because it runs inside one H3 call (no
cancellation point; 29 s on 05043's 20000-vertex comb) and allocates two
estimate-sized buffers outside the memory tracker. Both only matter for
large inputs, so this change uses `polygonToCells` only for polygons for
which that single call is provably bounded by one cancellation checkpoint
interval (`CancellationBudget::units_per_check`), and charges that bound
to the budget before the call:

- containment mode 0 only (the only mode `polygonToCells` implements);
- no inner rings: `maxPolygonToCellsSize` sizes its tables from the outer
  loop only, so hole tracing and per-candidate hole tests are not bounded
  by `size` (an empty inner ring counts too);
- not transmeridian (its edge tracing interpolates longitude linearly),
  bbox at most pi wide and within 85 degrees of latitude: the skipped
  estimate can exceed MAX_ARRAY_SIZE for a tiny polygon only near a pole
  or for a bbox spanning most longitudes, so these keep the walk and its
  TOO_LARGE_ARRAY_SIZE outcome;
- at most 4 * (res + 2) vertices: legacy pays ~1.9 us per vertex, the walk
  ~11 us per level; where legacy loses (res 1 with 16+ vertices) the walk
  is kept;
- units = edge_samples * (size + 1) + 16 * size * (size + 2 + vertices)
  <= 65536, with `size` from `maxPolygonToCellsSize` (the call recomputes
  the same value) and `edge_samples` the exact count `_getEdgeHexagons`
  traces (`lineHexEstimate`'s formula with `_hexRadiusKm` of the
  resolution's first pentagon, cached per resolution from public calls).
  Every insertion into the `size`-slot hashes probes at most `size` slots
  (else E_FAILED), each traced point costs one insertion, and the flood
  tests at most 14 * size neighbours, each with at most `size` probes and
  one point-in-polygon pass over the loop's edges.

`polygonToCells` returning E_FAILED (degenerate bbox, 1-vertex rings,
hash overflow) falls back to the walk; any other H3 error is reported as
the walk reports its own. The legacy output is sorted, because the walk
returns cells in ascending order, so results are identical. In practice
the bound admits polygons of up to about 6 cells; larger ones keep the
walk at today's speed.

Validation (local RelWithDebInfo, base = master):
- issue's query 5.76 s -> 0.72 s, its second query 6.18 s -> 1.18 s,
  same results;
- 1.24M random polygons (holes, empty holes, multipolygons, pentagon
  neighbourhoods, near-pole, polar caps, wider than 180 degrees,
  transmeridian, concave, degenerate) at resolutions 0-15: byte-identical
  arrays and identical errors;
- 149-point sweep over resolution x vertices x size: worst fix/base 1.034;
- worst case at the bound: 0.089 ms per polygon;
- new performance test 1.92 s -> 0.24 s.

Closes ClickHouse#123877

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport v26.7-must-backport v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

h3PolygonToCellsWithContainment hangs unkillably on degenerate polygon coordinates

6 participants