Skip to content

Fix out-of-bounds read in pointInPolygon on an unbounded bounding box - #115035

Merged
nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-point-in-polygon-unbounded-grid
Aug 17, 2026
Merged

nihalzp merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-point-in-polygon-unbounded-grid

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #11375

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 an out-of-bounds read in pointInPolygon with a constant polygon whose bounding box is unbounded, for example when a coordinate reaches +-DBL_MAX. Such a polygon is now rejected with BAD_ARGUMENTS, and a polygon with an empty ring is treated as having no interior. Previously the query could return a wrong result, or abort the server in builds with hardening or sanitizers enabled.

Description

SELECT pointInPolygon((1e308, 1.), [(-1.7976931348623157e308, 0.), (1.7976931348623157e308, 0.), (0., 2.)])
reads a cells element out of range, on default settings and with no elevated privileges. With
libc++ hardening or a sanitizer it aborts (vector[] index out of bounds); otherwise it switches
on a garbage cell type. Found by the targeted AST fuzzer:
report
(the carrier PR is unrelated to this code).

Root cause. calcGridAttributes validated the derived scales for finiteness but tested the
bounding-box span only for == 0. 1 / +-inf is +-0.0, which is finite, so an infinite span
passed validation; contains then computed inf * 0.0 = NaN, which compared false against both
range guards, static_cast<int>(NaN) gave INT_MIN, and the cell index overflowed.

Change. Classify the span where it is computed: non-positive means no interior
(has_empty_bound), non-finite is rejected with BAD_ARGUMENTS. Six lines in the only writer of
the grid scales, so every reader is covered at once. <= 0 rather than !(span > 0) keeps a NaN
span throwing, as it does today.

Scope. Only the preprocessed grid used for constant polygons is changed. A non-constant
polygon column takes the on-the-fly ray-casting path, which builds no grid and cannot reach this
out-of-bounds read; it does lose precision on an unbounded span (inf/inf in the edge formula),
a separate pre-existing issue deliberately left alone here.

Validation. Measured against pristine HEAD. Three carriers stop aborting: the wide polygon
above, an empty ring, and an empty ring inside a multipolygon (which tripped a boost R-tree
assertion). A fourth, an unbounded span on the y axis, silently returned wrong answers (1
where an affine analogue proves 0). Wide but finite polygons (1e200) keep their results.
3 existing tests extended, each verified to fail before the change; the polygon suite is green.

Behavior matrix (pristine HEAD vs this PR)

01940_point_in_polygon_ubsan changes expectation from 0 to BAD_ARGUMENTS: its polygon has
an inf vertex, so the span is now rejected before contains runs, where its 0 came from the
query point guard. That guard stays covered by 00500_point_in_polygon_nan.

statement settings HEAD this PR
(1e308,1.) vs [(-M,0.),(M,0.),(0.,2.)] default abort BAD_ARGUMENTS
same, multipolygon / with a hole default abort BAD_ARGUMENTS
empty ring, large point validate_polygons=0 abort 0
[[[]]] multipolygon validate_polygons=0 boost assertion 0
y-unbounded [(0.,-M),(1.,M),(2.,0.)], (1.,-1e308) validate_polygons=0 1 (wrong) BAD_ARGUMENTS
NaN span [(inf,0.),(inf,0.1),(inf,0.2)] validate_polygons=0 BAD_ARGUMENTS BAD_ARGUMENTS
1e200 span, (0.,1.) / (1e199,0.5) default 1 / 1 1 / 1
zero span, point polygon validate_polygons=0 0 0
issue #11375 NaN-point repro default 0 0

M = 1.7976931348623157e308.

Version info

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

…nding box

calcGridAttributes validated the derived grid scales for finiteness but tested
the bounding-box span only for equality with zero. Since 1 / +-inf is +-0.0,
which is finite, an infinite span passed that validation. contains() then
computed (x + x_shift) * x_scale as inf * 0.0 = NaN; NaN compares false against
both the < 0 and > grid_size range guards, static_cast<int>(NaN) yields INT_MIN,
and getCellIndex signed-overflows before indexing a 64-element cells vector.

Classify the span where it is computed instead: a non-positive span (zero, or
the inverse box boost::geometry::envelope leaves for an empty geometry) means
the polygon has no interior, and a non-finite span is rejected with
BAD_ARGUMENTS. This is the only writer of cell_width, cell_height, x_scale and
y_scale, so every reader is covered at once, and no NaN can reach getCellIndex:
with a finite positive span, inf * positive_finite is +-inf, which the existing
range guard already catches.

The predicate is <= 0 rather than !(span > 0) because the two differ only for
NaN. A NaN span already throws BAD_ARGUMENTS today, and !(span > 0) is true for
NaN, which would have turned that into a silent 0.

Four carriers, each measured against pristine HEAD and the patched binary:

  - a polygon with vertices at +-DBL_MAX aborts on default settings (this is
    what the targeted AST fuzzer found; parseRing's mulOverflow guard does not
    stop it because the vertices have y == 0, so the product is 0);
  - an empty ring aborts under validate_polygons = 0;
  - an empty ring inside a multipolygon trips a boost R-tree assertion,
    "Indexable is invalid", from the inverse-box envelope;
  - an unbounded span on the y axis does not abort but returns wrong results:
    for the triangle (0,-DBL_MAX),(1,DBL_MAX),(2,0) it answers 1 at (1,-1e308),
    (1.5,1e308) and (0.5,1e308), where scaling y by 1/DBL_MAX, an affine map
    that preserves inside/outside, proves the answer is 0.

Wide but finite polygons keep their results, pinned by non-regression rows.

Three existing tests are extended, each verified to fail before this change;
two of them fail by the server dying, which is the defect itself. The
01940_point_in_polygon_ubsan expectation changes from 0 to BAD_ARGUMENTS: its
polygon has an inf vertex, the same query already throws on default settings
because only validate_polygons = 0 reaches the grid at all, and its 0 came from
the -inf query point hitting the isFinite guard rather than from grid
arithmetic. That matches 04318_polygon_dict_nan_inf_coordinates, which rejects
infinite polygon coordinates.

Issue ClickHouse#11375 reported the same assertion at the same line in 2020 and was fixed
by adding the NaN point guard; that repro still returns 0. This defect arrives
through the span instead, which the point guard does not cover.

Found by the AST fuzzer (amd_debug, targeted), STID 2501-4c25:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112930&sha=27e32067e2142071df32a1cd106e533e54ae645e&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding in round 1,
0 in round 2 after the PR contract was narrowed), plus my own cold review of the resulting
code (5 nits) performed before reading the implementation notes.

# Sev Finding Verdict Evidence / action
1 ❌ The BAD_ARGUMENTS contract is implemented only for constant polygons; a non-constant polygon column can still return wrong results for the same unbounded span (pointInPolygon.cpp:565-628) AGREE Reproduced the arithmetic independently: in isInsideRing the edge term (x2-x1)*(py-y1)/(y2-y1) on [(0,-M),(1,M),(2,0)] with py = 1e308 evaluates inf/inf = NaN, so point_x < NaN is false for every x; versus the affine analogue it disagrees at point_x 0.9 and 0.78. Fixed by narrowing the stated contract, not the code: that path builds no grid and cannot reach the out-of-bounds read, and its precision loss predates this PR. The changelog entry now says "with a constant polygon" and a Scope paragraph states the limitation explicitly. Re-gated against the new contract: 0 findings.
2 💡 PR title exceeded 70 characters AGREE, fixed Retitled, 69 characters.
3 💡 PR body over the concision budget AGREE, fixed Condensed to 2947 visible characters, 290-word description.
4 💡 Flipping 01940_point_in_polygon_ubsan to BAD_ARGUMENTS drops its coverage of the non-finite query-point guard DISAGREE The span check now fires before contains, so that test no longer reaches the point guard, but the guard stays covered by 00500_point_in_polygon_nan.sql (NaN point, all-finite polygon) and 03095_join_filter_push_down_right_stream_filled.sql (materialize((-inf, 1023)), finite bounding box). No coverage lost.
5 💡 The default-settings rows assert an error code that bg::is_valid can also raise, so the oracle is not by itself specific to the span check DISAGREE Two of the new rows run with validate_polygons = 0, bypassing is_valid entirely, and every new row was measured to fail on pristine HEAD. Stateless tests have no message-matching oracle, so a stricter form is not available.
6 💡 Comment budget on the source diff DISAGREE 3 added comment lines against 3 added code lines, each stating a local floating-point invariant (1 / +-inf is finite; NaN is not <= 0) with no reference to the fix or its history. No trim.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20260816-190300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One statement, default settings, no SET: SELECT pointInPolygon((1e308, 1.), [(-1.7976931348623157e308, 0.), (1.7976931348623157e308, 0.), (0., 2.)]) aborts vector[] index out of bounds on pristine HEAD. Not a probabilistic repro.
b Root cause explained? Yes. calcGridAttributes validated the derived scales but tested the span only for == 0. 1 / +-inf == +-0.0 is finite, so an infinite span passed validation; contains then computed inf * 0.0 = NaN, NaN compared false against both range guards, static_cast<int>(NaN) gave INT_MIN, and getCellIndex overflowed into a 64-element cells.
c Fix matches root cause? Yes. Validated at the single writer of cell_width/cell_height/x_scale/y_scale, before the scales are derived. Not a symptom guard: a NaN check inside contains would leave x_scale == 0 in the object for every other reader. Clamping, a saturating getCellIndex, and tightening parseRing's mulOverflow were rejected (the last regresses working 1e200 polygons).
d Test intent preserved / new tests added? Yes. 3 existing files extended, 0 assertions removed or weakened, 0 new files. 01940's expectation change (0 to BAD_ARGUMENTS) is justified by measurement: its polygon has an inf vertex, the same query already throws on default settings, and its 0 came from the -inf query point hitting the finiteness guard rather than from the grid. That guard stays covered by 00500_point_in_polygon_nan.sql and 03095_join_filter_push_down_right_stream_filled.sql.
e Both directions demonstrated? Yes. 19-row matrix on two binaries built in the same worktree (BuildID f6598f3d... vs 9bf69336..., each asserted against SELECT lower(buildId()) before measuring). Per file: all three FAIL on HEAD (two by the server dying) and pass with the change, so no new assertion is vacuous.
f Fix is general across code paths? Yes, within the preprocessed-grid path this defect lives in. Carriers verified individually: cells[] (crash site), polygons[] on the complexPolygon arm (reached only via a valid cell), buildGrid's cell_box, PointInMultiPolygonRTree::contains, and its R-tree bulk-build (which tripped a boost Indexable is invalid assertion). The two sibling has_empty_bound sites need no change: one tests corner equality with no division, the other derives the flag from boxes.empty(). The non-constant polygon column path is a different algorithm (on-the-fly ray casting), builds no grid, and cannot reach this out-of-bounds read; its own loss of precision on an unbounded span is pre-existing and out of scope, as the PR description states.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. x and y axis spans; positive, zero, negative, infinite and NaN spans; polygon, multipolygon and polygon-with-hole; LowCardinality point (Nullable is rejected earlier by the signature); Float32 and Float64; empty ring; point polygon; denormal span; huge-but-finite span; small and huge query points. A non-constant polygon column was also measured, and is unchanged by this PR in both directions (see row f).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, or serialized format touched, so no SettingsChangesHistory.cpp entry. Three user-visible changes, each replacing an abort or undefined behavior: previously-aborting empty-ring inputs now return 0; unbounded-span inputs now throw BAD_ARGUMENTS; the 01940 case above now throws. Every currently-working input keeps its answer, pinned by non-regression rows.
i Invariants and contracts preserved? Yes. The invariant "cells and polygons are indexed only via a coordinate derived from a finite, strictly positive cell size" is now established where it is written. has_empty_bound keeps its meaning ("no interior, every point outside"); buildGrid still returns early on it; the throw exits before any partially-initialized scale is published; the preprocessed-polygon cache is left unchanged on a throwing load, so repeats stay deterministic (verified across repeated and interleaved queries). No new state, lock, allocation, or error path.

Session id: cron:clickhouse-impl-slot-6:20260816-174300

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [58f6131]

Summary: ✅


AI Review

Summary

This PR hardens the constant-polygon grid builder in pointInPolygon against unbounded bounding boxes and extends stateless coverage for the reproduced cases. The new calcGridAttributes guard does fix the downstream out-of-bounds access, but the stated +-DBL_MAX fix path is still incomplete because constant-polygon parsing performs an out-of-range Float64 to Int64 conversion before the new BAD_ARGUMENTS check ever runs.

Findings

❌ Blockers

  • [src/Functions/PolygonUtils.h:401] The new unbounded-span rejection happens only after executeImpl -> parseConstPolygon -> parseRing, and parseRing still evaluates static_cast<Int64>(x_data[i]) / static_cast<Int64>(y_data[i]) at src/Functions/pointInPolygon.cpp:721. For the PR's own +-1.7976931348623157e308 repro those casts are already out of range, so the query can still enter undefined behavior before this guard gets a chance to reject it.
    Suggested fix: reject or normalize the raw Float64 coordinates before the integral cast, or replace that mulOverflow heuristic with a check that reasons about the actual downstream arithmetic without relying on out-of-range integer conversion.
Tests
  • ⚠️ The merge-blocking Finish Workflow hook currently reports that no per-arch bugfix-validation job validated the changed functional tests on master. Once the parser-side UB is removed, add or adjust one focused stateless regression so the Bug Fix claim is also proved in the bugfix-validation environment.
Final Verdict

Changes requested: the grid-side fix looks correct, but the constant-polygon parser still has undefined behavior on the same +-DBL_MAX input that this PR claims to make safe.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 10/10 (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 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @rschu1ze, could you review this? pointInPolygon built its lookup grid after checking only that the derived scales were finite, but 1 / +-inf is +-0.0 and passes that check, so a polygon spanning +-DBL_MAX produced a NaN grid coordinate, an INT_MIN cell index, and an out-of-bounds read of cells (an abort in hardened and sanitizer builds, wrong results otherwise); the span itself is now validated where it is computed.

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
}

/// 1 / +-inf is +-0.0, which is finite: the scales below would pass their own check.
if (!isFinite(cell_width) || !isFinite(cell_height))

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.

load still goes through parseConstPolygon before it constructs PointInPolygonWithGrid, so the exact +-DBL_MAX repro from the PR body reaches parseRing first. That code still does static_cast<Int64>(x_data[i]) / static_cast<Int64>(y_data[i]) inside mulOverflow (src/Functions/pointInPolygon.cpp:721), and those conversions are already out of range for +-1.7976931348623157e308.

So this new guard fixes the downstream contains OOB once a Polygon object exists, but it does not make the motivating input well-defined end-to-end: the parser can still enter undefined behavior before BAD_ARGUMENTS is thrown. Can we reject these coordinates before the Int64 cast, or replace that precheck with one that does not rely on out-of-range integral conversion?

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.

All three citations check out: load calls parseConstPolygon before constructing the impl, the static_cast<Int64> at pointInPolygon.cpp:721 is real, and +-DBL_MAX is outside Int64 range, so that conversion is UB. I reproduced the conversion standalone under -fsanitize=undefined.

I am not changing it here, for three measured reasons.

Pre-existing and untouched. This PR's source change is +7/-1 in PolygonUtils.h alone. pointInPolygon.cpp has 0 hunks.

Deliberately ignorelisted since 2021. tests/ubsan_ignorelist.txt:17 carries src:*/Functions/pointInPolygon.cpp under the comment "Some value is outside the range of representable values of type 'long' on user-provided data inside boost::geometry - ignore" (339c12f), wired in at cmake/sanitize.cmake:129,139. There is no live signal either: over 180 days CIDB has 0 rows citing pointInPolygon.cpp next to "runtime error" (control: 970 "runtime error" rows overall) and 0 float-cast-overflow reports anywhere.

The suggested precheck would reject queries that work today. INT64_MAX is 9.22e18, so a cast-range check excludes most of the double range, and polygons above it currently give correct answers. Every coordinate below is out of Int64 range, and these return 1, 0, 1:

SELECT pointInPolygon((1e19, 0.5), [(0., 0.), (2e19, 0.), (2e19, 1.), (0., 1.)]); -- inside
SELECT pointInPolygon((3e19, 0.5), [(0., 0.), (2e19, 0.), (2e19, 1.), (0., 1.)]); -- outside
SELECT pointInPolygon((1e199, 0.5), [(0., 0.), (1e200, 0.), (1e200, 1.), (0., 1.)]);

Rejecting out-of-Int64-range coordinates turns all three into errors, including the inside/outside pair that discriminates correctly today. The cast result is also discarded: only the overflow flag is read, and the vertex stored is the raw Float64 pair.

On the end-to-end point: the motivating input is well-defined in observable behaviour after this change. On the two binaries built from this branch, the repro aborts with vector[] index out of bounds before, and returns Code: 36 ... bounding box is unbounded after. Making that precheck range-correct is a fair separate change, but it moves the accepted coordinate domain and does not belong in a P0 out-of-bounds fix.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 58f6131a5 with master ce6df4653 (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 694.64 MiB 691.62 MiB -3.01 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 58f6131

CI is fully finished on this head and it is clean: 177 check-runs, 160 success / 17 skipped,
0 failed, 0 cancelled, 0 still running. Config Workflow and Finish Workflow both succeeded,
and the praktika report is top-level OK with 0 dropped jobs, so the filtered matrix is a real
run rather than a void one. CIDB has 336859 rows across 162 checks for this commit.

Check / test Reason Owner / fixing PR
Config Workflow / Pre Hooks (20:08:38Z, 20:51:58Z) superseded: can be tested label was not yet applied when the workflow first dispatched not applicable, the same job re-ran green at 21:19:53Z on this identical commit
Finish Workflow / Post Hooks (20:10:18Z, 20:54:34Z) superseded: new_tests_check.py saw the Bugfix validation jobs still undispatched behind the gate above not applicable, the same job re-ran green at 01:38:47Z, with Bugfix validation (functional tests, amd64/aarch64) and (unit tests) all success

Those four CIDB rows are historical, not open. All predate the label being applied; both jobs then
completed success on the same commit_sha, and the praktika report for this head reports 0
dropped jobs at every depth, which is why the run is treated as covered rather than label-gated.

The three regression tests ran on this head with 0 failures:
00500_point_in_polygon_empty_bound 265 executions across 20 jobs, 01700_point_in_polygon_ubsan
265, 01940_point_in_polygon_ubsan 267. All ten Stress test (*) flavours, Upgrade check (amd_release) and the fuzzer jobs are green. Counts come from an aggregate CIDB query over this
commit, not from a tally of the job list.

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

@nihalzp
nihalzp added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 84d3205 Aug 17, 2026
529 of 535 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
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-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants