Skip to content

Reject out-of-domain coordinates in the h3 polygon functions - #116225

Closed
alexey-milovidov wants to merge 3 commits into
masterfrom
h3-polygon-reject-out-of-domain-coordinates
Closed

alexey-milovidov wants to merge 3 commits into
masterfrom
h3-polygon-reject-out-of-domain-coordinates

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

h3PolygonToCellsWithContainment could spin in an effectively unbounded loop inside the H3 library when a vertex of the polygon was outside the domain latitude and longitude are defined on. The loop runs inside a single maxPolygonToCellsSizeExperimental call, so it observes neither max_execution_time nor KILL QUERY - the query below had is_cancelled = 1 and had been running for 500 seconds when the stress-test hung check gave up:

SELECT sum(length(h3PolygonToCellsWithContainment([(37.81331899998324, materialize(-122.40898669999721)), (-122.35447369999936, 37.71980619999785), (9007199254740991., 100000000000000000000.)], 9, 0)))
FROM numbers(257)

(The AST fuzzer produced it from 04910_h3_array_building_no_quadratic_realloc.)

H3 derives the part of the grid its polyfill has to walk from the polygon's bounding box, and reduces the resolution it walks at until that box holds about ten cells. With a latitude of 1e20 degrees the rough area that heuristic computes comes out negative, no reduction happens, and the walk covers every cell of the target resolution - about 4.9e9 cells at resolution 9, measured at roughly 250k cells per second.

H3 itself only rejects coordinates that are not finite, so this checks the domain before calling into it: longitude in [-180, 180] and latitude in [-90, 90] degrees, which is H3's own VALID_RANGE_BBOX. Coordinates outside that range never produced anything useful anyway - H3 does not wrap longitudes, so a polygon at longitude 200 returns an empty array today. Both h3PolygonToCells and h3PolygonToCellsWithContainment now throw ARGUMENT_OUT_OF_BOUND, for the holes of a polygon as well as for its exterior ring.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2797514bd2d8b632984538bb9989356995b8a7c8&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

Closes: #116195
Related: #115893
Related: #112203

One thing this does not fix, measured while investigating: a polygon whose bounding box is degenerate with perfectly valid coordinates - all vertices on one meridian, or a box spanning exactly [-180, 180] - also makes the area heuristic yield 0 and defeats the resolution reduction. The walk is then along a one-dimensional strip rather than over the whole grid, so it is finite: 30 seconds in a release build for a 20-degree meridian at resolution 15. That needs a change in the H3 resolution heuristic itself, which is why it is left out here.

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 reject coordinates outside their domain (longitude in [-180, 180], latitude in [-90, 90] degrees) instead of running for an unbounded time that could not be interrupted by max_execution_time or KILL QUERY.


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

`h3PolygonToCellsWithContainment` could spin in an effectively unbounded
loop inside the H3 library when a vertex of the polygon was outside the
domain latitude and longitude are defined on. The loop is inside a single
`maxPolygonToCellsSizeExperimental` call, so it observes neither
`max_execution_time` nor `KILL QUERY`: the query in the report below had
`is_cancelled = 1` and had been running for 500 seconds when the hung
check gave up.

H3 derives the part of the grid its polyfill has to walk from the
polygon's bounding box, and it reduces the resolution it walks at until
that box holds about ten cells. With a latitude of `1e20` degrees the
rough area the heuristic computes comes out negative, no reduction
happens, and the walk covers every cell of the target resolution -
about 4.9e9 cells at resolution 9.

H3 itself only rejects coordinates that are not finite, so check the
domain before calling into it: longitude in `[-180, 180]` and latitude
in `[-90, 90]` degrees, which is H3's own `VALID_RANGE_BBOX`. Values
outside it never produced anything useful anyway - a polygon at
longitude 200 returns an empty array today, because H3 does not wrap
longitudes.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=2797514bd2d8b632984538bb9989356995b8a7c8&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

Closes: #116195
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f8b5f0]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_hedged_requests/test.py::test_receive_timeout1 FAIL cidb
Performance Comparison (arm_release, master_head, 5/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

This PR adds an explicit longitude/latitude domain check before the two H3 polygon functions call into H3's polyfill path, so inputs outside [-180, 180] x [-90, 90] now fail fast with ARGUMENT_OUT_OF_BOUND instead of entering the uninterruptible library call that motivated the fix. I did not find a correctness, safety, or test-coverage issue in the current patch.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit 1f8b5f0.

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

Changed lines: Changed C/C++ lines covered: 43/43 (100.00%) · 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 1f8b5f057 with master 5742d8296 (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

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

Job report

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

A more complete implementation here: #116335 It both rejects out of domain coordinates and implements better timeout checks

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116225&sha=4a99f82e7b2fe4628b8224e6db30aca5c55a34f3&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 and provide a fix in a separate PR. Two tests failed there, both unrelated to this PR (it only touches the h3 polygon functions): 03312_squashing_with_low_card_mem_usage (a recurring darwin-runner disk-capacity flake, failing across unrelated PRs since 2026-08-18 — already reported on #111985) and 03826_calculate_subcolumn_size_during_merge_tree_read (also failing across unrelated PRs since 2026-08-18, no open issue found). If a fix is already in progress, link it here. I have merged master into this branch for a fresh CI run.

@groeneai

Copy link
Copy Markdown
Collaborator

Both failures on that run are the same macOS runner disk exhaustion, not two defects: Code: 243. DB::Exception: Cannot reserve ... not enough space. (NOT_ENOUGH_SPACE), both on host ip-172-31-7-227, 100 seconds apart.

Over the last 21 days of Fast test (arm_darwin), 12 failures carry NOT_ENOUGH_SPACE, spread over 9 pull requests and 5 distinct runner hosts, first on 2026-08-18, which matches the onset you saw: 03312_squashing_with_low_card_mem_usage 6, 03826_calculate_subcolumn_size_during_merge_tree_read 5, and 04647_no_blocks_marshalling_for_local_shard_plan once, where the reservation that failed was 1.00 MiB. That last one is why 03826 needs no issue and no separate fix of its own: the host reaches zero free space and whichever test reserves next dies, so the victim list is just the tests that write the most at that moment.

The fix is already open: #113605, since 2026-08-06. On master Runner.check_post_run still begins with if config.init_environment == Environment.MACOS: return (ci/praktika/infrastructure/runner/runner-init.py:430), so the df guard never runs on those hosts, and they are also exempt from the max_jobs recycle (:345), so free space ratchets down across jobs until a reservation fails on whichever test happens to be running. The PR moves the check out of that early return and also calls it from _check_conditions, so a host that boots full refuses the next job instead of failing the one after. It bounds the damage; it does not identify what fills the disk, which needs on-runner measurement that CI does not collect today.

It is mergeable and waiting on review from the runner owner: @ Algunenano asked @ leshikus to look on 2026-08-06, and I posted the per-job evidence the same day. There is no open issue for either test.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (1f8b5f0572cf) for a fresh run. Both reds on 7bf4ed2b are unrelated to this PR (it only touches the h3 polygon functions):

@groeneai, investigate the second one: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116225&sha=7bf4ed2b2ff741cbdd47defab99250eec27d8fa5&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 and provide a fix in a separate PR. If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. That red is not the #109698 mechanism, and the fix for it is already on master.

The single fatal in that run is on the pre-upgrade server (v26.7.5.10), during TRUNCATE ALL TABLES FROM test_1, and the uncaught exception is not a logical error:

Terminate called for uncaught exception:
Code: 1001, type: std::__1::filesystem::filesystem_error, e.what() = filesystem error: in posix_stat:
failed to determine attributes for the specified path: File name too long
["/var/lib/clickhouse/disks/s3/store/a36/.../all_1_1_0/skp_idx_auto_minmax_index_%E4%B8%80...%E4%B8%B2.idx"]
 7. DB::DiskLocal::existsFile
 8. DB::DataPartStorageOnDiskFull::existsFileImpl
 9. DB::IMergeTreeDataPart::getStreamNameOrHash
10. DB::IMergeTreeDataPart::hasSecondaryIndex
11. DB::MergeTreeData::removePartContributionToColumnAndSecondaryIndexSizes
12. DB::MergeTreeData::Transaction::commit

hasSecondaryIndex probes the unhashed escaped index file name before the hashed one. With a long non-ASCII index name that path exceeds NAME_MAX, and 26.7's DiskLocal::existsFile used the throwing fs::is_regular_file overload, so a plain "not found under this name" probe raised filesystem_error instead of returning false. The probe runs inside the NOEXCEPT_SCOPE of Transaction::commit, so it becomes std::terminate.

Fixed on master by #111816 (@ Algunenano, merged 2026-08-04), commits ddfe555fb75 and d1060b6c2aa: DiskLocal::existsFile / existsDirectory / existsFileOrDirectory now treat only std::errc::filename_too_long as "does not exist" and re-throw every other stat error. There is no master fix left to write, so I am not opening a PR for it.

It still fires here because the guard is on master and 26.8 but not on 26.7, 26.6 or 26.3, and find_previous_release installs the newest release below the build version, which is v26.7.5.10 while 26.8 has no release tag yet. The post-upgrade 26.9.1.1 server in that same run logged no fatal. CIDB has 3 Upgrade check (amd_release) hits across 3 PRs in 30 days, all after v26.7.5.10 shipped on 2026-08-21. This stops when 26.8 is released. If you want it quiet before then, the two commits above touch only src/Disks/DiskLocal.cpp (+28/-3) and cherry-pick cleanly, but a v26.7-must-backport label on #111816 would drag the settings promotion along with them, so that needs a separate cherry-pick rather than the label.

One caveat on the reported name. Logical error '!part.empty()' (STID: 3563-49ac) appears exactly once in the 87 MB server log, as a comment line in the old release's copy of 04367_lambda_arg_backquoted_dot_no_logical_error.sql echoed into a TYPE_MISMATCH message, and creation_csn is not set appears zero times. ci/jobs/scripts/log_parser.py names a fatal after the first Logical error ... string anywhere in the log, whichever query printed it; #111708 fixes that. #109698 itself is the separate non-transactional TRUNCATE stamping removal_csn = 1 over a part whose transactional creation has not published, owned by @ tuanpach's open #105116. The two share only the Transaction::commit frame.

@Algunenano Algunenano self-assigned this Aug 31, 2026
@Algunenano

Copy link
Copy Markdown
Member

Closing in favour of #116335, which includes this fix and several others

@Algunenano Algunenano closed this Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

h3PolygonToCellsWithContainment hangs unkillably on degenerate polygon coordinates

3 participants