Skip to content

Fix wrong results of pointInPolygon for ordinary constant polygons - #123767

Merged
nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-point-in-polygon-grid-cells
Oct 8, 2026
Merged

nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-point-in-polygon-grid-cells

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123740

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 pointInPolygon with a constant polygon returning wrong results for some points of ordinary polygons, for example 0 for the point (0.76, 0.01) inside the polygon [(1, 0), (0, 1), (-1, 0), (0, -1)], or 1 for a point inside a small hole. The results now match those for a non-constant polygon.

Description

On 26.8.10.6 (also 26.3 and master), SELECT pointInPolygon((0.76, 0.01), [(1., 0.), (0., 1.), (-1., 0.), (0., -1.)]) returns 0 for a point inside the polygon; with materialize it returns 1. With the hole [(3.1, 3.1), (3.3, 3.1), (3.3, 3.3), (3.1, 3.3)] in the square 0..8, (3.2, 3.2) is reported inside. 25.3 answers the first query correctly.

Root cause. For a constant polygon, PointInPolygonWithGrid precomputes an 8x8 grid and classified each cell from boost::geometry::intersection(polygon, cell). That overlay is wrong at degenerate positions (a vertex on a cell corner, or within a few ulps of a grid line); since the boost 1.90 update this also happens for ordinary polygons. A hole inside one cell was ignored (no return after addComplexPolygonCell), and complex cells used boost::geometry::within, whose collinearity tolerance misplaces points near very short edges.

Change. Each cell is now classified from the polygon edges that enter it, counted with an exact orientation predicate (side_robust): none means inside or outside by the cell centre, one gives that edge's half-plane, two give the AND or OR of their half-planes (by the turn at their shared vertex, or by which side of one edge the other lies), three or more store every ring clipped to the cell. Complex cells and cell centres use the crossing number test of the non-constant path. Polygons with coordinates outside [2^-300, 2^300], where the predicate could overflow or underflow, use complex cells. The grid builds over 10x faster and complex cells answer 2-7x faster.

Validation. The new test compares constant and materialize polygons at such positions and fails on master. A differential check on 6711 degenerate polygons (735K points, exact rational reference) finds no wrong point farther than 1e-15 from an edge; master has 2962. Two references change: a boundary point, and invalid polygons under validate_polygons = 0.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1797-master (included in 26.10 and later)

groeneai and others added 2 commits October 3, 2026 19:40
`pointInPolygon` with a constant polygon builds an 8x8 grid over the bounding
box and classified each cell from `boost::geometry::intersection(polygon, cell)`.
That overlay is not robust at degenerate positions (a vertex on a cell corner,
a vertex within a few ulps of a grid line): it returns the whole cell, the whole
polygon or a clip with a missing edge, and the cell is then classified as fully
inside, fully outside or with the wrong half-planes. Since contrib/boost moved
from 1.83 to 1.90 this hits ordinary polygons, e.g. the unit diamond returns 0
for (0.76, 0.01). Independently, a hole inside a single cell was ignored:
`addComplexPolygonCell` was not followed by a `return`, so the cell was then
overwritten by the centre test.

Each cell is now classified from the polygon edges that enter the open cell
(Liang-Barsky): none -> the centre test; one -> the half-plane of that edge;
two -> the AND or OR of their half-planes, decided by the turn at the shared
vertex, or for two separate chords by the side of the second chord; three or
more -> a complex cell whose polygon is every ring clipped by the slightly
expanded cell with Sutherland-Hodgman, which keeps the winding number of every
point inside the cell. The grid no longer uses boost overlay and builds about
10x faster; query time is unchanged.

Two existing references change: 00500_point_in_polygon_empty_bound (the point
lies on the polygon boundary, where the result is unspecified) and
04897_point_in_polygon_primary_key_invalid_polygon (counts for invalid polygons
under `validate_polygons = 0`, documented as possibly incorrect; the primary key
and full scan counts still agree).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tive to the edge

An edge with an endpoint strictly inside a grid cell now always counts as entering
that cell, so both edges at a vertex inside the cell are seen and the cell is
classified by the turn at that vertex rather than by one edge's extended line.

A half-plane is stored as the edge origin and direction and evaluated as
`dx * (y - y0) - dy * (x - x0)`, so its sign does not depend on how far the
polygon is from the origin.

The test covers a polygon vertex at a quarter of the bounding box and a small
triangle near 1e9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

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

Pre-publication review by an independent model (engine: codex) plus my own review; 5 findings over 2 rounds.

# Sev Finding Verdict Evidence / action
1 ❌ A vertex a few ulps inside a grid cell was seen by only one of its two edges, so that edge's line misclassified part of the cell (PolygonUtils.h, crossesBox) AGREE, fixed @ 6540824 an edge with an endpoint strictly inside the cell now always counts; 2 test lines, red without the change
2 ⚠️ Half-planes evaluated in absolute coordinates lose the sign near an edge of a polygon far from the origin (HalfPlane) AGREE, fixed @ 6540824 evaluated relative to the edge start; 1 test line, red without the change
3 ⚠️ Build-time and query-time claims need measurements DISAGREE out-of-tree benchmark with both algorithms in one -O2 binary on the final code (build about 10x faster, queries within 5% except the holed case master answers wrongly), plus real-binary perf tests 0.96-1.05
4 💡 Stale comment on the centre-test addCell AGREE, fixed @ 6540824 comment updated
5 💡 The existing CellType comments say "polyline of two sections", while two separate chords also map to the AND type AGREE, not changed lines outside this diff; contains reads the types only as AND / OR

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20261003-212600

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test 05322_point_in_polygon_const_matches_non_const fails on master on every run (no randomness): 9 point checks and 5 lattice counts of constant-vs-materialize disagreements (132, 66, 55, 331, 400).
b Root cause explained? Yes. The constant-polygon grid classified each cell from boost::geometry::intersection(polygon, cell), which is wrong at degenerate and near-degenerate positions (whole cell, whole polygon or a clip missing an edge); a hole inside one cell was also dropped because addComplexPolygonCell was not followed by a return.
c Fix matches root cause? Yes. Cells are classified from the polygon's own edges that enter them (0, 1, 2 or 3+ edges), and complex cells store an exact Sutherland-Hodgman clip, so boost overlay is no longer used by the grid.
d Test intent preserved / new tests added? Yes. New 20-query test; two existing references change only for a boundary point (00500_point_in_polygon_empty_bound) and for invalid polygons under validate_polygons = 0 (04897, whose primary key vs full scan invariants still hold).
e Both directions demonstrated? Yes. Master: 14 of 20 lines wrong; fix: all match. Mutations of the turn, separate-chord, hole and centre branches each fail their lines; the three control lines pass on master and are failed by the mutations. Removing the inside-vertex count fails the two notch lines, and absolute-coordinate half-planes fail the line near 1e9.
f Fix is general across code paths? Yes. One classifier for every cell; polygon, multipolygon (one grid per polygon) and multi-argument hole forms are covered by test lines. The primary key atom and polygon dictionaries do not use this grid (dictionaries checked: correct).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Holes (including empty and degenerate ones), near-degenerate sin/cos vertices, invalid polygons, very large x coordinates and boundary points were checked; 158 existing constant calls from 29 tests give the same answers. Coordinates are cast to Float64 before the grid, so type wrappers do not reach it.
h Backward compatible? (maintainer-approved exception only) Yes. No settings, formats or stored state change; only wrong results and documented-unspecified ones (boundary points, invalid polygons) differ.
i Invariants and contracts preserved? Yes. Each cell's predicate equals point-in-polygon for every non-boundary point of the cell; the centre test is used only when no edge enters the cell; all loops are bounded by ring sizes; contains and getAllocatedBytes are unchanged; corrected rings are required, as before.

Session id: cron:clickhouse-impl-self-slot-57:20261003-204100

@groeneai
groeneai requested review from nihalzp and scanhex12 October 3, 2026 21:56
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5748f68]

Summary: ✅


AI Review

Summary

This PR replaces the constant-polygon grid classification in pointInPolygon with edge-based cell classification, switches complex/empty-cell evaluation to the same crossing-number test used by the non-constant path, and adds focused regressions for the degenerate cases called out in prior review. I reviewed the current diff, the prior review discussion, and the updated code paths in src/Functions/PolygonUtils.h; I do not see a remaining correctness issue in the changed logic that warrants a new inline finding.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 5748f68.

Metric Baseline Current Δ
Lines 88.30% 88.20% -0.10%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 145/146 (99.32%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). labels Oct 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5748f68e1 with master 54ff83b1b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 321b9ccdd; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

4 object files changed (-1.81 MiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/pointInPolygon.cpp.o 5.98 MiB 4.18 MiB -1.81 MiB (-30.23%)

719 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

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

Job report

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6540824

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
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails with relocation R_X86_64_PC32 out of range; the same job is red on master and on 166 PRs in the last 24h #123738 (external, merged 2026-10-04 01:14Z). This workflow was dispatched at 21:55Z, before that merge, so the fix is not in the tree that ran; a master merge to pick it up follows
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04316_reader_executor_basic not from this PR: the test's single-server count (0 instead of 1) does not hold when parallel replicas split the read #123709 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04819_dynamic_aggregate_function_state_version not from this PR: the test's first client block exits with code 1 under parallel replicas, the Native binary-type mismatch between a replica and the initiator; 42 PRs in 24h #123649 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04266_text_index_tokens_cardinality_order not from this PR: the replicas' Reading tokens log lines reach the initiator and land in the output; 24 PRs in 24h #123688 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05257_sql_security_view_sealed not from this PR: a replica cannot run the SQL SECURITY DEFINER view's read as the definer, so the row policy check fails with ACCESS_DENIED; 88 PRs in 24h #123729 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant not from this PR: under a Replicated database the replicated CREATE VIEW stores the nested WITH alias qualified with the database, so the view reads the same-named table (view 10 instead of 100); 180 PRs in 24h #123790 (external, open)
Mergeable Check, PR rollups, red only because of the rows above #123738, #123709, #123649, #123688, #123729, #123790

None of these touches pointInPolygon, and 05322_point_in_polygon_const_matches_non_const passed. The three arm_binary lanes above come from #122853, which #123789 reverted on master at 00:14Z; #123790 re-lands them. All 157 checks completed and CH Inc sync passed; CIDB has no other FAIL or ERROR on this head.

Session id: cron:our-pr-ci-monitor:20261004-013156

@nihalzp nihalzp self-assigned this Oct 4, 2026

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

There are few edge cases that produce wrong result:

1

The polygon's lowest vertex (0.24999999999999994, 0) lies on the bottom border of the bounding box, two doubles left of the grid line x = 0.25. The point is the centre of grid cell [0.125, 0.25] × [0, 0.125], outside the polygon. Both edges at that vertex cross this cell over a piece only a few ulps long, and rounding in the midpoint test of crossesBox counts only one of them. The cell becomes singleLine, and that one edge's half-plane marks the whole cell as inside.

SELECT pointInPolygon((0.1875, 0.0625), [(0.24999999999999994, 0.0), (1.0, 0.3), (1.0, 1.0), (0.0, 1.0), (0.0, 0.95), (0.5, 0.9)]);
  • PR: 1
  • master: 0
  • expected: 0

2

A star polygon on a 1/32 lattice with coordinates nudged by up to three doubles, which turns two of them into subnormals (1.5e-323, -5e-324). The vertex (0.25000000000000006, -5e-324) lies on the bottom border, one double left of the grid line x = 0.2500000000000001. The point is the centre of the grid cell to the left of that vertex, outside the polygon. Same cause as case 1: crossesBox counts only one of the vertex's two edges, and the singleLine cell is marked inside.

SELECT pointInPolygon((0.18750000000000008, 0.0625), [(0.21874999999999997, 0.49999999999999994), (1.5e-323, 0.40625), (0.4062499999999999, 0.43749999999999994), (0.3125, 0.15624999999999997), (0.25000000000000006, -5e-324), (0.43749999999999983, 0.031249999999999993), (0.4687499999999999, 0.1875), (0.6874999999999999, 0.28125), (0.7812500000000002, 0.28125000000000017), (0.6562500000000003, 0.46875000000000017), (0.7187499999999998, 0.5000000000000003), (0.71875, 0.5937499999999999), (1.0000000000000004, 0.7187499999999998), (0.84375, 0.6562500000000001), (0.8124999999999999, 0.8749999999999998), (0.59375, 0.6562499999999999), (0.5312500000000002, 0.5624999999999998), (0.5312499999999999, 0.6249999999999997), (0.5, 0.9687500000000002), (0.40625000000000017, 1.0), (0.34375000000000017, 0.9062499999999999), (0.2812500000000001, 0.8124999999999998), (0.21874999999999994, 0.8124999999999997), (0.18749999999999992, 0.6874999999999998)]);
  • PR: 1
  • master: 0
  • expected: 0

3

A pentagon with vertices on a 1/16 lattice, nudged by up to four doubles. Its lowest vertex (0.24999999999999994, 0) sits exactly as in case 1, and the point is again the centre of cell [0.125, 0.25] × [0, 0.125], outside the polygon. Same cause as case 1: of the two edges at that vertex, crossesBox counts only the one going to (1, 0.5625), and its half-plane marks the whole cell as inside.

SELECT pointInPolygon((0.1875, 0.0625), [(0.4375000000000002, 0.4999999999999999), (0.24999999999999994, 0.0), (1.0, 0.5625), (0.5624999999999997, 1.0), (0.0, 0.5625000000000002)]);
  • PR: 1
  • master: 0
  • expected: 0

4

A hexagon with vertices on a 1/16 lattice, nudged by up to four doubles. Its leftmost vertex (0, 0.7500000000000001) lies on the left border, one double above the grid line y = 0.75. The point is the centre of cell [0, 0.125] × [0.75, 0.875], whose bottom-left corner touches that vertex; it is outside the polygon. Same cause as case 1 with x and y swapped: crossesBox counts only one of the vertex's two edges, so the cell becomes singleLine and is marked inside.

SELECT pointInPolygon((0.0625, 0.8125), [(0.3124999999999998, 0.0), (0.49999999999999994, 0.31249999999999994), (1.0, 0.7499999999999999), (0.6250000000000004, 1.0), (0.5, 0.6874999999999997), (0.0, 0.7500000000000001)]);
  • PR: 1
  • master: 0
  • expected: 0

5

A square about 1e-6 across at (0.5, -0.25) with two small holes. The point lies about 1e-8 below the bottom edge of the triangular hole, an edge only about 1.6e-8 long, so the point is inside the polygon. The hole makes this a complex cell, answered by boost::geometry::within. Boost's collinearity tolerance places the point on the hole's edge, even on the whole, unclipped polygon, and within returns 0 for boundary points. master's complex cells use the same call: it answers this point correctly, but answers 13 of 400 test points in this cell wrongly.

SELECT pointInPolygon((0.5000007707394368, -0.24999994741116524), [[(0.5, -0.25), (0.500001, -0.25), (0.500001, -0.249999), (0.5, -0.249999)], [(0.500000125, -0.24999975), (0.50000025, -0.24999975), (0.50000025, -0.249999625), (0.500000125, -0.249999625)], [(0.500000765625, -0.2499999375), (0.50000078125, -0.2499999375), (0.5000007734375, -0.249999875)]]);
  • PR: 0
  • master: 1
  • expected: 1

6

A 23-vertex polygon about 1e-6 across at (0.5, -0.25), and a point inside it. Its grid cell is a complex cell. boost::geometry::within gives the correct answer on the whole polygon, but on the polygon clipped to the cell, which contains a spike, boost places the point on the boundary and within returns 0. master gets this point wrong too.

SELECT pointInPolygon((0.5000003894894368, -0.24999925366116524), [(0.5, -0.2499995625), (0.500000375, -0.2499995625), (0.500000265625, -0.249999703125), (0.5000004375, -0.249999828125), (0.5000005, -0.2499995625), (0.500000546875, -0.25), (0.500000609375, -0.24999971875), (0.500000671875, -0.24999971875), (0.500001, -0.24999965625), (0.500000796875, -0.2499995625), (0.500000703125, -0.24999953125), (0.5000008125, -0.24999953125), (0.50000075, -0.24999925), (0.500000671875, -0.249999078125), (0.500000515625, -0.24999921875), (0.5000005, -0.249999375), (0.50000046875, -0.24999934375), (0.50000028125, -0.249999), (0.500000296875, -0.249999109375), (0.50000040625, -0.24999934375), (0.5000003125, -0.249999203125), (0.50000009375, -0.249999234375), (0.500000046875, -0.249999421875)]);
  • PR: 0
  • master: 0
  • expected: 1

7

A square about 1e-6 across at (0.5, -0.25) with two small holes. The point lies about 4e-9 to the right of the triangular hole, inside the polygon. It falls in a complex cell, and boost's within places it on the hole's edge, even on the whole polygon, so it returns 0. master gets this point wrong too.

SELECT pointInPolygon((0.5000000832394368, -0.24999940366116524), [[(0.5, -0.25), (0.500001, -0.25), (0.500001, -0.249999), (0.5, -0.249999)], [(0.5000000526357758, -0.24999944017885178), (0.5000000945093698, -0.24999944017885178), (0.5000000735725728, -0.24999939154485615)], [(0.5000001495231287, -0.24999934829611353), (0.5000002028428762, -0.24999934829611353), (0.5000002028428762, -0.24999930877053325), (0.5000001495231287, -0.24999930877053325)]]);
  • PR: 0
  • master: 0
  • expected: 1

8

A comb-shaped polygon whose boundary along y = 0.1875 has two extra collinear vertices only 1e-12 apart, which form an edge 1e-12 long. The point is 1e-6 directly below that short edge, inside the polygon. It falls in a complex cell, and boost's within places it on the short edge, even on the whole polygon, so it returns 0. master gets this point wrong too.

SELECT pointInPolygon((0.654267174011323, 0.187499), [(0.0, 0.0), (1.0, 0.0), (1.0, 0.875), (0.9375, 0.875), (0.9375, 0.5625), (0.6875, 0.5625), (0.6875, 0.1875), (0.6542671740120364, 0.1875), (0.6542671740110364, 0.1875), (0.5, 0.1875), (0.5, 0.6875), (0.125, 0.6875), (0.125, 1.0), (0.0625, 1.0), (0.0625, 0.875), (0.0, 0.875)]);
  • PR: 0
  • master: 0
  • expected: 1

9

A unit square with a slanted slot, about 9e-16 wide, cut from the top edge down to y = 0.3. The point is 0.001 directly below the slot's bottom edge, which is also only about 9e-16 long, so it is inside the polygon. It falls in a complex cell, and boost's within places it on that tiny edge, even on the whole polygon, so it returns 0. master answers this point correctly, but gave similar wrong answers for wider slots in the same tests.

SELECT pointInPolygon((0.60916694932799, 0.299), [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.32605962407053535, 1.0), (0.6091669493279903, 0.3), (0.6091669493279894, 0.3), (0.32605962407053446, 1.0), (0.0, 1.0)]);
  • PR: 0
  • master: 1
  • expected: 1

…on grid

Review of ClickHouse#123767 found constant polygons whose grid cells were still
classified wrongly:

- A vertex on the cell border a few doubles from a grid line: both of its
  edges enter the cell over an ulp-sized piece, and the Liang-Barsky
  midpoint test counted only one of them, so the cell became `singleLine`
  with the wrong half-plane. The census of edges entering a cell is now
  exact: a separating-axis test with the exact orientation predicate of
  boost (`side_robust`, Shewchuk's adaptive arithmetic). The turn and the
  strip side for two crossing edges use the same predicate. The predicate
  is exact only without overflow and underflow of products, so polygons
  with nonzero coordinates outside [2^-300, 2^300] fall back to complex
  cells for every cell an edge's bounding box overlaps.
- Complex cells and the centre test used `boost::geometry::within`, whose
  collinearity tolerance puts points far from a tiny edge (1e-8 from a
  1.6e-8 hole edge, 0.001 from a 9e-16 slot edge) on the boundary. They now
  use the crossing number test of the non-constant path.

Grid build is faster again and complex cells answer 2-7x faster
(out-of-tree -O2 port: geo10k 1375 -> 247 ms per 2M points).

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, all nine reproduced. Fixed in 5748f68:

  • Cases 1-4: the edges entering a cell are now counted exactly. An edge enters the open cell if its bounding box overlaps the cell and its line strictly separates two cell corners, decided with boost's exact orientation predicate side_robust (Shewchuk's adaptive arithmetic) instead of the rounded Liang-Barsky midpoint. The turn at a shared vertex and the side of one edge relative to the other use the same predicate. It is exact only while products of coordinate differences neither overflow nor underflow, so a polygon with a nonzero coordinate outside [2^-300, 2^300] uses complex cells wherever an edge's bounding box overlaps the cell; case 2, with its subnormal coordinates, takes that path.
  • Cases 5-9: complex cells and the centre test of empty cells no longer use boost::geometry::within. They use the crossing number test of the non-constant path, on the clipped rings.

The nine queries are in 05322. A differential check of constant vs materialize on 6711 random polygons of these shapes (lattice vertices nudged by up to four doubles, some subnormal; vertices on the bounding box a few doubles from a grid line; tiny squares with holes; collinear vertices 1e-15 to 1e-9 apart; slots 3e-16 to 1e-6 wide), 735K points, each disagreement checked with exact rational arithmetic, finds no wrong answer farther than 1e-15 from an edge (master: 2962, previous head: 1920). On the remaining near-edge points the non-constant path is wrong about as often. Grid build got faster and complex cells answer 2-7x faster (-O2 copy of the class, 2M queries on a 10k-vertex polygon: 1375 to 247 ms).

@groeneai
groeneai requested a review from nihalzp October 7, 2026 09:22
@nihalzp
nihalzp added this pull request to the merge queue Oct 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Oct 7, 2026
@nihalzp
nihalzp added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit 563ba21 Oct 8, 2026
152 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 8, 2026
After ClickHouse#123767 both point-in-polygon algorithms and the primary key
analysis agree with the unscaled result for valid polygons scaled by
powers of two up to 2^512 (about 1.3e154), so 1e100 was more
conservative than needed. 1e150 keeps a margin below that.

The 05320 polygon huge in both axes moves from the rejected lines to the
evaluated ones, at 1e150.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to fastio/ClickHouse that referenced this pull request Oct 10, 2026
`clipRing` copies the ring into `points` and runs four clip passes, each
ending with `points.swap(clipped)`. After the fourth swap `points` owns the
original copy again, so every complex grid cell of a cached
`PointInPolygonWithGrid` kept a buffer with the capacity of the whole ring.
A 100k-vertex polygon took 46.4 MB of the polygon cache instead of 3.3 MB,
and a polygon over ~550k vertices no longer fit the default 256 MiB cache,
so it was rebuilt for every block.

Shrink the returned ring. The cache entry is back to the size of 26.8/26.9
(3,252,640 bytes for the 100k-vertex circle). The regression came from
ClickHouse#123767 and is not in a release.

Closes ClickHouse#124567

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

can be tested Allows running workflows for external contributors comp-geo Geospatial functions and related libs (e.g., H3, S2, geo distance). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

3 participants