You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ja...@apache.org on 2026/07/16 21:48:38 UTC

(sedona-db) branch main updated: feat(rust/sedona-raster-gdal): add RS_Clip (#1000)

This is an automated email from the ASF dual-hosted git repository.

james-willis pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/sedona-db.git


The following commit(s) were added to refs/heads/main by this push:
     new 456aabcb5 feat(rust/sedona-raster-gdal): add RS_Clip (#1000)
456aabcb5 is described below

commit 456aabcb528db060183e86597a4e94795e5579c7
Author: James Willis <ja...@users.noreply.github.com>
AuthorDate: Thu Jul 16 14:48:33 2026 -0700

    feat(rust/sedona-raster-gdal): add RS_Clip (#1000)
---
 docs/reference/python.md                          |    2 +
 docs/reference/sql/rs_clip.qmd                    |  135 ++
 python/sedonadb/pyproject.toml                    |    1 +
 python/sedonadb/python/sedonadb/raster.py         |   37 +
 python/sedonadb/python/sedonadb/raster_testing.py |  329 +++++
 python/sedonadb/tests/functions/test_rs_clip.py   |  360 ++++++
 python/sedonadb/tests/test_raster.py              |   45 +
 rust/sedona-raster-functions/src/crs_utils.rs     |   21 +
 rust/sedona-raster-functions/src/executor.rs      |   34 +-
 rust/sedona-raster-gdal/Cargo.toml                |    8 +-
 rust/sedona-raster-gdal/benches/rs_clip.rs        |  140 ++
 rust/sedona-raster-gdal/src/lib.rs                |    2 +
 rust/sedona-raster-gdal/src/register.rs           |    1 +
 rust/sedona-raster-gdal/src/rs_clip.rs            | 1435 +++++++++++++++++++++
 rust/sedona-schema/src/raster.rs                  |   20 +
 15 files changed, 2559 insertions(+), 11 deletions(-)

diff --git a/docs/reference/python.md b/docs/reference/python.md
index 5a93ab5aa..d2066ee67 100644
--- a/docs/reference/python.md
+++ b/docs/reference/python.md
@@ -24,6 +24,8 @@
 
 ::: sedonadb.testing
 
+::: sedonadb.raster_testing
+
 ::: sedonadb.dbapi
 
 ::: sedonadb.udf
diff --git a/docs/reference/sql/rs_clip.qmd b/docs/reference/sql/rs_clip.qmd
new file mode 100644
index 000000000..4867a4411
--- /dev/null
+++ b/docs/reference/sql/rs_clip.qmd
@@ -0,0 +1,135 @@
+---
+# 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.
+
+title: RS_Clip
+description: >
+  Clips a raster to a geometry, setting pixels outside the geometry to nodata
+  and (by default) cropping to the geometry's bounding box.
+kernels:
+  - returns: raster
+    args:
+    - raster
+    - {name: band, type: integer}
+    - {name: geom, type: geometry}
+  - returns: raster
+    args:
+    - raster
+    - {name: band, type: integer}
+    - {name: geom, type: geometry}
+    - {name: all_touched, type: boolean}
+  - returns: raster
+    args:
+    - raster
+    - {name: band, type: integer}
+    - {name: geom, type: geometry}
+    - {name: all_touched, type: boolean}
+    - {name: no_data_value, type: double}
+  - returns: raster
+    args:
+    - raster
+    - {name: band, type: integer}
+    - {name: geom, type: geometry}
+    - {name: all_touched, type: boolean}
+    - {name: no_data_value, type: double}
+    - {name: crop, type: boolean}
+  - returns: raster
+    args:
+    - raster
+    - name: band
+      type: integer
+      description: >
+        1-based index of the band to clip, or 0 to clip every band. A NULL
+        band yields a NULL result.
+    - name: geom
+      type: geometry
+      description: >
+        Clip geometry. Reprojected into the raster's CRS when both carry one;
+        it is an error for exactly one side to have a CRS.
+    - name: all_touched
+      type: boolean
+      description: >
+        If true, keep every pixel the geometry touches; otherwise keep only
+        pixels whose center falls inside it. Defaults to false.
+    - name: no_data_value
+      type: double
+      description: >
+        Value written to pixels outside the geometry. Defaults to the band's
+        own nodata value, or the band data type's minimum if it has none. It is
+        an error if the value does not fit the band's data type.
+    - name: crop
+      type: boolean
+      description: Crop the output to the geometry's bounding box. Defaults to true.
+    - name: lenient
+      type: boolean
+      description: >
+        If true, a geometry that does not intersect the raster yields NULL;
+        if false, it raises an error. Defaults to true.
+---
+
+::: callout-warning
+**Experimental.** This function is experimental; its behavior may change without notice.
+:::
+
+## Description
+
+`RS_Clip` clips a raster to a geometry, in the spirit of PostGIS `ST_Clip`.
+Pixels of the selected band that fall outside the geometry are set to the
+band's nodata value (or `no_data_value` if given); pixels inside are kept. When
+`crop` is true (the default) the output is cropped to the geometry's bounding
+box intersected with the raster extent, snapped to the pixel grid; unselected
+pixels within that window remain as nodata padding. Otherwise the original
+extent is preserved.
+
+The geometry is reprojected into the raster's CRS when both carry one. If
+exactly one side has a CRS, the call errors; if neither does, the geometry is
+used as-is.
+
+A pixel is selected only when its center falls inside the geometry. A geometry
+smaller than a pixel, or a thin sliver, can therefore select no pixels even
+though it overlaps the raster; set `all_touched` to true to keep every pixel the
+geometry touches instead.
+
+The clip is a 2-D `(y, x)` operation. For an N-D raster (bands with extra
+dimensions such as `time`), the same mask and crop window are broadcast across
+every non-spatial plane, so the non-spatial dimensions are preserved and only
+the `(y, x)` extent changes.
+
+## Examples
+
+```sql
+SELECT RS_Width(
+  RS_Clip(
+    RS_Example(),
+    1,
+    ST_GeomFromText('POLYGON ((60 90, 160 90, 160 190, 60 190, 60 90))', 'OGC:CRS84')
+  )
+);
+```
+
+```sql
+SELECT RS_Width(
+  RS_Clip(
+    RS_Example(),
+    1,
+    ST_GeomFromText('POLYGON ((60 90, 160 90, 160 190, 60 190, 60 90))', 'OGC:CRS84'),
+    false,
+    0.0,
+    false
+  )
+);
+```
diff --git a/python/sedonadb/pyproject.toml b/python/sedonadb/pyproject.toml
index b0f83c6a8..fa7802be5 100644
--- a/python/sedonadb/pyproject.toml
+++ b/python/sedonadb/pyproject.toml
@@ -43,6 +43,7 @@ test = [
     "pytest",
     "pyyaml",
     "rasterio",
+    "sedonadb-expr",
 ]
 geopandas = [
     "adbc-driver-manager[dbapi]",
diff --git a/python/sedonadb/python/sedonadb/raster.py b/python/sedonadb/python/sedonadb/raster.py
index 8512b7e3b..186fbf22f 100644
--- a/python/sedonadb/python/sedonadb/raster.py
+++ b/python/sedonadb/python/sedonadb/raster.py
@@ -200,6 +200,30 @@ class Raster:
         bands_array = self._array.field("bands").flatten()
         return [Band(bands_array, i) for i in range(len(bands_array))]
 
+    def to_numpy(self) -> "np.ndarray":
+        """Convert this raster's bands to a single `(band, ...)` numpy array.
+
+        A single-band raster returns a view of the band's buffer, zero-copy
+        when `Band.to_numpy` is. Stacking a multiband raster allocates a new
+        contiguous array and copies each band into it, because every band
+        lives in its own buffer. All bands must share one shape and dtype;
+        mixed-dtype rasters raise rather than silently promoting.
+        """
+        import numpy as np
+
+        bands = self.bands
+        if not bands:
+            raise ValueError("Raster has no bands")
+        dtypes = {band.data_type for band in bands}
+        if len(dtypes) > 1:
+            raise ValueError(
+                f"Bands have mixed data types {sorted(dtypes)}; "
+                "convert them individually with Band.to_numpy()"
+            )
+        if len(bands) == 1:
+            return np.expand_dims(bands[0].to_numpy(), 0)
+        return np.stack([band.to_numpy() for band in bands])
+
     def __repr__(self) -> str:
         """Return a string representation of this raster."""
         return f"<Raster {self.width}x{self.height}, {len(self.bands)} band(s)>"
@@ -253,6 +277,19 @@ class Band:
         type_id = self._py_field("data_type")
         return BAND_DATA_TYPES[type_id].lower()
 
+    @property
+    def nodata(self):
+        """The band's nodata sentinel unpacked in the band's dtype, or None.
+
+        Integer bands return an int (exact for the full Int64/UInt64 range);
+        floating bands return a float.
+        """
+        raw = self._py_field("nodata")
+        if raw is None:
+            return None
+        type_id = self._py_field("data_type")
+        return struct.unpack("<" + BAND_DATA_TYPE_STRUCT_CHARS[type_id], raw)[0]
+
     @property
     def source_data(self) -> memoryview:
         """The raw source data buffer as a memoryview.
diff --git a/python/sedonadb/python/sedonadb/raster_testing.py b/python/sedonadb/python/sedonadb/raster_testing.py
new file mode 100644
index 000000000..e3656448d
--- /dev/null
+++ b/python/sedonadb/python/sedonadb/raster_testing.py
@@ -0,0 +1,329 @@
+# 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.
+
+"""Cross-engine parity testing for raster (`RS_*`) functions.
+
+The raster sibling of the `DBEngine` framework in `sedonadb.testing`.
+Geometry parity broadcasts one SQL string to every engine; raster engines
+cannot share SQL — rasterio is not a SQL engine, and raster SQL dialects
+disagree on function names and argument order — so parity here is
+operation-level instead: `RasterEngine` exposes one method per operation
+(`clip()`, ...) returning plain decoded values, and each engine translates
+the operation into its own invocation.
+
+Engines come in two kinds, which changes how tests compare results:
+
+- **Dialect engines** (`SedonaDB`; a Sedona Spark engine belongs here too)
+  execute the function under test and compare strictly — exact pixels, exact
+  nodata, exact NULL/error behavior.
+- **Reference engines** (`Rasterio`) reconstruct the operation from library
+  primitives; engine-specific policy (like nodata precedence) is resolved by
+  the caller before comparing.
+
+Test fixtures follow one pattern: define the raster once as a numpy array +
+GDAL geotransform, write it to a CRS-less GeoTIFF with `write_geotiff` (no
+CRS on either side, so nothing reprojects and results stay bit-comparable),
+and hand the same file to every engine.
+"""
+
+import os
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, List, Mapping, Optional, Tuple
+
+import numpy as np
+import pyarrow as pa
+
+
+@dataclass
+class ClipResult:
+    """One clipped raster decoded to plain values.
+
+    `pixels` is `(band, rows, cols)`, `gdal_transform` is GDAL-order
+    `(origin_x, scale_x, skew_x, origin_y, skew_y, scale_y)`, and `nodata`
+    holds one sentinel per band (unpacked in the band's dtype).
+    """
+
+    pixels: "np.ndarray"
+    gdal_transform: Tuple[float, ...]
+    nodata: List[Any]
+
+
+class RasterEngine(ABC):
+    """Executes raster operations on one engine for cross-engine comparison."""
+
+    @classmethod
+    def create_or_skip(cls, *args, **kwargs):
+        """Create this engine, or skip the calling test if it can't be built.
+
+        If `SEDONADB_PYTHON_NO_SKIP_TESTS` is set the failure propagates
+        instead, so CI can't silently skip.
+        """
+        try:
+            return cls(*args, **kwargs)
+        except Exception as e:
+            if os.environ.get("SEDONADB_PYTHON_NO_SKIP_TESTS", "false") in (
+                "true",
+                "1",
+            ):
+                raise
+            import pytest
+
+            pytest.skip(f"Can't create {cls.__name__} raster engine: {e}")
+
+    @abstractmethod
+    def clip(
+        self,
+        path,
+        geometry_wkt: str,
+        *,
+        band: int = 0,
+        all_touched: bool = False,
+        nodata: Optional[float] = None,
+        crop: bool = True,
+    ) -> Optional[ClipResult]:
+        """Clip the GeoTIFF at `path` to a WKT geometry.
+
+        `band` 0 selects all bands, otherwise the 1-based band. Returns None
+        when the geometry selects no pixels and the engine's lenient behavior
+        yields a NULL/absent result.
+        """
+
+
+class SedonaDB(RasterEngine):
+    """Runs `RS_*` on a SedonaDB connection — the engine under test."""
+
+    def __init__(self, con=None):
+        import sedonadb
+
+        self._con = con if con is not None else sedonadb.connect()
+
+    @classmethod
+    def create_or_skip(cls, *args, **kwargs):
+        # Never skip on the engine under test: a construction failure here is
+        # a bug, not a missing optional backend.
+        return cls(*args, **kwargs)
+
+    def clip(
+        self, path, geometry_wkt, *, band=0, all_touched=False, nodata=None, crop=True
+    ):
+        (result,) = self.clip_rows(
+            path,
+            [
+                {
+                    "wkt": geometry_wkt,
+                    "band": band,
+                    "all_touched": all_touched,
+                    "nodata": nodata,
+                    "crop": crop,
+                }
+            ],
+        )
+        return result
+
+    def clip_rows(self, path, rows) -> List[Optional[ClipResult]]:
+        """Run `RS_Clip` once over an N-row table, one row per parameter combo.
+
+        Options travel as table columns rather than literals so the kernel
+        executes its real array path (literals constant-fold). Each row is a
+        dict with keys `wkt`, `band`, `all_touched`, `nodata` (None = use the
+        band's own), and `crop`. Returns one `ClipResult` (or None for NULL
+        rows) per input row, in input order.
+        """
+        table = pa.table(
+            {
+                "idx": pa.array(range(len(rows)), type=pa.int64()),
+                "path": pa.array([str(path)] * len(rows), type=pa.utf8()),
+                "wkt": pa.array([r["wkt"] for r in rows], type=pa.utf8()),
+                "band": pa.array([r["band"] for r in rows], type=pa.int32()),
+                "all_touched": pa.array(
+                    [r["all_touched"] for r in rows], type=pa.bool_()
+                ),
+                "nodata": pa.array([r["nodata"] for r in rows], type=pa.float64()),
+                "crop": pa.array([r["crop"] for r in rows], type=pa.bool_()),
+            }
+        )
+        df = self._con.create_data_frame(table)
+        result = (
+            df.select(
+                "idx",
+                r=df.path.funcs.rs_frompath().funcs.rs_clip(
+                    df.band,
+                    self._con.funcs.st_geomfromtext(df.wkt),
+                    df.all_touched,
+                    df.nodata,
+                    df.crop,
+                ),
+            )
+            .sort("idx")
+            .to_arrow_table()["r"]
+        )
+        return [decode_raster(result[i]) for i in range(len(result))]
+
+
+class Rasterio(RasterEngine):
+    """Reference implementation composed from rasterio primitives.
+
+    The window is `rasterio.features.geometry_window` (geometry bounds ∩
+    raster extent, snapped outward to the grid), the selection is
+    `rasterio.features.geometry_mask`, and pixels compose as "inside the
+    geometry: source value verbatim; outside: `nodata`". This is deliberately
+    not `rasterio.mask.mask`, which additionally reads the source masked and
+    so remaps pixels *valued* at the band nodata to the output nodata — a
+    policy Sedona (Spark and DB) does not follow.
+
+    As a reference engine it takes no position on nodata precedence: `nodata`
+    must be the already-resolved fill value, so `clip()` errors when it is
+    None rather than guessing.
+
+    One caveat on independence: both this engine and SedonaDB ultimately burn
+    geometries with GDAL's rasterizer (rasterio bundles its own GDAL), so the
+    pixel-center/all_touched selection rule itself is shared. The genuinely
+    independent implementations under comparison are everything on top of the
+    burn: window snapping, crop copy, transform shift, nodata handling, and
+    band handling.
+    """
+
+    def __init__(self):
+        import rasterio  # noqa: F401 — availability probe for create_or_skip
+        import shapely  # noqa: F401
+
+    def clip(
+        self, path, geometry_wkt, *, band=0, all_touched=False, nodata=None, crop=True
+    ):
+        import rasterio
+        import rasterio.features
+        import rasterio.windows
+        import shapely
+
+        if nodata is None:
+            raise ValueError(
+                "Rasterio is a reference engine: pass the resolved nodata fill"
+            )
+
+        geom = shapely.from_wkt(geometry_wkt)
+        with rasterio.open(str(path)) as src:
+            if band < 0 or band > src.count:
+                raise ValueError(
+                    f"band {band} out of range for a {src.count}-band raster"
+                )
+            if crop:
+                window = rasterio.features.geometry_window(src, [geom])
+            else:
+                window = rasterio.windows.Window(0, 0, src.width, src.height)
+            transform = src.window_transform(window)
+            data = src.read(window=window)
+            inside = rasterio.features.geometry_mask(
+                [geom],
+                out_shape=(data.shape[1], data.shape[2]),
+                transform=transform,
+                all_touched=all_touched,
+                invert=True,
+            )
+            # numpy raises for out-of-range fills but silently truncates
+            # fractional ones (250.7 -> 250 on uint8); a lossy fill would make
+            # the reference mirror the very bug it exists to catch.
+            fill = np.asarray(nodata, dtype=data.dtype)
+            if float(fill) != float(nodata):
+                raise ValueError(
+                    f"nodata {nodata} is not exactly representable as {data.dtype}"
+                )
+            pixels = np.where(inside, data, fill)
+
+        if band != 0:
+            pixels = pixels[band - 1 : band]
+        return ClipResult(pixels, tuple(transform.to_gdal()), [nodata] * len(pixels))
+
+
+def decode_raster(scalar) -> Optional[ClipResult]:
+    """Decode one `sedona.raster` Arrow scalar to a `ClipResult` (None if NULL)."""
+    if not scalar.is_valid:
+        return None
+    raster = scalar.as_py()
+    return ClipResult(
+        raster.to_numpy(),
+        tuple(raster.transform),
+        [band.nodata for band in raster.bands],
+    )
+
+
+def write_geotiff(path, data: "np.ndarray", *, gdal_transform, nodata=None) -> None:
+    """Write a `(bands, height, width)` array as a CRS-less GeoTIFF.
+
+    `gdal_transform` is GDAL-order `(origin_x, scale_x, skew_x, origin_y,
+    skew_y, scale_y)`; `nodata` (optional) becomes the per-band nodata of
+    every band.
+    """
+    import rasterio
+    from rasterio.transform import Affine
+
+    bands, height, width = data.shape
+    with rasterio.open(
+        str(path),
+        "w",
+        driver="GTiff",
+        height=height,
+        width=width,
+        count=bands,
+        dtype=str(data.dtype),
+        transform=Affine.from_gdal(*gdal_transform),
+        nodata=nodata,
+    ) as dst:
+        dst.write(data)
+
+
+def dtype_min(dtype):
+    """The minimum representable value of a numpy dtype — SedonaDB's default
+    nodata sentinel when neither an explicit value nor a band nodata exists."""
+    dtype = np.dtype(dtype)
+    if dtype.kind == "f":
+        return float(np.finfo(dtype).min)
+    return int(np.iinfo(dtype).min)
+
+
+def random_raster_data(
+    dtype,
+    *,
+    bands: int,
+    height: int,
+    width: int,
+    seed: int = 42,
+    plants: Optional[Mapping[Tuple[int, int], Any]] = None,
+) -> "np.ndarray":
+    """Random `(bands, height, width)` pixels with adversarial values planted.
+
+    The dtype extremes always go in opposite corners (values that must
+    round-trip through any operation that keeps them, and be overwritten by
+    any that fills them). `plants` maps `(row, col)` to a value written into
+    every band — use it to place values the test's geometry or nodata choices
+    make meaningful.
+    """
+    rng = np.random.default_rng(seed)
+    dtype = np.dtype(dtype)
+    if dtype.kind == "f":
+        data = ((rng.random((bands, height, width)) - 0.5) * 200.0).astype(dtype)
+        info = np.finfo(dtype)
+    else:
+        info = np.iinfo(dtype)
+        data = rng.integers(
+            info.min, info.max, size=(bands, height, width), dtype=dtype, endpoint=True
+        )
+    data[:, 0, 0] = info.max
+    data[:, -1, -1] = info.min
+    for (row, col), value in (plants or {}).items():
+        data[:, row, col] = value
+    return data
diff --git a/python/sedonadb/tests/functions/test_rs_clip.py b/python/sedonadb/tests/functions/test_rs_clip.py
new file mode 100644
index 000000000..e1083c91a
--- /dev/null
+++ b/python/sedonadb/tests/functions/test_rs_clip.py
@@ -0,0 +1,360 @@
+# 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.
+
+"""RS_Clip cross-checked against a rasterio reference implementation.
+
+Every parity test defines the raster once (numpy array + GDAL geotransform,
+written to a CRS-less GeoTIFF) and clips it through both raster engines from
+`sedonadb.raster_testing`, comparing pixels, geotransform, and nodata
+exactly. Option permutations run as rows of one query (via
+`SedonaDB.clip_rows`) so the kernel executes its real array path rather than
+constant-folding literals. Cases rasterio cannot express (empty-mask
+lenient/strict semantics, out-of-range nodata) are asserted directly against
+RS_Clip's documented behavior.
+"""
+
+import numpy as np
+import pyarrow as pa
+import pytest
+
+from sedonadb.expr import lit
+from sedonadb.raster_testing import (
+    Rasterio,
+    SedonaDB,
+    decode_raster,
+    dtype_min,
+    random_raster_data,
+    write_geotiff,
+)
+
+pytest.importorskip("rasterio")
+pytest.importorskip("shapely")
+
+
+# GDAL-order geotransform: origin (100, 500), 2-wide by 3-tall north-up pixels.
+# With a 7x6 raster the extent is x in [100, 114], y in [482, 500]; pixel
+# boundaries sit at even x and at y = 482 + 3k, so geometry coordinates below
+# deliberately avoid those values (no floor/ceil ambiguity in either engine).
+GDAL_TRANSFORM = (100.0, 2.0, 0.0, 500.0, 0.0, -3.0)
+BANDS, HEIGHT, WIDTH = 3, 6, 7
+
+GEOM_RECT = (
+    "POLYGON ((102.6 495.8, 109.3 495.8, 109.3 485.9, 102.6 485.9, 102.6 495.8))"
+)
+GEOM_TRIANGLE = "POLYGON ((101.3 498.6, 112.4 496.9, 104.2 483.7, 101.3 498.6))"
+GEOM_HOLE = (
+    "POLYGON ((102.6 495.8, 109.3 495.8, 109.3 485.9, 102.6 485.9, 102.6 495.8), "
+    "(104.7 492.2, 107.1 492.2, 107.1 489.4, 104.7 489.4, 104.7 492.2))"
+)
+# Extends past the west and north edges of the raster: the crop window is the
+# envelope intersected with the raster extent.
+GEOM_OVERHANG = "POLYGON ((95 505, 106.3 505, 106.3 490.7, 95 490.7, 95 505))"
+# A strip crossing the x = 104 pixel boundary but containing no pixel center
+# (centers sit at odd x): selects nothing unless all_touched.
+GEOM_SLIVER = "POLYGON ((103.6 499, 104.4 499, 104.4 483, 103.6 483, 103.6 499))"
+GEOM_DISJOINT = "POLYGON ((900 900, 910 900, 910 890, 900 890, 900 900))"
+
+# Explicit no_data_value argument and the band nodata baked into the fixture
+# GeoTIFF, per dtype. Values are chosen representable in the dtype and distinct
+# from each other so a mixup shows up in the comparison.
+EXPLICIT_NODATA = {
+    "uint8": 250.0,
+    "uint16": 65000.0,
+    "int16": -9999.0,
+    "int32": -99999.0,
+    "float32": -9999.5,
+    "float64": -12345.5,
+}
+BAND_NODATA = {
+    "uint8": 200.0,
+    "uint16": 60000.0,
+    "int16": -8888.0,
+    "int32": -88888.0,
+    "float32": -8888.5,
+    "float64": -23456.5,
+}
+
+
+@pytest.fixture()
+def sedona(con):
+    return SedonaDB(con)
+
+
+@pytest.fixture()
+def reference():
+    return Rasterio.create_or_skip()
+
+
+def _test_data(dtype, band_nodata=None):
+    """Fixture pixels with plants tied to this module's geometries: the dtype
+    minimum at (3, 2), whose pixel center (105, 489.5) is inside GEOM_TRIANGLE
+    at either all_touched setting — so an extreme value must survive a clip
+    verbatim. When ``band_nodata`` is given it is planted at (2, 3), also
+    inside GEOM_TRIANGLE: a source pixel *valued* at the band nodata stays
+    verbatim under a different explicit no_data_value (RS_Clip does not remap
+    it the way rasterio.mask.mask would)."""
+    plants = {(3, 2): dtype_min(dtype)}
+    if band_nodata is not None:
+        plants[(2, 3)] = band_nodata
+    return random_raster_data(
+        dtype, bands=BANDS, height=HEIGHT, width=WIDTH, plants=plants
+    )
+
+
+def _assert_clip_matches_reference(got, reference, tiff, row, fill):
+    """Compare one RS_Clip result against the rasterio reference clip.
+
+    ``fill`` is the resolved nodata (explicit argument or band nodata or dtype
+    minimum); it is always passed to the reference explicitly because
+    rasterio's own fallback for a nodata-less band is 0 while RS_Clip's is the
+    dtype minimum.
+    """
+    expected = reference.clip(
+        tiff,
+        row["wkt"],
+        band=row["band"],
+        all_touched=row["all_touched"],
+        nodata=fill,
+        crop=row["crop"],
+    )
+
+    np.testing.assert_array_equal(got.pixels, expected.pixels, err_msg=f"row: {row}")
+    assert got.gdal_transform == pytest.approx(
+        expected.gdal_transform, rel=1e-12, abs=1e-12
+    )
+    assert got.nodata == expected.nodata, f"row: {row}"
+
+
+@pytest.mark.parametrize("dtype", list(EXPLICIT_NODATA))
+def test_rs_clip_matches_rasterio_permutations(sedona, reference, tmp_path, dtype):
+    """Cross-product of the optional arguments, one row per combination: band
+    (0 = all bands, 1..3), all_touched, explicit vs band nodata, crop — over
+    two geometries chosen so every axis discriminates. GEOM_TRIANGLE's
+    diagonal edges make all_touched matter but its envelope spans the whole
+    raster (crop is a no-op there); GEOM_HOLE's interior window has nonzero
+    offsets, so its crop=True rows shift the transform and shrink the shape
+    while crop=False rows must fill outside an interior window."""
+    tiff = tmp_path / f"clip_{dtype}.tif"
+    write_geotiff(
+        tiff,
+        _test_data(dtype, band_nodata=BAND_NODATA[dtype]),
+        gdal_transform=GDAL_TRANSFORM,
+        nodata=BAND_NODATA[dtype],
+    )
+
+    rows = [
+        {
+            "wkt": wkt,
+            "band": band,
+            "all_touched": at,
+            "nodata": nd,
+            "crop": crop,
+        }
+        for wkt in (GEOM_TRIANGLE, GEOM_HOLE)
+        for band in (0, 1, 2, 3)
+        for at in (False, True)
+        for nd in (None, EXPLICIT_NODATA[dtype])
+        for crop in (True, False)
+    ]
+    results = sedona.clip_rows(tiff, rows)
+
+    for row, got in zip(rows, results):
+        assert got is not None, f"row: {row}"
+        fill = row["nodata"] if row["nodata"] is not None else BAND_NODATA[dtype]
+        _assert_clip_matches_reference(got, reference, tiff, row, fill)
+
+
+@pytest.mark.parametrize("all_touched", [False, True])
+@pytest.mark.parametrize(
+    "wkt",
+    [GEOM_RECT, GEOM_TRIANGLE, GEOM_HOLE, GEOM_OVERHANG],
+    ids=["rect", "triangle", "hole", "overhang"],
+)
+def test_rs_clip_matches_rasterio_geometries(
+    sedona, reference, tmp_path, wkt, all_touched
+):
+    """Geometry shapes: axis-aligned, diagonal edges, interior ring, and an
+    envelope overhanging the raster edge (crop window = envelope ∩ extent)."""
+    tiff = tmp_path / "clip_geom.tif"
+    write_geotiff(
+        tiff,
+        _test_data("uint8"),
+        gdal_transform=GDAL_TRANSFORM,
+        nodata=BAND_NODATA["uint8"],
+    )
+
+    row = {
+        "wkt": wkt,
+        "band": 0,
+        "all_touched": all_touched,
+        "nodata": None,
+        "crop": True,
+    }
+    got = sedona.clip(tiff, wkt, all_touched=all_touched)
+    assert got is not None
+    _assert_clip_matches_reference(got, reference, tiff, row, BAND_NODATA["uint8"])
+
+
+@pytest.mark.parametrize("dtype", list(EXPLICIT_NODATA) + ["int8", "int64", "uint64"])
+def test_rs_clip_default_nodata_sentinel_matches_rasterio(
+    sedona, reference, tmp_path, dtype
+):
+    """No explicit nodata and no band nodata: masked pixels get the dtype
+    minimum (exact even for 64-bit integers — no f64 round-trip), and the
+    output band records it. GEOM_TRIANGLE leaves most of its crop window
+    outside the geometry, so the sentinel is actually written to pixels, not
+    just metadata. rasterio is handed the same sentinel because its own
+    nodata-less fallback is 0."""
+    tiff = tmp_path / f"clip_sentinel_{dtype}.tif"
+    write_geotiff(tiff, _test_data(dtype), gdal_transform=GDAL_TRANSFORM)
+
+    row = {
+        "wkt": GEOM_TRIANGLE,
+        "band": 1,
+        "all_touched": False,
+        "nodata": None,
+        "crop": True,
+    }
+    got = sedona.clip(tiff, GEOM_TRIANGLE, band=1)
+    assert got is not None
+    _assert_clip_matches_reference(got, reference, tiff, row, dtype_min(dtype))
+
+
+def test_rs_clip_signature_defaults(con, tmp_path):
+    """Each shorter signature behaves as the full 7-arg form with the defaults
+    filled in: all_touched = false, no_data_value = the band's own, crop = true,
+    lenient = true."""
+    tiff = tmp_path / "clip_sigs.tif"
+    write_geotiff(
+        tiff,
+        _test_data("uint8"),
+        gdal_transform=GDAL_TRANSFORM,
+        nodata=BAND_NODATA["uint8"],
+    )
+    df = con.create_data_frame(
+        pa.table({"path": pa.array([str(tiff)]), "wkt": pa.array([GEOM_TRIANGLE])})
+    )
+
+    def clip(**kwargs):
+        expr = df.path.funcs.rs_frompath().rst.clip(
+            1, con.funcs.st_geomfromtext(df.wkt), **kwargs
+        )
+        return decode_raster(df.select(r=expr).to_arrow_table()["r"][0])
+
+    full = clip(all_touched=False, no_data_value=lit(None), crop=True, lenient=True)
+    for kwargs in [
+        {},
+        {"all_touched": False},
+        {"all_touched": False, "no_data_value": lit(None)},
+    ]:
+        result = clip(**kwargs)
+        np.testing.assert_array_equal(
+            result.pixels, full.pixels, err_msg=f"kwargs: {kwargs!r}"
+        )
+        assert result.gdal_transform == full.gdal_transform, f"kwargs: {kwargs!r}"
+        assert result.nodata == full.nodata, f"kwargs: {kwargs!r}"
+
+    # One SQL-text invocation retained so the SQL parser path stays covered
+    # (everything else in this module routes through the expression API).
+    sql_tab = con.sql(
+        "SELECT RS_Clip(RS_FromPath($1), 1, ST_GeomFromText($2)) AS r",
+        params=(str(tiff), GEOM_TRIANGLE),
+    ).to_arrow_table()
+    sql_result = decode_raster(sql_tab["r"][0])
+    np.testing.assert_array_equal(sql_result.pixels, full.pixels)
+    assert sql_result.nodata == full.nodata
+
+
+def test_rs_clip_empty_mask_is_null_when_lenient(sedona, reference, tmp_path):
+    """rasterio has no equivalent of lenient: a geometry selecting no pixels
+    (sliver between pixel centers, or fully disjoint) yields NULL by default,
+    and all_touched rescues the sliver case."""
+    tiff = tmp_path / "clip_empty.tif"
+    write_geotiff(
+        tiff,
+        _test_data("uint8"),
+        gdal_transform=GDAL_TRANSFORM,
+        nodata=BAND_NODATA["uint8"],
+    )
+
+    rows = [
+        {
+            "wkt": GEOM_SLIVER,
+            "band": 1,
+            "all_touched": False,
+            "nodata": None,
+            "crop": True,
+        },
+        {
+            "wkt": GEOM_DISJOINT,
+            "band": 1,
+            "all_touched": False,
+            "nodata": None,
+            "crop": True,
+        },
+        {
+            "wkt": GEOM_SLIVER,
+            "band": 1,
+            "all_touched": True,
+            "nodata": None,
+            "crop": True,
+        },
+    ]
+    results = sedona.clip_rows(tiff, rows)
+
+    assert results[0] is None
+    assert results[1] is None
+    assert results[2] is not None
+    _assert_clip_matches_reference(
+        results[2], reference, tiff, rows[2], BAND_NODATA["uint8"]
+    )
+
+
+def test_rs_clip_strict_and_argument_errors(con, tmp_path):
+    """Error pathways: strict (lenient = false) empty-mask messages depend on
+    all_touched; a non-representable nodata and an out-of-range band error
+    regardless of leniency."""
+    tiff = tmp_path / "clip_errors.tif"
+    write_geotiff(
+        tiff,
+        _test_data("uint8"),
+        gdal_transform=GDAL_TRANSFORM,
+        nodata=BAND_NODATA["uint8"],
+    )
+
+    def clip_strict(geom_wkt, *, all_touched=False, nodata=None, band=1):
+        df = con.create_data_frame(
+            pa.table({"path": pa.array([str(tiff)]), "wkt": pa.array([geom_wkt])})
+        )
+        expr = df.path.funcs.rs_frompath().rst.clip(
+            band,
+            con.funcs.st_geomfromtext(df.wkt),
+            all_touched=all_touched,
+            no_data_value=lit(None) if nodata is None else nodata,
+            crop=True,
+            lenient=False,
+        )
+        return df.select(r=expr).to_arrow_table()
+
+    with pytest.raises(Exception, match="do not intersect"):
+        clip_strict(GEOM_DISJOINT, all_touched=True)
+    with pytest.raises(Exception, match="selects no pixels"):
+        clip_strict(GEOM_SLIVER)
+    with pytest.raises(Exception, match="not a valid UInt8 value"):
+        clip_strict(GEOM_RECT, nodata=-5.0)
+    with pytest.raises(Exception, match="out of range"):
+        clip_strict(GEOM_RECT, band=4)
diff --git a/python/sedonadb/tests/test_raster.py b/python/sedonadb/tests/test_raster.py
index 574d62396..01b403a9d 100644
--- a/python/sedonadb/tests/test_raster.py
+++ b/python/sedonadb/tests/test_raster.py
@@ -399,3 +399,48 @@ def test_get_binary_view_buffer_sliced():
         mv = _get_binary_view_buffer(arr, index=i)
         assert mv is not None
         assert bytes(mv) == expected
+
+
+@pytest.mark.parametrize(
+    ("dtype", "nodata"),
+    [
+        ("uint8", 200),
+        ("int8", -100),
+        ("uint16", 60000),
+        ("int16", -8888),
+        ("uint32", 4_000_000_000),
+        ("int32", -88888),
+        ("uint64", 2**64 - 1),
+        ("int64", -(2**63)),
+        ("float32", -9999.5),
+        ("float64", -12345.5),
+    ],
+)
+def test_band_nodata(dtype, nodata):
+    r = Raster.from_numpy(np.zeros((2, 3), dtype=dtype), nodata=nodata)
+    assert r.bands[0].nodata == nodata
+
+
+def test_band_nodata_unset():
+    r = Raster.from_numpy(np.zeros((2, 3), dtype="uint8"))
+    assert r.bands[0].nodata is None
+
+
+def test_raster_to_numpy_single_band_is_zero_copy():
+    data = np.arange(6, dtype="float32").reshape(2, 3)
+    r = Raster.from_numpy(data)
+    out = r.to_numpy()
+
+    assert out.shape == (1, 2, 3)
+    np.testing.assert_array_equal(out[0], data)
+    assert np.shares_memory(out, r.bands[0].to_numpy())
+
+
+def test_raster_to_numpy_multiband_stacks(con):
+    tab = con.sql("SELECT RS_Example() AS raster").to_arrow_table()
+    r = tab["raster"][0].as_py()
+    out = r.to_numpy()
+
+    assert out.shape == (3, 32, 64)
+    for i, band in enumerate(r.bands):
+        np.testing.assert_array_equal(out[i], band.to_numpy())
diff --git a/rust/sedona-raster-functions/src/crs_utils.rs b/rust/sedona-raster-functions/src/crs_utils.rs
index 35dd77afb..07ebb754c 100644
--- a/rust/sedona-raster-functions/src/crs_utils.rs
+++ b/rust/sedona-raster-functions/src/crs_utils.rs
@@ -17,11 +17,32 @@
 
 use std::borrow::Cow;
 
+use datafusion_common::config::ConfigOptions;
 use datafusion_common::{exec_datafusion_err, exec_err, DataFusionError, Result};
+use sedona_common::option::SedonaOptions;
 use sedona_geometry::transform::{transform, CrsEngine};
+use sedona_proj::transform::with_global_proj_engine;
 use sedona_schema::crs::{deserialize_crs, CoordinateReferenceSystem, Crs, CrsRef};
 use wkb::reader::read_wkb;
 
+/// Run `f` with the session's CRS engine: the [`SedonaOptions`] runtime engine
+/// when config options are available (the query path), falling back to the
+/// process-global PROJ engine otherwise (e.g. direct `invoke_batch` calls).
+pub fn with_crs_engine<T>(
+    config_options: Option<&ConfigOptions>,
+    f: impl FnOnce(&dyn CrsEngine) -> Result<T>,
+) -> Result<T> {
+    if let Some(options) = config_options.and_then(|o| o.extensions.get::<SedonaOptions>()) {
+        f(options.runtime.crs_engine().as_ref())
+    } else {
+        let mut f = Some(f);
+        with_global_proj_engine(|engine| {
+            let f = f.take().expect("engine closure runs once");
+            f(engine)
+        })
+    }
+}
+
 /// Resolve an optional CRS string to a concrete CRS object.
 ///
 /// - If `crs_str` is `Some` and deserializes to a known CRS, that CRS is returned.
diff --git a/rust/sedona-raster-functions/src/executor.rs b/rust/sedona-raster-functions/src/executor.rs
index 3e7ea71fc..0e03029ae 100644
--- a/rust/sedona-raster-functions/src/executor.rs
+++ b/rust/sedona-raster-functions/src/executor.rs
@@ -665,18 +665,32 @@ impl<'a, 'b> RasterExecutor<'a, 'b> {
     /// Converts the output into a [ColumnarValue::Scalar] if all arguments were scalars,
     /// or a [ColumnarValue::Array] otherwise.
     pub fn finish(&self, out: ArrayRef) -> Result<ColumnarValue> {
-        for arg in self.args {
-            match arg {
-                // If any argument was an array, we return an array
-                ColumnarValue::Array(_) => {
-                    return Ok(ColumnarValue::Array(out));
-                }
-                ColumnarValue::Scalar(_) => {}
-            }
+        Self::finish_over(self.args, out)
+    }
+
+    /// Like [`Self::finish`], but decides array-vs-scalar over an explicit
+    /// argument list. For kernels that project only their raster/geometry
+    /// arguments into the executor (via [`Self::new_with_num_iterations`]),
+    /// pass the *full* UDF argument list: a per-row option column over a
+    /// scalar raster/geometry must still yield an N-row array.
+    pub fn finish_over(args: &[ColumnarValue], out: ArrayRef) -> Result<ColumnarValue> {
+        if args
+            .iter()
+            .any(|arg| matches!(arg, ColumnarValue::Array(_)))
+        {
+            Ok(ColumnarValue::Array(out))
+        } else {
+            Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(&out, 0)?))
         }
+    }
 
-        // All arguments are scalars, return a scalar
-        Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(&out, 0)?))
+    /// The number of rows implied by an argument list: the length of the first
+    /// array argument, or 1 when every argument is a scalar. The public
+    /// counterpart of the row count the constructor derives, for kernels that
+    /// need it over their *full* argument list before projecting a subset into
+    /// the executor (see [`Self::new_with_num_iterations`]).
+    pub fn num_iterations_over(args: &[ColumnarValue]) -> usize {
+        Self::calc_num_iterations(args)
     }
 
     /// Calculates the number of iterations that should happen based on the
diff --git a/rust/sedona-raster-gdal/Cargo.toml b/rust/sedona-raster-gdal/Cargo.toml
index a5d58f876..e30ad1da4 100644
--- a/rust/sedona-raster-gdal/Cargo.toml
+++ b/rust/sedona-raster-gdal/Cargo.toml
@@ -42,6 +42,7 @@ sedona-common = { workspace = true }
 sedona-expr = { workspace = true }
 sedona-functions = { workspace = true }
 sedona-gdal = { workspace = true }
+sedona-proj = { workspace = true }
 sedona-raster = { workspace = true }
 sedona-raster-functions = { workspace = true }
 sedona-schema = { workspace = true }
@@ -54,11 +55,16 @@ bindgen = ["sedona-gdal/bindgen"]
 [dev-dependencies]
 criterion = { workspace = true }
 sedona-gdal = { workspace = true, features = ["gdal-sys"] }
-sedona-testing = { workspace = true }
 sedona-proj = { workspace = true, features = ["proj-sys"] }
+sedona-testing = { workspace = true, features = ["criterion"] }
 tempfile = { workspace = true }
 tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
 
+[[bench]]
+harness = false
+name = "rs_clip"
+path = "benches/rs_clip.rs"
+
 [[bench]]
 harness = false
 name = "rs_frompath"
diff --git a/rust/sedona-raster-gdal/benches/rs_clip.rs b/rust/sedona-raster-gdal/benches/rs_clip.rs
new file mode 100644
index 000000000..d499bec14
--- /dev/null
+++ b/rust/sedona-raster-gdal/benches/rs_clip.rs
@@ -0,0 +1,140 @@
+// 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.
+
+//! Benchmarks for the RS_Clip UDF.
+//!
+//! RS_Clip rasterizes the clip geometry into a mask, sets pixels outside it to
+//! nodata, and (by default) crops to the geometry's bounding box.
+//!
+//! Each case builds a raster whose world extent is exactly the clip-polygon
+//! generator's `[-10, 10]²` bounds at the requested resolution, so every
+//! generated polygon lands on the raster and the full mask/crop path runs.
+//! `all_touched = true` guarantees an overlapping polygon burns at least one
+//! pixel even when it is smaller than a cell (otherwise a sub-pixel polygon
+//! would produce an empty mask and hit the no-intersection early return — which
+//! is what an earlier version of this benchmark accidentally measured, because
+//! it placed the rasters far outside the polygons entirely).
+//!
+//! Axes:
+//! - **Raster resolution** (`64²`, `256²`, `1024²`) with a small polygon: cost
+//!   is dominated by O(width × height) mask handling (rasterize + mask scan).
+//! - **Clip polygon complexity** (vertex count) at a fixed resolution, driving
+//!   the GDAL rasterization cost.
+//! - **Large clip**: a polygon covering most of the raster, so the mask/crop
+//!   copy (`apply_mask_and_crop`) dominates rather than mask rasterization.
+
+use std::sync::Arc;
+
+use arrow_array::{ArrayRef, BinaryArray, BooleanArray, Int32Array};
+use arrow_schema::DataType;
+use criterion::{criterion_group, criterion_main, Criterion};
+use datafusion_expr::ScalarUDF;
+use sedona_schema::datatypes::{SedonaType, RASTER, WKB_GEOMETRY};
+use sedona_testing::{
+    benchmark_util::BenchmarkArgSpec, create::make_wkb, raster_spec::RasterSpec,
+    testers::ScalarUdfTester,
+};
+
+fn criterion_benchmark(c: &mut Criterion) {
+    let f = sedona_raster_gdal::register::default_function_set();
+    let udf: ScalarUDF = f
+        .scalar_udf("rs_clip")
+        .expect("rs_clip is registered")
+        .clone()
+        .into();
+
+    // RS_Clip(raster, band, geom, all_touched).
+    let tester = ScalarUdfTester::new(
+        udf,
+        vec![
+            RASTER,
+            SedonaType::Arrow(DataType::Int32),
+            WKB_GEOMETRY,
+            SedonaType::Arrow(DataType::Boolean),
+        ],
+    );
+
+    let band: ArrayRef = Arc::new(Int32Array::from(vec![1]));
+    let all_touched: ArrayRef = Arc::new(BooleanArray::from(vec![true]));
+
+    // A north-up raster covering exactly the polygon generator's [-10, 10]²
+    // bounds at the requested resolution, so every generated polygon overlaps.
+    let build_raster = |w: i64, h: i64| -> ArrayRef {
+        let transform = [-10.0, 20.0 / w as f64, 0.0, 10.0, 0.0, -20.0 / h as f64];
+        let values = vec![1u8; (w * h) as usize];
+        Arc::new(
+            RasterSpec::d2(w, h)
+                .band_values(&values)
+                .crs(None)
+                .transform(transform)
+                .build(),
+        )
+    };
+
+    // `c` is passed in rather than captured, so several cases can share it.
+    let run = |c: &mut Criterion, label: &str, raster: ArrayRef, geom: ArrayRef| {
+        c.bench_function(label, |b| {
+            b.iter(|| {
+                tester
+                    .invoke_arrays(vec![
+                        raster.clone(),
+                        band.clone(),
+                        geom.clone(),
+                        all_touched.clone(),
+                    ])
+                    .unwrap()
+            })
+        });
+    };
+
+    let gen_polygon = |vertices: usize| -> ArrayRef {
+        BenchmarkArgSpec::Polygon(vertices)
+            .build_arrays(0, 1, 1)
+            .expect("build clip polygon")
+            .remove(0)
+    };
+
+    // Resolution sweep (simple 8-vertex polygon).
+    for (w, h) in [(64i64, 64i64), (256, 256), (1024, 1024)] {
+        let label = format!("raster-gdal rs_clip Clip(Raster({w}x{h}), Polygon(8))");
+        run(c, &label, build_raster(w, h), gen_polygon(8));
+    }
+
+    // Polygon-complexity axis at a fixed 64×64 resolution.
+    run(
+        c,
+        "raster-gdal rs_clip Clip(Raster(64x64), Polygon(50))",
+        build_raster(64, 64),
+        gen_polygon(50),
+    );
+
+    // Large clip: the polygon covers nearly the whole raster, so the crop copy
+    // (apply_mask_and_crop) dominates — this is where its row memcpy matters.
+    let big_geom: ArrayRef = Arc::new(BinaryArray::from_iter_values([make_wkb(
+        "POLYGON ((-9.5 -9.5, 9.5 -9.5, 9.5 9.5, -9.5 9.5, -9.5 -9.5))",
+    )
+    .as_slice()]));
+    run(
+        c,
+        "raster-gdal rs_clip Clip(Raster(1024x1024), Polygon(large))",
+        build_raster(1024, 1024),
+        big_geom,
+    );
+}
+
+criterion_group!(benches, criterion_benchmark);
+criterion_main!(benches);
diff --git a/rust/sedona-raster-gdal/src/lib.rs b/rust/sedona-raster-gdal/src/lib.rs
index 5e16602ca..8892224c1 100644
--- a/rust/sedona-raster-gdal/src/lib.rs
+++ b/rust/sedona-raster-gdal/src/lib.rs
@@ -34,6 +34,7 @@ mod gdal_dataset_provider;
 
 mod raster_loader;
 mod rs_as_raster;
+mod rs_clip;
 mod rs_frompath;
 mod rs_metadata;
 mod rs_polygonize;
@@ -47,6 +48,7 @@ pub use gdal_common::{
 };
 pub use raster_loader::{GdalLoader, GDAL_FORMAT};
 pub use rs_as_raster::rs_as_raster_udf;
+pub use rs_clip::rs_clip_udf;
 pub use rs_frompath::rs_frompath_udf;
 pub use rs_metadata::rs_metadata_udf;
 pub use rs_polygonize::rs_polygonize_udf;
diff --git a/rust/sedona-raster-gdal/src/register.rs b/rust/sedona-raster-gdal/src/register.rs
index 38c6cde93..b8789825d 100644
--- a/rust/sedona-raster-gdal/src/register.rs
+++ b/rust/sedona-raster-gdal/src/register.rs
@@ -21,6 +21,7 @@ use sedona_expr::function_set::FunctionSet;
 pub fn default_function_set() -> FunctionSet {
     let mut function_set = FunctionSet::new();
     function_set.insert_scalar_udf(crate::rs_as_raster::rs_as_raster_udf());
+    function_set.insert_scalar_udf(crate::rs_clip::rs_clip_udf());
     function_set.insert_scalar_udf(crate::rs_frompath::rs_frompath_udf());
     function_set.insert_scalar_udf(crate::rs_metadata::rs_metadata_udf());
     function_set.insert_scalar_udf(crate::rs_polygonize::rs_polygonize_udf());
diff --git a/rust/sedona-raster-gdal/src/rs_clip.rs b/rust/sedona-raster-gdal/src/rs_clip.rs
new file mode 100644
index 000000000..6112ac8ae
--- /dev/null
+++ b/rust/sedona-raster-gdal/src/rs_clip.rs
@@ -0,0 +1,1435 @@
+// 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.
+
+//! RS_Clip UDF - Clip a raster to a geometry boundary
+//!
+//! Similar to PostGIS ST_Clip, this function clips a raster to the extent of a geometry.
+//! Pixels outside the geometry are set to a nodata value: the explicit `no_data_value`
+//! argument if given, otherwise the band's own nodata value, otherwise the minimum value
+//! of the band's data type (so masked pixels stay distinguishable from real data).
+
+use std::sync::Arc;
+
+use arrow_array::ArrayRef;
+use datafusion_common::cast::{as_boolean_array, as_float64_array, as_int32_array};
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::error::Result;
+use datafusion_common::exec_err;
+use datafusion_common::{exec_datafusion_err, ScalarValue};
+use datafusion_expr::{ColumnarValue, Volatility};
+use sedona_common::sedona_internal_err;
+use sedona_gdal::gdal::Gdal;
+use sedona_gdal::geo_transform::{GeoTransform, GeoTransformEx};
+use sedona_gdal::mem::MemDatasetBuilder;
+use sedona_gdal::raster::types::GdalDataType;
+use sedona_gdal::vector::geometry::Geometry;
+
+use arrow_schema::DataType;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_raster::array::RasterRefImpl;
+use sedona_raster::builder::RasterBuilder;
+use sedona_raster::traits::{is_spatial_dim_pair, RasterRef};
+use sedona_raster_functions::crs_utils::{crs_transform_wkb, resolve_crs, with_crs_engine};
+use sedona_raster_functions::rs_ensure_loaded::{
+    NEEDS_PIXELS_METADATA_KEY, RETURNS_BYTES_METADATA_KEY,
+};
+use sedona_raster_functions::RasterExecutor;
+use sedona_schema::datatypes::{SedonaType, RASTER};
+use sedona_schema::matchers::ArgMatcher;
+use sedona_schema::raster::BandDataType;
+
+use crate::gdal_common::with_gdal;
+use crate::gdal_dataset_provider::configure_thread_local_options;
+use sedona_raster::traits::nodata_f64_to_bytes;
+
+/// RS_Clip() scalar UDF implementation
+///
+/// Clips a raster to a geometry boundary.
+///
+/// Signatures:
+/// - `RS_Clip(raster, band, geom)` — 3 args
+/// - `RS_Clip(raster, band, geom, allTouched)` — 4 args
+/// - `RS_Clip(raster, band, geom, allTouched, noDataValue)` — 5 args
+/// - `RS_Clip(raster, band, geom, allTouched, noDataValue, crop)` — 6 args
+/// - `RS_Clip(raster, band, geom, allTouched, noDataValue, crop, lenient)` — 7 args
+pub fn rs_clip_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "rs_clip",
+        vec![
+            Arc::new(RsClip { arg_count: 3 }), // (raster, band, geom)
+            Arc::new(RsClip { arg_count: 4 }), // (raster, band, geom, allTouched)
+            Arc::new(RsClip { arg_count: 5 }), // (raster, band, geom, allTouched, noDataValue)
+            Arc::new(RsClip { arg_count: 6 }), // (raster, band, geom, allTouched, noDataValue, crop)
+            Arc::new(RsClip { arg_count: 7 }), // (raster, band, geom, allTouched, noDataValue, crop, lenient)
+        ],
+        Volatility::Immutable,
+    )
+    // Reads band pixels (so the planner materializes OutDb rasters via
+    // RS_EnsureLoaded first) and emits a fresh InDb raster (so its output is
+    // already loaded and isn't wrapped again).
+    .with_metadata(NEEDS_PIXELS_METADATA_KEY, "true")
+    .with_metadata(RETURNS_BYTES_METADATA_KEY, "true")
+}
+
+/// Kernel implementation for RS_Clip
+#[derive(Debug)]
+struct RsClip {
+    /// Number of arguments in the matched signature (3..=7)
+    arg_count: usize,
+}
+
+impl SedonaScalarKernel for RsClip {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matchers = match self.arg_count {
+            3 => vec![
+                // RS_Clip(raster, band, geom)
+                ArgMatcher::is_raster(),
+                ArgMatcher::is_integer(),
+                ArgMatcher::is_geometry_or_geography(),
+            ],
+            4 => vec![
+                // RS_Clip(raster, band, geom, allTouched)
+                ArgMatcher::is_raster(),
+                ArgMatcher::is_integer(),
+                ArgMatcher::is_geometry_or_geography(),
+                ArgMatcher::is_boolean(),
+            ],
+            5 => vec![
+                // RS_Clip(raster, band, geom, allTouched, noDataValue)
+                ArgMatcher::is_raster(),
+                ArgMatcher::is_integer(),
+                ArgMatcher::is_geometry_or_geography(),
+                ArgMatcher::is_boolean(),
+                ArgMatcher::is_numeric(),
+            ],
+            6 => vec![
+                // RS_Clip(raster, band, geom, allTouched, noDataValue, crop)
+                ArgMatcher::is_raster(),
+                ArgMatcher::is_integer(),
+                ArgMatcher::is_geometry_or_geography(),
+                ArgMatcher::is_boolean(),
+                ArgMatcher::is_numeric(),
+                ArgMatcher::is_boolean(),
+            ],
+            7 => vec![
+                // RS_Clip(raster, band, geom, allTouched, noDataValue, crop, lenient)
+                ArgMatcher::is_raster(),
+                ArgMatcher::is_integer(),
+                ArgMatcher::is_geometry_or_geography(),
+                ArgMatcher::is_boolean(),
+                ArgMatcher::is_numeric(),
+                ArgMatcher::is_boolean(),
+                ArgMatcher::is_boolean(),
+            ],
+            _ => {
+                return sedona_internal_err!("RS_Clip: unexpected arg_count {}", self.arg_count);
+            }
+        };
+
+        let matcher = ArgMatcher::new(matchers, RASTER);
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        self.invoke_batch_from_args(arg_types, args, &SedonaType::Arrow(DataType::Null), 0, None)
+    }
+
+    fn invoke_batch_from_args(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+        _return_type: &SedonaType,
+        _num_rows: usize,
+        config_options: Option<&ConfigOptions>,
+    ) -> Result<ColumnarValue> {
+        let num_iterations = RasterExecutor::num_iterations_over(args);
+
+        // Band is always at index 1, geom is always at index 2.
+        let geom_arg_idx: usize = 2;
+
+        // Expand band to array
+        let band_array = args[1]
+            .clone()
+            .cast_to(&arrow_schema::DataType::Int32, None)?
+            .into_array(num_iterations)?;
+        let band_array = as_int32_array(&band_array)?.clone();
+
+        // allTouched at index 3 (when arg_count >= 4)
+        let all_touched_array = if self.arg_count >= 4 {
+            args[3]
+                .clone()
+                .cast_to(&arrow_schema::DataType::Boolean, None)?
+                .into_array(num_iterations)?
+        } else {
+            ScalarValue::Boolean(Some(false)).to_array_of_size(num_iterations)?
+        };
+        let all_touched_array = as_boolean_array(&all_touched_array)?.clone();
+
+        // noDataValue at index 4 (when arg_count >= 5)
+        let nodata_array = if self.arg_count >= 5 {
+            args[4]
+                .clone()
+                .cast_to(&arrow_schema::DataType::Float64, None)?
+                .into_array(num_iterations)?
+        } else {
+            ScalarValue::Float64(None).to_array_of_size(num_iterations)?
+        };
+        let nodata_array = as_float64_array(&nodata_array)?.clone();
+
+        // crop at index 5 (when arg_count >= 6), default true
+        let crop_array = if self.arg_count >= 6 {
+            args[5]
+                .clone()
+                .cast_to(&arrow_schema::DataType::Boolean, None)?
+                .into_array(num_iterations)?
+        } else {
+            ScalarValue::Boolean(Some(true)).to_array_of_size(num_iterations)?
+        };
+        let crop_array = as_boolean_array(&crop_array)?.clone();
+
+        // lenient at index 6 (when arg_count >= 7), default true
+        let lenient_array = if self.arg_count >= 7 {
+            args[6]
+                .clone()
+                .cast_to(&arrow_schema::DataType::Boolean, None)?
+                .into_array(num_iterations)?
+        } else {
+            ScalarValue::Boolean(Some(true)).to_array_of_size(num_iterations)?
+        };
+        let lenient_array = as_boolean_array(&lenient_array)?.clone();
+
+        let mut band_iter = band_array.iter();
+        let mut all_touched_iter = all_touched_array.iter();
+        let mut nodata_iter = nodata_array.iter();
+        let mut crop_iter = crop_array.iter();
+        let mut lenient_iter = lenient_array.iter();
+
+        // Build output rasters
+        let mut builder = RasterBuilder::new(num_iterations);
+
+        let exec_arg_types = vec![arg_types[0].clone(), arg_types[geom_arg_idx].clone()];
+        let exec_args = vec![args[0].clone(), args[geom_arg_idx].clone()];
+        let executor =
+            RasterExecutor::new_with_num_iterations(&exec_arg_types, &exec_args, num_iterations);
+
+        with_gdal(|gdal| {
+            configure_thread_local_options(gdal, config_options)?;
+            with_crs_engine(config_options, |engine| {
+                executor.execute_raster_wkb_crs_void(|raster_opt, wkb_opt, geom_crs| {
+                // Advance every option iterator in lockstep. A NULL in the band
+                // or any boolean flag propagates to a NULL output row (SQL
+                // semantics) — in particular a NULL band must NOT fall through
+                // to the "band 0 = all bands" mode. `no_data_value` is the
+                // exception: its NULL is the meaningful "not supplied" sentinel
+                // (the 3/4-arg signatures pass NULL here), so it stays an Option.
+                let band = band_iter.next().flatten();
+                let all_touched = all_touched_iter.next().flatten();
+                let nodata_value = nodata_iter.next().flatten();
+                let crop = crop_iter.next().flatten();
+                let lenient = lenient_iter.next().flatten();
+                let (Some(band), Some(all_touched), Some(crop), Some(lenient)) =
+                    (band, all_touched, crop, lenient)
+                else {
+                    builder.append_null()?;
+                    return Ok(());
+                };
+
+                let (raster, geom_wkb) = match (raster_opt, wkb_opt) {
+                    (Some(r), Some(w)) => (r, w),
+                    _ => {
+                        builder.append_null()?;
+                        return Ok(());
+                    }
+                };
+
+                let raster_crs = resolve_crs(raster.crs())?;
+                let geom_wkb = match (geom_crs, raster_crs.as_deref()) {
+                    (Some(geom_crs), Some(raster_crs)) => {
+                        crs_transform_wkb(geom_wkb, geom_crs, raster_crs, engine)?
+                    }
+                    (None, None) => geom_wkb.to_vec(),
+                    (Some(_), None) => {
+                        return exec_err!(
+                            "Cannot operate on geometry and raster: raster has no CRS but geometry does"
+                        )
+                    }
+                    (None, Some(_)) => {
+                        return exec_err!(
+                            "Cannot operate on geometry and raster: geometry has no CRS but raster does"
+                        )
+                    }
+                };
+
+                // Band 0 means "all bands" (handled in clip_raster, which also
+                // range-checks the upper bound). A negative band is an error,
+                // not a silent clamp to band 1.
+                if band < 0 {
+                    return exec_err!(
+                        "RS_Clip: band must be >= 0 (0 = all bands), got {band}"
+                    );
+                }
+                let band_index = band as usize;
+                match clip_raster(
+                    gdal,
+                    raster,
+                    &geom_wkb,
+                    band_index,
+                    nodata_value,
+                    all_touched,
+                    crop,
+                ) {
+                    Ok(Some(clipped_data)) => {
+                        build_clipped_raster(&mut builder, raster, &clipped_data)?
+                    }
+                    Ok(None) => {
+                        // The clip mask is empty — no pixel was selected. `lenient`
+                        // yields NULL either way; strict errors, with a message
+                        // conditioned on `all_touched`: when it is already true an
+                        // empty mask means the geometry is genuinely disjoint,
+                        // whereas with the default `all_touched = false` the
+                        // geometry may still overlap but fall between pixel centers.
+                        if lenient {
+                            builder.append_null()?;
+                        } else if all_touched {
+                            return exec_err!("RS_Clip: raster and geometry do not intersect");
+                        } else {
+                            return exec_err!(
+                                "RS_Clip: geometry selects no pixels; it may fall between \
+                                 pixel centers — pass all_touched => true to keep any pixel it touches"
+                            );
+                        }
+                    }
+                    // A genuine failure (malformed WKB, GDAL error, …) always
+                    // propagates — it is not the no-intersection case `lenient`
+                    // is meant to soften.
+                    Err(e) => return Err(e),
+                }
+
+                Ok(())
+            })
+            })?;
+
+            // Decide array-vs-scalar over *all* args, not just the raster/geom
+            // the executor was given: a per-row band/option column over a scalar
+            // raster+geom must still yield an N-row array.
+            let out: ArrayRef = Arc::new(builder.finish()?);
+            RasterExecutor::finish_over(args, out)
+        })
+    }
+}
+
+/// One clipped band: masked/cropped bytes plus the N-D layout needed to rebuild
+/// it. The clip is a 2-D `(y, x)` operation broadcast across every non-spatial
+/// plane, so `dim_names` are unchanged from the source and only the trailing
+/// `(y, x)` extent of `shape` shrinks when cropping.
+struct ClippedBand {
+    /// Masked/cropped bytes, plane-major in the band's dim order.
+    data: Vec<u8>,
+    /// Visible dim names, unchanged from the source band (e.g. `["time","y","x"]`).
+    dim_names: Vec<String>,
+    /// Output shape: leading non-spatial dims unchanged, trailing `(y, x)` clipped.
+    shape: Vec<i64>,
+    data_type: BandDataType,
+    /// nodata sentinel bytes written for masked-out pixels.
+    nodata: Vec<u8>,
+    /// Source band name, preserved so clipping a named/N-D band keeps it
+    /// addressable by name on the output.
+    name: Option<String>,
+}
+
+/// Data for a clipped raster
+struct ClippedRasterData {
+    /// One entry per processed band.
+    bands: Vec<ClippedBand>,
+    /// Crop window in pixel coordinates (col_off, row_off, width, height):
+    /// the geometry's envelope intersected with the raster extent, snapped
+    /// outward to the pixel grid. `None` means the full original raster
+    /// extent was kept (crop=false).
+    crop_window: Option<CropWindow>,
+}
+
+/// A rectangular crop window in pixel coordinates.
+#[derive(Debug, Clone, Copy)]
+struct CropWindow {
+    col_off: usize,
+    row_off: usize,
+    width: usize,
+    height: usize,
+}
+
+/// Clip a raster to a geometry.
+///
+/// Returns `Ok(None)` when the geometry does not intersect the raster extent
+/// (caller decides how to handle based on `lenient`).
+fn clip_raster(
+    gdal: &Gdal,
+    raster: &RasterRefImpl<'_>,
+    geom_wkb: &[u8],
+    band_num: usize,
+    custom_nodata: Option<f64>,
+    all_touched: bool,
+    crop: bool,
+) -> Result<Option<ClippedRasterData>> {
+    let metadata = raster.metadata();
+    let bands = raster.bands();
+    let width = metadata.width() as usize;
+    let height = metadata.height() as usize;
+
+    // Parse geometry from WKB
+    let geometry = gdal
+        .geometry_from_wkb(geom_wkb)
+        .map_err(|e| exec_datafusion_err!("Failed to parse geometry from WKB: {}", e))?;
+
+    let geotransform = [
+        metadata.upper_left_x(),
+        metadata.scale_x(),
+        metadata.skew_x(),
+        metadata.upper_left_y(),
+        metadata.skew_y(),
+        metadata.scale_y(),
+    ];
+
+    // The clip window is the geometry's envelope intersected with the raster
+    // extent, snapped outward to the pixel grid — the window PostGIS ST_Clip,
+    // `gdalwarp -crop_to_cutline`, and Sedona Spark's RS_Clip use. Knowing it
+    // up front rejects disjoint geometries before any GDAL work and bounds the
+    // mask to the window instead of the full raster.
+    let Some(window) = envelope_window(&geometry, &geotransform, width, height)? else {
+        return Ok(None);
+    };
+
+    // Create a mask raster covering only the clip window, with the geotransform
+    // shifted to the window's upper-left corner.
+    let mask_dataset =
+        MemDatasetBuilder::create(gdal, window.width, window.height, 1, GdalDataType::UInt8)
+            .map_err(|e| exec_datafusion_err!("Failed to create mask dataset: {}", e))?;
+    let (window_ulx, window_uly) = geotransform.apply(window.col_off as f64, window.row_off as f64);
+    let mask_geotransform = [
+        window_ulx,
+        geotransform[1],
+        geotransform[2],
+        window_uly,
+        geotransform[4],
+        geotransform[5],
+    ];
+    mask_dataset
+        .set_geo_transform(&mask_geotransform)
+        .map_err(|e| exec_datafusion_err!("Failed to set geotransform: {}", e))?;
+
+    // GDAL's MEM driver zero-fills owned band buffers at creation, so the mask
+    // already reads 0 (outside) everywhere; rasterize_affine burns 1 inside the
+    // geometry. No explicit zero-init write needed.
+    gdal.rasterize_affine(
+        &mask_dataset,
+        &[1], // band 1
+        &[geometry],
+        &[1.0], // burn value = 1 (inside)
+        all_touched,
+    )
+    .map_err(|e| exec_datafusion_err!("Failed to rasterize geometry: {}", e))?;
+
+    // Read the (window-sized) mask
+    let mask_band = mask_dataset
+        .rasterband(1)
+        .map_err(|e| exec_datafusion_err!("Failed to get mask band: {}", e))?;
+    let mask_buffer = mask_band
+        .read_as::<u8>(
+            (0, 0),
+            (window.width, window.height),
+            (window.width, window.height),
+            None,
+        )
+        .map_err(|e| exec_datafusion_err!("Failed to read mask: {}", e))?;
+    let mask = mask_buffer.data();
+
+    // The envelope may overlap the raster while the geometry itself selects no
+    // pixel (e.g. it falls between pixel centers); that is still the
+    // no-intersection case.
+    let has_intersection = mask.iter().any(|&v| v != 0);
+    if !has_intersection {
+        return Ok(None);
+    }
+
+    let crop_window = if crop { Some(window) } else { None };
+
+    // Determine which bands to process
+    let band_indices: Vec<usize> = if band_num == 0 {
+        (1..=bands.len()).collect()
+    } else {
+        if band_num > bands.len() {
+            return exec_err!("Band {} is out of range (1-{})", band_num, bands.len());
+        }
+        vec![band_num]
+    };
+
+    // Process each band. The clip is a 2-D (y, x) operation; for an N-D band
+    // (extra leading dims such as time) the same mask and crop window are
+    // broadcast across every non-spatial plane.
+    let mut clipped_bands = Vec::with_capacity(band_indices.len());
+
+    for &band_idx in &band_indices {
+        let band = bands
+            .band(band_idx)
+            .map_err(|e| exec_datafusion_err!("Failed to get band {}: {}", band_idx, e))?;
+        // `band_idx` is 1-based; the `band_name` accessor is 0-based.
+        let band_name = raster.band_name(band_idx - 1).map(|s| s.to_string());
+
+        let band_metadata = band.metadata();
+        let data_type = band_metadata.data_type()?;
+
+        // The trailing two axes are the spatial (y, x) plane; anything before
+        // them is a stack of planes the 2-D clip is broadcast over.
+        let shape = band.shape().to_vec();
+        let dim_names: Vec<String> = band.dim_names().iter().map(|s| s.to_string()).collect();
+        let ndim = shape.len();
+        if ndim < 2 {
+            return exec_err!(
+                "RS_Clip: band {} has {} dimension(s); a 2-D (y, x) plane is required",
+                band_idx,
+                ndim
+            );
+        }
+        // The trailing two dims must actually be the spatial (y, x) pair. A band
+        // whose trailing dims are e.g. ["x","y"] is legal at the format level and
+        // would otherwise be masked/cropped transposed on a square raster; mirror
+        // the `is_spatial_dim_pair` guard the GDAL bridge (gdal_common) performs.
+        if !is_spatial_dim_pair(&dim_names[ndim - 2], &dim_names[ndim - 1]) {
+            return exec_err!(
+                "RS_Clip: band {} trailing dims {:?} are not a (y, x) spatial pair",
+                band_idx,
+                &dim_names[ndim - 2..]
+            );
+        }
+        let (plane_h, plane_w) = (shape[ndim - 2] as usize, shape[ndim - 1] as usize);
+        if plane_w != width || plane_h != height {
+            return exec_err!(
+                "RS_Clip: band {} spatial extent {}x{} does not match the raster {}x{}",
+                band_idx,
+                plane_w,
+                plane_h,
+                width,
+                height
+            );
+        }
+        let n_planes: usize = shape[..ndim - 2].iter().map(|&d| d as usize).product();
+
+        // `as_contiguous` borrows the band bytes; we only ever read them here
+        // (the mask/crop helpers allocate their own output), so no copy is needed.
+        let nd_buffer = band.nd_buffer().map_err(|e| {
+            exec_datafusion_err!("RS_Clip: failed to read band {}: {}", band_idx, e)
+        })?;
+        let original_data = nd_buffer.as_contiguous().map_err(|e| {
+            exec_datafusion_err!("RS_Clip: band {} is not contiguous: {}", band_idx, e)
+        })?;
+
+        // nodata precedence: the explicit argument, then the band's own nodata
+        // bytes (used verbatim — no lossy f64 round-trip for Int64/UInt64),
+        // then the band data type's minimum value. An explicit value that is
+        // not exactly representable in the band's data type (fractional for an
+        // integer band, out of range, or a 64-bit integer beyond 2^53) errors
+        // rather than silently saturating — e.g. -9999 on UInt8 would collide
+        // with real zero-adjacent data.
+        let nodata_bytes: Vec<u8> = match custom_nodata {
+            Some(cn) => nodata_f64_to_bytes(cn, &data_type).map_err(|e| {
+                exec_datafusion_err!("RS_Clip: invalid no_data_value for band {band_idx}: {e}")
+            })?,
+            None => match band_metadata.nodata_value() {
+                Some(bytes) => bytes.to_vec(),
+                None => data_type.min_value_le_bytes(),
+            },
+        };
+
+        let byte_size = data_type.byte_size();
+        let in_plane_bytes = width * height * byte_size;
+        if original_data.len() != n_planes * in_plane_bytes {
+            return exec_err!(
+                "RS_Clip: band {} byte length {} does not match {} planes of {}x{}",
+                band_idx,
+                original_data.len(),
+                n_planes,
+                width,
+                height
+            );
+        }
+
+        // Apply the (shared) mask/crop to each plane, then concatenate.
+        let out_plane_bytes = match crop_window {
+            Some(cw) => cw.width * cw.height * byte_size,
+            None => in_plane_bytes,
+        };
+        let mut clipped_data = Vec::with_capacity(n_planes * out_plane_bytes);
+        for plane in 0..n_planes {
+            let plane_bytes = &original_data[plane * in_plane_bytes..(plane + 1) * in_plane_bytes];
+            let clipped_plane = if let Some(cw) = crop_window {
+                apply_mask_and_crop(plane_bytes, mask, width, &data_type, &nodata_bytes, &cw)?
+            } else {
+                apply_mask_to_band(
+                    plane_bytes,
+                    mask,
+                    width,
+                    height,
+                    &data_type,
+                    &nodata_bytes,
+                    &window,
+                )?
+            };
+            clipped_data.extend_from_slice(&clipped_plane);
+        }
+
+        // Output shape: leading dims unchanged; trailing (y, x) becomes the crop
+        // window when cropping, else the original plane extent.
+        let (out_h, out_w) = match crop_window {
+            Some(cw) => (cw.height as i64, cw.width as i64),
+            None => (height as i64, width as i64),
+        };
+        let mut out_shape = shape[..ndim - 2].to_vec();
+        out_shape.push(out_h);
+        out_shape.push(out_w);
+
+        clipped_bands.push(ClippedBand {
+            data: clipped_data,
+            dim_names,
+            shape: out_shape,
+            data_type,
+            nodata: nodata_bytes,
+            name: band_name,
+        });
+    }
+
+    Ok(Some(ClippedRasterData {
+        bands: clipped_bands,
+        crop_window,
+    }))
+}
+
+/// Compute the clip window: the geometry's envelope intersected with the
+/// raster extent, snapped outward to the pixel grid. Returns `None` when the
+/// envelope is disjoint from the raster extent (no clipping possible).
+///
+/// The envelope corners are mapped through the inverse geotransform (all four,
+/// so a skewed/rotated raster still gets a correct superset window) and the
+/// resulting pixel-space bbox is floored/ceiled to whole pixels. A degenerate
+/// envelope (point/line) landing exactly on a grid line is widened to one
+/// pixel so the rasterizer — not the snapping — decides whether it burns.
+fn envelope_window(
+    geometry: &Geometry,
+    geotransform: &GeoTransform,
+    width: usize,
+    height: usize,
+) -> Result<Option<CropWindow>> {
+    let env = geometry.envelope();
+    let inverse = geotransform
+        .invert()
+        .map_err(|e| exec_datafusion_err!("RS_Clip: geotransform is not invertible: {}", e))?;
+
+    let corners = [
+        (env.MinX, env.MinY),
+        (env.MinX, env.MaxY),
+        (env.MaxX, env.MinY),
+        (env.MaxX, env.MaxY),
+    ];
+    let mut min_col = f64::INFINITY;
+    let mut max_col = f64::NEG_INFINITY;
+    let mut min_row = f64::INFINITY;
+    let mut max_row = f64::NEG_INFINITY;
+    for (x, y) in corners {
+        let (col, row) = inverse.apply(x, y);
+        min_col = min_col.min(col);
+        max_col = max_col.max(col);
+        min_row = min_row.min(row);
+        max_row = max_row.max(row);
+    }
+
+    let col0 = min_col.floor();
+    let row0 = min_row.floor();
+    let col1 = max_col.ceil().max(col0 + 1.0);
+    let row1 = max_row.ceil().max(row0 + 1.0);
+
+    // Intersect with the raster extent. `>=` also rejects the NaN envelope of
+    // an empty geometry.
+    let col0 = col0.max(0.0);
+    let row0 = row0.max(0.0);
+    let col1 = col1.min(width as f64);
+    let row1 = row1.min(height as f64);
+    if !(col0 < col1 && row0 < row1) {
+        return Ok(None);
+    }
+
+    Ok(Some(CropWindow {
+        col_off: col0 as usize,
+        row_off: row0 as usize,
+        width: (col1 - col0) as usize,
+        height: (row1 - row0) as usize,
+    }))
+}
+
+/// Apply mask to band data (no cropping — preserves original dimensions).
+/// The mask covers only `window`; every pixel outside it is outside the
+/// geometry's envelope and therefore nodata.
+fn apply_mask_to_band(
+    original_data: &[u8],
+    mask: &[u8],
+    width: usize,
+    height: usize,
+    data_type: &BandDataType,
+    nodata_bytes: &[u8],
+    window: &CropWindow,
+) -> Result<Vec<u8>> {
+    let byte_size = data_type.byte_size();
+    let nodata_row: Vec<u8> = nodata_bytes.repeat(width);
+    let mut result = vec![0u8; width * height * byte_size];
+
+    let row_bytes = width * byte_size;
+    for row in 0..height {
+        let dst_row = &mut result[row * row_bytes..(row + 1) * row_bytes];
+        if row < window.row_off || row >= window.row_off + window.height {
+            dst_row.copy_from_slice(&nodata_row);
+            continue;
+        }
+        // Within a window row: nodata left and right of the window, source
+        // bytes inside it (masked-out pixels overwritten below).
+        let win_start = window.col_off * byte_size;
+        let win_end = (window.col_off + window.width) * byte_size;
+        dst_row[..win_start].copy_from_slice(&nodata_row[..win_start]);
+        dst_row[win_end..].copy_from_slice(&nodata_row[win_end..]);
+        let src_start = row * row_bytes + win_start;
+        dst_row[win_start..win_end]
+            .copy_from_slice(&original_data[src_start..src_start + (win_end - win_start)]);
+
+        let mask_row_start = (row - window.row_off) * window.width;
+        for col in 0..window.width {
+            if mask[mask_row_start + col] == 0 {
+                let dst = win_start + col * byte_size;
+                dst_row[dst..dst + byte_size].copy_from_slice(nodata_bytes);
+            }
+        }
+    }
+
+    Ok(result)
+}
+
+/// Apply mask AND crop to the given crop window in one pass. The mask is
+/// window-sized (row-major over `cw.width`×`cw.height`); the source data is
+/// the full raster plane.
+fn apply_mask_and_crop(
+    original_data: &[u8],
+    mask: &[u8],
+    full_width: usize,
+    data_type: &BandDataType,
+    nodata_bytes: &[u8],
+    cw: &CropWindow,
+) -> Result<Vec<u8>> {
+    let byte_size = data_type.byte_size();
+    let row_bytes = cw.width * byte_size;
+    let mut result = vec![0u8; cw.height * row_bytes];
+
+    // The crop-window columns of a source row are contiguous, so copy each row
+    // in one bulk memcpy (which vectorizes) rather than per pixel, then overwrite
+    // only the masked-out pixels with nodata. Masked pixels are written twice —
+    // once by the bulk copy, once here — but the bulk memcpy is far cheaper than
+    // the dynamic-width per-pixel copy it replaces.
+    for row in 0..cw.height {
+        let src_row = cw.row_off + row;
+        let src_start = (src_row * full_width + cw.col_off) * byte_size;
+        let dst_start = row * row_bytes;
+        result[dst_start..dst_start + row_bytes]
+            .copy_from_slice(&original_data[src_start..src_start + row_bytes]);
+
+        let mask_row_start = row * cw.width;
+        for col in 0..cw.width {
+            if mask[mask_row_start + col] == 0 {
+                let dst = dst_start + col * byte_size;
+                result[dst..dst + byte_size].copy_from_slice(nodata_bytes);
+            }
+        }
+    }
+
+    Ok(result)
+}
+
+/// Build the clipped raster via the N-D builder. A 2-D raster is just the
+/// `["y", "x"]` case; an N-D raster keeps its non-spatial dims and only its
+/// `(y, x)` extent changes when cropping.
+fn build_clipped_raster(
+    builder: &mut RasterBuilder,
+    original_raster: &RasterRefImpl<'_>,
+    clipped_data: &ClippedRasterData,
+) -> Result<()> {
+    // Geotransform is 2-D and shared across all planes. A crop shifts the
+    // upper-left by the pixel offset; scale/skew are unchanged.
+    // Layout: [upper_left_x, scale_x, skew_x, upper_left_y, skew_y, scale_y].
+    let src = original_raster.transform();
+    let transform: [f64; 6] = if let Some(cw) = clipped_data.crop_window {
+        let new_ulx = src[0] + cw.col_off as f64 * src[1] + cw.row_off as f64 * src[2];
+        let new_uly = src[3] + cw.row_off as f64 * src[5] + cw.col_off as f64 * src[4];
+        [new_ulx, src[1], src[2], new_uly, src[4], src[5]]
+    } else {
+        [src[0], src[1], src[2], src[3], src[4], src[5]]
+    };
+
+    // Spatial extent after the clip. `spatial_dims`/`spatial_shape` are kept in
+    // the raster's own axis order (X-first, as the readers emit), so map each
+    // spatial dim to its clipped size by name rather than assuming an order.
+    let spatial_dims = original_raster.spatial_dims();
+    let spatial_shape: Vec<i64> = match clipped_data.crop_window {
+        None => original_raster.spatial_shape().to_vec(),
+        Some(cw) => {
+            let x_dim = original_raster.x_dim();
+            spatial_dims
+                .iter()
+                .map(|&d| {
+                    if d == x_dim {
+                        cw.width as i64
+                    } else {
+                        cw.height as i64
+                    }
+                })
+                .collect()
+        }
+    };
+
+    builder
+        .start_raster_nd(
+            &transform,
+            &spatial_dims,
+            &spatial_shape,
+            original_raster.crs(),
+        )
+        .map_err(|e| exec_datafusion_err!("Failed to start raster: {}", e))?;
+
+    for band in &clipped_data.bands {
+        let dim_names: Vec<&str> = band.dim_names.iter().map(String::as_str).collect();
+        builder
+            .start_band_nd(
+                band.name.as_deref(),
+                &dim_names,
+                &band.shape,
+                band.data_type,
+                Some(&band.nodata),
+                None,
+                None,
+            )
+            .map_err(|e| exec_datafusion_err!("Failed to start band: {}", e))?;
+        builder.band_data_writer().append_value(&band.data);
+        builder
+            .finish_band()
+            .map_err(|e| exec_datafusion_err!("Failed to finish band: {}", e))?;
+    }
+
+    builder
+        .finish_raster()
+        .map_err(|e| exec_datafusion_err!("Failed to finish raster: {}", e))?;
+
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use arrow_array::StructArray;
+    use sedona_expr::scalar_udf::SedonaScalarKernel;
+    use sedona_proj::transform::with_global_proj_engine;
+    use sedona_raster::array::RasterStructArray;
+    use sedona_schema::crs::deserialize_crs;
+    use sedona_schema::datatypes::Edges;
+    use sedona_testing::create::make_wkb;
+    use sedona_testing::raster_spec::RasterSpec;
+
+    /// A 4×2 EPSG:4326 raster, origin (0, 2), 1×1 north-up pixels — world extent
+    /// x ∈ [0, 4], y ∈ [0, 2]. One UInt8 band with values 1..=8 (row-major).
+    fn test_raster_array() -> StructArray {
+        RasterSpec::d2(4, 2)
+            .band_values(&[1u8, 2, 3, 4, 5, 6, 7, 8])
+            .crs(Some("EPSG:4326"))
+            .transform([0.0, 1.0, 0.0, 2.0, 0.0, -1.0])
+            .build()
+    }
+
+    #[test]
+    fn test_rs_clip_basic() {
+        // crop=false: the output keeps the original extent and band byte length;
+        // pixels outside the clip polygon are set to nodata.
+        let array = test_raster_array();
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+
+            // Left half of the raster: x ∈ [0, 2], y ∈ [0, 2].
+            let geom_wkb = make_wkb("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))");
+            let clipped = clip_raster(gdal, &raster, &geom_wkb, 0, None, false, false)?
+                .expect("Should have intersection");
+
+            let original_len = raster
+                .bands()
+                .band(1)
+                .unwrap()
+                .nd_buffer()
+                .unwrap()
+                .as_contiguous()
+                .unwrap()
+                .len();
+            assert!(!clipped.bands.is_empty(), "Should have at least one band");
+            assert_eq!(
+                clipped.bands[0].data.len(),
+                original_len,
+                "Clipped band should have same size as original when crop=false"
+            );
+            // The polygon covers cols 0-1 of both rows; cols 2-3 lie outside
+            // the geometry envelope entirely and must also read nodata (0, the
+            // UInt8 minimum) — this pins the outside-window fill.
+            assert_eq!(clipped.bands[0].data, vec![1u8, 2, 0, 0, 5, 6, 0, 0]);
+            assert!(
+                clipped.crop_window.is_none(),
+                "crop_window should be None when crop=false"
+            );
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn test_rs_clip_crop() {
+        // crop=true: the output shrinks to the geometry's bbox window.
+        let array = test_raster_array();
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+            let metadata = raster.metadata();
+
+            // Top-left quadrant: x ∈ [0, 2], y ∈ [1, 2] — covers pixel centers
+            // (0.5, 1.5) and (1.5, 1.5), i.e. a 2×1 window.
+            let geom_wkb = make_wkb("POLYGON((0 1, 2 1, 2 2, 0 2, 0 1))");
+            let clipped = clip_raster(gdal, &raster, &geom_wkb, 0, None, false, true)?
+                .expect("Should have intersection");
+            let cw = clipped
+                .crop_window
+                .expect("crop_window should be set when crop=true");
+
+            let byte_size = clipped.bands[0].data_type.byte_size();
+            assert_eq!(
+                clipped.bands[0].data.len(),
+                cw.width * cw.height * byte_size,
+                "Cropped band data size should match crop window"
+            );
+            // Both window pixels are inside the polygon, so the cropped band
+            // holds the source values for that 2×1 window (row-major) — this
+            // pins the row-copy offsets in `apply_mask_and_crop`.
+            assert_eq!(
+                clipped.bands[0].data,
+                vec![1u8, 2],
+                "cropped band should keep the source pixel values in the window"
+            );
+            assert!(
+                (cw.width as i64) < metadata.width(),
+                "Cropped width should be smaller"
+            );
+            assert!(
+                (cw.height as i64) < metadata.height(),
+                "Cropped height should be smaller"
+            );
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn crop_uses_envelope_window_not_tight_mask_bbox() {
+        // PostGIS ST_Clip / gdalwarp -crop_to_cutline semantics: the crop
+        // window is the geometry's envelope ∩ raster extent snapped to the
+        // grid, keeping unselected envelope pixels as nodata padding — not the
+        // tight bbox of the selected mask pixels.
+        let array = test_raster_array();
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+
+            // Right triangle with envelope x ∈ [0, 3], y ∈ [0, 2] — a 3×2
+            // pixel window. Only three pixel centers fall inside it: (0.5, 1.5)
+            // -> 1, (0.5, 0.5) -> 5, (1.5, 0.5) -> 6. The tight mask bbox
+            // would be 2×2; the envelope window must be 3×2 with nodata (0)
+            // padding on the unselected pixels.
+            let geom_wkb = make_wkb("POLYGON((0 0, 3 0, 0 2, 0 0))");
+            let clipped = clip_raster(gdal, &raster, &geom_wkb, 0, None, false, true)?
+                .expect("Should have intersection");
+
+            let cw = clipped.crop_window.expect("crop_window should be set");
+            assert_eq!(
+                (cw.col_off, cw.row_off, cw.width, cw.height),
+                (0, 0, 3, 2),
+                "crop window should be the snapped envelope, not the mask bbox"
+            );
+            assert_eq!(clipped.bands[0].data, vec![1u8, 0, 0, 5, 6, 0]);
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn test_rs_clip_no_intersection() {
+        let array = test_raster_array();
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+            // Far outside the raster's [0,4]×[0,2] extent.
+            let geom_wkb = make_wkb("POLYGON((100 100, 101 100, 101 101, 100 101, 100 100))");
+            let result = clip_raster(gdal, &raster, &geom_wkb, 0, None, false, true)?;
+            assert!(result.is_none(), "Should return None for no intersection");
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn test_rs_clip_crs_mismatch() {
+        // A geometry given in EPSG:3857 must be reprojected to the raster's
+        // EPSG:4326 before clipping, yielding the same result as the equivalent
+        // EPSG:4326 geometry.
+        let array = test_raster_array();
+
+        // Build the EPSG:3857 geometry with the same PROJ engine the UDF uses,
+        // so the test is robust to axis-order / normalization across builds.
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let crs_3857 = deserialize_crs("EPSG:3857").unwrap().unwrap();
+
+        let geom_wkb_4326 = make_wkb("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))");
+        let geom_wkb_3857 = with_global_proj_engine(|engine| {
+            crs_transform_wkb(&geom_wkb_4326, crs_4326.as_ref(), crs_3857.as_ref(), engine)
+        })
+        .unwrap();
+
+        // 3-arg variant: RS_Clip(raster, band, geom).
+        let kernel = RsClip { arg_count: 3 };
+        let raster_scalar = ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(array)));
+        let band_type = SedonaType::Arrow(DataType::Int32);
+        let band_val = ColumnarValue::Scalar(ScalarValue::Int32(Some(1)));
+
+        let clip_band1 = |geom_type: SedonaType, geom_wkb: Vec<u8>| -> Vec<u8> {
+            let result = kernel
+                .invoke_batch(
+                    &[RASTER, band_type.clone(), geom_type],
+                    &[
+                        raster_scalar.clone(),
+                        band_val.clone(),
+                        ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                    ],
+                )
+                .unwrap();
+            match result {
+                ColumnarValue::Scalar(ScalarValue::Struct(struct_array)) => {
+                    let array = RasterStructArray::try_new(struct_array.as_ref()).unwrap();
+                    array
+                        .get(0)
+                        .unwrap()
+                        .bands()
+                        .band(1)
+                        .unwrap()
+                        .nd_buffer()
+                        .unwrap()
+                        .as_contiguous()
+                        .unwrap()
+                        .to_vec()
+                }
+                _ => panic!("Expected raster scalar result"),
+            }
+        };
+
+        let band_data_4326 = clip_band1(
+            SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+            geom_wkb_4326,
+        );
+        let band_data_3857 = clip_band1(
+            SedonaType::Wkb(Edges::Planar, Some(crs_3857)),
+            geom_wkb_3857,
+        );
+
+        assert_eq!(band_data_4326, band_data_3857);
+    }
+
+    #[test]
+    fn test_rs_clip_nd_broadcasts_across_planes() {
+        // A [time=2, y=2, x=4] raster: clipping with a 2-D polygon crops the
+        // (y, x) plane and broadcasts the same mask across both time planes,
+        // preserving the time dimension. Values 1..=16 (C order): time 0 is
+        // rows [1,2,3,4] / [5,6,7,8], time 1 is [9..12] / [13..16].
+        let array = RasterSpec::nd(&["time", "y", "x"], &[2, 2, 4])
+            .band_values(&[1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
+            .crs(Some("EPSG:4326"))
+            .transform([0.0, 1.0, 0.0, 2.0, 0.0, -1.0])
+            .build();
+
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let geom_wkb = make_wkb("POLYGON((0 1, 2 1, 2 2, 0 2, 0 1))");
+
+        // RS_Clip(raster, band, geom, allTouched, noData, crop=true).
+        let kernel = RsClip { arg_count: 6 };
+        let result = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+                    SedonaType::Arrow(DataType::Boolean),
+                    SedonaType::Arrow(DataType::Float64),
+                    SedonaType::Arrow(DataType::Boolean),
+                ],
+                &[
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(array))),
+                    ColumnarValue::Scalar(ScalarValue::Int32(Some(1))),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                    ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))),
+                    ColumnarValue::Scalar(ScalarValue::Float64(Some(0.0))),
+                    ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))),
+                ],
+            )
+            .unwrap();
+
+        let out = match result {
+            ColumnarValue::Scalar(ScalarValue::Struct(s)) => s,
+            _ => panic!("Expected raster scalar result"),
+        };
+        let rasters = RasterStructArray::try_new(out.as_ref()).unwrap();
+        let raster = rasters.get(0).unwrap();
+        let band = raster.bands().band(1).unwrap();
+
+        // The time dim is preserved; (y, x) is cropped to the 1×2 mask window.
+        assert_eq!(band.dim_names(), vec!["time", "y", "x"]);
+        assert_eq!(band.shape(), &[2, 1, 2]);
+
+        // The crop window is cols 0-1 of row 0, applied to both planes:
+        // time 0 -> [1, 2], time 1 -> [9, 10].
+        let bytes = band.nd_buffer().unwrap().as_contiguous().unwrap();
+        assert_eq!(bytes, &[1u8, 2, 9, 10]);
+    }
+
+    #[test]
+    fn test_default_nodata_sentinel_is_type_minimum() {
+        // Unsigned types floor at 0; signed/float at their most-negative value.
+        assert_eq!(BandDataType::UInt8.min_value_le_bytes(), vec![0u8]);
+        assert_eq!(
+            BandDataType::UInt64.min_value_le_bytes(),
+            0u64.to_le_bytes()
+        );
+        assert_eq!(
+            BandDataType::Int8.min_value_le_bytes(),
+            i8::MIN.to_le_bytes()
+        );
+        assert_eq!(
+            BandDataType::Int64.min_value_le_bytes(),
+            i64::MIN.to_le_bytes()
+        );
+        assert_eq!(
+            BandDataType::Float64.min_value_le_bytes(),
+            f64::MIN.to_le_bytes()
+        );
+    }
+
+    /// A 2×1, two-band EPSG:4326 raster (band 1 = [1,2], band 2 = [10,20]) — the
+    /// two bands differ so a per-band clip is observably distinct.
+    fn two_band_raster() -> StructArray {
+        RasterSpec::d2(2, 1)
+            .band_values(&[1u8, 2])
+            .band_values(&[10u8, 20])
+            .crs(Some("EPSG:4326"))
+            .transform([0.0, 1.0, 0.0, 1.0, 0.0, -1.0])
+            .build()
+    }
+
+    #[test]
+    fn scalar_raster_geom_with_band_column_yields_all_rows() {
+        // Regression: a constant raster+geom with a per-row band column must
+        // produce an N-row array, not collapse to row 0. (The executor only sees
+        // [raster, geom], so output packaging must consider all args.)
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let geom_wkb = make_wkb("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))");
+
+        let kernel = RsClip { arg_count: 3 };
+        let result = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+                ],
+                &[
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(two_band_raster()))),
+                    ColumnarValue::Array(Arc::new(arrow_array::Int32Array::from(vec![1, 2]))),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                ],
+            )
+            .unwrap();
+
+        // Must be a 2-row array (not a broadcast scalar), with row 0 clipping
+        // band 1 and row 1 clipping band 2 — distinct outputs.
+        let arr = match result {
+            ColumnarValue::Array(a) => a,
+            ColumnarValue::Scalar(_) => panic!("expected an array; the batch collapsed to row 0"),
+        };
+        let rasters =
+            RasterStructArray::try_new(arr.as_any().downcast_ref::<StructArray>().unwrap())
+                .unwrap();
+        assert_eq!(rasters.len(), 2);
+        let band_data = |row: usize| {
+            rasters
+                .get(row)
+                .unwrap()
+                .bands()
+                .band(1)
+                .unwrap()
+                .nd_buffer()
+                .unwrap()
+                .as_contiguous()
+                .unwrap()
+                .to_vec()
+        };
+        // Row 0 clipped band 1 (values 1,2); row 1 clipped band 2 (values 10,20).
+        assert_ne!(band_data(0), band_data(1));
+    }
+
+    #[test]
+    fn band_zero_clips_all_bands() {
+        // Band 0 means "all bands" — it must reach clip_raster as 0, not be
+        // clamped to 1.
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let geom_wkb = make_wkb("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))");
+        let kernel = RsClip { arg_count: 3 };
+        let result = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+                ],
+                &[
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(two_band_raster()))),
+                    ColumnarValue::Scalar(ScalarValue::Int32(Some(0))),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                ],
+            )
+            .unwrap();
+        let out = match result {
+            ColumnarValue::Scalar(ScalarValue::Struct(s)) => s,
+            _ => panic!("expected raster scalar"),
+        };
+        let raster = RasterStructArray::try_new(out.as_ref())
+            .unwrap()
+            .get(0)
+            .unwrap();
+        assert_eq!(raster.bands().len(), 2, "band 0 should clip all bands");
+    }
+
+    #[test]
+    fn negative_band_errors() {
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let geom_wkb = make_wkb("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))");
+        let kernel = RsClip { arg_count: 3 };
+        let err = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+                ],
+                &[
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(two_band_raster()))),
+                    ColumnarValue::Scalar(ScalarValue::Int32(Some(-1))),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                ],
+            )
+            .unwrap_err()
+            .to_string();
+        assert!(err.contains("band must be >= 0"), "unexpected error: {err}");
+    }
+
+    #[test]
+    fn malformed_geometry_errors_even_when_lenient() {
+        // `lenient` (default true) softens only the no-intersection case; a
+        // genuine failure (garbage WKB) must still error, not become NULL.
+        let kernel = RsClip { arg_count: 3 };
+        let err = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, None),
+                ],
+                &[
+                    // No CRS on raster or geom, so we reach rasterization with the
+                    // garbage WKB rather than erroring on a CRS mismatch first.
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(
+                        RasterSpec::d2(2, 1)
+                            .band_values(&[1u8, 2])
+                            .crs(None)
+                            .transform([0.0, 1.0, 0.0, 1.0, 0.0, -1.0])
+                            .build(),
+                    ))),
+                    ColumnarValue::Scalar(ScalarValue::Int32(Some(1))),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(vec![0xff, 0xff, 0xff, 0xff]))),
+                ],
+            )
+            .unwrap_err();
+        // The point is it errored rather than returning a NULL raster.
+        let _ = err;
+    }
+
+    #[test]
+    fn null_band_yields_null() {
+        // A NULL band must propagate to NULL, not silently clip every band.
+        let crs_4326 = deserialize_crs("EPSG:4326").unwrap().unwrap();
+        let geom_wkb = make_wkb("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))");
+        let kernel = RsClip { arg_count: 3 };
+        let result = kernel
+            .invoke_batch(
+                &[
+                    RASTER,
+                    SedonaType::Arrow(DataType::Int32),
+                    SedonaType::Wkb(Edges::Planar, Some(crs_4326)),
+                ],
+                &[
+                    ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(two_band_raster()))),
+                    ColumnarValue::Scalar(ScalarValue::Int32(None)),
+                    ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb))),
+                ],
+            )
+            .unwrap();
+        match result {
+            ColumnarValue::Scalar(sv) => {
+                assert!(
+                    sv.is_null(),
+                    "NULL band should yield NULL, not clip all bands"
+                )
+            }
+            other => panic!("expected scalar, got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn custom_nodata_out_of_range_errors() {
+        // A UInt8 band can't represent -9999; reject it rather than saturating
+        // it to 0 (which would collide with real zero-valued data).
+        let array = test_raster_array(); // one UInt8 band
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+            let geom_wkb = make_wkb("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))");
+
+            let err = match clip_raster(gdal, &raster, &geom_wkb, 1, Some(-9999.0), false, false) {
+                Err(e) => e.to_string(),
+                Ok(_) => panic!("expected out-of-range nodata to error"),
+            };
+            assert!(
+                err.contains("not a valid UInt8 value"),
+                "unexpected error: {err}"
+            );
+
+            // A fractional nodata can't be represented in an integer band either.
+            let err = match clip_raster(gdal, &raster, &geom_wkb, 1, Some(2.5), false, false) {
+                Err(e) => e.to_string(),
+                Ok(_) => panic!("expected fractional nodata to error"),
+            };
+            assert!(
+                err.contains("not a valid UInt8 value"),
+                "unexpected error: {err}"
+            );
+
+            // An in-range custom nodata is accepted.
+            let ok = clip_raster(gdal, &raster, &geom_wkb, 1, Some(200.0), false, false)?;
+            assert!(ok.is_some(), "in-range custom nodata should be accepted");
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn preserves_band_name() {
+        // Clipping a named band keeps the name on the output band.
+        let array = RasterSpec::d2(4, 2)
+            .band_values(&[1u8, 2, 3, 4, 5, 6, 7, 8])
+            .name("elevation")
+            .crs(Some("EPSG:4326"))
+            .transform([0.0, 1.0, 0.0, 2.0, 0.0, -1.0])
+            .build();
+        with_gdal(|gdal| {
+            let rasters = RasterStructArray::try_new(&array).unwrap();
+            let raster = rasters.get(0).unwrap();
+            let geom_wkb = make_wkb("POLYGON((0 0, 2 0, 2 2, 0 2, 0 0))");
+            let clipped = clip_raster(gdal, &raster, &geom_wkb, 1, None, false, false)?
+                .expect("Should have intersection");
+            assert_eq!(
+                clipped.bands[0].name.as_deref(),
+                Some("elevation"),
+                "clipped band should keep the source band name"
+            );
+            Ok::<_, datafusion_common::DataFusionError>(())
+        })
+        .unwrap();
+    }
+
+    #[test]
+    fn strict_no_pixel_message_depends_on_all_touched() {
+        // With lenient=false and an empty clip mask, the strict error is
+        // conditioned on all_touched: a plain "do not intersect" when every
+        // touched pixel was already considered, and a sub-pixel hint otherwise.
+        let geom_wkb = make_wkb("POLYGON((100 100, 101 100, 101 101, 100 101, 100 100))");
+        // No CRS on raster or geom, so we reach the mask check rather than a
+        // CRS-mismatch error first.
+        let raster = RasterSpec::d2(4, 2)
+            .band_values(&[1u8, 2, 3, 4, 5, 6, 7, 8])
+            .crs(None)
+            .transform([0.0, 1.0, 0.0, 2.0, 0.0, -1.0])
+            .build();
+        let arg_types = [
+            RASTER,
+            SedonaType::Arrow(DataType::Int32),
+            SedonaType::Wkb(Edges::Planar, None),
+            SedonaType::Arrow(DataType::Boolean),
+            SedonaType::Arrow(DataType::Float64),
+            SedonaType::Arrow(DataType::Boolean),
+            SedonaType::Arrow(DataType::Boolean),
+        ];
+        let kernel = RsClip { arg_count: 7 };
+        let invoke = |all_touched: bool| {
+            kernel
+                .invoke_batch(
+                    &arg_types,
+                    &[
+                        ColumnarValue::Scalar(ScalarValue::Struct(Arc::new(raster.clone()))),
+                        ColumnarValue::Scalar(ScalarValue::Int32(Some(1))),
+                        ColumnarValue::Scalar(ScalarValue::Binary(Some(geom_wkb.clone()))),
+                        ColumnarValue::Scalar(ScalarValue::Boolean(Some(all_touched))),
+                        ColumnarValue::Scalar(ScalarValue::Float64(None)),
+                        ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))), // crop
+                        ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))), // lenient
+                    ],
+                )
+                .unwrap_err()
+                .to_string()
+        };
+        assert!(
+            invoke(true).contains("do not intersect"),
+            "all_touched=true should give the disjoint message"
+        );
+        let msg = invoke(false);
+        assert!(
+            msg.contains("selects no pixels") && msg.contains("all_touched"),
+            "all_touched=false should hint at the sub-pixel case: {msg}"
+        );
+    }
+}
diff --git a/rust/sedona-schema/src/raster.rs b/rust/sedona-schema/src/raster.rs
index 9e49781fa..2244f1f3b 100644
--- a/rust/sedona-schema/src/raster.rs
+++ b/rust/sedona-schema/src/raster.rs
@@ -160,6 +160,26 @@ pub enum BandDataType {
 }
 
 impl BandDataType {
+    /// The minimum representable value of this data type, as the little-endian
+    /// bytes of the type itself. Conventionally used as a nodata sentinel when
+    /// no explicit nodata is available — never a silent 0, which would be
+    /// indistinguishable from real zero-valued pixels. Byte form (rather than
+    /// `f64`) so `Int64`/`UInt64` minima stay exact.
+    pub fn min_value_le_bytes(&self) -> Vec<u8> {
+        match self {
+            BandDataType::UInt8 => u8::MIN.to_le_bytes().to_vec(),
+            BandDataType::UInt16 => u16::MIN.to_le_bytes().to_vec(),
+            BandDataType::UInt32 => u32::MIN.to_le_bytes().to_vec(),
+            BandDataType::UInt64 => u64::MIN.to_le_bytes().to_vec(),
+            BandDataType::Int8 => i8::MIN.to_le_bytes().to_vec(),
+            BandDataType::Int16 => i16::MIN.to_le_bytes().to_vec(),
+            BandDataType::Int32 => i32::MIN.to_le_bytes().to_vec(),
+            BandDataType::Int64 => i64::MIN.to_le_bytes().to_vec(),
+            BandDataType::Float32 => f32::MIN.to_le_bytes().to_vec(),
+            BandDataType::Float64 => f64::MIN.to_le_bytes().to_vec(),
+        }
+    }
+
     /// Byte size of a single pixel for this data type.
     pub fn byte_size(&self) -> usize {
         match self {