You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "jiayuasu (via GitHub)" <gi...@apache.org> on 2026/04/26 22:20:31 UTC

[PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

jiayuasu opened a new pull request, #2863:
URL: https://github.com/apache/sedona/pull/2863

   ## Did you read the Contributor Guide?
   
   - Yes, I have read the [Contributor Rules](https://sedona.apache.org/latest/community/rule/) and [Contributor Development Guide](https://sedona.apache.org/latest/community/develop/)
   
   ## Is this PR related to a ticket?
   
   - Yes, the PR name follows the format `[GH-XXX] my subject`. Closes #2857
   
   ## What changes were proposed in this PR?
   
   `ST_S2CellIDs` returned a covering that under-covered the planar input polygon along long non-meridional edges (~0.92% of the reporter's polygon at level 12). Sedona geometry-type objects are planar — an edge between two vertices is a straight line in `(longitude, latitude)` space — but S2 connects the same vertices with great-circle arcs on the sphere. The two interpretations agree at the vertices but diverge along the edges (a great-circle arc between two points at the same northern latitude bulges poleward of the planar chord). Handing JTS vertices to S2 directly produces a spherical polygon whose interior is *smaller* than the planar polygon's, and the S2 covering of that smaller polygon misses thin slivers of the original input.
   
   This PR JTS-buffers the input by an upper bound on the worst-case great-circle/chord deviation before converting to S2:
   
   - **Polygon**: per-edge midpoint deviation across exterior + interior rings. Buffering offsets edges in place, so per-edge analysis is tight.
   - **LineString**: bbox-corner pairs (SW–NE diagonal, NW–SE diagonal, worst-case east-west). Buffering turns the line into a polygon corridor whose long edges span the line's full envelope (especially for collinear segments JTS simplifies away), which per-segment analysis under-bounds. Diagonal great-circle arcs deviate more than east-west arcs at high latitudes, so we probe both.
   - A 1.5× safety multiplier absorbs numerical error and the small additional deviation the buffered polygon's own (slightly different) edges introduce.
   
   Multi-geometries are decomposed by \`GeomUtils.extractGeometryCollection\` upstream and each leaf is buffered/covered independently.
   
   ### Status of the reported bug
   
   | Metric                           | Before (master) | After (this PR) |
   |----------------------------------|-----------------|-----------------|
   | Original polygon area            | 22.1941 deg²    | 22.1941 deg²    |
   | Cells returned at level 12       | 49,086          | 53,192 (+8.4%)  |
   | Uncovered area                   | 0.20349708 deg² | **0.0**         |
   | Uncovered fraction               | 0.916897%       | **0.000000%**   |
   | \`coverage.covers(input)\`       | **false**       | **true**        |
   
   ![GH-2857 before / after](https://github.com/jiayuasu/sedona/raw/fix/s2-cellids-coverage/docs/image/GH-2857/coverage_before_after.png)
   
   The dark-blue outline is the input polygon. Light-blue fill is the union of cell geometries returned by \`ST_S2ToGeom(ST_S2CellIDs(...))\`. Red is \`input.difference(coverage)\` — the planar input area not covered. The bottom row zooms in on the southern boundary where the issue showed the slivers concentrated.
   
   ### Side effect for \`LineString\`
   
   After the buffer, a line input becomes a polygon corridor before S2 sees it. Returned cells therefore cover a thin strip *around* the line rather than only cells the line geometrically traverses. This is documented in the new "Planar input, spherical cells" note in the SQL / Flink / Snowflake \`ST_S2CellIDs\` pages. Use a sufficiently fine \`level\` to keep the corridor narrow.
   
   ## How was this patch tested?
   
   \`mvn -pl common test -Dtest=FunctionsTest\` — 284 tests, all green.
   
   New test cases in \`common/src/test/java/org/apache/sedona/common/FunctionsTest.java\`:
   
   - \`testS2CoverageContainsInput\` — the reporter's exact polygon at level 12; reproduces \`0.20349708 deg² uncovered\` on master, passes after the fix.
   - \`testS2CoverageContainsLineString\` — long east-west line at mid-latitude.
   - \`testS2CoverageContainsMultiPolygon\` — disjoint polygons, decomposition + per-leaf buffer.
   - \`testS2CoverageContainsMultiLineString\` — north / south / diagonal multi-segment lines (the diagonal case is what required the diagonal-aware envelope bound).
   - \`testS2CoverageContainsGeometryCollection\` — heterogeneous Polygon + LineString.
   - \`testS2CoverageContainsPolygonWithHole\` — exterior + interior ring deviations.
   - \`testS2CoverageContainsHighLatitudePolygon\` — 80°N polygon with 60° east-west edges.
   
   Existing tests (including \`S2CellIDs\` spatial-join correctness, MBR equivalence, single-cell polygons, lines, points) continue to pass.
   
   ## Did this PR include necessary documentation updates?
   
   - Yes, I have updated the documentation. Added a "Planar input, spherical cells" note to \`ST_S2CellIDs.md\` for SQL, Flink, and Snowflake explaining the planar-vs-spherical mismatch, when no extra cells are added (meridional/equator-aligned edges), and the LineString corridor consequence. No public API surface changed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144386793


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,163 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {
+      // Only compute the (expensive, ~50k-cell) difference on failure, to surface a useful
+      // diagnostic. Happy path skips the full geometric union/difference work.

Review Comment:
   The comment says the happy path “skips the full geometric union/difference work”, but the union is computed unconditionally just above; only the `difference` is skipped. Please reword this to avoid implying that the union is avoided on success.
   ```suggestion
         // diagnostic. The happy path still computes the union above, but skips this difference.
   ```



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,218 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs whose
+    // envelope spans more than 180° in longitude (which only happens when the input
+    // straddles the antimeridian, since real-world inputs don't span half the globe in
+    // lng), buffering produces a polygon that goes the wrong way around the globe and
+    // explodes the S2 covering. Skip the buffer for those inputs; the original GH-2857
+    // miscoverage only affects edges that go the "long" way in (lng, lat) space, which
+    // these inputs by definition do not.
+    boolean spansAntimeridian = geom.getEnvelopeInternal().getWidth() > 180.0;
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;

Review Comment:
   The antimeridian detection/comment is based on `envelope.getWidth() > 180`, but that condition can also be true for geometries that simply span a very wide longitude range without actually straddling the antimeridian. In that case `eps` is forced to 0 and the buffer/containment fix is skipped, potentially reintroducing under-coverage for long non-meridional edges. Consider detecting antimeridian crossing per-edge (e.g., any segment with |Δlng| > 180 after wrapping) or otherwise updating the heuristic/comment so it doesn’t assert that width>180 “only happens” for antimeridian straddles.



##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,163 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {

Review Comment:
   This test always computes `coverage = Functions.union(polygons)` where `polygons` can be ~50k cell geometries at level 12, and several other new tests do the same. `Functions.union(Geometry[])` delegates to `GeometryCollection.union()`, which is typically expensive for tens of thousands of polygons and can significantly slow/flake CI. Consider replacing the full union with a cheaper containment strategy (e.g., spatial index over cell polygons + point/segment sampling on the input), or at least gating the union behind a faster preliminary check so the heavy union work only runs when needed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144348746


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,189 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    double eps = arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. We can only
+      // hand a single S2Region back to callers, so cover the largest piece — the smaller
+      // pieces are typically tiny artifacts of the buffer operation rather than real input.
+      Polygon largest = (Polygon) buffered.getGeometryN(0);
+      for (int i = 1; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        if (p.getArea() > largest.getArea()) {
+          largest = p;
+        }
+      }
+      return S2Utils.toS2Polygon(largest);
     }
     throw new IllegalArgumentException(
         "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
   }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
+    } else if (geom instanceof LineString) {
+      maxDev = envelopeDeviationDegrees(geom);
+    }
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * the plain Euclidean mean of the (lng, lat) coordinates.
+   */
+  private static double edgeDeviationDegrees(Coordinate a, Coordinate b) {
+    S2Point aPt = toS2Point(a);
+    S2Point bPt = toS2Point(b);
+    double mx = aPt.getX() + bPt.getX();
+    double my = aPt.getY() + bPt.getY();
+    double mz = aPt.getZ() + bPt.getZ();
+    double norm = Math.sqrt(mx * mx + my * my + mz * mz);
+    if (norm < 1e-15) {
+      // Antipodal endpoints — the great circle through them is not unique, so there is no
+      // well-defined midpoint to compare against. Returning 0 effectively skips this edge;
+      // antipodal inputs aren't realistic for S2 covering anyway.
+      return 0.0;
+    }
+    S2LatLng midSpherical = new S2LatLng(new S2Point(mx / norm, my / norm, mz / norm));
+    double midSphericalLat = midSpherical.latDegrees();
+    double midSphericalLng = midSpherical.lngDegrees();
+    double midChordLat = (a.y + b.y) / 2.0;
+    double midChordLng = (a.x + b.x) / 2.0;
+    double dLat = midSphericalLat - midChordLat;
+    double dLng = midSphericalLng - midChordLng;
+    // Wrap longitude difference into [-180, 180]. Without this, an edge straddling the
+    // antimeridian (e.g. -179° to +179°) would compute dLng ≈ 358° and produce a bogus
+    // ~360° deviation rather than the small actual deviation.
+    if (dLng > 180.0) dLng -= 360.0;
+    else if (dLng < -180.0) dLng += 360.0;
+    return Math.sqrt(dLat * dLat + dLng * dLng);

Review Comment:
   Fixed in 5229c3b4c4. Two layers:
   
   1. `edgeDeviationDegrees` now wraps `b.x − a.x` into `[-180, 180]` before averaging, then wraps the result back, so the chord midpoint is computed on the shorter longitudinal arc. An edge `(179°, y) → (-179°, y)` now yields a chord midpoint at ±180°, matching the great-circle midpoint, and the deviation is ≈ 0 as expected.
   2. `toS2Region` separately skips the JTS buffer entirely when the input envelope spans `> 180°` in longitude. JTS planar buffer doesn't understand antimeridian crossing — it would produce a polygon going the wrong way around the globe (the long way), which exploded the cell count to OOM in tests. Skipping the buffer is safe for these inputs because the original GH-2857 miscoverage only affects edges that go the "long" way in (lng, lat) space, which antimeridian-crossing edges by definition do not.
   
   `envelopeDeviationDegrees` also has a defense-in-depth fallback to per-segment `ringMaxDeviationDegrees` when `env.getWidth() > 180`, in case anyone calls it directly. New test `testS2CoverageContainsAntimeridianLine` locks in correctness and a sane cell count for the antimeridian case.



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,189 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    double eps = arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. We can only
+      // hand a single S2Region back to callers, so cover the largest piece — the smaller
+      // pieces are typically tiny artifacts of the buffer operation rather than real input.
+      Polygon largest = (Polygon) buffered.getGeometryN(0);
+      for (int i = 1; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        if (p.getArea() > largest.getArea()) {
+          largest = p;
+        }
+      }
+      return S2Utils.toS2Polygon(largest);

Review Comment:
   Fixed in 5229c3b4c4. The MultiPolygon branch now builds a single `S2Polygon` containing every component's exterior + interior loops via `toS2Loop`, so no shells are dropped and the containment guarantee holds for every part of the buffered geometry. This only triggers in rare cases where JTS buffer of self-touching/figure-8 inputs collapses to MultiPolygon; non-self-touching inputs still go through the single-Polygon branch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144871613


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,260 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge rather than via envelope width: an envelope-width heuristic fires for
+    // any polygon whose bbox spans > 180° of longitude even if no individual edge
+    // does (e.g. a tessellated wide polygon with intermediate vertices), and we'd
+    // incorrectly skip the buffer for those, reintroducing the GH-2857 miscoverage on
+    // their long non-meridional edges. Per-edge |Δlng| > 180° fires only when the
+    // input genuinely contains an edge that wraps the antimeridian. (For a coarse
+    // polygon with a single edge spanning > 180° both heuristics agree, and skipping
+    // the buffer is the safe choice — JTS buffer can't usefully process such an edge
+    // anyway.)
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.

Review Comment:
   Fixed in c7a7a3d1e3. Same misleading example was in this Javadoc as in the toS2Region comment I fixed last round; missed it. Updated to describe the actual differentiating case — a tessellated wide geometry whose envelope spans >180° but every edge stays under 180° — and noted that for a coarse single-edge case both heuristics agree and skipping the buffer is the safe choice anyway.



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,260 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge rather than via envelope width: an envelope-width heuristic fires for
+    // any polygon whose bbox spans > 180° of longitude even if no individual edge
+    // does (e.g. a tessellated wide polygon with intermediate vertices), and we'd
+    // incorrectly skip the buffer for those, reintroducing the GH-2857 miscoverage on
+    // their long non-meridional edges. Per-edge |Δlng| > 180° fires only when the
+    // input genuinely contains an edge that wraps the antimeridian. (For a coarse
+    // polygon with a single edge spanning > 180° both heuristics agree, and skipping
+    // the buffer is the safe choice — JTS buffer can't usefully process such an edge
+    // anyway.)
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.
+   */
+  private static boolean crossesAntimeridian(Geometry geom) {
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      if (ringCrossesAntimeridian(poly.getExteriorRing().getCoordinates())) {
+        return true;
+      }
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        if (ringCrossesAntimeridian(poly.getInteriorRingN(i).getCoordinates())) {
+          return true;
+        }
+      }
+      return false;
+    } else if (geom instanceof LineString) {
+      return ringCrossesAntimeridian(geom.getCoordinates());
+    }
+    return false;
+  }
+
+  private static boolean ringCrossesAntimeridian(Coordinate[] coords) {
+    for (int i = 0; i < coords.length - 1; i++) {
+      if (Math.abs(coords[i + 1].x - coords[i].x) > 180.0) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * computed in (lng, lat) space by averaging latitudes directly and averaging longitudes via the
+   * wrapped delta in [-180, 180], so antimeridian-spanning edges (e.g. 179° → -179°) use the
+   * shorter longitudinal interval rather than the naive `(a.x + b.x) / 2` which would land on the
+   * far side of the globe and produce a bogus ~180° deviation.
+   */
+  private static double edgeDeviationDegrees(Coordinate a, Coordinate b) {
+    S2Point aPt = toS2Point(a);
+    S2Point bPt = toS2Point(b);
+    double mx = aPt.getX() + bPt.getX();
+    double my = aPt.getY() + bPt.getY();
+    double mz = aPt.getZ() + bPt.getZ();
+    double norm = Math.sqrt(mx * mx + my * my + mz * mz);
+    if (norm < 1e-15) {
+      // Antipodal endpoints — the great circle through them is not unique, so there is no
+      // well-defined midpoint to compare against. Returning 0 effectively skips this edge;
+      // antipodal inputs aren't realistic for S2 covering anyway.
+      return 0.0;

Review Comment:
   Fixed in c7a7a3d1e3. The silent zero-return was the wrong choice — agreed it can hide a real correctness issue. `edgeDeviationDegrees` now throws `IllegalArgumentException` for antipodal endpoints with both coordinates in the message.
   
   Confirmed callers degrade gracefully: `Functions.s2CellIDs` already wraps `toS2Region` in `try/catch (IllegalArgumentException)` (Functions.java:1729) and falls back to per-coordinate cell IDs, so an antipodal-edge throw routes the geometry through the existing degenerate-input path rather than corrupting the covering.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu merged PR #2863:
URL: https://github.com/apache/sedona/pull/2863


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3145211104


##########
docs/api/snowflake/vector-data/Spatial-Indexing/ST_S2CellIDs.md:
##########
@@ -27,6 +27,36 @@ Format: `ST_S2CellIDs(geom: geometry, level: Int)`
 
 Return type: `Array<Long>`
 
+!!! note "Planar input, spherical cells"
+    Sedona geometry type objects are planar: an edge between two vertices is a straight line in
+    `(longitude, latitude)` space. S2 cells are spherical: an edge between two vertices is a
+    great-circle arc on the unit sphere. The two interpretations agree at the vertices but not
+    along the edges — for example, a great-circle arc connecting two points at the same
+    non-equatorial latitude bulges *toward the nearer pole* rather than following the parallel.
+
+    Without compensation this would let the returned cells under-cover the original planar
+    geometry along long, non-meridional edges (the bug reported in
+    [GH-2857](https://github.com/apache/sedona/issues/2857)). To prevent that, `ST_S2CellIDs`
+    JTS-buffers the input by an upper bound on the great-circle/chord deviation before
+    converting it to an S2 region. The result is a covering that always *contains* the
+    original planar geometry, at the cost of a small number of extra boundary cells. Inputs
+    that are themselves spherical (e.g. polygons whose edges are explicitly meridians or the
+    equator) see no additional cells.
+
+    For `LineString` and `MultiLineString` inputs the buffer turns the line into a polygon
+    corridor, so the returned cells cover a thin strip *around* the line rather than only
+    cells the line geometrically passes through. Use a sufficiently fine `level` to keep the
+    corridor narrow.

Review Comment:
   This note claims `ST_S2CellIDs` buffers inputs before converting to an S2 region, but the implementation skips buffering for antimeridian-crossing geometries (see `S2Utils.toS2Region` / `crossesAntimeridian`). Please document that exception here because it affects output (no extra boundary cells / no LineString corridor) for those cases.
   ```suggestion
       JTS-buffers inputs that do **not** cross the antimeridian by an upper bound on the
       great-circle/chord deviation before converting them to an S2 region. The result is a
       covering that always *contains* the original planar geometry, at the cost of a small
       number of extra boundary cells. Inputs that are themselves spherical (e.g. polygons
       whose edges are explicitly meridians or the equator) see no additional cells. Geometries
       that cross the antimeridian are an exception: they are converted to an S2 region without
       this compensating buffer, so they do not get the extra boundary cells described above.
   
       For `LineString` and `MultiLineString` inputs where buffering is applied, the buffer turns
       the line into a polygon corridor, so the returned cells cover a thin strip *around* the
       line rather than only cells the line geometrically passes through. Antimeridian-crossing
       lines are the exception because the buffer is skipped for them. Use a sufficiently fine
       `level` to keep the corridor narrow.
   ```



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,267 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */

Review Comment:
   `toS2Region`’s Javadoc says the input is JTS-buffered before converting to S2, but the implementation explicitly skips buffering when `crossesAntimeridian(geom)` is true (`eps = 0.0`). Please update the Javadoc to document this exception (and the rationale), otherwise the “guaranteed to contain”/buffer description is misleading for antimeridian-crossing inputs.



##########
docs/api/flink/Spatial-Indexing/ST_S2CellIDs.md:
##########
@@ -29,6 +29,36 @@ Return type: `Array<Long>`
 
 Since: `v1.4.0`
 
+!!! note "Planar input, spherical cells"
+    Sedona geometry type objects are planar: an edge between two vertices is a straight line in
+    `(longitude, latitude)` space. S2 cells are spherical: an edge between two vertices is a
+    great-circle arc on the unit sphere. The two interpretations agree at the vertices but not
+    along the edges — for example, a great-circle arc connecting two points at the same
+    non-equatorial latitude bulges *toward the nearer pole* rather than following the parallel.
+
+    Without compensation this would let the returned cells under-cover the original planar
+    geometry along long, non-meridional edges (the bug reported in
+    [GH-2857](https://github.com/apache/sedona/issues/2857)). To prevent that, `ST_S2CellIDs`
+    JTS-buffers the input by an upper bound on the great-circle/chord deviation before
+    converting it to an S2 region. The result is a covering that always *contains* the
+    original planar geometry, at the cost of a small number of extra boundary cells. Inputs
+    that are themselves spherical (e.g. polygons whose edges are explicitly meridians or the
+    equator) see no additional cells.
+
+    For `LineString` and `MultiLineString` inputs the buffer turns the line into a polygon
+    corridor, so the returned cells cover a thin strip *around* the line rather than only
+    cells the line geometrically passes through. Use a sufficiently fine `level` to keep the
+    corridor narrow.

Review Comment:
   This note says `ST_S2CellIDs` buffers the input before S2 conversion, but the code skips buffering for antimeridian-crossing geometries (see `S2Utils.toS2Region`, `crossesAntimeridian`). Please mention this exception here since it changes behavior (no extra boundary cells / no LineString corridor) for those inputs.
   ```suggestion
       normally JTS-buffers the input by an upper bound on the great-circle/chord deviation
       before converting it to an S2 region. The result is a covering that always *contains*
       the original planar geometry, at the cost of a small number of extra boundary cells.
       Antimeridian-crossing geometries are an exception: they are converted without this
       extra buffer, so they do not gain those additional boundary cells from buffering.
       Inputs that are themselves spherical (e.g. polygons whose edges are explicitly
       meridians or the equator) see no additional cells.
   
       For `LineString` and `MultiLineString` inputs, when this buffer is applied, it turns
       the line into a polygon corridor, so the returned cells cover a thin strip *around*
       the line rather than only cells the line geometrically passes through. Antimeridian-
       crossing lines are again an exception because buffering is skipped for them. Use a
       sufficiently fine `level` to keep the corridor narrow.
   ```



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,267 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge rather than via envelope width: an envelope-width heuristic fires for
+    // any polygon whose bbox spans > 180° of longitude even if no individual edge
+    // does (e.g. a tessellated wide polygon with intermediate vertices), and we'd
+    // incorrectly skip the buffer for those, reintroducing the GH-2857 miscoverage on
+    // their long non-meridional edges. Per-edge |Δlng| > 180° fires only when the
+    // input genuinely contains an edge that wraps the antimeridian. (For a coarse
+    // polygon with a single edge spanning > 180° both heuristics agree, and skipping
+    // the buffer is the safe choice — JTS buffer can't usefully process such an edge
+    // anyway.)
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }

Review Comment:
   In `envelopeDeviationDegrees`, the `if (crossesAntimeridian(geom)) { ... }` branch appears unreachable in the current design: `toS2Region` skips calling `arcChordBufferDegrees` (and therefore `envelopeDeviationDegrees`) entirely when `crossesAntimeridian(geom)` is true (`eps = 0.0`). Consider removing this dead branch (and its comment) or restructuring so the antimeridian handling lives in one place, to avoid misleading future readers about which paths are actually exercised.
   ```suggestion
   
   ```



##########
docs/api/sql/Spatial-Indexing/ST_S2CellIDs.md:
##########
@@ -29,6 +29,36 @@ Return type: `Array<Long>`
 
 Since: `v1.4.0`
 
+!!! note "Planar input, spherical cells"
+    Sedona geometry type objects are planar: an edge between two vertices is a straight line in
+    `(longitude, latitude)` space. S2 cells are spherical: an edge between two vertices is a
+    great-circle arc on the unit sphere. The two interpretations agree at the vertices but not
+    along the edges — for example, a great-circle arc connecting two points at the same
+    non-equatorial latitude bulges *toward the nearer pole* rather than following the parallel.
+
+    Without compensation this would let the returned cells under-cover the original planar
+    geometry along long, non-meridional edges (the bug reported in
+    [GH-2857](https://github.com/apache/sedona/issues/2857)). To prevent that, `ST_S2CellIDs`
+    JTS-buffers the input by an upper bound on the great-circle/chord deviation before
+    converting it to an S2 region. The result is a covering that always *contains* the
+    original planar geometry, at the cost of a small number of extra boundary cells. Inputs
+    that are themselves spherical (e.g. polygons whose edges are explicitly meridians or the
+    equator) see no additional cells.
+
+    For `LineString` and `MultiLineString` inputs the buffer turns the line into a polygon
+    corridor, so the returned cells cover a thin strip *around* the line rather than only
+    cells the line geometrically passes through. Use a sufficiently fine `level` to keep the
+    corridor narrow.
+

Review Comment:
   This note states that `ST_S2CellIDs` “JTS-buffers the input … before converting it to an S2 region”, but the implementation skips buffering for antimeridian-crossing geometries (see `S2Utils.toS2Region`, which sets `eps = 0.0` when an edge has |Δlng|>180). Please document that exception here as it affects output (no extra boundary cells / no LineString corridor) for those inputs.
   ```suggestion
       normally JTS-buffers the input by an upper bound on the great-circle/chord deviation
       before converting it to an S2 region. The result is a covering that always *contains*
       the original planar geometry, at the cost of a small number of extra boundary cells.
       Inputs that are themselves spherical (e.g. polygons whose edges are explicitly meridians
       or the equator) see no additional cells.
   
       Exception: buffering is skipped for geometries that cross the antimeridian (that is, an
       edge has `|Δlng| > 180`). For those inputs, the output reflects the unbuffered S2
       region: there are no extra boundary cells from this compensation step.
   
       For `LineString` and `MultiLineString` inputs, when buffering is applied it turns the
       line into a polygon corridor, so the returned cells cover a thin strip *around* the line
       rather than only cells the line geometrically passes through. Use a sufficiently fine
       `level` to keep the corridor narrow. Antimeridian-crossing line inputs are not buffered,
       so they do not get this corridor.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144348268


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,139 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    Geometry uncovered = input.difference(coverage);
+    double uncoveredArea = uncovered.getArea();
+    log.info(
+        "S2 cells: {}, input area: {}, uncovered area: {} ({} %)",

Review Comment:
   Done in 5229c3b4c4. Wrapped the difference/area/log block in `if (!coverage.covers(input)) { … fail(...) }` so the ~50k-cell union/difference only runs on failure. Happy path is now just the containment check.



##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,139 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    Geometry uncovered = input.difference(coverage);
+    double uncoveredArea = uncovered.getArea();
+    log.info(
+        "S2 cells: {}, input area: {}, uncovered area: {} ({} %)",
+        cellIds.length, input.getArea(), uncoveredArea, (uncoveredArea / input.getArea()) * 100.0);
+    assertTrue(
+        String.format(
+            "Coverage does not contain input. Missing %.8f deg^2 (%.6f%%)",
+            uncoveredArea, (uncoveredArea / input.getArea()) * 100.0),
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsLineString() throws ParseException {
+    // Long east-west line at mid-latitude. The great-circle arc bulges poleward of the JTS
+    // chord, so before the buffer fix the cells along the parallel were missed in the middle.
+    Geometry line = geomFromWKT("LINESTRING (-102 37, -94 37)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage of LineString does not contain the line itself.", coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiPolygon() throws ParseException {
+    // Two disjoint polygons, both at mid-northern latitude with long east-west edges.
+    String wkt =
+        "MULTIPOLYGON ("
+            + "((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "((-90 50, -80 50, -80 53, -90 53, -90 50)))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiPolygon.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiLineString() throws ParseException {
+    // Three disjoint multi-segment lines: northern hemisphere, southern hemisphere, and a
+    // diagonal climb. Each is decomposed and buffered independently before S2 covering.
+    String wkt =
+        "MULTILINESTRING ("
+            + "(-102 37, -98 37, -94 37),"
+            + "(-90 -42, -85 -42, -80 -42),"
+            + "(-100 50, -95 55, -90 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiLineString.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsGeometryCollection() throws ParseException {
+    String wkt =
+        "GEOMETRYCOLLECTION ("
+            + "POLYGON ((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "LINESTRING (10 60, 20 60, 30 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the GeometryCollection.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsPolygonWithHole() throws ParseException {
+    // Outer ring at mid-latitude with long east-west edges; an inner hole. Both rings need
+    // their great-circle bulge accounted for so the buffer applies to interior rings too.
+    String wkt =
+        "POLYGON ("
+            + "(-102 37, -94 37, -94 40, -102 40, -102 37),"
+            + "(-100 38, -96 38, -96 39, -100 39, -100 38))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue("S2 cell coverage does not contain a polygon with a hole.", coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsHighLatitudePolygon() throws ParseException {
+    // Polygon near 80°N: tan(φ) is large, so the buffer cap (1°) and 89° latitude clamp need
+    // to keep the arc-chord bound from blowing up.

Review Comment:
   Done in 5229c3b4c4. The 1° cap and 89° latitude clamp existed in an earlier iteration and were removed when `edgeDeviationDegrees` was rewritten to use the actual great-circle midpoint (which handles all latitudes/orientations exactly). Updated the comment to describe the actual implementation: the test verifies the arc-chord deviation calculation stays correct at high latitude without any rigid cap or clamp.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144826670


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,260 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge rather than via envelope width: an envelope-width heuristic fires for
+    // any polygon whose bbox spans > 180° of longitude even if no individual edge
+    // does (e.g. a tessellated wide polygon with intermediate vertices), and we'd
+    // incorrectly skip the buffer for those, reintroducing the GH-2857 miscoverage on
+    // their long non-meridional edges. Per-edge |Δlng| > 180° fires only when the
+    // input genuinely contains an edge that wraps the antimeridian. (For a coarse
+    // polygon with a single edge spanning > 180° both heuristics agree, and skipping
+    // the buffer is the safe choice — JTS buffer can't usefully process such an edge
+    // anyway.)
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.
+   */
+  private static boolean crossesAntimeridian(Geometry geom) {
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      if (ringCrossesAntimeridian(poly.getExteriorRing().getCoordinates())) {
+        return true;
+      }
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        if (ringCrossesAntimeridian(poly.getInteriorRingN(i).getCoordinates())) {
+          return true;
+        }
+      }
+      return false;
+    } else if (geom instanceof LineString) {
+      return ringCrossesAntimeridian(geom.getCoordinates());
+    }
+    return false;
+  }
+
+  private static boolean ringCrossesAntimeridian(Coordinate[] coords) {
+    for (int i = 0; i < coords.length - 1; i++) {
+      if (Math.abs(coords[i + 1].x - coords[i].x) > 180.0) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * computed in (lng, lat) space by averaging latitudes directly and averaging longitudes via the
+   * wrapped delta in [-180, 180], so antimeridian-spanning edges (e.g. 179° → -179°) use the
+   * shorter longitudinal interval rather than the naive `(a.x + b.x) / 2` which would land on the
+   * far side of the globe and produce a bogus ~180° deviation.
+   */
+  private static double edgeDeviationDegrees(Coordinate a, Coordinate b) {
+    S2Point aPt = toS2Point(a);
+    S2Point bPt = toS2Point(b);
+    double mx = aPt.getX() + bPt.getX();
+    double my = aPt.getY() + bPt.getY();
+    double mz = aPt.getZ() + bPt.getZ();
+    double norm = Math.sqrt(mx * mx + my * my + mz * mz);
+    if (norm < 1e-15) {
+      // Antipodal endpoints — the great circle through them is not unique, so there is no
+      // well-defined midpoint to compare against. Returning 0 effectively skips this edge;
+      // antipodal inputs aren't realistic for S2 covering anyway.
+      return 0.0;

Review Comment:
   `edgeDeviationDegrees` returns `0.0` when the endpoints are antipodal (`norm < 1e-15`). That silently underestimates the required buffer and breaks the method’s documented guarantee that the resulting S2Region contains the input (an antipodal edge can have large arc/chord divergence, and S2’s great-circle is not uniquely defined). Consider throwing an IllegalArgumentException for antipodal (or near-antipodal) endpoints, or returning a conservative non-zero bound so callers don’t get incorrect under-coverage without noticing.
   ```suggestion
         // Antipodal or near-antipodal endpoints do not define a unique great-circle midpoint.
         // Returning 0 would silently underestimate the required buffer and can break containment.
         throw new IllegalArgumentException(
             "Cannot compute edge deviation for antipodal or near-antipodal coordinates: "
                 + a
                 + " to "
                 + b);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144299844


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,139 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    Geometry uncovered = input.difference(coverage);
+    double uncoveredArea = uncovered.getArea();
+    log.info(
+        "S2 cells: {}, input area: {}, uncovered area: {} ({} %)",

Review Comment:
   This test unions all returned cell polygons and then computes `input.difference(coverage)` unconditionally. For the GH-2857 reproducer this is ~50k+ cells at level 12, so `union`/`difference` can become a major CPU/memory cost in unit tests. Consider (a) only computing `difference`/area when `covers` fails (so the heavy work is on failure only), and/or (b) avoiding a full geometric union by checking containment against a spatial index / prepared geometries / sampled boundary points, or using an S2-side containment check.



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,189 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    double eps = arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. We can only
+      // hand a single S2Region back to callers, so cover the largest piece — the smaller
+      // pieces are typically tiny artifacts of the buffer operation rather than real input.
+      Polygon largest = (Polygon) buffered.getGeometryN(0);
+      for (int i = 1; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        if (p.getArea() > largest.getArea()) {
+          largest = p;
+        }
+      }
+      return S2Utils.toS2Polygon(largest);

Review Comment:
   If `geom.buffer(eps)` returns a `MultiPolygon`, the current behavior picks the largest polygon and discards the rest. This can break the stated guarantee that the resulting S2Region contains the original planar geometry (discarded components can still contain parts of the buffered/original geometry). Since `S2Polygon` can represent multiple shells via multiple `S2Loop`s, consider converting *all* polygons in the MultiPolygon into loops (or unioning the MultiPolygon before conversion) instead of dropping components.



##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,139 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    Geometry uncovered = input.difference(coverage);
+    double uncoveredArea = uncovered.getArea();
+    log.info(
+        "S2 cells: {}, input area: {}, uncovered area: {} ({} %)",
+        cellIds.length, input.getArea(), uncoveredArea, (uncoveredArea / input.getArea()) * 100.0);
+    assertTrue(
+        String.format(
+            "Coverage does not contain input. Missing %.8f deg^2 (%.6f%%)",
+            uncoveredArea, (uncoveredArea / input.getArea()) * 100.0),
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsLineString() throws ParseException {
+    // Long east-west line at mid-latitude. The great-circle arc bulges poleward of the JTS
+    // chord, so before the buffer fix the cells along the parallel were missed in the middle.
+    Geometry line = geomFromWKT("LINESTRING (-102 37, -94 37)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage of LineString does not contain the line itself.", coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiPolygon() throws ParseException {
+    // Two disjoint polygons, both at mid-northern latitude with long east-west edges.
+    String wkt =
+        "MULTIPOLYGON ("
+            + "((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "((-90 50, -80 50, -80 53, -90 53, -90 50)))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiPolygon.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiLineString() throws ParseException {
+    // Three disjoint multi-segment lines: northern hemisphere, southern hemisphere, and a
+    // diagonal climb. Each is decomposed and buffered independently before S2 covering.
+    String wkt =
+        "MULTILINESTRING ("
+            + "(-102 37, -98 37, -94 37),"
+            + "(-90 -42, -85 -42, -80 -42),"
+            + "(-100 50, -95 55, -90 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiLineString.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsGeometryCollection() throws ParseException {
+    String wkt =
+        "GEOMETRYCOLLECTION ("
+            + "POLYGON ((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "LINESTRING (10 60, 20 60, 30 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the GeometryCollection.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsPolygonWithHole() throws ParseException {
+    // Outer ring at mid-latitude with long east-west edges; an inner hole. Both rings need
+    // their great-circle bulge accounted for so the buffer applies to interior rings too.
+    String wkt =
+        "POLYGON ("
+            + "(-102 37, -94 37, -94 40, -102 40, -102 37),"
+            + "(-100 38, -96 38, -96 39, -100 39, -100 38))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue("S2 cell coverage does not contain a polygon with a hole.", coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsHighLatitudePolygon() throws ParseException {
+    // Polygon near 80°N: tan(φ) is large, so the buffer cap (1°) and 89° latitude clamp need
+    // to keep the arc-chord bound from blowing up.

Review Comment:
   This test comment mentions a “buffer cap (1°) and 89° latitude clamp”, but the current implementation in `S2Utils.arcChordBufferDegrees/edgeDeviationDegrees` does not apply any explicit cap or latitude clamp (no occurrences in `S2Utils`). Either implement those safeguards as described, or update the comment to match the actual behavior so future readers aren’t misled about how high-latitude cases are handled.
   ```suggestion
       // Polygon near 80°N with a long east-west edge. This verifies that S2 coverage still
       // contains the input at high latitude without assuming any explicit buffer cap or
       // latitude clamp in the underlying arc-chord deviation calculation.
   ```



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,189 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    double eps = arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. We can only
+      // hand a single S2Region back to callers, so cover the largest piece — the smaller
+      // pieces are typically tiny artifacts of the buffer operation rather than real input.
+      Polygon largest = (Polygon) buffered.getGeometryN(0);
+      for (int i = 1; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        if (p.getArea() > largest.getArea()) {
+          largest = p;
+        }
+      }
+      return S2Utils.toS2Polygon(largest);
     }
     throw new IllegalArgumentException(
         "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
   }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
+    } else if (geom instanceof LineString) {
+      maxDev = envelopeDeviationDegrees(geom);
+    }
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * the plain Euclidean mean of the (lng, lat) coordinates.
+   */
+  private static double edgeDeviationDegrees(Coordinate a, Coordinate b) {
+    S2Point aPt = toS2Point(a);
+    S2Point bPt = toS2Point(b);
+    double mx = aPt.getX() + bPt.getX();
+    double my = aPt.getY() + bPt.getY();
+    double mz = aPt.getZ() + bPt.getZ();
+    double norm = Math.sqrt(mx * mx + my * my + mz * mz);
+    if (norm < 1e-15) {
+      // Antipodal endpoints — the great circle through them is not unique, so there is no
+      // well-defined midpoint to compare against. Returning 0 effectively skips this edge;
+      // antipodal inputs aren't realistic for S2 covering anyway.
+      return 0.0;
+    }
+    S2LatLng midSpherical = new S2LatLng(new S2Point(mx / norm, my / norm, mz / norm));
+    double midSphericalLat = midSpherical.latDegrees();
+    double midSphericalLng = midSpherical.lngDegrees();
+    double midChordLat = (a.y + b.y) / 2.0;
+    double midChordLng = (a.x + b.x) / 2.0;
+    double dLat = midSphericalLat - midChordLat;
+    double dLng = midSphericalLng - midChordLng;
+    // Wrap longitude difference into [-180, 180]. Without this, an edge straddling the
+    // antimeridian (e.g. -179° to +179°) would compute dLng ≈ 358° and produce a bogus
+    // ~360° deviation rather than the small actual deviation.
+    if (dLng > 180.0) dLng -= 360.0;
+    else if (dLng < -180.0) dLng += 360.0;
+    return Math.sqrt(dLat * dLat + dLng * dLng);

Review Comment:
   edgeDeviationDegrees computes the chord midpoint longitude as the raw average `(a.x + b.x) / 2.0`. For edges that cross the antimeridian (e.g., 179° to -179°), this yields a midpoint near 0° and produces a ~180° ‘deviation’ even though the true arc/chord deviation is small. The later wrap of `dLng` does not fix the incorrect midpoint. Compute the chord midpoint using wrapped longitude deltas (wrap `b.x - a.x` into [-180, 180] and then `a.x + delta/2`, wrapped back) so antimeridian-spanning geometries don’t get an enormous buffer and over-covering.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144487263


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,181 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {
+      // The union above is unavoidable for an exact containment check; we additionally
+      // skip the (expensive, ~50k-cell) difference on the happy path and only compute it
+      // on failure to surface a useful diagnostic.
+      Geometry uncovered = input.difference(coverage);
+      double uncoveredArea = uncovered.getArea();
+      fail(
+          String.format(
+              "Coverage does not contain input. Missing %.8f deg^2 (%.6f%%)",
+              uncoveredArea, (uncoveredArea / input.getArea()) * 100.0));
+    }
+  }
+
+  @Test
+  public void testS2CoverageContainsLineString() throws ParseException {
+    // Long east-west line at mid-latitude. The great-circle arc bulges poleward of the JTS
+    // chord, so before the buffer fix the cells along the parallel were missed in the middle.
+    Geometry line = geomFromWKT("LINESTRING (-102 37, -94 37)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage of LineString does not contain the line itself.", coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiPolygon() throws ParseException {
+    // Two disjoint polygons, both at mid-northern latitude with long east-west edges.
+    String wkt =
+        "MULTIPOLYGON ("
+            + "((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "((-90 50, -80 50, -80 53, -90 53, -90 50)))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiPolygon.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiLineString() throws ParseException {
+    // Three disjoint multi-segment lines: northern hemisphere, southern hemisphere, and a
+    // diagonal climb. Each is decomposed and buffered independently before S2 covering.
+    String wkt =
+        "MULTILINESTRING ("
+            + "(-102 37, -98 37, -94 37),"
+            + "(-90 -42, -85 -42, -80 -42),"
+            + "(-100 50, -95 55, -90 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiLineString.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsGeometryCollection() throws ParseException {
+    String wkt =
+        "GEOMETRYCOLLECTION ("
+            + "POLYGON ((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "LINESTRING (10 60, 20 60, 30 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the GeometryCollection.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsPolygonWithHole() throws ParseException {
+    // Outer ring at mid-latitude with long east-west edges; an inner hole. Both rings need
+    // their great-circle bulge accounted for so the buffer applies to interior rings too.
+    String wkt =
+        "POLYGON ("
+            + "(-102 37, -94 37, -94 40, -102 40, -102 37),"
+            + "(-100 38, -96 38, -96 39, -100 39, -100 38))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue("S2 cell coverage does not contain a polygon with a hole.", coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsAntimeridianLine() throws ParseException {
+    // Edge crossing the antimeridian. The naive chord midpoint (a.x+b.x)/2 would land at
+    // 0° longitude — the opposite side of the planet — and produce a ~180° bogus deviation.
+    // Verify that the buffer stays small (so we don't blow up the cell count) and that the
+    // returned cells still cover the line.
+    Geometry line = geomFromWKT("LINESTRING (179 5, -179 5)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    // Sanity check: a 2°-long edge near the equator at level 12 should not produce
+    // millions of cells. If antimeridian chord-midpoint handling is wrong the buffer
+    // explodes by ~180° and the cell count would be enormous.
+    assertTrue(
+        "Antimeridian-spanning line produced too many cells (chord midpoint likely wrong): "
+            + cellIds.length,
+        cellIds.length < 5000);
+    assertTrue(
+        "S2 cell coverage of antimeridian-spanning LineString does not contain the line.",
+        coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsWideNonAntimeridianPolygon() throws ParseException {
+    // Polygon spanning >180° in longitude but NOT crossing the antimeridian (every edge has
+    // |Δlng| < 180°). An envelope-width-based antimeridian heuristic would incorrectly skip
+    // the buffer here and reintroduce GH-2857 miscoverage along the long east-west edges;
+    // the per-edge heuristic correctly leaves the buffer on.
+    String wkt = "POLYGON ((-100 30, 100 30, 100 50, -100 50, -100 30))";

Review Comment:
   Good catch — fixed in 659a9eee12. The original WKT had four edges with `|Δlng| = 200`, so my per-edge heuristic correctly flagged it as antimeridian-crossing and the test was passing only because the buffer was skipped (not for the reason the test name and comment claimed). New WKT `((-100 30, -10 30, 100 30, 100 50, 10 50, -100 50, -100 30))` keeps the envelope 200° wide but every individual edge is under 180°, so the per-edge check returns false and the buffer is actually applied — which is the path the test is meant to exercise.



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge (any edge with |Δlng| > 180° must wrap) rather than via the envelope:
+    // the envelope-width heuristic also fires for wide non-straddling polygons (e.g.
+    // a polygon spanning -100° to +100°), which would incorrectly skip the buffer and
+    // reintroduce the GH-2857 miscoverage along their long non-meridional edges.

Review Comment:
   Fixed in 659a9eee12. You're right that a coarse `-100°→+100°` edge has `|Δlng|=200` and gets classified as crossing under both heuristics, so it's not the case where per-edge differs from envelope-width. Reworded the comment to describe the actual differentiating case (a *tessellated* wide polygon with intermediate vertices, where envelope width > 180° but every edge is < 180°), and noted that for a coarse single-edge spanning > 180° both heuristics agree and skipping the buffer is the safe choice anyway since JTS planar buffer can't process such an edge usefully.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144420894


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,163 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {
+      // Only compute the (expensive, ~50k-cell) difference on failure, to surface a useful
+      // diagnostic. Happy path skips the full geometric union/difference work.

Review Comment:
   Done in 1537d9c22c. Updated the comment to clarify that the union itself is unavoidable for an exact containment check; only the difference is gated on failure.



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,218 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs whose
+    // envelope spans more than 180° in longitude (which only happens when the input
+    // straddles the antimeridian, since real-world inputs don't span half the globe in
+    // lng), buffering produces a polygon that goes the wrong way around the globe and
+    // explodes the S2 covering. Skip the buffer for those inputs; the original GH-2857
+    // miscoverage only affects edges that go the "long" way in (lng, lat) space, which
+    // these inputs by definition do not.
+    boolean spansAntimeridian = geom.getEnvelopeInternal().getWidth() > 180.0;
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;

Review Comment:
   Good catch — fixed in 1537d9c22c. Replaced the envelope-width heuristic with a per-edge check (`|Δlng| > 180°` on any edge) that only fires for actual antimeridian crossings, not for wide non-straddling polygons. Added `testS2CoverageContainsWideNonAntimeridianPolygon` (a -100° to +100° polygon, 200° wide but no antimeridian crossing) to lock that behavior in: that test would fail under the previous envelope-width heuristic because the buffer would be skipped and the long east-west edges would reintroduce the original miscoverage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144445168


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }

Review Comment:
   Fixed in ad87b7161a. The behavior was already correct — `LinearRing extends LineString` in JTS so `instanceof LineString` matches LinearRing too — but the message was misleading by listing LinearRing as if it were a separately-handled type. Updated both the early-guard and final-throw messages to `"only Polygon or LineString (including LinearRing) types can be converted to S2Region"`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144421388


##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,163 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {

Review Comment:
   Acknowledged but not changed. The full FunctionsTest suite (286 tests including all the new coverage assertions) runs in ~34 s on my laptop and the CI build job has historically been the long pole on Sedona PRs by orders of magnitude — these tests do not move that needle.
   
   `testS2CoverageContainsInput` is the only one at level 12 with the full reporter polygon (~50k cells); the rest run at level 6–10 on simpler inputs and produce only a few thousand cells each. The level-12 test is the canonical regression for the reported issue and uses the union/difference pair to give a precise area diagnostic on failure, which a sampling/index-based check cannot.
   
   A spatial-index-based sampling check would be cheaper but inexact (it could miss thin slivers between sample points, which is exactly the failure mode this PR fixes). Given the actual measured cost and the value of an exact containment assertion on the reproducer, I think keeping `Functions.union` + `covers` is the right tradeoff. Happy to revisit if these tests show up in CI flakiness or runtime budgets later.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144429788


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
-    if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
-    } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    }

Review Comment:
   `toS2Region` rejects anything that's not a `Polygon` or `LineString`, but the thrown message still claims `LinearRing` is supported (both at the early guard and the final throw). Either update the message/Javadoc to match the actual supported types, or extend the guard to accept `LinearRing` and convert it appropriately (e.g., via `toS2Loop`). Mismatched error messages make it harder to debug callers that pass unsupported geometries.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144476452


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge (any edge with |Δlng| > 180° must wrap) rather than via the envelope:
+    // the envelope-width heuristic also fires for wide non-straddling polygons (e.g.
+    // a polygon spanning -100° to +100°), which would incorrectly skip the buffer and
+    // reintroduce the GH-2857 miscoverage along their long non-meridional edges.

Review Comment:
   The comment here says the per-edge antimeridian check avoids false positives for wide non-straddling polygons like one spanning -100° to +100°, but the current predicate (`|Δlng| > 180°` on any edge) will still return true for a direct edge from -100° to +100° (|Δlng|=200). Either tighten the detection to only treat *actual* dateline-straddling edges as antimeridian-crossing (or require longitudes to be normalized and document that), or update this comment/example so it matches the behavior.
   ```suggestion
       // using the current per-edge longitude-jump test in crossesAntimeridian(geom),
       // rather than an envelope-width heuristic: envelope width alone can misclassify
       // broad geometries as antimeridian-spanning and incorrectly skip the buffer,
       // reintroducing the GH-2857 miscoverage along long non-meridional edges.
   ```



##########
common/src/test/java/org/apache/sedona/common/FunctionsTest.java:
##########
@@ -1081,6 +1081,181 @@ public void testS2ToGeom() {
     assertTrue(polygons[100].intersects(target));
   }
 
+  @Test
+  public void testS2CoverageContainsInput() throws ParseException {
+    String wkt =
+        "POLYGON ((-102.060778 39.9999603, -102.0535384 40.0119065, -101.98532 40.0122906, "
+            + "-95.30829 40.009008, -95.2456364 39.9564784, -95.1982467 39.9455019, "
+            + "-95.1964657 39.9113444, -95.1460439 39.9142017, -95.1316877 39.8855881, "
+            + "-95.087643 39.8717975, -95.0389987 39.8749063, -95.0146232 39.9088422, "
+            + "-94.9403146 39.906409, -94.9183761 39.8846514, -94.9329504 39.8578468, "
+            + "-94.8824331 39.8409102, -94.8675709 39.8227528, -94.878404 39.787242, "
+            + "-94.9266292 39.7786779, -94.9070076 39.7679231, -94.8631596 39.779774, "
+            + "-94.8497103 39.7604914, -94.8545514 39.7397163, -94.8985678 39.7150641, "
+            + "-94.9584897 39.7331377, -94.9637588 39.6814526, -95.0187723 39.6615712, "
+            + "-95.0456083 39.6252182, -95.0430365 39.5826542, -95.0650104 39.5677387, "
+            + "-95.0985514 39.570063, -95.1012286 39.5462821, -95.0459187 39.5064755, "
+            + "-95.0320969 39.4709074, -94.976457 39.4475392, -94.9362514 39.3964717, "
+            + "-94.8781205 39.3949417, -94.8733156 39.3663291, -94.9014695 39.3495654, "
+            + "-94.8963639 39.3135051, -94.8237994 39.2609956, -94.8194328 39.2178517, "
+            + "-94.7789019 39.214907, -94.7398645 39.1789812, -94.6785238 39.1931279, "
+            + "-94.6533801 39.1816662, -94.6517728 39.1640754, -94.605515 39.1696807, "
+            + "-94.5791896 39.1504025, -94.5983384 39.1134256, -94.6095667 36.9948123, "
+            + "-102.045765 36.9847897, -102.060778 39.9999603))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] polygons =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(polygons);
+    if (!coverage.covers(input)) {
+      // The union above is unavoidable for an exact containment check; we additionally
+      // skip the (expensive, ~50k-cell) difference on the happy path and only compute it
+      // on failure to surface a useful diagnostic.
+      Geometry uncovered = input.difference(coverage);
+      double uncoveredArea = uncovered.getArea();
+      fail(
+          String.format(
+              "Coverage does not contain input. Missing %.8f deg^2 (%.6f%%)",
+              uncoveredArea, (uncoveredArea / input.getArea()) * 100.0));
+    }
+  }
+
+  @Test
+  public void testS2CoverageContainsLineString() throws ParseException {
+    // Long east-west line at mid-latitude. The great-circle arc bulges poleward of the JTS
+    // chord, so before the buffer fix the cells along the parallel were missed in the middle.
+    Geometry line = geomFromWKT("LINESTRING (-102 37, -94 37)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage of LineString does not contain the line itself.", coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiPolygon() throws ParseException {
+    // Two disjoint polygons, both at mid-northern latitude with long east-west edges.
+    String wkt =
+        "MULTIPOLYGON ("
+            + "((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "((-90 50, -80 50, -80 53, -90 53, -90 50)))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiPolygon.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsMultiLineString() throws ParseException {
+    // Three disjoint multi-segment lines: northern hemisphere, southern hemisphere, and a
+    // diagonal climb. Each is decomposed and buffered independently before S2 covering.
+    String wkt =
+        "MULTILINESTRING ("
+            + "(-102 37, -98 37, -94 37),"
+            + "(-90 -42, -85 -42, -80 -42),"
+            + "(-100 50, -95 55, -90 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the MultiLineString.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsGeometryCollection() throws ParseException {
+    String wkt =
+        "GEOMETRYCOLLECTION ("
+            + "POLYGON ((-102 37, -94 37, -94 40, -102 40, -102 37)),"
+            + "LINESTRING (10 60, 20 60, 30 60))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 10);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue(
+        "S2 cell coverage does not contain every member of the GeometryCollection.",
+        coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsPolygonWithHole() throws ParseException {
+    // Outer ring at mid-latitude with long east-west edges; an inner hole. Both rings need
+    // their great-circle bulge accounted for so the buffer applies to interior rings too.
+    String wkt =
+        "POLYGON ("
+            + "(-102 37, -94 37, -94 40, -102 40, -102 37),"
+            + "(-100 38, -96 38, -96 39, -100 39, -100 38))";
+    Geometry input = geomFromWKT(wkt, 0);
+    Long[] cellIds = Functions.s2CellIDs(input, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    assertTrue("S2 cell coverage does not contain a polygon with a hole.", coverage.covers(input));
+  }
+
+  @Test
+  public void testS2CoverageContainsAntimeridianLine() throws ParseException {
+    // Edge crossing the antimeridian. The naive chord midpoint (a.x+b.x)/2 would land at
+    // 0° longitude — the opposite side of the planet — and produce a ~180° bogus deviation.
+    // Verify that the buffer stays small (so we don't blow up the cell count) and that the
+    // returned cells still cover the line.
+    Geometry line = geomFromWKT("LINESTRING (179 5, -179 5)", 0);
+    Long[] cellIds = Functions.s2CellIDs(line, 12);
+    Geometry[] cells =
+        Functions.s2ToGeom(Arrays.stream(cellIds).mapToLong(Long::longValue).toArray());
+    Geometry coverage = Functions.union(cells);
+    // Sanity check: a 2°-long edge near the equator at level 12 should not produce
+    // millions of cells. If antimeridian chord-midpoint handling is wrong the buffer
+    // explodes by ~180° and the cell count would be enormous.
+    assertTrue(
+        "Antimeridian-spanning line produced too many cells (chord midpoint likely wrong): "
+            + cellIds.length,
+        cellIds.length < 5000);
+    assertTrue(
+        "S2 cell coverage of antimeridian-spanning LineString does not contain the line.",
+        coverage.covers(line));
+  }
+
+  @Test
+  public void testS2CoverageContainsWideNonAntimeridianPolygon() throws ParseException {
+    // Polygon spanning >180° in longitude but NOT crossing the antimeridian (every edge has
+    // |Δlng| < 180°). An envelope-width-based antimeridian heuristic would incorrectly skip
+    // the buffer here and reintroduce GH-2857 miscoverage along the long east-west edges;
+    // the per-edge heuristic correctly leaves the buffer on.
+    String wkt = "POLYGON ((-100 30, 100 30, 100 50, -100 50, -100 30))";

Review Comment:
   In this test, the WKT `POLYGON ((-100 30, 100 30, ...))` includes an edge with |Δlng| = 200 (> 180). With the current `crossesAntimeridian` implementation (|Δlng| > 180 per edge), this polygon will be classified as antimeridian-crossing and the buffer will be skipped, contradicting the comment that it is “NOT crossing the antimeridian” and that the per-edge heuristic “leaves the buffer on”. Consider rewriting the WKT to keep the envelope width > 180 while ensuring every edge has |Δlng| < 180 (e.g., add intermediate vertices), so the test actually exercises the intended non-antimeridian-wide case.
   ```suggestion
       String wkt =
           "POLYGON ((-100 30, -10 30, 100 30, 100 50, 10 50, -100 50, -100 30))";
   ```



##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge (any edge with |Δlng| > 180° must wrap) rather than via the envelope:
+    // the envelope-width heuristic also fires for wide non-straddling polygons (e.g.
+    // a polygon spanning -100° to +100°), which would incorrectly skip the buffer and
+    // reintroduce the GH-2857 miscoverage along their long non-meridional edges.
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.
+   */
+  private static boolean crossesAntimeridian(Geometry geom) {
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      if (ringCrossesAntimeridian(poly.getExteriorRing().getCoordinates())) {
+        return true;
+      }
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        if (ringCrossesAntimeridian(poly.getInteriorRingN(i).getCoordinates())) {
+          return true;
+        }
+      }
+      return false;
+    } else if (geom instanceof LineString) {
+      return ringCrossesAntimeridian(geom.getCoordinates());
+    }
+    return false;
+  }
+
+  private static boolean ringCrossesAntimeridian(Coordinate[] coords) {
+    for (int i = 0; i < coords.length - 1; i++) {
+      if (Math.abs(coords[i + 1].x - coords[i].x) > 180.0) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * the plain Euclidean mean of the (lng, lat) coordinates.

Review Comment:
   The Javadoc says the chord midpoint is the plain Euclidean mean of (lng, lat), but the implementation intentionally wraps the longitude delta into [-180, 180] before averaging to handle antimeridian-spanning edges. Please update the comment to reflect the wrapped-longitude midpoint logic so readers don’t assume it’s a simple `(a.x + b.x)/2`.
   ```suggestion
      * computed in (lng, lat) space by averaging latitude directly and averaging longitude using the
      * wrapped delta in [-180, 180] so antimeridian-spanning edges use the shorter longitudinal span
      * rather than a naive {@code (a.x + b.x) / 2}.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "jiayuasu (via GitHub)" <gi...@apache.org>.
jiayuasu commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144487691


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,252 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge (any edge with |Δlng| > 180° must wrap) rather than via the envelope:
+    // the envelope-width heuristic also fires for wide non-straddling polygons (e.g.
+    // a polygon spanning -100° to +100°), which would incorrectly skip the buffer and
+    // reintroduce the GH-2857 miscoverage along their long non-meridional edges.
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.
+   */
+  private static boolean crossesAntimeridian(Geometry geom) {
+    if (geom instanceof Polygon) {
+      Polygon poly = (Polygon) geom;
+      if (ringCrossesAntimeridian(poly.getExteriorRing().getCoordinates())) {
+        return true;
+      }
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        if (ringCrossesAntimeridian(poly.getInteriorRingN(i).getCoordinates())) {
+          return true;
+        }
+      }
+      return false;
+    } else if (geom instanceof LineString) {
+      return ringCrossesAntimeridian(geom.getCoordinates());
+    }
+    return false;
+  }
+
+  private static boolean ringCrossesAntimeridian(Coordinate[] coords) {
+    for (int i = 0; i < coords.length - 1; i++) {
+      if (Math.abs(coords[i + 1].x - coords[i].x) > 180.0) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Per-edge deviation bound for a ring/path: walk consecutive vertex pairs and return the largest
+   * single-edge great-circle/chord deviation. Used for polygon rings (exterior and interior), where
+   * buffering preserves edge lengths and per-edge analysis is tight.
+   */
+  private static double ringMaxDeviationDegrees(Coordinate[] coords) {
+    double maxDev = 0.0;
+    for (int i = 0; i < coords.length - 1; i++) {
+      double dev = edgeDeviationDegrees(coords[i], coords[i + 1]);
+      if (dev > maxDev) {
+        maxDev = dev;
+      }
+    }
+    return maxDev;
+  }
+
+  /**
+   * Primitive deviation for a single edge: the (lng, lat) distance between the planar chord
+   * midpoint and the great-circle arc midpoint.
+   *
+   * <p>Why the midpoint: a great-circle arc between two points is symmetric about its midpoint, and
+   * the (lng, lat) deviation from the chord is maximized there. So the midpoint deviation equals
+   * the maximum deviation along the edge — there's no need to sample multiple points.
+   *
+   * <p>The great-circle midpoint is computed by averaging the two endpoint S2Points (unit vectors
+   * on the sphere) and renormalizing — a standard spherical-midpoint trick. The chord midpoint is
+   * the plain Euclidean mean of the (lng, lat) coordinates.

Review Comment:
   Fixed in 659a9eee12. The "plain Euclidean mean" wording was correct in an earlier iteration but became stale when the antimeridian fix added wrapped-delta logic. Updated the Javadoc to describe what the code actually does: latitudes averaged directly, longitudes via wrapped delta in [-180, 180] so antimeridian-spanning edges use the shorter longitudinal interval rather than landing on the far side of the globe.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [GH-2857] Fix ST_S2CellIDs under-covering planar polygons along non-meridional edges [sedona]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #2863:
URL: https://github.com/apache/sedona/pull/2863#discussion_r3144500007


##########
common/src/main/java/org/apache/sedona/common/utils/S2Utils.java:
##########
@@ -107,13 +107,260 @@ public static Polygon toJTSPolygon(S2CellId cellId) {
     return new GeometryFactory().createPolygon(coords);
   }
 
+  /**
+   * Convert a JTS planar geometry into an S2Region whose lat/lng projection is guaranteed to
+   * contain the input geometry.
+   *
+   * <p>Why a buffer is needed: Sedona geometries are planar — an edge between two vertices is a
+   * straight line in (lng, lat) space — but S2 connects the same vertices with a great-circle arc
+   * on the sphere. The two interpretations agree at the vertices but diverge along the edges (e.g.
+   * the great-circle arc between two points at the same northern latitude bulges northward, leaving
+   * the parallel that would form the planar chord). If we hand the JTS vertices to S2 directly, the
+   * spherical polygon's interior is *smaller* than the planar polygon's interior along
+   * non-meridional edges, so the S2 covering misses thin slivers of the original planar polygon
+   * (see GH-2857).
+   *
+   * <p>To compensate, we JTS-buffer the input by an upper bound on the worst-case great-circle
+   * deviation before converting to S2. A side effect for {@link LineString} inputs is that the
+   * buffer turns the line into a polygon corridor; downstream callers therefore see cells in a thin
+   * strip around the line rather than only cells the line geometrically traverses.
+   */
   public static S2Region toS2Region(Geometry geom) throws IllegalArgumentException {
+    if (!(geom instanceof Polygon) && !(geom instanceof LineString)) {
+      throw new IllegalArgumentException(
+          "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+    }
+    // JTS planar buffer doesn't understand antimeridian crossing — for inputs that
+    // straddle the antimeridian, buffering produces a polygon that goes the wrong way
+    // around the globe and explodes the S2 covering. Detect antimeridian crossing
+    // per-edge rather than via envelope width: an envelope-width heuristic fires for
+    // any polygon whose bbox spans > 180° of longitude even if no individual edge
+    // does (e.g. a tessellated wide polygon with intermediate vertices), and we'd
+    // incorrectly skip the buffer for those, reintroducing the GH-2857 miscoverage on
+    // their long non-meridional edges. Per-edge |Δlng| > 180° fires only when the
+    // input genuinely contains an edge that wraps the antimeridian. (For a coarse
+    // polygon with a single edge spanning > 180° both heuristics agree, and skipping
+    // the buffer is the safe choice — JTS buffer can't usefully process such an edge
+    // anyway.)
+    boolean spansAntimeridian = crossesAntimeridian(geom);
+    double eps = spansAntimeridian ? 0.0 : arcChordBufferDegrees(geom);
+    Geometry buffered = (eps > 0) ? geom.buffer(eps) : geom;
+    if (buffered instanceof Polygon) {
+      return S2Utils.toS2Polygon((Polygon) buffered);
+    } else if (buffered instanceof LineString) {
+      // Only reachable when eps == 0 (e.g. a single-point degenerate line). Normal lines
+      // become Polygon corridors after buffer and are handled above.
+      return S2Utils.toS2PolyLine((LineString) buffered);
+    } else if (buffered instanceof MultiPolygon && buffered.getNumGeometries() > 0) {
+      // JTS buffer of self-touching geometries can collapse to MultiPolygon. Build a single
+      // S2Polygon containing every component's loops so the resulting region still contains
+      // every part of the buffered geometry; dropping components would silently break the
+      // containment guarantee for the discarded shells.
+      List<S2Loop> loops = new ArrayList<>();
+      for (int i = 0; i < buffered.getNumGeometries(); i++) {
+        Polygon p = (Polygon) buffered.getGeometryN(i);
+        loops.add(toS2Loop(p.getExteriorRing()));
+        for (int j = 0; j < p.getNumInteriorRing(); j++) {
+          loops.add(toS2Loop(p.getInteriorRingN(j)));
+        }
+      }
+      return new S2Polygon(loops);
+    }
+    throw new IllegalArgumentException(
+        "only Polygon or LineString (including LinearRing) types can be converted to S2Region");
+  }
+
+  /**
+   * Compute the JTS buffer amount (in degrees) needed so that the spherical interpretation of the
+   * buffered geometry fully contains the original planar geometry.
+   *
+   * <p>The buffer must be at least as large as the largest great-circle/chord deviation among the
+   * edges that S2 will eventually see. Polygons and lines need different bounds because JTS buffer
+   * affects their edges differently:
+   *
+   * <ul>
+   *   <li><b>Polygon</b>: each existing edge is offset perpendicularly in place; corners get
+   *       rounded into many short arcs, but no edge is dramatically lengthened. The buffered
+   *       polygon's edges therefore have ~the same length as the originals, so the original
+   *       polygon's per-edge deviation is a tight upper bound on what the buffered polygon's edges
+   *       will exhibit. We use {@link #ringMaxDeviationDegrees}.
+   *   <li><b>LineString</b>: buffering produces a corridor whose long top/bottom edges span the
+   *       line's full envelope — far longer than any individual segment when consecutive segments
+   *       are collinear (JTS often simplifies them away). Per-segment deviation severely
+   *       under-bounds the corridor's actual edge deviation. We bound by virtual edges across the
+   *       envelope via {@link #envelopeDeviationDegrees}.
+   * </ul>
+   *
+   * <p>The 1.5× safety multiplier absorbs numerical error and the small additional deviation the
+   * buffered polygon's own (slightly different) edges introduce on top of the bound.
+   */
+  private static double arcChordBufferDegrees(Geometry geom) {
+    double maxDev = 0.0;
     if (geom instanceof Polygon) {
-      return S2Utils.toS2Polygon((Polygon) geom);
+      Polygon poly = (Polygon) geom;
+      maxDev = Math.max(maxDev, ringMaxDeviationDegrees(poly.getExteriorRing().getCoordinates()));
+      for (int i = 0; i < poly.getNumInteriorRing(); i++) {
+        maxDev =
+            Math.max(maxDev, ringMaxDeviationDegrees(poly.getInteriorRingN(i).getCoordinates()));
+      }
     } else if (geom instanceof LineString) {
-      return S2Utils.toS2PolyLine((LineString) geom);
+      maxDev = envelopeDeviationDegrees(geom);
     }
-    throw new IllegalArgumentException(
-        "only object of Polygon, LinearRing, LineString type can be converted to S2Region");
+    return maxDev * 1.5;
+  }
+
+  /**
+   * Conservative deviation upper bound for a geometry, derived from its bounding envelope rather
+   * than its actual edges.
+   *
+   * <p>Used for {@link LineString} inputs because, after JTS buffer, the corridor's long edges are
+   * not the line's segments — they connect the line's extreme endpoints (or close to it). To bound
+   * them we probe three virtual edges across the envelope:
+   *
+   * <ul>
+   *   <li>The two diagonals (SW–NE and NW–SE) — diagonal great-circle arcs deviate more than
+   *       east-west arcs of the same Δλ at high latitudes, and a buffered corridor's long edges can
+   *       run in either direction depending on the line's orientation.
+   *   <li>The worst-case east-west edge at whichever latitude (top or bottom of the envelope) has
+   *       the larger absolute value — east-west arcs bulge poleward, so the deviation grows with
+   *       |latitude|, and an envelope-spanning east-west arc is what a horizontal collinear line
+   *       would buffer into.
+   * </ul>
+   *
+   * <p>The max across these three bounds the deviation any corridor edge could plausibly exhibit.
+   * This deliberately over-bounds zigzag lines whose actual corridor edges are short; the
+   * alternative (per-segment analysis) silently fails on collinear inputs.
+   */
+  private static double envelopeDeviationDegrees(Geometry geom) {
+    Envelope env = geom.getEnvelopeInternal();
+    if (env.isNull()) {
+      return 0.0;
+    }
+    if (crossesAntimeridian(geom)) {
+      // JTS envelopes don't understand antimeridian crossing — a line from (179, y) to
+      // (-179, y) reports a 358°-wide envelope even though the actual edge is 2° long. The
+      // envelope-corner virtual edges would then describe a near-globe-spanning chord and
+      // produce a meaninglessly huge deviation. For such inputs, fall back to per-segment
+      // analysis, which works directly off the actual edges and is correct regardless of
+      // antimeridian crossings.
+      return ringMaxDeviationDegrees(geom.getCoordinates());
+    }
+    Coordinate sw = new Coordinate(env.getMinX(), env.getMinY());
+    Coordinate se = new Coordinate(env.getMaxX(), env.getMinY());
+    Coordinate ne = new Coordinate(env.getMaxX(), env.getMaxY());
+    Coordinate nw = new Coordinate(env.getMinX(), env.getMaxY());
+    // For the east-west probe, pick whichever latitude band of the envelope is further from
+    // the equator — that's where same-Δλ great-circle arcs deviate most from the chord.
+    double signedLat =
+        Math.abs(env.getMinY()) > Math.abs(env.getMaxY()) ? env.getMinY() : env.getMaxY();
+    Coordinate ewWest = new Coordinate(env.getMinX(), signedLat);
+    Coordinate ewEast = new Coordinate(env.getMaxX(), signedLat);
+    double max = edgeDeviationDegrees(sw, ne);
+    max = Math.max(max, edgeDeviationDegrees(nw, se));
+    max = Math.max(max, edgeDeviationDegrees(ewWest, ewEast));
+    return max;
+  }
+
+  /**
+   * Detect whether {@code geom} crosses the antimeridian by walking its edges and checking whether
+   * any has an absolute longitudinal delta greater than 180°. An edge from (179°, y) to (-179°, y)
+   * is 2° long going across the antimeridian but 358° in raw lng deltas, so |Δlng| > 180° is a
+   * reliable per-edge antimeridian indicator. Using the actual edges (not the envelope width)
+   * avoids false positives for wide non-straddling polygons like one spanning -100° to +100°.

Review Comment:
   The Javadoc for `crossesAntimeridian` says the per-edge `|Δlng| > 180°` test “avoids false positives for wide non-straddling polygons like one spanning -100° to +100°”, but a direct edge from -100° to +100° has |Δlng|=200 and *will* be classified as crossing by this predicate. Please reword this sentence to match the actual behavior (e.g., the differentiating case is a tessellated wide polygon whose envelope spans >180° but every individual edge stays <180°).
   ```suggestion
      * avoids false positives for wide non-straddling geometries whose overall longitude span may
      * exceed 180° but whose individual edges all stay at or below 180°, such as a tessellated
      * polygon spanning -100° to +100°.
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org