Skip to content

Add geo aggregate functions #80186 - #101273

Open
zhemalb wants to merge 117 commits into
ClickHouse:masterfrom
zhemalb:geo-aggregate-functions-80186
Open

zhemalb wants to merge 117 commits into
ClickHouse:masterfrom
zhemalb:geo-aggregate-functions-80186

Conversation

@zhemalb

@zhemalb zhemalb commented Mar 30, 2026 •

Copy link
Copy Markdown

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 group
  • groupPolygonIntersection — intersection of polygonal geometries in a group
  • groupConvexHull — convex hull of grouped point, linear, and polygonal geometries

The functions support typed Geo inputs and Geometry variant columns, State / Merge combinators, binary aggregate-state serialization with writer/reader invariant checks and corruption guards, and well-defined empty-geometry semantics.

Closes: #80186

Changelog category:

  • New Feature

Changelog entry

Added geospatial aggregate functions groupPolygonUnion, groupPolygonIntersection, and groupConvexHull.

Documentation entry for user-facing changes

  • Documentation is written in code


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

Copilot AI review requested due to automatic review settings March 30, 2026 21:25
@CLAassistant

CLAassistant commented Mar 30, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zhemalb
zhemalb marked this pull request as draft March 30, 2026 21:25

Copilot AI left a comment

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.

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, and groupConvexHull.
  • 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.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [26f9bfb]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds groupPolygonUnion, groupPolygonIntersection, and groupConvexHull, including typed and Geometry inputs, aggregate-state serialization, and geometry optimizations. Two remaining issues in groupPolygonIntersection can reject valid inputs or valid partial-state merges. Request changes.

Findings

⚠️ Majors

  1. The merge limit is checked before the complete RHS participates. AggregateFunctionGroupPolygonIntersect.cpp:658 calls SharedExteriorRows::insert for each RHS tier, enforcing the point cap before later tiers can simplify earlier holes. With the production state structs and exact Boost revision, reducing the cap to 4,000 gives two valid shared-row states of 3,515 and 1,015 points: live merging throws, but materializing the RHS first produces an equivalent successful 3,510-point result. The integer sawtooth 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.

  2. Rectangle clipping can select an invalid combined result despite valid operands. AggregateFunctionGeoUtils.cpp:839 checks individual clipped polygons, then selects their assembled MultiPolygon without a cross-component validity certificate. On the exact PR binary, a valid two-component rectangular geometry clipped by a valid narrow rectangle passes both input checks, but aggregation throws BAD_ARGUMENTS for an invalid self-intersection near (3, 3). The general polygonsIntersectionCartesian result passes the same aggregate's input validation. Require a conservative certificate for the complete candidate before selecting this kernel; use the general overlay when that certificate cannot be established.

Tests
  • ⚠️ Add focused coverage for merging live shared-exterior states versus the same RHS after a binary round trip, including a later covering hole that reduces the final point count.
  • ⚠️ Add the rectangle-clipping reproduction with separate input and general-overlay validity controls. Six existing focused stateless regressions (05453, 05508, 05509, 05510, 05511, 05512) matched their references on the PR binary; they do not cover these failures.
Final Verdict

⚠️ Request changes. Check the shared-row point cap after the complete merge, establish cross-component validity before selecting rectangle clipping, and add the two focused regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 31, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

The test_database_iceberg_nessie_catalog and test_database_iceberg_lakekeeper_catalog failures in this PR's CI are false positives caused by a bug in PR #100583 (merged to master on 2026-04-09 at 11:19 UTC). That PR broke the metadata file path resolution in getMetadataLocation for Iceberg catalog tests — it produced a doubled S3 key like table_path/warehouse-rest/table_path/metadata/... instead of table_path/metadata/..., causing MinIO to return 403.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

The flaky check failure is fixed in #102148, let's update the branch.

@zhemalb
zhemalb marked this pull request as ready for review April 28, 2026 19:47
@zhemalb
zhemalb marked this pull request as draft May 1, 2026 15:13
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

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.

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator

Fix: #129874. Here the six Iceberg jobs fail for a reason the report failure hid: the Iceberg rewrite refuses all 20 new tests, because Point, Ring, Polygon and MultiPolygon columns have no Iceberg equivalent (run-errors.tsv in logs.tar.zst). With no query left to compare, the report step failed (INCORRECT_RESULT_OF_SCALAR_SUBQUERY, then the missing all-query-metrics.tsv), and Errors while building the report. replaced the per-test errors. With #129874 the report builds: the check reports 20 errors, each with the hint to mark the test <test iceberg="0"> or list it in tests/performance/iceberg_skip_list.txt, which this PR still needs (#128261 fails a new test that cannot run on Iceberg tables on purpose). PRs whose changed tests only run on the new server, like #113575, get a normal report.

Comment thread tests/performance/group_convex_hull.xml Resolved
zhemalb and others added 16 commits November 8, 2026 19:05
… 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]>
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]>
@zhemalb

zhemalb commented Nov 8, 2026

Copy link
Copy Markdown
Author

Update: correctness fixes and performance work since 02d8f6f

This 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

  • Validator accepted invalid input (8d28b29). The phase-5 shortcut skipped relate for components whose envelopes merely touch. Under Boost's tolerance such components can still have intersecting interiors, so groupPolygonIntersection could silently drop a component (area 3 instead of an error). The shortcut now requires separation by more than geoSeparationMargin, like the other shortcuts. Regression test: 05510.
  • Wide coordinates on targets where WideCoordinate is cpp_bin_float_quad (macOS ARM64, PPC64LE, d31a3d1). Boost.Geometry promoted that type to double inside segment_ratio, so 1-7% of non-axis-aligned overlays above about 1e154 came out invalid. The trait is specialized and asserted, so every build checks it.
  • Shared-exterior intersection (cd387fa, then cfd68f0). The first version computed the exterior minus the union of all holes with one difference. Review found three inputs where that disagrees with intersecting the rows: holes 1 ULP apart along a shared edge (area 99 instead of 97), a hole touching the exterior inside an edge (holes dropped), and holes enclosing an island ("disconnected interior"). The current version intersects the rows themselves in size tiers, which uses the same overlays as the eager path. All three cases are in 05511.
  • Tests that did not test their claim: 05509, 05220 and 05221 relied on a subquery ORDER BY that RemoveRedundantSorting removes for an order-independent aggregate; they now set query_plan_remove_redundant_sorting = 0.
  • State formats: only the current formats are accepted (groupConvexHull version 3, one chunk for a non-empty groupPolygonIntersection state). The earlier formats were never released.

Performance

Morning head 02d8f6f against 37eac52, same x86 machine and build flags, clickhouse local, max_threads = 1, minimum of 3 runs. Times include process start (about 0.08 s) and data generation. An A/A run of the old build stayed within 3%.

Workload Before After Speedup
groupPolygonIntersection, shared exterior, 3000 overlapping triangle holes 99.2 s 0.72 s 138x
groupPolygonIntersection, shared exterior, 4000 overlapping octagon holes 19.5 s 0.40 s 49x
groupPolygonUnion, 16k overlapping pairs, shuffled 6.97 s 1.00 s 7.0x
groupPolygonUnion, 40k disjoint squares, shuffled 1.42 s 0.38 s 3.8x
groupPolygonUnion, 4096 squares touching at corners 1.14 s 0.33 s 3.5x
groupConvexHull, 20M Gaussian points 3.31 s 1.39 s 2.4x
groupConvexHull, 20M points on a grid 1.85 s 0.85 s 2.2x
groupConvexHull, 20M uniform points 2.89 s 1.51 s 1.9x
groupConvexHull, 1M groups of 10 points 2.76 s 2.57 s 1.07x

Unchanged within noise: overlapping union strip, rectangle intersections, and hulls whose points are all vertices.

What changed:

  • groupConvexHull: points strictly inside the Akl-Toussaint quadrilateral are dropped before sorting (exact predicate, identical output and state); the hull chains are reserved for small inputs. std::sort stays: on x86, ipnsort with a branchless comparator was 9% faster on uniform input but 16% slower when every point is a hull vertex. (a153b91 says it switched to ipnsort; it did not.)
  • groupPolygonUnion: results that are valid by construction (envelope union, margin-separated concatenation) skip re-validation; small operands compare component envelopes pairwise; large operands overlay only the components within the margin of each other and append the rest.
  • groupPolygonIntersection: rows with a common exterior, which can never intersect to empty, are intersected in size tiers once the state reaches 256 points; smaller states keep the eager path and its exact output layout.

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

  • New stateless tests 05510, 05511, 05512; comments in about ten tests updated to match what they check.
  • The 20 performance tests are consolidated into group_convex_hull.xml, group_polygon_union.xml and group_polygon_intersection.xml: 25 queries of 0.17-0.83 s each, deterministic fills, iceberg="0".
  • Documentation now states the order independence of groupConvexHull, its degenerate outputs, and that unnamed arrays need a geometry type.
  • All 57 geo stateless tests pass locally, twice, with randomized settings.

Not addressed

  • The hole R-tree in groupPolygonIntersection is kept per group once two rows share an exterior (about 800 bytes each).
  • A typed addBatchSinglePlace for Point columns in groupConvexHull, and a dedicated rectangle-with-rectangle intersection kernel (it would change the documented example's vertex order).

eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
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]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 17, 2026
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 18, 2026 09:25

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

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.

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

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.

[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.

This branch has not been deployed

No deployments
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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Aggregate functions for Geo types

8 participants