Repository navigation
Conversation
There was a problem hiding this comment.
Pull request overview
Adds new geospatial aggregate functions to ClickHouse for polygon set operations and convex hull computation, including support for Geometry (Variant) columns, State/Merge combinators, and extensive stateless/performance test coverage.
Changes:
- Registers three new aggregate functions:
groupPolygonUnion,groupPolygonIntersection, andgroupConvexHull. - Implements Boost.Geometry-based aggregation logic plus a shared Geo serde/variant utility header.
- Adds a broad set of stateless correctness/robustness tests, plus performance benchmarks and doc stubs.
Reviewed changes
Copilot reviewed 48 out of 49 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
| src/AggregateFunctions/registerAggregateFunctions.cpp | Wires the new geo aggregate functions into the factory registration path. |
| src/AggregateFunctions/AggregateFunctionGroupPolygonUnion.cpp | Implements polygon union aggregation with chunking, reduction, and serde. |
| src/AggregateFunctions/AggregateFunctionGroupPolygonIntersect.cpp | Implements polygon intersection aggregation with early-empty short-circuit and serde. |
| src/AggregateFunctions/AggregateFunctionGroupConvexHull.cpp | Implements convex hull aggregation over multiple geo input kinds with compression and serde. |
| src/AggregateFunctions/AggregateFunctionGeoUtils.h | Introduces shared helpers for Geometry(Variant) type resolution and polygonal serde/validation utilities. |
| docs/en/sql-reference/aggregate-functions/reference/groupPolygonUnion.md | Adds doc stub for groupPolygonUnion (autogen placeholders). |
| docs/en/sql-reference/aggregate-functions/reference/groupPolygonIntersection.md | Adds doc stub for groupPolygonIntersection (autogen placeholders). |
| docs/en/sql-reference/aggregate-functions/reference/groupConvexHull.md | Adds doc stub for groupConvexHull (autogen placeholders). |
| tests/queries/0_stateless/04027_group_convex_hull.sql | Base correctness tests for groupConvexHull. |
| tests/queries/0_stateless/04028_group_polygon_union.sql | Base correctness tests for groupPolygonUnion. |
| tests/queries/0_stateless/04029_group_polygon_intersect.sql | Base correctness tests for groupPolygonIntersection. |
| tests/queries/0_stateless/04030_group_geo_aggregates_errors.sql | Negative tests for type/arity/NaN/Inf rejection. |
| tests/queries/0_stateless/04031_group_geo_aggregates_state_merge.sql | State/Merge round-trip coverage for the new aggregates. |
| tests/queries/0_stateless/04032_group_geo_aggregates_extended.sql | Extended coverage incl. thresholds and Geometry mixed inputs. |
| tests/queries/0_stateless/04033_group_geo_aggregates_invalid_polygon.sql | Negative tests for invalid polygons and polygonal Geometry values. |
| tests/queries/0_stateless/04033_group_geo_aggregates_invalid_polygon.reference | Empty reference file for the negative-test-only query. |
| tests/queries/0_stateless/04034_group_geo_aggregates_order_invariance.sql | Checks order invariance (direct aggregation) for all three functions. |
| tests/queries/0_stateless/04034_group_geo_aggregates_order_invariance.reference | Expected output for order invariance tests. |
| tests/queries/0_stateless/04035_group_geo_aggregates_merge_shapes.sql | Validates different merge shapes and State/Merge equivalence. |
| tests/queries/0_stateless/04035_group_geo_aggregates_merge_shapes.reference | Expected output for merge shape tests. |
| tests/queries/0_stateless/04036_group_geo_aggregates_topology.sql | Exercises complex topology cases (touching edges/vertices, holes, degenerates). |
| tests/queries/0_stateless/04036_group_geo_aggregates_topology.reference | Expected output for topology tests. |
| tests/queries/0_stateless/04037_group_geo_aggregates_geometry_variants.sql | Mixed Geometry(Variant) scenarios and equivalence checks. |
| tests/queries/0_stateless/04037_group_geo_aggregates_geometry_variants.reference | Expected output for Geometry(Variant) scenario tests. |
| tests/queries/0_stateless/04038_group_geo_aggregates_geometry_variant_errors.sql | Geometry(Variant) error handling incl. NaN/Inf and non-polygonal inputs. |
| tests/queries/0_stateless/04038_group_geo_aggregates_geometry_variant_errors.reference | Expected output for Geometry(Variant) error tests. |
| tests/queries/0_stateless/04039_group_geo_aggregates_merge_thresholds.sql | Tests merge-side reduction threshold paths for union/intersection. |
| tests/queries/0_stateless/04039_group_geo_aggregates_merge_thresholds.reference | Expected output for merge threshold tests. |
| tests/queries/0_stateless/04040_group_geo_aggregates_merge_robustness.sql | Robustness tests for serialize/deserialize and merge tree patterns + stress. |
| tests/queries/0_stateless/04040_group_geo_aggregates_merge_robustness.reference | Expected output for robustness/stress tests. |
| tests/queries/0_stateless/04041_group_geo_aggregates_const_geometry.sql | Covers ColumnConst(Geometry) execution paths. |
| tests/queries/0_stateless/04041_group_geo_aggregates_const_geometry.reference | Expected output for const Geometry tests. |
| tests/queries/0_stateless/04042_group_geo_aggregates_empty_geometry.sql | Defines semantics for empty geometries (union neutral / intersect absorbing). |
| tests/queries/0_stateless/04042_group_geo_aggregates_empty_geometry.reference | Expected output for empty geometry tests. |
| tests/queries/0_stateless/04043_group_geo_aggregates_odd_chunks.sql | Exercises pairwise reduction/merge behavior with odd chunk counts. |
| tests/queries/0_stateless/04043_group_geo_aggregates_odd_chunks.reference | Expected output for odd chunk tests. |
| tests/queries/0_stateless/04044_group_geo_aggregates_geometry_table.sql | Validates behavior on actual Geometry table columns. |
| tests/queries/0_stateless/04044_group_geo_aggregates_geometry_table.reference | Expected output for Geometry table tests. |
| tests/queries/0_stateless/04045_group_geo_aggregates_null_vs_empty.sql | Tests NULL-vs-empty semantics across all three aggregates. |
| tests/queries/0_stateless/04045_group_geo_aggregates_null_vs_empty.reference | Expected output for NULL-vs-empty tests. |
| tests/queries/0_stateless/04046_group_geo_aggregates_malformed_state.sql | Verifies malformed binary state rejection paths. |
| tests/queries/0_stateless/04046_group_geo_aggregates_malformed_state.reference | Expected output for malformed state tests. |
| tests/performance/group_polygon_union.xml | Adds a performance micro-benchmark for polygon union. |
| tests/performance/group_polygon_union_scaling.xml | Adds scaling scenarios for polygon union. |
| tests/performance/group_polygon_intersect.xml | Adds performance scenarios for intersection (overlap + early-empty). |
| tests/performance/group_polygon_intersect_scenarios.xml | Adds scaling scenarios for intersection. |
| tests/performance/group_convex_hull.xml | Adds performance scenarios for convex hull (dense + heavy). |
| tests/performance/group_convex_hull_scaling.xml | Adds scaling scenarios for convex hull. |
|
Workflow [PR], commit [26f9bfb] Summary: ❌
AI ReviewSummaryAdds Findings
Tests
Final Verdict |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
|
The The bug was reverted by PR #102247 (merged at ~14:48 UTC). All nessie/lakekeeper test failures between these two merges are unrelated to this PR. |
|
The flaky check failure is fixed in #102148, let's update the branch. |
|
Acknowledged. I'm investigating why the Iceberg configuration fails instead of producing an empty report when a PR only adds or changes performance tests. No fix is in progress yet, so I'll follow up here with a PR (or my findings) shortly. |
|
Fix: #129874. Here the six Iceberg jobs fail for a reason the report failure hid: the Iceberg rewrite refuses all 20 new tests, because |
… boxes The phase-5 shortcut treated components whose bounding boxes only touch as having disjoint interiors. Boost.Geometry compares coordinates with a tolerance, so boundaries a few ULPs apart can still overlap: such input passed validation although boost::geometry::is_valid rejects it, and groupPolygonIntersection then silently dropped a component (area 3 instead of an error). Skip relate only when the boxes are separated by more than geoSeparationMargin, as the other shortcuts already do. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the hull A point strictly inside the triangle (left, bottom, right) or (right, top, left) cannot be a hull vertex. The exact predicate decides this and a degenerate triangle keeps the point, so the result and the serialized state are unchanged. Also sort with ipnsort and check the exact-zero cases of GeoHullSide only after the floating-point filter. groupConvexHull over 20M points (max_threads = 1, same result hash): gaussian 3.31 s -> 1.40 s, uniform square 2.91 s -> 1.50 s, grid 1.85 s -> 0.85 s. All-vertex and 1M-group inputs are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rectangle-envelope union and the concatenation of margin-separated, already validated operands cannot produce invalid geometry, yet every tier merge re-ran the full multipolygon validation on them. Keep the point budget check only. groupPolygonUnion of 40k shuffled disjoint polygons (max_threads = 1, same result hash): squares 1.39 s -> 0.66 s, triangles 1.13 s -> 0.58 s. Overlapping input is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
groupConvexHull is order-independent, so RemoveRedundantSorting removed the subquery ORDER BY that 05509, 05220 and 05221 use to vary the input order. Disable it there. Iceberg has no type for the geometry columns, so mark the new performance tests with iceberg="0". Co-Authored-By: Claude Opus 5.5 <[email protected]>
…operands The disjoint shortcut only compared global envelopes and probed component gaps with an R-tree for 64+ components. In shuffled input, early tier merges combine single polygons or small sets whose global envelopes overlap although no components do, so they went through boost::geometry::union_ and full result validation. Compare every pair of component envelopes (at most 32 * 32 checks) with the same margin instead, and apply the global check to single polygons too. groupPolygonUnion of 40k shuffled disjoint polygons (max_threads = 1, same result hash): squares 0.70 s -> 0.38 s, triangles 0.61 s -> 0.37 s. Overlapping input is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y result Co-Authored-By: Claude Opus 5.5 <[email protected]>
The functions have not been released, so no reader can meet the earlier formats from the development of this change: groupConvexHull states of version 2 and groupPolygonIntersection states with several chunks. Reject them instead of keeping compatibility code, and make the tests that built such states use the current format, so that they check the intended guard rather than the version byte. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With many groups, every finalization grew the lower and upper chains one push at a time. Reserve up to 256 points for each, so a small group needs one allocation per chain. GROUP BY into 1M groups of 10 points: 2.79 s -> 2.62 s, same result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Replace 20 files with 124 queries, many of them duplicates or a few milliseconds long, with one file per function and 24 queries of 0.1-1 s each. Fill the tables with max_threads = 1: a parallel INSERT SELECT reorders blocks, and the order matters for the union and intersection paths. Drop the early-empty query: its rows are skipped in microseconds, so it cannot be timed stably; stateless tests cover it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
groupPolygonIntersection of rows with a common exterior and holes that neither the disjoint nor the monotone path accepts overlaid and re-validated the whole growing state for every row, which is quadratic in the number of rows. Their intersection is the exterior minus the union of all holes, and it is never empty, because a hole touches the exterior at most at points. Once the state has 256 points, accumulate the holes in size tiers like groupPolygonUnion and compute the difference once, when the state is finalized, serialized, or meets a row with another exterior. Smaller states keep the eager overlay and its exact output layout. Shared exterior with overlapping holes (max_threads = 1, equal result geometry): 4000 octagons 19.5 s -> 0.25 s, 3000 random triangles 99 s -> 0.54 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…holes cd387fa computed exterior minus the union of all holes with one Boost.Geometry difference. Review found three inputs where that differs from intersecting the rows: - holes of one row that Boost accepts in a polygon but rejects as a multipolygon (a 1-ULP gap along a shared edge): the union dropped a hole, area 99 instead of 97; - a hole touching the exterior inside an edge at a non-representable position: the difference returned the bare exterior, area 4096 instead of 3861; - holes of different rows touching at points around an island: the difference kept them as touching holes and validation failed with "disconnected interior". All three come from subtracting point-touching geometry from the exterior. Keep the idea, since rows with a common exterior can never intersect to empty, but intersect the rows themselves in size tiers: the same polygon intersections as the eager path, only associated differently. Results now match the eager path on all three cases, which 05511 checks, and on six differential datasets. Shared exterior with overlapping holes (max_threads = 1): 4000 octagons 19.4 s -> 0.40 s, 3000 random triangles 98.7 s -> 0.71 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
For operands with 64 or more components, one contact between them (squares touching at corners, clusters of overlapping polygons) sent every component through boost::geometry::union_, whose cost grows with all of them. Collect the components within the margin of the other operand with the existing R-tree, overlay only those, validate the overlay together with the untouched components near it, and append the rest unchanged. If that validation fails, fall back to the full overlay. groupPolygonUnion (max_threads = 1, same areas and component counts): 4096 squares touching at corners 1.19 s -> 0.31 s, 16k overlapping pairs in shuffled order 6.78 s -> 1.00 s. Disjoint and overlapping-strip inputs are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Boost.Geometry promotes only default cpp_bin_float numbers to themselves and maps any other Boost.Multiprecision number to double. Where WideCoordinate is cpp_bin_float_quad (macOS ARM64, PPC64LE), segment_ratio then overflowed double for coordinates above about 1e154 and 1-7% of non-axis-aligned overlays came out invalid. Specialize the trait and assert it, so builds on every target check it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
groupConvexHull: the result and the state do not depend on input or merge order; degenerate hulls are padded to four points; every coordinate must be finite; an unnamed Array(Tuple(Float64, Float64)) is accepted as a Ring. groupPolygonUnion and groupPolygonIntersection: unnamed arrays are ambiguous and need a geometry type. Correction: a153b91 says it also sorts with ipnsort, but std::sort stayed. On x86 ipnsort with a branchless comparator made uniform inputs 9% faster and inputs whose points are all hull vertices 16% slower, so std::sort is kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword comments that described checks the tests no longer make (watermark growth, union thresholds, merge orders) and replace em dashes; make the mixed Geometry hull test actually mix a polygon with points. In the intersection perf test, sort only the needed columns inside the measured queries and double the hole rows so that the shortest query stays above 0.1 s on faster hosts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
clang-tidy (cppcoreguidelines-pro-type-member-init) rejects the uninitialized std::array of boxes added in 94c0738. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Update: correctness fixes and performance work since 02d8f6fThis round came out of a full review of the PR (performance plus differential testing against plain Boost.Geometry). All changes are on the branch as separate commits; the head is now 37eac52. Correctness
PerformanceMorning head 02d8f6f against 37eac52, same x86 machine and build flags,
Unchanged within noise: overlapping union strip, rectangle intersections, and hulls whose points are all vertices. What changed:
Results are geometrically identical; where the raw output differs, only the vertex or polygon order changed, which the documentation already leaves unspecified. Tests and docs
Not addressed
|
Since ClickHouse#128261 a PR that changes only performance tests runs the Iceberg jobs on the changed tests only, so often no query is measured on both servers (the Iceberg rewrite refuses every changed test, only partial queries, or a skipped test). Then analyze_queries crashed: query-run-metric-names.tsv is empty, so its scalar subquery throws INCORRECT_RESULT_OF_SCALAR_SUBQUERY, and the per-query loop never creates analyze/commands.txt and analyze/query-metric-stats.tsv. The denorm file was never written, report() stopped at its first read, before it wrote all-query-metrics.tsv and the other comparison files, the check said "Errors while building the report." instead of the per-test errors, and "Insert historical data" failed with FileNotFoundError. Create the two files before the loop, the same way confirm_changes already does for its own files, and take any(n) from the names file: an aggregate without GROUP BY returns one row, [] for an empty file and the only row otherwise. The Total ratio of a report with no compared query is the neutral 1x instead of nan, as for a test whose changes are all demoted. A run with compared queries writes the same files as before. Validated by replaying compare.sh (stage=analyze_queries) in the performance-comparison image on the CI artifacts of ClickHouse#101273, ClickHouse#113575 and ClickHouse#126132 (before: the CI errors; after: an empty errors.log, and "20 errors" with the Iceberg rewrite hint for ClickHouse#101273), and on a MergeTree job of ClickHouse#101273 (same analysis and report files). Related: ClickHouse#101273 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in `docs/_migration/slug-map.csv` by keeping its deletion from master (the `docs/_migration` folder was removed in master). Co-Authored-By: Claude Opus 5.5 <[email protected]>
AI review of a later commit does not approve the PR, see the AI Review comment.
| { | ||
| for (const auto & chunk : other.shared_rows->chunks) | ||
| { | ||
| if (!shared_rows->insert(chunk, function_name)) |
There was a problem hiding this comment.
[Major] Enforce the point limit after consuming the complete merged state
SharedExteriorRows::insert calls reduceAll and enforces the point limit on every iteration here, although a later RHS tier can simplify geometry introduced by an earlier one. Thus two valid partial states can fail to merge even when their complete intersection fits the limit, while serializing/materializing the RHS first makes the same merge succeed.
I reproduced this with the production state structs and exact Boost revision, lowering only the point cap to 4,000: a 3,515-point LHS and a 1,015-point RHS both use shared_rows; the RHS contains a complex sawtooth hole followed by a small rectangle covering that hole. The live merge throws on the first RHS tier. Materializing the RHS reduces it to 10 points, and the equivalent merge succeeds with 3,510 points. The same construction scales to roughly 9M and 2M vertices at the production 10M cap; that full-sized case was traced rather than executed.
Defer rejection until all RHS tiers have participated, then reduce and check the complete update, as the adjacent monotone merge already does. Please cover live merging versus merging the same RHS after a binary round trip.
| if (!representable) | ||
| break; | ||
| } | ||
| if (representable) |
There was a problem hiding this comment.
[Major] Require cross-component validity before selecting rectangle clipping
The per-polygon is_valid check does not establish that the assembled MultiPolygon is valid under Boost's tolerances. This branch can select a candidate that the caller rejects, even though the general overlay returns an accepted result for the same valid inputs.
Reproduced on this PR's binary with:
WITH
readWKTMultiPolygon('MULTIPOLYGON(((3 2.0000000000000004,3 6.0000000000000027,5.9999999999999973 6.0000000000000027,5.9999999999999973 2.0000000000000004,3 2.0000000000000004)),((1.0000000000000004 2,1.0000000000000004 4.0000000000000036,2.9999999999999996 4.0000000000000036,2.9999999999999996 2,1.0000000000000004 2)))') AS a,
readWKTMultiPolygon('MULTIPOLYGON(((2 3,2 3.000000000000001,4 3.000000000000001,4 3,2 3)))') AS b
SELECT groupPolygonIntersection(p)
FROM (SELECT arrayJoin([a, b]) AS p)
SETTINGS max_threads = 1;Each input succeeds as a one-row groupPolygonIntersection, and the result of polygonsIntersectionCartesian(a, b) also succeeds when validated through a one-row aggregate. Aggregating the two input rows instead throws BAD_ARGUMENTS with produced invalid polygonal geometry during reduction / invalid self-intersections near (3, 3): clipping aligns the almost adjacent components into a relationship that the validator rejects.
Require a conservative cross-component certificate before selecting this kernel; when it cannot be established, use the general overlay. Please add this valid-input regression alongside the rectangle intersection coverage.
Functions for geospatial aggregation #80186
Add three SQL aggregate functions for polygon set operations and convex hull computation:
groupPolygonUnion— union of polygonal geometries in a groupgroupPolygonIntersection— intersection of polygonal geometries in a groupgroupConvexHull— convex hull of grouped point, linear, and polygonal geometriesThe functions support typed Geo inputs and
Geometryvariant columns,State/Mergecombinators, binary aggregate-state serialization with writer/reader invariant checks and corruption guards, and well-defined empty-geometry semantics.Closes: #80186
Changelog category:
Changelog entry
Added geospatial aggregate functions
groupPolygonUnion,groupPolygonIntersection, andgroupConvexHull.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/101273]