diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index f94bb36f212..356edbba535 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -143,6 +143,7 @@ jobs: SKIP_TESTS: ${{ matrix.skipTests }} SEDONA_SKIP_LIBPOSTAL_TESTS: ${{ matrix.skipLibPostalTests }} FLINK_VERSION: ${{ matrix.flinkVersion }} + PYTHONPATH: ${{ github.workspace }}/python run: | SPARK_COMPAT_VERSION="${SPARK_VERSION:0:3}" diff --git a/docs/setup/install-scala.md b/docs/setup/install-scala.md index 928363dce6b..8f1bc96f72b 100644 --- a/docs/setup/install-scala.md +++ b/docs/setup/install-scala.md @@ -92,3 +92,5 @@ A self-contained project allows you to create multiple Scala / Java files and wr !!!note The detailed explanation of spark-submit is available on [Spark website](https://spark.apache.org/docs/latest/submitting-applications.html). + +See [Spark SQL geometry serialization](sql-geometry-serialization.md) before upgrading data stored with the legacy geometry UDT payload. diff --git a/docs/setup/sql-geometry-serialization.md b/docs/setup/sql-geometry-serialization.md new file mode 100644 index 00000000000..708fe4717db --- /dev/null +++ b/docs/setup/sql-geometry-serialization.md @@ -0,0 +1,81 @@ + + +# Spark SQL spatial serialization + +Starting in v2.0.0, Spark SQL geometry values use a signed four-byte little-endian SRID followed by ISO WKB internally. The JVM uses the public JTS IO implementation and Python uses Shapely WKB. The WKB type codes use ISO offsets (1000 for Z, 2000 for M, 3000 for ZM), and the writer emits little-endian WKB. Readers accept either WKB byte order; the SRID prefix is always little-endian. The prefix supplies the SRID for the whole geometry, including collection members. The SQL transport preserves SRID and supported XY, XYZ, XYM and XYZM layouts, including dimensional empties. Python M support depends on the installed Shapely/GEOS version. + +The UDT payload is not a standalone WKB/EWKB value: use `ST_AsBinary` or `ST_AsEWKB` for explicit interchange columns. This changes the internal payload of `GeometryUDT`; it does not change its SQL type name or the Python Shapely geometry API. The JVM writer retains its existing layout validation: explicitly different layouts within a polygon or multipart geometry are rejected, while general geometry collection members can retain independent layouts. Python follows Shapely's public WKB representation, which can preserve mixed member layouts instead of applying the compact SQL serializer's single-layout promotion. When Shapely/GEOS retains the declared dimensions, an XY/XYZ `MultiPoint` remains distinct from an all-XYZ `MultiPoint` whose first Z is NaN in `geom_equals_identical`. GEOS versions before 3.12 can treat a NaN-Z member as XY before Sedona receives the value. The public JVM WKB writer canonicalizes NaN payload bits and represents a point whose X and Y are both NaN as `POINT EMPTY`. SRIDs use the full signed 32-bit prefix instead of the compact format's 24-bit field. Finite coordinates and supported coordinate dimensions are preserved. + +## Geography SQL values + +`GeographyUDT` uses the same four-byte little-endian SRID prefix and ISO WKB contract. Geography retains its non-negative SRID requirement. The SQL payload uses ISO WKB without embedded SRIDs. The JVM preserves the WKB byte order and coordinate bytes of lazy geography values while normalizing their headers to ISO types; computed S2 values use the public S2 WKB writer. Python uses public Shapely WKB. This changes SQL transport only: S2 spherical computation, lazy/eager shape-index behavior and the Python `Geography` wrapper are preserved. + +Geometry and geography UDT payloads have the same framing, but their type metadata and computation remain distinct. They are also distinct from Spark 4.2 native spatial values, which use Spark's default serializer and native CRS validation. + +## Migrating persisted UDT values + +An ordinary Parquet file written with the old `GeometryUDT` can contain Sedona's compact serialization bytes under UDT metadata. These bytes are not the new SRID-prefixed ISO WKB payload and are not automatically converted by the new reader. The reader does not guess the stored encoding. Export such data with the old Sedona version before upgrading. For example: + +```python +# Run with the Sedona version that wrote the original UDT data. +old_df = sedona.read.parquet("old-udt-data") +old_df.selectExpr("id", "ST_AsEWKB(geom) AS geom_wkb").write.parquet( + "portable-wkb-data" +) +``` + +Then load the portable binary column with the new version: + +```python +portable_df = sedona.read.parquet("portable-wkb-data") +new_df = portable_df.selectExpr("id", "ST_GeomFromWKB(geom_wkb) AS geom") +``` + +Include the remaining non-geometry columns in the projection as appropriate. Check row counts, nulls, SRIDs and coordinate dimensions after migrating. Standard GeoParquet and explicit WKB/EWKB columns already use portable geometry encodings and do not need this compact-UDT conversion. + +### Geography UDT files + +Earlier `GeographyUDT` files contain a **big-endian** SRID prefix followed by WKB. The new SQL reader expects a **little-endian** prefix. Export these files with the version that wrote them before upgrading, even though their WKB coordinate payload may already be valid ISO WKB. There is no automatic format detection: SRID 0 looks identical, SRID 4326 becomes negative when byte-swapped, and SRID 1 can silently become 16777216. + +Export explicit EWKB and SRID columns with the old version. Convert to geometry only for this transport operation; the restored column remains geography: + +```python +old_df = sedona.read.parquet("old-geography-udt-data") +old_df.selectExpr( + "id", + "ST_AsEWKB(ST_GeogToGeometry(geog)) AS geog_wkb", + "ST_SRID(ST_GeogToGeometry(geog)) AS geog_srid", +).write.parquet("portable-geography-data") +``` + +On Spark 3.5–4.1, reconstruct geography with the new version and the explicit SRID column: + +```python +portable_df = sedona.read.parquet("portable-geography-data") +new_df = portable_df.selectExpr("id", "ST_GeogFromWKB(geog_wkb, geog_srid) AS geog") +``` + +Include other columns as needed and verify row counts, nulls, SRIDs, coordinate dimensions and representative spherical operations. Spark 4.2 native geography additionally requires a supported native CRS; changing the UDT framing does not relax that validation. Its built-in `ST_GeogFromWKB` takes one argument, so the two-argument reconstruction above is specific to older runtimes. Keep the separate SRID column when planning a native migration: EWKB writers can omit SRID 0, and a native constructor treats an absent CRS as 4326. Use an explicit Sedona UDT schema when retaining values outside the native contract rather than silently assigning a different CRS. Never relabel old geography bytes as new UDT data or infer their prefix byte order from the SRID's value. + +## Scope + +The RDD/Kryo geometry and geography serializers, spatial-index serializers, Python RDD framing and Flink serialization retain their existing formats. In particular, the common geography serializer used by these paths keeps its big-endian SRID prefix. Only Spark SQL geography callers use the new SQL serializer. Standard GeoParquet and explicit WKB/EWKB columns are unaffected by this UDT framing migration. + +Application code should pass Shapely objects through `GeometryType` or use SQL WKB functions at external boundaries. The legacy `geometry_serde` utilities remain available for their existing compact-format contract; their bytes are no longer the SQL geometry payload. diff --git a/python/sedona/spark/sql/functions.py b/python/sedona/spark/sql/functions.py index 354f459afc0..5ddfdc4f33b 100644 --- a/python/sedona/spark/sql/functions.py +++ b/python/sedona/spark/sql/functions.py @@ -22,7 +22,10 @@ import pandas as pd from sedona.spark.sql.types import GeometryType -from sedona.spark.utils import geometry_serde +from sedona.spark.utils.geometry_sql_serde import ( + deserialize_geometry, + serialize_geometry, +) from pyspark.sql.udf import UserDefinedFunction from pyspark.sql.types import DataType from shapely.geometry.base import BaseGeometry @@ -93,15 +96,13 @@ def _apply_shapely_series_udf( def apply(series: pd.Series) -> pd.Series: applied = series.apply( lambda x: ( - fn(geometry_serde.deserialize(x)[0]) + fn(deserialize_geometry(x)) if deserialize_geom and x is not None else fn(x) ) ) - return applied.apply( - lambda x: geometry_serde.serialize(x) if serialize_geom else x - ) + return applied.apply(lambda x: serialize_geometry(x) if serialize_geom else x) udf = UserDefinedFunction( apply, return_type, "SedonaPandasArrowUDF", evalType=SEDONA_SCALAR_EVAL_TYPE @@ -120,9 +121,7 @@ def apply(series: pd.Series) -> pd.Series: if deserialize_geom: series_data = gpd.GeoSeries( series.apply( - lambda x: ( - geometry_serde.deserialize(x)[0] if x is not None else None - ) + lambda x: (deserialize_geometry(x) if x is not None else None) ) ) @@ -131,7 +130,7 @@ def apply(series: pd.Series) -> pd.Series: # GeoSeries.apply retains geometry dtype for empty or all-null # results, which Arrow cannot convert to the binary storage type. return pd.Series( - [geometry_serde.serialize(geom) for geom in result], + [serialize_geometry(geom) for geom in result], index=result.index, dtype=object, ) @@ -144,13 +143,13 @@ def apply(series: pd.Series) -> pd.Series: def deserialize_geometry_if_geom(data): if isinstance(data, BaseGeometry): - return geometry_serde.deserialize(data)[0] + return deserialize_geometry(data) return data def serialize_to_geometry_if_geom(data, return_type: DataType): if isinstance(return_type, GeometryType): - return geometry_serde.serialize(data) + return serialize_geometry(data) return data diff --git a/python/sedona/spark/sql/types.py b/python/sedona/spark/sql/types.py index bb76f771569..06861c5d179 100644 --- a/python/sedona/spark/sql/types.py +++ b/python/sedona/spark/sql/types.py @@ -38,7 +38,10 @@ raster_serde = None SedonaRaster = None -from sedona.spark.utils import geometry_serde +from sedona.spark.utils.geometry_sql_serde import ( + deserialize_geometry, + serialize_geometry, +) from sedona.spark.core.geom.geography import Geography from sedona.spark.core.geom.box2d import Box2D from sedona.spark.core.geom.box3d import Box3D @@ -70,11 +73,10 @@ def sqlType(cls): return BinaryType() def serialize(self, obj): - return geometry_serde.serialize(obj) + return serialize_geometry(obj) def deserialize(self, datum): - geom, offset = geometry_serde.deserialize(datum) - return geom + return deserialize_geometry(datum) @classmethod def module(cls): diff --git a/python/sedona/spark/utils/geography_sql_serde.py b/python/sedona/spark/utils/geography_sql_serde.py index 416d6588bf6..23e9f08935a 100644 --- a/python/sedona/spark/utils/geography_sql_serde.py +++ b/python/sedona/spark/utils/geography_sql_serde.py @@ -15,52 +15,31 @@ # specific language governing permissions and limitations # under the License. -"""Python transport for the existing JVM geography UDT: big-endian SRID and WKB.""" +"""SQL geography transport: little-endian signed SRID followed by ISO WKB.""" import struct from sedona.spark.core.geom.geography import Geography -from sedona.spark.utils import geometry_wkb - -_SRID_FLAG = 0x20000000 +from sedona.spark.utils import geometry_sql_serde def serialize_geography(geography): - """Encode a geography without changing the JVM geography or RDD formats.""" + """Encode SQL geography while preserving its non-negative SRID requirement.""" if geography is None: return None - payload = geometry_wkb.dumps(geography.geometry) - geometry_type = struct.unpack_from("i", srid) + payload + return payload def deserialize_geography(value): - """Decode the JVM's SRID prefix using Shapely's public EWKB reader.""" + """Decode SQL geography with the outer SRID as the authoritative value.""" if value is None: return None value = bytes(value) if len(value) < 9: raise ValueError("Geography payload must contain a four-byte SRID and WKB") - srid = struct.unpack_from(">i", value)[0] - if srid < 0: + if struct.unpack_from("" - geometry_type = struct.unpack_from(endian + "I", payload, 1)[0] - offset = 9 if geometry_type & _SRID_FLAG else 5 - # The outer SRID is authoritative. Embedding it in EWKB lets both Shapely - # 1.x and 2.x retain it without direct access to GEOS pointers. - ewkb = ( - payload[:1] - + struct.pack(endian + "Ii", geometry_type | _SRID_FLAG, srid) - + payload[offset:] - ) - return Geography(geometry_wkb.loads(ewkb)) + return Geography(geometry_sql_serde.deserialize_geometry(value)) diff --git a/python/sedona/spark/utils/geometry_sql_serde.py b/python/sedona/spark/utils/geometry_sql_serde.py new file mode 100644 index 00000000000..a01ec0e7082 --- /dev/null +++ b/python/sedona/spark/utils/geometry_sql_serde.py @@ -0,0 +1,123 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""SQL geometry transport: little-endian signed SRID followed by ISO WKB.""" + +import struct + +import shapely + +from sedona.spark.utils import geometry_wkb + + +def serialize_geometry(geometry): + """Encode a SQL geometry, retaining its SRID and supported coordinate dimensions.""" + if geometry is None: + return None + srid = geometry_wkb._get_srid(geometry) + if hasattr(shapely, "to_wkb") and geometry_wkb.geos_version >= (3, 10, 0): + payload = shapely.to_wkb( + geometry, + byte_order=1, + include_srid=False, + flavor="iso", + output_dimension=( + 4 + if hasattr(shapely, "has_m") and shapely.geos_version >= (3, 12, 0) + else 3 + ), + ) + else: + # Keep the shared writer's older-GEOS empty and Shapely 1.x type fixes. + # Only WKB headers are adapted; ordinates remain the public writer's bytes. + payload = _iso_headers(geometry_wkb.dumps(geometry)) + return struct.pack("" + geometry_type = struct.unpack_from(endian + "I", payload, 1)[0] + # The public EWKB reader restores SRID on Shapely 1.x as well as 2.x. + # Convert the root ISO type offset to EWKB flags before adding its SRID. + plain = geometry_type & 0x1FFFFFFF + layout, base = divmod(plain, 1000) + if layout > 3 or not 1 <= base <= 7: + raise ValueError("Invalid geometry WKB type") + flags = geometry_type & 0xC0000000 + if layout in (1, 3): + flags |= 0x80000000 + if layout in (2, 3): + flags |= 0x40000000 + offset = 9 if geometry_type & 0x20000000 else 5 + ewkb = ( + payload[:1] + + struct.pack(endian + "Ii", base | flags | 0x20000000, srid) + + payload[offset:] + ) + return geometry_wkb.loads(ewkb) + + +def _iso_headers(source): + """Adapt the legacy public writer's little-endian EWKB headers to ISO WKB.""" + result = bytearray() + position = 0 + pending = 1 + + def copy(size): + nonlocal position + end = position + size + if end > len(source): + raise ValueError("Invalid geometry WKB framing") + result.extend(source[position:end]) + position = end + + def count(): + value = struct.unpack_from("= (3, 12, 0) +LAYOUTS = [ + (0, (1.0, 2.0)), + (1000, (1.0, 2.0, 3.0)), + pytest.param( + 2000, + (1.0, 2.0, 3.0), + marks=pytest.mark.skipif(not HAS_M, reason="Shapely cannot retain M"), + ), + pytest.param( + 3000, + (1.0, 2.0, 3.0, 4.0), + marks=pytest.mark.skipif(not HAS_M, reason="Shapely cannot retain M"), + ), +] + def _point_wkb(endian="<", srid=None): header = struct.pack( @@ -42,26 +58,59 @@ def _srid(geometry): return struct.unpack_from("i", srid) + _point_wkb() + GeographyType().serialize(geography) == struct.pack(""]) -@pytest.mark.parametrize("srid", [0, 4326]) +@pytest.mark.parametrize("srid", [0, 1, 4326]) def test_decode_jvm_geography_in_either_wkb_byte_order(endian, srid): - value = GeographyType().deserialize(struct.pack(">i", srid) + _point_wkb(endian)) + value = GeographyType().deserialize(struct.pack("i", 4269) + _point_wkb(srid=4326)) - assert _srid(value.geometry) == 4269 +@pytest.mark.parametrize("srid", [0, 1, 4269]) +def test_outer_srid_is_authoritative_for_embedded_ewkb(srid): + value = GeographyType().deserialize(struct.pack("= (3, 12, 0) +LAYOUTS = [ + (0, (1.0, 2.0)), + (1000, (1.0, 2.0, 3.0)), + pytest.param( + 2000, + (1.0, 2.0, 3.0), + marks=pytest.mark.skipif(not HAS_M, reason="Shapely cannot retain M"), + ), + pytest.param( + 3000, + (1.0, 2.0, 3.0, 4.0), + marks=pytest.mark.skipif(not HAS_M, reason="Shapely cannot retain M"), + ), +] + + +def _with_srid(geometry, srid): + return wkb.loads(wkb.dumps(geometry, srid=srid, include_srid=True)) + + +def _srid(geometry): + payload = wkb.dumps(geometry, big_endian=False, include_srid=True) + flags = struct.unpack_from(""]) +@pytest.mark.parametrize("buffer_type", [bytes, bytearray, memoryview]) +def test_geometry_udt_reads_external_iso_wkb_and_owns_coordinates( + byte_order, buffer_type +): + source = bytearray( + struct.pack(""]) +def test_geometry_udt_preserves_full_signed_srid(srid, byte_order): + payload = struct.pack(" b.BaseGeometry: udf = ( translate_batch if udf_type == SedonaUDFType.GEO_SERIES else translate_geometry ) - encoded = pd.Series([geometry_serde.serialize(geom) for geom in geometries]) + encoded = pd.Series([serialize_geometry(geom) for geom in geometries]) result = udf.func(encoded) arrow_result = pa.Array.from_pandas(result, type=pa.binary()) assert arrow_result.to_pylist() == list(result) @@ -117,8 +120,13 @@ def translate_geometry(geom: b.BaseGeometry) -> b.BaseGeometry: for actual, geometry in zip(result, expected): if geometry is None: assert actual is None + elif geometry.is_empty: + # Shapely 1.x Point() internally holds an empty GeometryCollection. + decoded = deserialize_geometry(actual) + assert decoded.is_empty + assert decoded.geom_type == type(geometry).__name__ else: - assert geometry_serde.deserialize(actual)[0].equals_exact(geometry, 0) + assert deserialize_geometry(actual).equals_exact(geometry, 0) def test_shapely_scalar_udf_passes_null_to_callback(): @@ -127,7 +135,7 @@ def replace_null(geom: b.BaseGeometry) -> b.BaseGeometry: return Point(9, 10) if geom is None else geom result = replace_null.func(pd.Series([None])) - assert geometry_serde.deserialize(result.iloc[0])[0].equals_exact(Point(9, 10), 0) + assert deserialize_geometry(result.iloc[0]).equals_exact(Point(9, 10), 0) class TestSedonaArrowUDF(TestBase): diff --git a/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java new file mode 100644 index 00000000000..f68bb7aa936 --- /dev/null +++ b/spark/common/src/main/java/org/apache/spark/sql/sedona_sql/types/PublicWkbHeaderAdapter.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.spark.sql.sedona_sql.types; + +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** Converts public WKB headers to ISO types without changing coordinate bytes. */ +public final class PublicWkbHeaderAdapter { + public static byte[] toIsoWkb(byte[] source) { + Cursor sizing = new Cursor(source, null); + int length = sizing.walk(); + if (!sizing.changed) return source; + byte[] result = new byte[length]; + new Cursor(source, result).walk(); + return result; + } + + private static final class Cursor { + final byte[] source; + final ByteBuffer input, output; + int outputSize; + boolean changed; + + Cursor(byte[] source, byte[] target) { + this.source = source; + input = ByteBuffer.wrap(source); + output = target == null ? null : ByteBuffer.wrap(target); + } + + IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid WKB framing at byte " + input.position()); + } + + int count() { + int n = input.getInt(); + if (n < 0) throw invalid(); + if (output != null) output.putInt(n); + outputSize += Integer.BYTES; + return n; + } + + void coordinates(long bytes) { + if (bytes > input.remaining()) throw invalid(); + int n = (int) bytes; + if (output != null) output.put(source, input.position(), n); + outputSize += n; + input.position(input.position() + n); + } + + int walk() { + try { + long pending = 1; + while (pending-- > 0) { + byte endian = input.get(); + if (endian != 0 && endian != 1) throw invalid(); + ByteOrder order = endian == 1 ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; + input.order(order); + int code = input.getInt(), plain = code & 0x1fffffff; + int base = plain % 1000, layout = plain / 1000; + if (base < 1 || base > 7 || layout > 3) throw invalid(); + boolean z = (code & 0x80000000) != 0 || layout == 1 || layout == 3; + boolean m = (code & 0x40000000) != 0 || layout == 2 || layout == 3; + int iso = base + (z ? 1000 : 0) + (m ? 2000 : 0); + int dimensions = 2 + (z ? 1 : 0) + (m ? 1 : 0); + if ((code & 0x20000000) != 0) input.getInt(); // Caller supplies the SRID separately. + changed |= code != iso; + if (output != null) output.order(order).put(endian).putInt(iso); + outputSize += 5; + switch (base) { + case 1: + coordinates(dimensions * 8L); + break; + case 2: + coordinates(count() * (dimensions * 8L)); + break; + case 3: + int rings = count(); + if (rings > input.remaining() / 4) throw invalid(); + for (int i = 0; i < rings; i++) coordinates(count() * (dimensions * 8L)); + break; + default: + pending += count(); + } + if (pending > input.remaining() / 5) throw invalid(); + } + coordinates(input.remaining()); // Leave trailing-byte acceptance to the caller. + return outputSize; + } catch (BufferUnderflowException e) { + throw invalid(); + } + } + } +} diff --git a/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeographySerializer.scala b/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeographySerializer.scala new file mode 100644 index 00000000000..dd8dcb46dfa --- /dev/null +++ b/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeographySerializer.scala @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sedona.sql.utils + +import java.nio.{ByteBuffer, ByteOrder} +import java.util.Arrays + +import org.apache.sedona.common.S2Geography.{Geography, WKBGeography, WKBWriter} +import org.apache.spark.sql.sedona_sql.types.PublicWkbHeaderAdapter +import org.locationtech.jts.io.ByteOrderValues + +/** SQL geography transport. The common geography serializer retains its separate RDD format. */ +object GeographySerializer { + def serialize(geography: Geography): Array[Byte] = { + if (geography == null) return null + val source = geography match { + // Preserve lazy coordinates and layouts without constructing JTS or S2 objects. + case value: WKBGeography => value.getWKBBytes + case _ => new WKBWriter(2, ByteOrderValues.LITTLE_ENDIAN, false).write(geography) + } + val wkb = PublicWkbHeaderAdapter.toIsoWkb(source) + ByteBuffer + .allocate(Integer.BYTES + wkb.length) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(geography.getSRID) + .put(wkb) + .array() + } + + def deserialize(value: Array[Byte]): Geography = { + if (value == null) return null + if (value.length < Integer.BYTES + 5) { + throw new IllegalArgumentException("Truncated SQL geography payload") + } + // Geography retains WKB, so it must own its bytes rather than alias a mutable row buffer. + // The public factory also retains the configured eager/lazy S2 initialization behavior. + WKBGeography.fromWKB(Arrays.copyOfRange(value, Integer.BYTES, value.length), readSRID(value)) + } + + def readSRID(value: Array[Byte]): Int = { + if (value.length < Integer.BYTES) { + throw new IllegalArgumentException("Truncated spatial SRID header") + } + ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).getInt + } +} diff --git a/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeometrySerializer.scala b/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeometrySerializer.scala index a75a88f7ba2..3aff008aa84 100644 --- a/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeometrySerializer.scala +++ b/spark/common/src/main/scala/org/apache/sedona/sql/utils/GeometrySerializer.scala @@ -18,11 +18,18 @@ */ package org.apache.sedona.sql.utils -import org.apache.sedona.common.geometrySerde +import java.nio.{ByteBuffer, ByteOrder} +import java.util.Arrays + +import org.apache.sedona.common.geometrySerde.{GeometrySerializer => LayoutPolicy} +import org.apache.spark.sql.sedona_sql.types.PublicWkbHeaderAdapter +import org.datasyslab.jts.io.{WKBReader, WKBWriter} import org.locationtech.jts.geom.{Geometry, GeometryFactory} +import org.locationtech.jts.io.{ByteOrderValues, ParseException} /** - * SerDe using the WKB reader and writer objects + * SQL geometry transport: a signed little-endian int32 SRID followed by ISO WKB. RDD/index + * serializers use their separate compact format. */ object GeometrySerializer { @@ -32,17 +39,39 @@ object GeometrySerializer { * @param geometry * JTS geometry * @return - * Array of bites represents this geometry + * SRID-prefixed ISO WKB preserving coordinate dimensions */ def serialize(geometry: Geometry): Array[Byte] = { - geometrySerde.GeometrySerializer.serialize(geometry) + if (geometry == null) return null + validateLayout(geometry) + val writer = new WKBWriter(4, ByteOrderValues.LITTLE_ENDIAN, false) + writer.setPreserveCoordinateDimensions(true) + val wkb = PublicWkbHeaderAdapter.toIsoWkb(writer.write(geometry)) + ByteBuffer + .allocate(Integer.BYTES + wkb.length) + .order(ByteOrder.LITTLE_ENDIAN) + .putInt(geometry.getSRID) + .put(wkb) + .array() + } + + // Preserve the existing layout contract without using compact byte serialization. + // General collections have independent member layouts; polygons and multipart values do not. + private def validateLayout(geometry: Geometry): Unit = { + if (geometry != null) { + if (geometry.getGeometryType == "GeometryCollection") { + (0 until geometry.getNumGeometries).foreach(i => validateLayout(geometry.getGeometryN(i))) + } else { + LayoutPolicy.getCoordinateType(geometry) + } + } } /** - * Given ArrayData returns Geometry + * Given SRID-prefixed ISO WKB bytes returns Geometry * * @param value - * ArrayData + * SRID-prefixed ISO WKB bytes * @return * JTS geometry */ @@ -50,6 +79,18 @@ object GeometrySerializer { if (value == null) { return new GeometryFactory().createGeometryCollection() } - geometrySerde.GeometrySerializer.deserialize(value) + if (value.length < Integer.BYTES) { + throw new IllegalArgumentException("Truncated spatial SRID header") + } + val srid = ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).getInt + try { + // The byte-array reader bounds declared counts by payload size; its stream entry point does not. + WKBReader + .forDeclaredDimensions(srid) + .read(Arrays.copyOfRange(value, Integer.BYTES, value.length)) + } catch { + case e: ParseException => + throw new IllegalArgumentException("Invalid serialized Geometry", e) + } } } diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/UDT/GeographyUDT.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/UDT/GeographyUDT.scala index d2092372470..59f554d7736 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/UDT/GeographyUDT.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/UDT/GeographyUDT.scala @@ -21,7 +21,8 @@ package org.apache.spark.sql.sedona_sql.UDT import org.apache.spark.sql.types._ import org.json4s.JsonDSL._ import org.json4s.JsonAST.JValue -import org.apache.sedona.common.S2Geography.{GeographyWKBSerializer, Geography} +import org.apache.sedona.common.S2Geography.Geography +import org.apache.sedona.sql.utils.GeographySerializer class GeographyUDT extends UserDefinedType[Geography] { override def sqlType: DataType = BinaryType @@ -31,11 +32,11 @@ class GeographyUDT extends UserDefinedType[Geography] { override def userClass: Class[Geography] = classOf[Geography] override def serialize(obj: Geography): Array[Byte] = - GeographyWKBSerializer.serialize(obj) + GeographySerializer.serialize(obj) override def deserialize(datum: Any): Geography = { datum match { - case value: Array[Byte] => GeographyWKBSerializer.deserialize(value) + case value: Array[Byte] => GeographySerializer.deserialize(value) } } diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/ST_CollectAgg.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/ST_CollectAgg.scala index 097dd5ef324..8337a943954 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/ST_CollectAgg.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/ST_CollectAgg.scala @@ -23,9 +23,8 @@ import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, Da import scala.collection.mutable.ArrayBuffer import org.apache.sedona.common.Functions -import org.apache.sedona.common.S2Geography.GeographyWKBSerializer import org.apache.sedona.common.geography.{Functions => GeographyFunctions} -import org.apache.sedona.sql.utils.GeometrySerializer +import org.apache.sedona.sql.utils.{GeographySerializer, GeometrySerializer} import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{Expression, ImplicitCastInputTypes} import org.apache.spark.sql.catalyst.expressions.aggregate.{ImperativeAggregate, TypedImperativeAggregate} @@ -93,9 +92,8 @@ private[apache] case class ST_Collect_Agg( if (buffer.isEmpty) { null } else if (isGeography) { - val geographies = buffer.map(GeographyWKBSerializer.deserialize) - GeographyWKBSerializer.serialize( - GeographyFunctions.createMultiGeography(geographies.toArray)) + val geographies = buffer.map(GeographySerializer.deserialize) + GeographySerializer.serialize(GeographyFunctions.createMultiGeography(geographies.toArray)) } else { val geometries = buffer.map(GeometrySerializer.deserialize) GeometrySerializer.serialize(Functions.createMultiGeometry(geometries.toArray)) @@ -163,19 +161,9 @@ private object ST_Collect_Agg { inputExpressions.head } - private def readGeographySRID(value: Array[Byte]): Int = { - if (value.length < Integer.BYTES) { - throw new IllegalArgumentException("Invalid serialized Geography in ST_Collect_Agg") - } - ((value(0) & 0xff) << 24) | - ((value(1) & 0xff) << 16) | - ((value(2) & 0xff) << 8) | - (value(3) & 0xff) - } - private def requireMatchingSRID(left: Array[Byte], right: Array[Byte]): Unit = { - val leftSRID = readGeographySRID(left) - val rightSRID = readGeographySRID(right) + val leftSRID = GeographySerializer.readSRID(left) + val rightSRID = GeographySerializer.readSRID(right) if (leftSRID != rightSRID) { throw new IllegalArgumentException( s"ST_Collect_Agg requires all Geography inputs to have the same SRID; " + diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/implicits.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/implicits.scala index bdbd88db664..c38b85b75e2 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/implicits.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/expressions/implicits.scala @@ -18,9 +18,9 @@ */ package org.apache.spark.sql.sedona_sql.expressions -import org.apache.sedona.common.S2Geography.{Geography, GeographyWKBSerializer} +import org.apache.sedona.common.S2Geography.Geography import org.apache.sedona.common.geometryObjects.{Box2D, Box3D} -import org.apache.sedona.sql.utils.GeometrySerializer +import org.apache.sedona.sql.utils.{GeographySerializer, GeometrySerializer} import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.Expression import org.apache.spark.sql.catalyst.util.ArrayData @@ -68,7 +68,7 @@ object implicits { serdeAware.evalWithoutSerialization(input).asInstanceOf[Geography] case _ => inputExpression.eval(input).asInstanceOf[Array[Byte]] match { - case binary: Array[Byte] => GeographyWKBSerializer.deserialize(binary) + case binary: Array[Byte] => GeographySerializer.deserialize(binary) case _ => null } } @@ -213,7 +213,7 @@ object implicits { } def toGeography: Geography = arrayData match { - case binary: Array[Byte] => GeographyWKBSerializer.deserialize(binary) + case binary: Array[Byte] => GeographySerializer.deserialize(binary) case _ => null } } @@ -231,7 +231,7 @@ object implicits { implicit class GeographyEnhancer(geog: Geography) { - def toGenericArrayData: Array[Byte] = GeographyWKBSerializer.serialize(geog) + def toGenericArrayData: Array[Byte] = GeographySerializer.serialize(geog) } } diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala index f67fea76f00..68459bc7dc0 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/BroadcastIndexJoinExec.scala @@ -18,11 +18,10 @@ */ package org.apache.spark.sql.sedona_sql.strategy.join -import org.apache.sedona.common.S2Geography.GeographyWKBSerializer import org.apache.sedona.common.geography.{Functions => GeographyFunctions} import org.apache.sedona.core.spatialOperator.{SpatialPredicate, SpatialPredicateEvaluators} import org.apache.sedona.core.spatialOperator.SpatialPredicateEvaluators.SpatialPredicateEvaluator -import org.apache.sedona.sql.utils.{GeometrySerializer, RasterSerializer} +import org.apache.sedona.sql.utils.{GeographySerializer, GeometrySerializer, RasterSerializer} import scala.collection.JavaConverters._ import org.apache.spark.broadcast.Broadcast @@ -308,7 +307,7 @@ case class BroadcastIndexJoinExec( if (serialized == null) { (null, row) } else { - val geog = GeographyWKBSerializer.deserialize(serialized) + val geog = GeographySerializer.deserialize(serialized) val radius = boundDistance.eval(row).asInstanceOf[Double] val baseEnvelope = JoinedGeometry.geographyToEnvelopeGeometry(geog) val shape = if (streamSideExpands) { @@ -365,7 +364,7 @@ case class BroadcastIndexJoinExec( if (serialized == null) { (null, row) } else { - val geog = GeographyWKBSerializer.deserialize(serialized) + val geog = GeographySerializer.deserialize(serialized) val shape = JoinedGeometry.geographyToEnvelopeGeometry(geog) shape.setUserData(GeographyJoinShape(geog, row)) (shape, row) diff --git a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/TraitJoinQueryBase.scala b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/TraitJoinQueryBase.scala index 99e31498737..80f50f89229 100644 --- a/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/TraitJoinQueryBase.scala +++ b/spark/common/src/main/scala/org/apache/spark/sql/sedona_sql/strategy/join/TraitJoinQueryBase.scala @@ -19,10 +19,9 @@ package org.apache.spark.sql.sedona_sql.strategy.join import org.apache.sedona.common.Constructors -import org.apache.sedona.common.S2Geography.GeographyWKBSerializer import org.apache.sedona.core.spatialRDD.SpatialRDD import org.apache.sedona.core.utils.SedonaConf -import org.apache.sedona.sql.utils.{GeometrySerializer, RasterSerializer} +import org.apache.sedona.sql.utils.{GeographySerializer, GeometrySerializer, RasterSerializer} import org.apache.spark.rdd.RDD import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{Expression, UnsafeRow} @@ -80,7 +79,7 @@ trait TraitJoinQueryBase { if (geogBytes == null) { None } else { - val geog = GeographyWKBSerializer.deserialize(geogBytes) + val geog = GeographySerializer.deserialize(geogBytes) val shape = JoinedGeometry.geographyToEnvelopeGeometry(geog) shape.setUserData(GeographyJoinShape(geog, x.copy)) Some(shape) @@ -223,7 +222,7 @@ trait TraitJoinQueryBase { if (geogBytes == null) { None } else { - val geog = GeographyWKBSerializer.deserialize(geogBytes) + val geog = GeographySerializer.deserialize(geogBytes) val distance = boundRadius.eval(x).asInstanceOf[Double] val baseEnvelope = JoinedGeometry.geographyToEnvelopeGeometry(geog) val expandedEnvelope = diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeographySerializerSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeographySerializerSuite.scala new file mode 100644 index 00000000000..15bb257cfe3 --- /dev/null +++ b/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeographySerializerSuite.scala @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sedona.sql + +import java.nio.{ByteBuffer, ByteOrder} +import java.util.Arrays + +import org.apache.sedona.common.S2Geography.{GeographyWKBSerializer, WKBGeography} +import org.apache.sedona.common.geography.Constructors +import org.apache.spark.sql.sedona_sql.UDT.GeographyUDT +import org.datasyslab.jts.io.WKBReader +import org.scalatest.funsuite.AnyFunSuite + +class SqlGeographySerializerSuite extends AnyFunSuite { + private val point = WKBReader.hexToBytes("0101000000000000000000F03F0000000000000040") + private def header(srid: Int) = + ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(srid).array() + private def decode(bytes: Array[Byte]) = + GeographyUDT.deserialize(bytes).asInstanceOf[WKBGeography] + + test("SQL geography writes a little endian SRID without changing common geography bytes") { + Seq(0, 1, 4326, Int.MaxValue).foreach { srid => + val geography = WKBGeography.fromWKB(point.clone(), srid) + val bytes = GeographyUDT.serialize(geography) + assert(bytes.sameElements(header(srid) ++ point)) + assert(decode(bytes).getSRID == srid) + val common = GeographyWKBSerializer.serialize(geography) + assert(ByteBuffer.wrap(common).getInt == srid) + assert(common.drop(4).sameElements(point)) + assert(GeographyWKBSerializer.deserialize(common).getSRID == srid) + } + } + + test("SQL geography reads independent ISO point fixtures with either WKB byte order") { + Seq( + "E61000000101000000000000000000F03F0000000000000040", + "E610000000000000013FF00000000000004000000000000000").foreach { hex => + val result = decode(WKBReader.hexToBytes(hex)) + assert(result.getSRID == 4326) + assert(result.getPointX == 1.0 && result.getPointY == 2.0) + } + } + + test("SQL geography normalizes EWKB headers without parsing lazy S2 values") { + val input = WKBReader.hexToBytes( + "01010000E0110F0000000000000000F03F000000000000004000000000000008400000000000001040") + val expected = WKBReader.hexToBytes( + "01B90B0000000000000000F03F000000000000004000000000000008400000000000001040") + val geography = WKBGeography.fromWKB(input, 4326) + val bytes = GeographyUDT.serialize(geography) + assert(bytes.sameElements(header(4326) ++ expected)) + Seq("jtsGeometry", "s2Geography", "shapeIndexGeography").foreach { name => + val field = classOf[WKBGeography].getDeclaredField(name) + field.setAccessible(true) + assert(field.get(geography) == null) + } + assert( + input.sameElements(WKBReader.hexToBytes( + "01010000E0110F0000000000000000F03F000000000000004000000000000008400000000000001040"))) + val result = decode(bytes) + assert(result.getSRID == 4326 && result.getWKBBytes.sameElements(expected)) + val coords = result.getJTSGeometry.getCoordinates.head + assert(coords.getZ == 3.0 && coords.getM == 4.0) + } + + test("SQL geography keeps independent collection layouts and dimensional empties") { + val xy = point + val zmEmpty = WKBReader.hexToBytes( + "01B90B0000000000000000F87F000000000000F87F000000000000F87F000000000000F87F") + val collection = WKBReader.hexToBytes("010700000002000000") ++ xy ++ zmEmpty + Seq(collection, zmEmpty, WKBReader.hexToBytes("01BA0B000000000000")).foreach { wkb => + val restored = decode(GeographyUDT.serialize(WKBGeography.fromWKB(wkb, 4326))) + assert(restored.getWKBBytes.sameElements(wkb)) + assert(restored.getSRID == 4326) + } + } + + test("SQL geography owns decoded and encoded buffers") { + val source = point.clone() + val geography = WKBGeography.fromWKB(source, 4326) + val encoded = GeographyUDT.serialize(geography) + val restored = decode(encoded) + Arrays.fill(source, 0.toByte) + assert(encoded.drop(4).sameElements(point)) + Arrays.fill(encoded, 0.toByte) + assert(restored.getWKBBytes.sameElements(point)) + assert(restored.getPointX == 1.0 && restored.getSRID == 4326) + } + + test("SQL geography retains computed S2 values and empty lines") { + Seq("POINT (1 2)", "POLYGON ((0 0, 2 0, 0 2, 0 0))", "LINESTRING EMPTY") + .foreach { wkt => + val lazyValue = Constructors.geogFromWKT(wkt, 4326).asInstanceOf[WKBGeography] + val computed = lazyValue.getS2Geography + val encoded = GeographyUDT.serialize(computed) + assert(ByteBuffer.wrap(encoded).order(ByteOrder.LITTLE_ENDIAN).getInt == 4326) + val result = decode(encoded) + assert(result.getSRID == 4326) + assert(result.getJTSGeometry.equalsExact(lazyValue.getJTSGeometry, 1e-12)) + } + } + + test("SQL geography retains eager S2 initialization and rejects negative SRIDs") { + val previous = WKBGeography.isEagerShapeIndex + try { + WKBGeography.setEagerShapeIndex(true) + val result = decode(header(4326) ++ point) + val field = classOf[WKBGeography].getDeclaredField("shapeIndexGeography") + field.setAccessible(true) + assert(field.get(result) != null) + } finally WKBGeography.setEagerShapeIndex(previous) + intercept[IllegalArgumentException] { decode(header(-1) ++ point) } + (0 until 9).foreach { length => + intercept[IllegalArgumentException] { decode((header(4326) ++ point).take(length)) } + } + } +} diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeometrySerializerSuite.scala b/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeometrySerializerSuite.scala new file mode 100644 index 00000000000..f247ea1cfa9 --- /dev/null +++ b/spark/common/src/test/scala/org/apache/sedona/sql/SqlGeometrySerializerSuite.scala @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sedona.sql + +import org.apache.sedona.sql.utils.GeometrySerializer +import org.datasyslab.jts.io.{WKBReader, WKTReader} +import org.locationtech.jts.geom.{Coordinate, GeometryCollection, GeometryFactory, LineString, Point} +import org.scalatest.funsuite.AnyFunSuite + +class SqlGeometrySerializerSuite extends AnyFunSuite { + private def read(text: String) = { + val reader = WKTReader.forDeclaredDimensions() + reader.setIsOldJtsCoordinateSyntaxAllowed(false) + reader.read(text) + } + private def decode(bytes: Array[Byte]) = { + val srid = java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt + WKBReader.forDeclaredDimensions(srid).read(bytes.drop(4)) + } + + test("SQL geometry bytes are a little endian SRID followed by ISO WKB") { + val point = read("POINT (1 2)") + point.setSRID(4326) + val bytes = GeometrySerializer.serialize(point) + assert( + bytes.sameElements( + WKBReader.hexToBytes("E61000000101000000000000000000F03F0000000000000040"))) + val decoded = decode(bytes).asInstanceOf[Point] + assert(decoded.getX == 1 && decoded.getY == 2) + assert(decoded.getSRID == 4326) + assert(decoded.getCoordinateSequence.getDimension == 2) + } + + test("SQL geometry reads independent ISO fixtures with either WKB byte order") { + val fixtures = Seq( + "E61000000101000000000000000000F03F0000000000000040", + "E610000000000000013FF00000000000004000000000000000") + fixtures.foreach { hex => + val point = GeometrySerializer.deserialize(WKBReader.hexToBytes(hex)).asInstanceOf[Point] + assert(point.getX == 1 && point.getY == 2) + assert(point.getSRID == 4326) + } + } + + Seq(("", 2, 0), (" Z", 3, 0), (" M", 3, 1), (" ZM", 4, 1)).foreach { + case (layout, dimensions, measures) => + val values = layout match { + case " ZM" => "1 2 3 4" + case " Z" | " M" => "1 2 3" + case _ => "1 2" + } + test(s"SQL geometry preserves declared $dimensions/$measures point ordinates") { + val bytes = GeometrySerializer.serialize(read(s"POINT$layout ($values)")) + val point = decode(bytes).asInstanceOf[Point] + val seq = point.getCoordinateSequence + assert(seq.getDimension == dimensions && seq.getMeasures == measures) + (0 until dimensions).foreach(i => assert(seq.getOrdinate(0, i) == i + 1.0)) + val roundTrip = GeometrySerializer.deserialize(bytes).asInstanceOf[Point] + assert(roundTrip.getCoordinateSequence.getDimension == dimensions) + assert(roundTrip.getCoordinateSequence.getMeasures == measures) + } + test(s"SQL geometry preserves declared $dimensions/$measures empty point and line") { + Seq("POINT", "LINESTRING").foreach { kind => + val restored = decode(GeometrySerializer.serialize(read(s"$kind$layout EMPTY"))) + assert(restored.isEmpty && restored.getGeometryType.toUpperCase == kind) + val seq = restored match { + case p: Point => p.getCoordinateSequence + case l: LineString => l.getCoordinateSequence + } + assert(seq.getDimension == dimensions && seq.getMeasures == measures) + } + } + } + + test("SQL geometry preserves independent geometry collection layouts") { + val factory = new GeometryFactory() + val collection = factory.createGeometryCollection( + Array(read("POINT (1 2)"), read("POINT Z (3 4 5)"), read("POINT M (6 7 8)"))) + val result = decode(GeometrySerializer.serialize(collection)) + val layouts = (0 until result.getNumGeometries).map { i => + val seq = result.getGeometryN(i).asInstanceOf[Point].getCoordinateSequence + (seq.getDimension, seq.getMeasures) + } + assert(layouts == Seq((2, 0), (3, 0), (3, 1))) + } + + test("SQL geometry rejects explicitly heterogeneous multipart layouts") { + val factory = new GeometryFactory() + val points = + Array(read("POINT (1 2)").asInstanceOf[Point], read("POINT Z (3 4 5)").asInstanceOf[Point]) + intercept[IllegalArgumentException] { + GeometrySerializer.serialize(factory.createMultiPoint(points)) + } + } + + test("SQL geometry keeps ambiguous unmarked JTS coordinates compact") { + val point = new GeometryFactory().createPoint(new Coordinate(1, 2)) + val result = decode(GeometrySerializer.serialize(point)).asInstanceOf[Point] + assert(result.getCoordinateSequence.getDimension == 2) + assert(result.getX == 1 && result.getY == 2) + } + + test("SQL multipart geometry retains ordinates established beside ambiguous JTS sequences") { + val factory = new GeometryFactory() + val multi = factory.createMultiPoint( + Array( + factory.createPoint(new Coordinate(1, 2)), + read("POINT Z (3 4 5)").asInstanceOf[Point])) + val result = decode(GeometrySerializer.serialize(multi)) + assert(result.getGeometryN(0).asInstanceOf[Point].getX == 1) + assert(result.getGeometryN(1).getCoordinate.getZ == 5) + } + + test("SQL geometry preserves the factory SRID used by derived geometries") { + val polygon = read("POLYGON ((0 0, 4 0, 0 4, 0 0))") + polygon.setSRID(4326) + val result = GeometrySerializer.deserialize(GeometrySerializer.serialize(polygon)) + assert(result.getSRID == 4326) + assert(result.getFactory.getSRID == 4326) + assert(result.getCentroid.getSRID == 4326) + val collection = new GeometryFactory().createGeometryCollection(Array(polygon)) + collection.setSRID(4326) + val restored = GeometrySerializer.deserialize(GeometrySerializer.serialize(collection)) + assert(restored.getGeometryN(0).getFactory.getSRID == 4326) + } + + test("SQL geometry owns decoded coordinates and retains null join sentinel") { + val bytes = WKBReader.hexToBytes("000000000101000000000000000000F03F0000000000000040") + val point = GeometrySerializer.deserialize(bytes).asInstanceOf[Point] + java.util.Arrays.fill(bytes, 0.toByte) + assert(point.getX == 1 && point.getY == 2) + val empty = GeometrySerializer.deserialize(null) + assert(empty.isInstanceOf[GeometryCollection] && empty.isEmpty) + } + test("SQL geometry retains the full signed SRID independently of WKB byte order") { + Seq(Int.MinValue, -1, 0, 4326, 16777216, Int.MaxValue).foreach { srid => + Seq( + "0101000000000000000000F03F0000000000000040", + "00000000013FF00000000000004000000000000000").foreach { hex => + val header = java.nio.ByteBuffer + .allocate(4) + .order(java.nio.ByteOrder.LITTLE_ENDIAN) + .putInt(srid) + .array() + val point = GeometrySerializer.deserialize(header ++ WKBReader.hexToBytes(hex)) + assert(point.getSRID == srid && point.getFactory.getSRID == srid) + val bytes = GeometrySerializer.serialize(point) + assert(bytes.take(4).sameElements(header)) + assert( + bytes + .drop(4) + .sameElements(WKBReader.hexToBytes("0101000000000000000000F03F0000000000000040"))) + } + } + } + + test("SQL geometry emits ISO dimension offsets rather than EWKB flags") { + Seq(("", 1, "1 2"), (" Z", 1001, "1 2 3"), (" M", 2001, "1 2 3"), (" ZM", 3001, "1 2 3 4")) + .foreach { case (layout, typeCode, values) => + val bytes = GeometrySerializer.serialize(read(s"POINT$layout ($values)")) + assert(bytes(4) == 1) + assert( + java.nio.ByteBuffer + .wrap(bytes, 5, 4) + .order(java.nio.ByteOrder.LITTLE_ENDIAN) + .getInt == typeCode) + } + } + + test("SQL geometry rejects a truncated SRID header and incomplete point payload") { + val complete = WKBReader.hexToBytes("E61000000101000000000000000000F03F0000000000000040") + (0 until complete.length).foreach { length => + intercept[IllegalArgumentException] { + GeometrySerializer.deserialize(complete.take(length)) + } + } + assert(GeometrySerializer.serialize(null) == null) + } + + test("SQL geometry rejects oversized counts before allocating coordinates or members") { + // Tiny external payloads must not allocate arrays based on an unchecked count. + (2 to 7).foreach { kind => + val bytes = java.nio.ByteBuffer + .allocate(13) + .order(java.nio.ByteOrder.LITTLE_ENDIAN) + .putInt(4326) + .put(1.toByte) + .putInt(kind) + .putInt(Int.MaxValue) + .array() + intercept[IllegalArgumentException] { GeometrySerializer.deserialize(bytes) } + } + } +} diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala index 7aee687facd..2db91f5dbdd 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/geography/GeographyFunctionTest.scala @@ -364,7 +364,8 @@ class GeographyFunctionTest extends TestBaseScala { var hasExpectedMessage = false while (cause != null) { hasExpectedMessage ||= Option(cause.getMessage) - .exists(_.contains("same SRID")) + .exists(message => + message.contains("same SRID") && message.contains("4326") && message.contains("3857")) cause = cause.getCause } assertTrue(hasExpectedMessage) diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/predicateTestScala.scala b/spark/common/src/test/scala/org/apache/sedona/sql/predicateTestScala.scala index d8066f98604..4be54824b62 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/predicateTestScala.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/predicateTestScala.scala @@ -18,7 +18,7 @@ */ package org.apache.sedona.sql -import org.apache.sedona.common.geometrySerde.GeometrySerializer +import org.apache.sedona.sql.utils.GeometrySerializer import org.apache.spark.sql.Row import org.apache.spark.sql.catalyst.expressions.{EmptyRow, Literal} import org.apache.spark.sql.sedona_sql.UDT.GeometryUDT @@ -26,8 +26,6 @@ import org.apache.spark.sql.sedona_sql.expressions.{ST_Contains, ST_CoveredBy, S import org.apache.spark.sql.types.{IntegerType, StructField, StructType} import org.locationtech.jts.geom.{Coordinate, CoordinateXYZM, Geometry, GeometryFactory} import org.locationtech.jts.io.WKTReader -import org.mockito.ArgumentMatchers.any -import org.mockito.Mockito.{CALLS_REAL_METHODS, mockStatic, never, times} import java.util.Arrays @@ -607,7 +605,7 @@ class predicateTestScala extends TestBaseScala { } val polygon = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 1 2, 2 2, 2 1, 1 1))" val collection = s"GEOMETRYCOLLECTION (POINT (1 2), GEOMETRYCOLLECTION ($polygon))" - // (left, right, expected result); every pair is encoded with different bytes + // (left, right, expected result). Public WKB writers may canonicalize NaN payload bits. val cases: Seq[(Geometry, Geometry, Boolean)] = Seq( ( lineZM(new CoordinateXYZM(2, 2, Double.NaN, Double.NaN)), @@ -627,10 +625,9 @@ class predicateTestScala extends TestBaseScala { lineZM(new CoordinateXYZM(2, 2, 2, payloadNaN)), lineZM(new CoordinateXYZM(2, 2, 2, 2)), false)) - cases.foreach { case (left, right, _) => - assert( - !Arrays.equals(GeometrySerializer.serialize(left), GeometrySerializer.serialize(right))) - } + assert(cases.exists { case (left, right, _) => + !Arrays.equals(GeometrySerializer.serialize(left), GeometrySerializer.serialize(right)) + }) val schema = StructType( Seq( @@ -655,32 +652,35 @@ class predicateTestScala extends TestBaseScala { lineWithSrid.setSRID(4326) val bytesWithSrid = GeometrySerializer.serialize(lineWithSrid) def stored(value: Array[Byte]) = Literal.create(value, GeometryUDT()) - val constructed = - ST_GeomFromWKT(Seq(Literal("LINESTRING ZM (0 0 1 2, 1 1 3 4)"), Literal(0))) - - val mocked = mockStatic(classOf[GeometrySerializer], CALLS_REAL_METHODS) - try { - assert( - ST_EqualsIdentical(Seq(stored(bytes), stored(bytes.clone()))).eval(EmptyRow) == true) - mocked.verify(() => GeometrySerializer.deserialize(any(classOf[Array[Byte]])), never()) - - assert( - ST_EqualsIdentical(Seq(stored(bytes), stored(bytesWithSrid))).eval(EmptyRow) == true) - mocked.verify(() => GeometrySerializer.deserialize(any(classOf[Array[Byte]])), times(2)) - - assert(ST_EqualsIdentical(Seq(stored(bytes), stored(null))).eval(EmptyRow) == null) - assert(ST_EqualsIdentical(Seq(stored(null), stored(bytes))).eval(EmptyRow) == null) - assert(ST_EqualsIdentical(Seq(stored(null), stored(null))).eval(EmptyRow) == null) - - // Nested constructors are compared without serializing their results - mocked.clearInvocations() - assert(ST_EqualsIdentical(Seq(constructed, constructed)).eval(EmptyRow) == true) - assert(ST_EqualsIdentical(Seq(stored(bytes), constructed)).eval(EmptyRow) == true) - mocked.verify(() => GeometrySerializer.serialize(any(classOf[Geometry])), never()) - mocked.verify(() => GeometrySerializer.deserialize(any(classOf[Array[Byte]])), times(1)) - } finally { - mocked.close() + val constructed = ObjectOnlyGeometry( + ST_GeomFromWKT(Seq(Literal("LINESTRING ZM (0 0 1 2, 1 1 3 4)"), Literal(0)))) + + assert(ST_EqualsIdentical(Seq(stored(bytes), stored(bytes.clone()))).eval(EmptyRow) == true) + assert(ST_EqualsIdentical(Seq(stored(bytes), stored(bytesWithSrid))).eval(EmptyRow) == true) + assert(ST_EqualsIdentical(Seq(stored(bytes), stored(null))).eval(EmptyRow) == null) + assert(ST_EqualsIdentical(Seq(stored(null), stored(bytes))).eval(EmptyRow) == null) + assert(ST_EqualsIdentical(Seq(stored(null), stored(null))).eval(EmptyRow) == null) + + // Independent SRID/ISO WKB fixtures keep the byte-distinct NaN fallback covered even when the + // public writer canonicalizes NaN payloads while constructing DataFrame values. + val nanA = org.datasyslab.jts.io.WKBReader + .hexToBytes( + "0000000001B90B0000000000000000F03F0000000000000040000000000000F87F0000000000001040") + val nanB = nanA.clone() + nanB(25) = 1 + assert(!Arrays.equals(nanA, nanB)) + assert(ST_EqualsIdentical(Seq(stored(nanA), stored(nanB))).eval(EmptyRow) == true) + + // Identical buffers need no parsing; different buffers must still be decoded. + val invalid = Array[Byte](0, 1, 2) + assert( + ST_EqualsIdentical(Seq(stored(invalid), stored(invalid.clone()))).eval(EmptyRow) == true) + intercept[Exception] { + ST_EqualsIdentical(Seq(stored(invalid), stored(bytes))).eval(EmptyRow) } + // ObjectOnlyGeometry rejects SQL-byte evaluation, including the mixed stored/object case. + assert(ST_EqualsIdentical(Seq(constructed, constructed)).eval(EmptyRow) == true) + assert(ST_EqualsIdentical(Seq(stored(bytes), constructed)).eval(EmptyRow) == true) } it("Passed edge cases of ST_Contains and ST_Covers") { diff --git a/spark/common/src/test/scala/org/apache/sedona/sql/serdeAwareTest.scala b/spark/common/src/test/scala/org/apache/sedona/sql/serdeAwareTest.scala index 2033aa3664f..dee830c1795 100644 --- a/spark/common/src/test/scala/org/apache/sedona/sql/serdeAwareTest.scala +++ b/spark/common/src/test/scala/org/apache/sedona/sql/serdeAwareTest.scala @@ -18,14 +18,15 @@ */ package org.apache.sedona.sql -import org.apache.sedona.common.geometrySerde.GeometrySerializer +import org.apache.sedona.sql.utils.GeometrySerializer import org.apache.sedona.common.raster.RasterConstructors.fromArcInfoAsciiGrid import org.apache.sedona.common.raster.serde.Serde -import org.apache.spark.sql.catalyst.expressions.Literal -import org.apache.spark.sql.sedona_sql.expressions.{ST_Buffer, ST_GeomFromText, ST_Point, ST_Union} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, UnaryExpression} +import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback +import org.apache.spark.sql.sedona_sql.expressions.{SerdeAware, ST_Buffer, ST_GeomFromText, ST_Point, ST_Union} import org.apache.spark.sql.sedona_sql.expressions.raster.{RS_FromArcInfoAsciiGrid, RS_NumBands} import org.geotools.coverage.grid.GridCoverage2D -import org.locationtech.jts.geom.{Coordinate, Geometry, GeometryFactory} import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.{atMost, mockStatic} @@ -33,33 +34,17 @@ class SerdeAwareFunctionSpec extends TestBaseScala { describe("SerdeAwareFunction") { it("should save us some serialization and deserialization cost for geometries") { - // Mock GeometrySerializer - val factory = new GeometryFactory - val stubGeom = factory.createPoint(new Coordinate(1, 2)) - val mocked = mockStatic(classOf[GeometrySerializer]) - mocked - .when(() => GeometrySerializer.deserialize(any(classOf[Array[Byte]]))) - .thenReturn(stubGeom) - mocked - .when(() => GeometrySerializer.serialize(any(classOf[Geometry]))) - .thenReturn(Array[Byte](1, 2, 3)) - - val expr = ST_Union( - Seq( - ST_Buffer(Seq(ST_GeomFromText(Seq(Literal("POINT (1 2)"), Literal(0))), Literal(1.0))), - ST_Point(Seq(Literal(1.0), Literal(2.0), Literal(null))))) - - try { - // Evaluate an expression - expr.eval(null) - - // Verify number of invocations - mocked.verify(() => GeometrySerializer.deserialize(any(classOf[Array[Byte]])), atMost(0)) - mocked.verify(() => GeometrySerializer.serialize(any(classOf[Geometry])), atMost(1)) - } finally { - // Undo the mock - mocked.close() - } + val buffer = ObjectOnlyGeometry( + ST_Buffer( + Seq( + ObjectOnlyGeometry(ST_GeomFromText(Seq(Literal("POINT (1 2)"), Literal(0)))), + Literal(1.0)))) + val point = ObjectOnlyGeometry(ST_Point(Seq(Literal(1.0), Literal(2.0), Literal(null)))) + val expr = ST_Union(Seq(buffer, point)) + val result = GeometrySerializer.deserialize(expr.eval(null).asInstanceOf[Array[Byte]]) + assert(math.abs(result.getArea - math.Pi) < 0.03) + assert(result.getEnvelopeInternal.getMinX == 0.0) + assert(result.getEnvelopeInternal.getMaxX == 2.0) } it("should save us some serialization and deserialization cost for rasters") { @@ -98,3 +83,18 @@ class SerdeAwareFunctionSpec extends TestBaseScala { } } } + +/** A real computational child that fails if a parent asks for intermediate SQL bytes. */ +private[sql] case class ObjectOnlyGeometry(child: Expression) + extends UnaryExpression + with CodegenFallback + with SerdeAware { + override def dataType = child.dataType + override def nullable: Boolean = child.nullable + override def eval(input: InternalRow): Any = + throw new AssertionError("Unexpected intermediate geometry serialization") + override def evalWithoutSerialization(input: InternalRow): Any = + child.asInstanceOf[SerdeAware].evalWithoutSerialization(input) + override protected def withNewChildInternal(newChild: Expression): Expression = + copy(child = newChild) +} diff --git a/spark/spark-3.5/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala b/spark/spark-3.5/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala index 62733169288..7f2f93e068f 100644 --- a/spark/spark-3.5/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala +++ b/spark/spark-3.5/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala @@ -83,15 +83,15 @@ object ScalarUDF { |from shapely.geometry import Point |from sedona.sql.types import GeometryType |from pyspark.serializers import CloudPickleSerializer - |from sedona.utils import geometry_serde + |from sedona.spark.utils import geometry_sql_serde |from shapely import box |f = open('$path', 'wb'); |def w(x): | def apply_function(w): - | geom, offset = geometry_serde.deserialize(w) + | geom = geometry_sql_serde.deserialize_geometry(w) | bounds = geom.buffer(1).bounds | x = box(*bounds) - | return geometry_serde.serialize(x) + | return geometry_sql_serde.serialize_geometry(x) | return x.apply(apply_function) |f.write(CloudPickleSerializer().dumps((w, GeometryType()))) |""".stripMargin), diff --git a/spark/spark-4.0/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala b/spark/spark-4.0/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala index 62733169288..7f2f93e068f 100644 --- a/spark/spark-4.0/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala +++ b/spark/spark-4.0/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala @@ -83,15 +83,15 @@ object ScalarUDF { |from shapely.geometry import Point |from sedona.sql.types import GeometryType |from pyspark.serializers import CloudPickleSerializer - |from sedona.utils import geometry_serde + |from sedona.spark.utils import geometry_sql_serde |from shapely import box |f = open('$path', 'wb'); |def w(x): | def apply_function(w): - | geom, offset = geometry_serde.deserialize(w) + | geom = geometry_sql_serde.deserialize_geometry(w) | bounds = geom.buffer(1).bounds | x = box(*bounds) - | return geometry_serde.serialize(x) + | return geometry_sql_serde.serialize_geometry(x) | return x.apply(apply_function) |f.write(CloudPickleSerializer().dumps((w, GeometryType()))) |""".stripMargin), diff --git a/spark/spark-4.1/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala b/spark/spark-4.1/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala index 62733169288..7f2f93e068f 100644 --- a/spark/spark-4.1/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala +++ b/spark/spark-4.1/src/test/scala/org/apache/spark/sql/udf/TestScalarPandasUDF.scala @@ -83,15 +83,15 @@ object ScalarUDF { |from shapely.geometry import Point |from sedona.sql.types import GeometryType |from pyspark.serializers import CloudPickleSerializer - |from sedona.utils import geometry_serde + |from sedona.spark.utils import geometry_sql_serde |from shapely import box |f = open('$path', 'wb'); |def w(x): | def apply_function(w): - | geom, offset = geometry_serde.deserialize(w) + | geom = geometry_sql_serde.deserialize_geometry(w) | bounds = geom.buffer(1).bounds | x = box(*bounds) - | return geometry_serde.serialize(x) + | return geometry_sql_serde.serialize_geometry(x) | return x.apply(apply_function) |f.write(CloudPickleSerializer().dumps((w, GeometryType()))) |""".stripMargin),