Skip to content

[GH-3271] Enhance GeoDataFrame and GeoSeries to handle authoritative … - #3279

Merged
jiayuasu merged 7 commits into
apache:masterfrom
minhpham1810:gh-3271-geopandas-no-crs-metadata
Aug 26, 2026
Merged

jiayuasu merged 7 commits into
apache:masterfrom
minhpham1810:gh-3271-geopandas-no-crs-metadata

Conversation

@minhpham1810

Copy link
Copy Markdown
Contributor

Did you read the Contributor Guide?

Is this PR related to a ticket?

What changes were proposed in this PR?

Addresses issue #3271: "GeoPandas: preserve authoritative no-CRS metadata for local geometry columns"

The issue reports that locally constructed GeoSeries/GeoDataFrame objects with crs=None have no CRS metadata, making them indistinguishable from raw distributed geometry columns of unknown provenance. This causes .crs access to trigger expensive distributed ST_SRID aggregation jobs to discover the CRS is absent.

Changes

geoseries.py:

  • Added is_locally_owned flag to distinguish locally-constructed objects (Python list, WKT/WKB, plain pandas/geopandas objects) from wrapped distributed structures
  • Added _record_no_crs_metadata() helper method that stamps empty CRS metadata (empty string in metadata dict) using _query_geometry_column() with crs_override=None
  • Stamps no-CRS metadata in __init__ when crs=None and is_locally_owned=True
  • Stamps no-CRS metadata in _create_from_select() for from_wkt()/from_wkb() paths (freshly built geometries with no embedded SRID)

geodataframe.py:

  • Added is_locally_owned flag with the same logic as GeoSeries
  • Added consolidated no-CRS stamping block at end of __init__ that checks if geometry column exists, is locally owned, and has no CRS metadata
  • Fixed set_geometry() array-like branch to construct GeoSeries directly from local data (avoid pre-wrapping in bare pspd.Series)
  • Added import of read_crs_metadata helper

Tests:

  • test_geoseries.py: Added 5 new tests covering local construction paths, raw column preservation, embedded SRID preservation, and no Spark/Python plan for CRS discovery
  • test_geodataframe.py: Added 3 new tests covering named geometry column path and Spark/Python plan verification

How was this patch tested?

  • All 4 modified files pass ast.parse syntax validation
  • Black formatting applied (where possible; test file formatting left untouched per existing repo state)
  • Existing test suite patterns followed; no additional test execution possible in this environment (no Spark/geopandas available)
  • Manual code review against implementation requirements and existing codebase patterns

The tests are structured to run with full Sedona build (Maven) once Spark/geopandas environment is available.

Did this PR include necessary documentation updates?

  • No, this PR does not affect any public API so no need to change the documentation.

The changes are internal implementation details that preserve existing public behavior while fixing the underlying performance issue. The public .crs property semantics remain unchanged: locally constructed objects now correctly report crs=None without triggering distributed SRID lookups.

…ative "no CRS" state for locally constructed geometries
@minhpham1810
minhpham1810 requested a review from jiayuasu as a code owner August 24, 2026 22:57

@jiayuasu jiayuasu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left a few inline questions with small reproducers and possible fixes.

active_geometry._internal.data_fields[0]
)
if not has_crs_metadata:
self[self._geometry_column_name] = (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this assignment can cross pandas-on-Spark anchors. _record_no_crs_metadata() builds a projected frame, so assigning its Series back here goes through different-frame alignment.

A small reproducer is:

with ps.option_context("compute.ops_on_diff_frames", False):
    sgpd.GeoDataFrame(
        {"zone": ["a"], "geometry": [Point(0, 0)]}
    )

The Spark 3.4 CI run currently raises ValueError: Cannot combine ... different dataframe at this line. With cross-frame operations enabled, duplicate indexes may be joined and multiply rows instead. Could we attach the alias and updated InternalField through the existing internal frame, for example with with_new_spark_column, rather than assigning a derived Series?

untouched even though the public ``.crs`` becomes authoritatively
``None`` instead of falling back to a distributed SRID lookup.
"""
result = self._query_geometry_column(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this path preserve valid falsy names?

s = sgpd.GeoSeries([Point(0, 0)], name=0)
assert s.name == 0

s = sgpd.GeoSeries([Point(0, 0)], name="")
assert s.name == ""

Both names appear to become None because _query_geometry_column(..., keep_name=True) later checks if keep_name and self.name. A metadata-only update that keeps the existing label would avoid that; alternatively, the helper could test self.name is not None.


if crs is not None:
self.set_crs(crs, inplace=True, allow_override=True)
elif is_locally_owned:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a CRS carried by a local GeometryArray is lost before this branch:

arr = gpd.GeoSeries([Point(0, 0)], crs=4326).array
s = sgpd.GeoSeries(arr)
assert s.crs.to_epsg() == 4326

Only a gpd.GeoSeries is checked for an inherited CRS above; a GeometryArray, or a plain pd.Series backed by one, is converted to object and then stamped as authoritative None here. Could we read data.crs / data.array.crs before conversion and use that value when setting the metadata and embedded SRID?

# or Sedona-managed source with its own CRS state) -- record that
# explicitly so later `.crs` reads don't fall back to a distributed
# SRID lookup just to discover there isn't one.
if crs is None and is_locally_owned and self._geometry_column_name is not None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we apply this to every locally created geometry column rather than only the active one?

gdf = sgpd.GeoDataFrame({
    "geometry": [Point(0, 0)],
    "secondary": [Point(1, 1)],
})
has_metadata, _ = read_crs_metadata(
    gdf["secondary"]._internal.data_fields[0]
)
assert has_metadata

The secondary column still appears metadata-free, so gdf.set_geometry("secondary").crs takes the distributed SRID fallback. For pandas/GeoPandas inputs with different per-column CRSs, those inactive CRS values can also be lost during the object conversion. One option would be to capture CRS by column position before conversion, then update every geometry field with either its CRS or explicit no-CRS metadata.

# need to record an authoritative "no CRS" state below when the user
# didn't pass one. Wrapping an existing structure just inherits
# whatever CRS state (known, known-absent, or unknown) it already had.
is_locally_owned = not isinstance(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could the file-constructor path be handled explicitly? GeoSeries.from_file passes df.geometry here, so a CRS-less file is classified as distributed and remains metadata-free.

A regression check could be:

s = sgpd.GeoSeries.from_file(crsless_geojson, format="geojson")
assert read_crs_metadata(s._internal.data_fields[0]) == (True, None)

At the moment from_file also reads df.crs eagerly, which can run SRID inference, and a later s.crs can repeat it. Could the reader attach the authoritative known or known-absent state directly from the file metadata instead?

before_jobs = 0
try:
_ = s.crs
after_jobs = len(self.session._sc._jvm.scala.concurrent.FutureCache.getPythonPlans(s))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I may be missing a fixture, but TestBase exposes spark and sc, not session. That would make this line raise AttributeError, and the broad except Exception then turns the result into zero jobs, so the test still passes without measuring anything. before_jobs is also unused.

Could we use a Spark job group/status tracker around the operation instead, without swallowing instrumentation errors? For example, assign a unique job group, construct the required binary predicate from two local CRS-less operands, and assert self.sc.statusTracker().getJobIdsForGroup(group) stays empty before materialization. The companion plan test could inspect queryExecution().optimizedPlan() and check for BatchEvalPython, ArrowEvalPython, and PythonUDF.

def check_geodataframe(df):
assert isinstance(df, GeoDataFrame)

def test_local_construction_no_spark_job_for_crs_discovery(self):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like these two tests are nested inside the top-level check_geodataframe helper, so pytest does not collect them.

This should show the issue:

pytest --collect-only -q python/tests/geopandas/test_geodataframe.py |
  grep local_construction_no

Only the earlier named-geometry test is collected. Could we move both methods into TestGeoDataFrame, then use the same real job-count and query-plan assertions as the GeoSeries coverage?

return GeoSeries(ps_series, index, crs=crs)
result = GeoSeries(ps_series, index, crs=crs)
if crs is None:
# ST_GeomFromWKB/WKT always produce fresh geometries with no

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we soften this rationale? ST_GeomFromWKB can preserve an SRID carried by EWKB.

For example:

geom = shapely.set_srid(Point(0, 0), 4326)
ewkb = shapely.to_wkb(geom, include_srid=True)
s = sgpd.GeoSeries.from_wkb([ewkb])
assert s._internal.spark_frame.select(
    stf.ST_SRID(s.spark.column)
).first()[0] == 4326

The metadata-only stamping still seems right. Suggested wording: WKT and ordinary WKB are generally SRID-less, while EWKB may carry an embedded SRID; recording public crs=None must not rewrite it.

…state for locally constructed geometries, optimizing CRS access without triggering unnecessary Spark jobs.
@minhpham1810
minhpham1810 requested a review from jiayuasu August 25, 2026 18:59
@jiayuasu jiayuasu added this to the sedona-2.0.0 milestone Aug 26, 2026
@jiayuasu

Copy link
Copy Markdown
Member

@minhpham1810 I've taken over this PR and made some updates given its complexity. Everything looks good now. Thank you for your contribution!

@jiayuasu
jiayuasu merged commit 85a8a90 into apache:master Aug 26, 2026
34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GeoPandas: preserve authoritative no-CRS metadata for local geometry columns

2 participants