You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "zhangfengcdt (via GitHub)" <gi...@apache.org> on 2025/09/05 21:23:25 UTC

[PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

zhangfengcdt opened a new pull request, #33:
URL: https://github.com/apache/sedona-db/pull/33

   Implements native Rust versions of ST_Centroid and ST_Length functions using the geo-generic-alg library, providing substantial performance improvements over the existing GEOS-based implementations.
   
     - **Added ST_Centroid implementation** (`rust/sedona-geo/src/st_centroid.rs`)
       - Native Rust implementation using geo-generic-alg
       - Support for Point, LineString, Polygon, and GeometryCollection types
       - Registered as alternative to GEOS implementation
   
     - **Added ST_Length implementation** (`rust/sedona-geo/src/st_length.rs`)
       - Native Rust implementation using geo-generic-alg
       - Support for LineString, Polygon, and GeometryCollection types
       - Comprehensive length calculation including polygon perimeters
   
     - **Updated benchmark tests** (`benchmarks/test_functions.py`)
       - Modified ST_Length tests to use segments_large, collections_simple, and collections_complex tables
       - Enhanced test coverage for performance validation
   
   
   ## ST_Centroid
   
   Before the fix:
   ```
   ----------------------------------------------- benchmark 'table=polygons_complex': 2 tests ------------------------------------------------
   Name (time in ms)                                Median               Mean            StdDev                Min                Max
   --------------------------------------------------------------------------------------------------------------------------------------------
   test_st_centroid[polygons_complex-SedonaDB]      7.3047 (1.0)       7.3327 (1.0)      0.1581 (1.0)       7.0635 (1.0)       8.0731 (1.0)
   test_st_centroid[polygons_complex-DuckDB]       22.6901 (3.11)     22.9047 (3.12)     0.5560 (3.52)     22.4189 (3.17)     24.6498 (3.05)
   --------------------------------------------------------------------------------------------------------------------------------------------
   
   ---------------------------------------------- benchmark 'table=polygons_simple': 2 tests ---------------------------------------------
   Name (time in ms)                              Median              Mean            StdDev               Min               Max
   ---------------------------------------------------------------------------------------------------------------------------------------
   test_st_centroid[polygons_simple-DuckDB]       1.4665 (1.0)      1.4766 (1.0)      0.0496 (1.0)      1.4512 (1.0)      2.1513 (1.0)
   test_st_centroid[polygons_simple-SedonaDB]     2.3950 (1.63)     2.3920 (1.62)     0.0915 (1.84)     1.7250 (1.19)     2.7119 (1.26)
   ---------------------------------------------------------------------------------------------------------------------------------------
   
   
   ```
   
   After the fix:
   ```
   ----------------------------------------------- benchmark 'table=polygons_complex': 2 tests ------------------------------------------------
   Name (time in ms)                                Median               Mean            StdDev                Min                Max
   --------------------------------------------------------------------------------------------------------------------------------------------
   test_st_centroid[polygons_complex-SedonaDB]      3.6323 (1.0)       3.9803 (1.0)      0.6333 (1.0)       3.4603 (1.0)       6.2812 (1.0)
   test_st_centroid[polygons_complex-DuckDB]       24.0920 (6.63)     24.3458 (6.12)     0.6760 (1.07)     23.2327 (6.71)     25.6287 (4.08)
   --------------------------------------------------------------------------------------------------------------------------------------------
   
   ---------------------------------------------- benchmark 'table=polygons_simple': 2 tests ---------------------------------------------
   Name (time in ms)                              Median              Mean            StdDev               Min               Max
   ---------------------------------------------------------------------------------------------------------------------------------------
   test_st_centroid[polygons_simple-SedonaDB]     0.3798 (1.0)      0.3931 (1.0)      0.0368 (1.32)     0.3566 (1.0)      0.5098 (1.0)
   test_st_centroid[polygons_simple-DuckDB]       1.4620 (3.85)     1.4719 (3.74)     0.0278 (1.0)      1.4469 (4.06)     1.7360 (3.41)
   ---------------------------------------------------------------------------------------------------------------------------------------
   ```
   
   
   ## ST_Length
   
   Before the fix:
   ```
   ----------------------------------------------- benchmark 'table=collections_complex': 2 tests ----------------------------------------------
   Name (time in ms)                                 Median               Mean            StdDev                Min                Max
   ---------------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[collections_complex-DuckDB]        5.8670 (1.0)       5.9233 (1.0)      0.2211 (1.0)       5.5197 (1.0)       6.6817 (1.0)
   test_st_length[collections_complex-SedonaDB]     14.0494 (2.39)     14.4129 (2.43)     0.8906 (4.03)     13.7268 (2.49)     18.2037 (2.72)
   ---------------------------------------------------------------------------------------------------------------------------------------------
   
   --------------------------------------------- benchmark 'table=collections_simple': 2 tests ---------------------------------------------
   Name (time in ms)                               Median              Mean            StdDev               Min                Max
   -----------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[collections_simple-DuckDB]       0.7602 (1.0)      0.7618 (1.0)      0.0269 (1.0)      0.7120 (1.0)       1.1222 (1.0)
   test_st_length[collections_simple-SedonaDB]     9.4402 (12.42)    9.7369 (12.78)    0.7997 (29.74)    9.1862 (12.90)    14.2978 (12.74)
   -----------------------------------------------------------------------------------------------------------------------------------------
   
   -------------------------------------------- benchmark 'table=segments_large': 2 tests ---------------------------------------------
   Name (time in ms)                           Median              Mean            StdDev               Min               Max
   ------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[segments_large-DuckDB]       0.2080 (1.0)      0.2336 (1.0)      0.0436 (1.0)      0.1952 (1.0)      0.5038 (1.0)
   test_st_length[segments_large-SedonaDB]     2.7922 (13.42)    2.8142 (12.05)    0.1098 (2.52)     2.6992 (13.83)    3.4997 (6.95)
   ------------------------------------------------------------------------------------------------------------------------------------
   
   ```
   
   After the fix:
   ```
   --------------------------------------------- benchmark 'table=collections_complex': 2 tests ---------------------------------------------
   Name (time in ms)                                Median              Mean            StdDev               Min                Max
   ------------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[collections_complex-DuckDB]       5.8077 (1.0)      5.8841 (1.0)      0.3003 (1.0)      5.4656 (1.0)       6.8681 (1.0)
   test_st_length[collections_complex-SedonaDB]     7.4916 (1.29)     7.6525 (1.30)     0.6201 (2.06)     7.2600 (1.33)     12.8403 (1.87)
   ------------------------------------------------------------------------------------------------------------------------------------------
   
   -------------------------------------------- benchmark 'table=collections_simple': 2 tests ---------------------------------------------
   Name (time in ms)                               Median              Mean            StdDev               Min               Max
   ----------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[collections_simple-SedonaDB]     0.6839 (1.0)      0.6970 (1.0)      0.0463 (2.51)     0.6299 (1.0)      1.0530 (1.15)
   test_st_length[collections_simple-DuckDB]       0.7205 (1.05)     0.7246 (1.04)     0.0185 (1.0)      0.7102 (1.13)     0.9124 (1.0)
   ----------------------------------------------------------------------------------------------------------------------------------------
   
   -------------------------------------------- benchmark 'table=segments_large': 2 tests ---------------------------------------------
   Name (time in ms)                           Median              Mean            StdDev               Min               Max
   ------------------------------------------------------------------------------------------------------------------------------------
   test_st_length[segments_large-DuckDB]       0.2613 (1.06)     0.2591 (1.04)     0.0232 (1.0)      0.1965 (1.0)      0.4800 (1.0)
   test_st_length[segments_large-SedonaDB]     0.2463 (1.0)      0.2497 (1.0)      0.0292 (1.26)     0.2076 (1.06)     0.4960 (1.03)
   ------------------------------------------------------------------------------------------------------------------------------------
   
   ```
   
     ## Performance Results
   The native Rust implementations provide significant performance benefits, especially for simpler geometries, while maintaining full compatibility with the existing API.
   


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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330499606


##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,155 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use crate::centroid::extract_centroid_2d;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    let (x, y) = extract_centroid_2d(wkb)?;

Review Comment:
   DuckDB's library supports Z and M for centroids (and generally for all the operations it adds to its zero-copy geometry engine), so while this particular change is fine (because GEOS was also doing this particular operation in 2D and thus so were we), it's not a long-term solution for centroid (or other geo-based algorithms).



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330466702


##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,155 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use crate::centroid::extract_centroid_2d;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    let (x, y) = extract_centroid_2d(wkb)?;

Review Comment:
   Yes, good points about the challenges with 3D centroid calculations. The geo crate currently does NOT support Z or M dimensions, similar to how GEOS (the C++ library) also focuses on 2D operations.
   
   The geo crate U=uses Coord<T> with only x and y fields - purely 2D. So, if we were to add 3D support, it would require significant effort to add new data structures with Coord3D<T> and add Z-interpolation weighted by segment length and validate against other geo libraries.
   
   What I recommend is, for now, the geo crate maintains its focus on robust 2D operations. Adding 3D support would be a major architectural change that we need to design so that sedona-db supports them consistently with different engines. We would of course need to document the behavior for whatever we support or implement.
   
   What do you think on this? @Kontinuation @jiayuasu 



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2326247674


##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -493,18 +493,19 @@ def test_st_isempty(eng, geom, expected):
     ("geom", "expected"),
     [
         (None, None),
-        ("POINT EMPTY", 0),
+        # ("POINT EMPTY", 0),  # Not supported by geo implementation - throws ArrowInvalid error

Review Comment:
   this should be resoled now - checking empty before call to_geo



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "Kontinuation (via GitHub)" <gi...@apache.org>.
Kontinuation commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2329095040


##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,144 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use sedona_geometry::wkb_factory;
+use sedona_testing::fixtures::POINT_EMPTY_WKB;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    // Check for empty geometries first - they should return POINT EMPTY
+    if is_wkb_empty(wkb)? {
+        return Ok(POINT_EMPTY_WKB.to_vec());

Review Comment:
   nit: I'm not sure if using constants defined in `sedona_testing::fixtures` is a good idea. We can move the constant definition to somewhere else if the production code needs it.



##########
.github/workflows/rust.yml:
##########
@@ -99,6 +104,24 @@ jobs:
           # Update this key to force a new cache
           prefix-key: "rust-${{ matrix.name }}-v1"
 
+      - name: Free up disk space
+        run: |
+          echo "Available disk space before cleanup:"
+          df -h /
+
+          # Remove unnecessary packages and files
+          sudo apt-get clean
+          sudo rm -rf /usr/share/dotnet
+          sudo rm -rf /usr/local/lib/android
+          sudo rm -rf /opt/ghc
+          sudo rm -rf /opt/hostedtoolcache/CodeQL
+          sudo rm -rf /usr/local/share/boost
+          sudo rm -rf "$AGENT_TOOLSDIRECTORY"
+          docker system prune -af
+
+          echo "Available disk space after cleanup:"
+          df -h /

Review Comment:
   Can we use [`jlumbroso/free-disk-space`](https://github.com/jlumbroso/free-disk-space) for freeing up disk space? Apache Iceberg is also using it https://github.com/apache/iceberg/blob/c8541db1c905e05891596ffe157c12392e38c93c/.github/workflows/spark-ci.yml#L100-L102



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330683462


##########
rust/sedona-functions/src/st_isempty.rs:
##########
@@ -87,6 +87,10 @@ impl SedonaScalarKernel for STIsEmpty {
     }
 }
 
+pub fn is_wkb_empty(item: &Wkb) -> Result<bool> {
+    invoke_scalar(item)
+}
+

Review Comment:
   I have added is_empty.rs in sedona-geometry and refactored this and the st_centroid in geo module to use it.



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330473797


##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,150 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use geo_traits::Dimensions;
+use sedona_geometry::wkb_factory;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    // Check for empty geometries first - they should return POINT EMPTY
+    if is_wkb_empty(wkb)? {
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        return Ok(empty_point_wkb);
+    }
+
+    // Use Centroid trait directly on WKB, similar to how st_area uses unsigned_area()
+    if let Some(centroid_point) = wkb.centroid() {
+        // Extract coordinates from the centroid point
+        let x = centroid_point.x();
+        let y = centroid_point.y();
+
+        wkb_factory::wkb_point((x, y))
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))
+    } else {
+        // This should not happen for non-empty geometries, return POINT EMPTY as fallback
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        Ok(empty_point_wkb)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{Array, BinaryArray};
+    use datafusion_common::scalar::ScalarValue;
+    use rstest::rstest;
+    use sedona_functions::register::stubs::st_centroid_udf;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::testers::ScalarUdfTester;
+    use wkb::reader::Wkb;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let mut udf = st_centroid_udf();
+        udf.add_kernel(st_centroid_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        // Test with a polygon
+        let result = tester
+            .invoke_wkb_scalar(Some("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"))
+            .unwrap();
+
+        if let ScalarValue::Binary(Some(wkb_data)) = result {
+            let wkb = Wkb::try_new(&wkb_data).unwrap();
+            if let Some(centroid_point) = wkb.centroid() {
+                assert_eq!(centroid_point.x(), 1.0);
+                assert_eq!(centroid_point.y(), 1.0);
+            } else {
+                panic!("Expected centroid point");
+            }
+        } else {
+            panic!("Expected Binary result");
+        }

Review Comment:
   ```suggestion
           let result = tester
               .invoke_scalar("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))")
               .unwrap();
           tester.assert_scalar_result(result, "POINT (1 1)");
   ```



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,150 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use geo_traits::Dimensions;
+use sedona_geometry::wkb_factory;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);

Review Comment:
   I believe we have a named constant in `sedona-geometry/src/wkb-factory` for the minimum probable WKB element size per iteration. (I think most of the functions that have geometry output are using it)



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,150 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use geo_traits::Dimensions;
+use sedona_geometry::wkb_factory;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    // Check for empty geometries first - they should return POINT EMPTY
+    if is_wkb_empty(wkb)? {
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        return Ok(empty_point_wkb);
+    }
+
+    // Use Centroid trait directly on WKB, similar to how st_area uses unsigned_area()
+    if let Some(centroid_point) = wkb.centroid() {
+        // Extract coordinates from the centroid point
+        let x = centroid_point.x();
+        let y = centroid_point.y();
+
+        wkb_factory::wkb_point((x, y))
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))
+    } else {
+        // This should not happen for non-empty geometries, return POINT EMPTY as fallback
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        Ok(empty_point_wkb)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{Array, BinaryArray};
+    use datafusion_common::scalar::ScalarValue;
+    use rstest::rstest;
+    use sedona_functions::register::stubs::st_centroid_udf;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::testers::ScalarUdfTester;
+    use wkb::reader::Wkb;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let mut udf = st_centroid_udf();
+        udf.add_kernel(st_centroid_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+
+        assert_eq!(tester.return_type().unwrap(), WKB_GEOMETRY);
+
+        // Test with a polygon
+        let result = tester
+            .invoke_wkb_scalar(Some("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"))
+            .unwrap();
+
+        if let ScalarValue::Binary(Some(wkb_data)) = result {
+            let wkb = Wkb::try_new(&wkb_data).unwrap();
+            if let Some(centroid_point) = wkb.centroid() {
+                assert_eq!(centroid_point.x(), 1.0);
+                assert_eq!(centroid_point.y(), 1.0);
+            } else {
+                panic!("Expected centroid point");
+            }
+        } else {
+            panic!("Expected Binary result");
+        }
+
+        // Test with array
+        let input_wkt = vec![
+            Some("POINT(1 2)"),
+            None,
+            Some("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))"),
+        ];
+        let result_array = tester.invoke_wkb_array(input_wkt).unwrap();
+        let binary_array = result_array.as_any().downcast_ref::<BinaryArray>().unwrap();
+
+        // First element: POINT(1 2) - centroid should be (1, 2)
+        assert!(!binary_array.value(0).is_empty());
+        // Second element: NULL
+        assert!(binary_array.is_null(1));
+        // Third element: POLYGON centroid should be (1, 1)
+        assert!(!binary_array.value(2).is_empty());

Review Comment:
   ```suggestion
           assert_array_equal(&result_array, &create_array(&[Some("POINT (1 2)"), None, Some("POINT (1 1)")]);
   ```



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,150 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use geo_traits::Dimensions;
+use sedona_geometry::wkb_factory;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    // Check for empty geometries first - they should return POINT EMPTY
+    if is_wkb_empty(wkb)? {
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        return Ok(empty_point_wkb);
+    }
+
+    // Use Centroid trait directly on WKB, similar to how st_area uses unsigned_area()
+    if let Some(centroid_point) = wkb.centroid() {
+        // Extract coordinates from the centroid point
+        let x = centroid_point.x();
+        let y = centroid_point.y();

Review Comment:
   Not a blocker here because GEOS doesn't do this either, but DuckDB's centroid calculation includes support for Z and M coordinates.



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,150 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::Centroid;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_functions::st_isempty::is_wkb_empty;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use geo_traits::Dimensions;
+use sedona_geometry::wkb_factory;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    // Check for empty geometries first - they should return POINT EMPTY
+    if is_wkb_empty(wkb)? {
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        return Ok(empty_point_wkb);
+    }
+
+    // Use Centroid trait directly on WKB, similar to how st_area uses unsigned_area()
+    if let Some(centroid_point) = wkb.centroid() {
+        // Extract coordinates from the centroid point
+        let x = centroid_point.x();
+        let y = centroid_point.y();
+
+        wkb_factory::wkb_point((x, y))
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))
+    } else {
+        // This should not happen for non-empty geometries, return POINT EMPTY as fallback
+        let mut empty_point_wkb = Vec::new();
+        wkb_factory::write_wkb_empty_point(&mut empty_point_wkb, Dimensions::Xy)
+            .map_err(|e| datafusion_common::error::DataFusionError::External(Box::new(e)))?;
+        Ok(empty_point_wkb)
+    }

Review Comment:
   If there was an error calculating the centroid I think this should be passed on to the user with an `exec_err!()` instead of ignored



##########
rust/sedona-functions/src/st_isempty.rs:
##########
@@ -87,6 +87,10 @@ impl SedonaScalarKernel for STIsEmpty {
     }
 }
 
+pub fn is_wkb_empty(item: &Wkb) -> Result<bool> {
+    invoke_scalar(item)
+}
+

Review Comment:
   If we need this for something other than a scalar function, we can move it (and its tets) to `sedona-geometry/src/is_empty.rs`. This can also operate on `&impl GeometryTrait` rather than `&Wkb`.



##########
rust/sedona-geo/src/st_length.rs:
##########
@@ -0,0 +1,113 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::algorithm::{line_measures::Euclidean, LengthMeasurableExt};
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::SedonaType;
+use wkb::reader::Wkb;
+
+/// ST_Length() implementation using [LengthMeasurableExt] with Euclidean metric
+pub fn st_length_impl() -> ScalarKernelRef {
+    Arc::new(STLength {})
+}
+
+#[derive(Debug)]
+struct STLength {}
+
+impl SedonaScalarKernel for STLength {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Float64),
+        );
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = Float64Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    builder.append_value(invoke_scalar(&wkb)?);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<f64> {
+    Ok(wkb.length_ext(&Euclidean))
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{create_array, ArrayRef};
+    use datafusion_common::scalar::ScalarValue;
+    use rstest::rstest;
+    use sedona_functions::register::stubs::st_length_udf;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let mut udf = st_length_udf();
+        udf.add_kernel(st_length_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+
+        assert_eq!(
+            tester.return_type().unwrap(),
+            SedonaType::Arrow(DataType::Float64)
+        );
+
+        // Test with a line string
+        assert_eq!(
+            tester
+                .invoke_wkb_scalar(Some("LINESTRING (0 0, 3 4)"))
+                .unwrap(),
+            ScalarValue::Float64(Some(5.0))
+        );
+
+        let input_wkt = vec![
+            Some("POINT(1 2)"), // Point should have 0 length
+            None,
+            Some("LINESTRING (0 0, 3 4)"),      // Should have length 5
+            Some("LINESTRING (0 0, 1 0, 1 1)"), // Should have length 2
+        ];

Review Comment:
   Are polygons handled correctly here?



##########
rust/sedona-geo/Cargo.toml:
##########
@@ -48,6 +48,7 @@ sedona-expr = { path = "../sedona-expr" }
 sedona-functions = { path = "../sedona-functions" }
 sedona-geometry = { path = "../sedona-geometry" }
 sedona-schema = { path = "../sedona-schema" }
+sedona-testing = { path = "../sedona-testing" }

Review Comment:
   I think you can remove this!



##########
.github/workflows/rust.yml:
##########
@@ -99,6 +104,18 @@ jobs:
           # Update this key to force a new cache
           prefix-key: "rust-${{ matrix.name }}-v1"
 
+      - name: Free Disk Space (Ubuntu)
+        uses: jlumbroso/free-disk-space@main
+        with:

Review Comment:
   Can you try bumping the `prefix-key` just above here instead of this change? (If that doesn't work feel free to bring this back!)



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "zhangfengcdt (via GitHub)" <gi...@apache.org>.
zhangfengcdt commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330684224


##########
rust/sedona-geo/src/st_length.rs:
##########
@@ -0,0 +1,113 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::Float64Builder;
+use arrow_schema::DataType;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use geo_generic_alg::algorithm::{line_measures::Euclidean, LengthMeasurableExt};
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::SedonaType;
+use wkb::reader::Wkb;
+
+/// ST_Length() implementation using [LengthMeasurableExt] with Euclidean metric
+pub fn st_length_impl() -> ScalarKernelRef {
+    Arc::new(STLength {})
+}
+
+#[derive(Debug)]
+struct STLength {}
+
+impl SedonaScalarKernel for STLength {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Float64),
+        );
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = Float64Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    builder.append_value(invoke_scalar(&wkb)?);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<f64> {
+    Ok(wkb.length_ext(&Euclidean))
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{create_array, ArrayRef};
+    use datafusion_common::scalar::ScalarValue;
+    use rstest::rstest;
+    use sedona_functions::register::stubs::st_length_udf;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let mut udf = st_length_udf();
+        udf.add_kernel(st_length_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+
+        assert_eq!(
+            tester.return_type().unwrap(),
+            SedonaType::Arrow(DataType::Float64)
+        );
+
+        // Test with a line string
+        assert_eq!(
+            tester
+                .invoke_wkb_scalar(Some("LINESTRING (0 0, 3 4)"))
+                .unwrap(),
+            ScalarValue::Float64(Some(5.0))
+        );
+
+        let input_wkt = vec![
+            Some("POINT(1 2)"), // Point should have 0 length
+            None,
+            Some("LINESTRING (0 0, 3 4)"),      // Should have length 5
+            Some("LINESTRING (0 0, 1 0, 1 1)"), // Should have length 2
+        ];

Review Comment:
   test on polygon added



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

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


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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2330703164


##########
.github/workflows/rust.yml:
##########
@@ -97,7 +102,19 @@ jobs:
       - uses: Swatinem/rust-cache@v2
         with:
           # Update this key to force a new cache
-          prefix-key: "rust-${{ matrix.name }}-v1"
+          prefix-key: "rust-${{ matrix.name }}-v2"
+
+      - name: Free Disk Space (Ubuntu)
+        uses: jlumbroso/free-disk-space@main
+        with:
+          # Free up space by removing tools we don't need
+          tool-cache: false  # Keep tool cache as we need build tools
+          android: true      # Remove Android SDK (not needed)
+          dotnet: true       # Remove .NET runtime (not needed)
+          haskell: true      # Remove Haskell toolchain (not needed)
+          large-packages: false  # Keep essential packages including build-essential
+          swap-storage: true     # Remove swap file to free space
+          docker-images: true    # Remove docker images (not needed)

Review Comment:
   Can you revert this part of the change if it wasn't needed?



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2326121945


##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -493,18 +493,19 @@ def test_st_isempty(eng, geom, expected):
     ("geom", "expected"),
     [
         (None, None),
-        ("POINT EMPTY", 0),
+        # ("POINT EMPTY", 0),  # Not supported by geo implementation - throws ArrowInvalid error

Review Comment:
   We still have to handle these cases in the implementations (in this case, before they get passed to `to_geo()`).



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -493,18 +493,19 @@ def test_st_isempty(eng, geom, expected):
     ("geom", "expected"),
     [
         (None, None),
-        ("POINT EMPTY", 0),
+        # ("POINT EMPTY", 0),  # Not supported by geo implementation - throws ArrowInvalid error
         ("LINESTRING EMPTY", 0),
         ("POINT (0 0)", 0),
         ("LINESTRING (0 0, 0 1)", 1),
         ("MULTIPOINT ((0 0), (1 1))", 0),
         ("MULTILINESTRING ((0 0, 1 1), (1 1, 2 2))", 2.8284271247461903),
-        # Polygons contribute 0 because perimeters aren't included in the length calculation
-        ("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))", 0),
-        ("MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((0 0, 1 0, 1 1, 0 1, 0 0)))", 0),
+        # Geo implementation calculates polygon perimeters as length (differs from OGC standard)
+        # This provides more comprehensive length calculation including polygon boundaries
+        ("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))", 4.0),
+        ("MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((0 0, 1 0, 1 1, 0 1, 0 0)))", 8.0),

Review Comment:
   We still need to these to implemented correctly (this is the challenge with using the geo library for these functions)



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,155 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use crate::centroid::extract_centroid_2d;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    let (x, y) = extract_centroid_2d(wkb)?;
+
+    // Create WKB for POINT geometry
+    if x.is_nan() || y.is_nan() {
+        // Return POINT EMPTY
+        Ok(create_empty_point_wkb())
+    } else {
+        Ok(create_point_wkb(x, y))
+    }
+}
+
+fn create_point_wkb(x: f64, y: f64) -> Vec<u8> {
+    let mut wkb = Vec::with_capacity(21);
+    // Little endian
+    wkb.push(0x01);
+    // Point geometry type (1)
+    wkb.extend_from_slice(&1u32.to_le_bytes());
+    // X coordinate
+    wkb.extend_from_slice(&x.to_le_bytes());
+    // Y coordinate
+    wkb.extend_from_slice(&y.to_le_bytes());
+    wkb
+}

Review Comment:
   I believe there's a factory function for this in sedona-geometry



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,155 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use crate::centroid::extract_centroid_2d;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    let (x, y) = extract_centroid_2d(wkb)?;
+
+    // Create WKB for POINT geometry
+    if x.is_nan() || y.is_nan() {
+        // Return POINT EMPTY
+        Ok(create_empty_point_wkb())
+    } else {
+        Ok(create_point_wkb(x, y))
+    }
+}
+
+fn create_point_wkb(x: f64, y: f64) -> Vec<u8> {
+    let mut wkb = Vec::with_capacity(21);
+    // Little endian
+    wkb.push(0x01);
+    // Point geometry type (1)
+    wkb.extend_from_slice(&1u32.to_le_bytes());
+    // X coordinate
+    wkb.extend_from_slice(&x.to_le_bytes());
+    // Y coordinate
+    wkb.extend_from_slice(&y.to_le_bytes());
+    wkb
+}
+
+fn create_empty_point_wkb() -> Vec<u8> {
+    let mut wkb = Vec::with_capacity(21);
+    // Little endian
+    wkb.push(0x01);
+    // Point geometry type (1)
+    wkb.extend_from_slice(&1u32.to_le_bytes());
+    // NaN coordinates for empty point
+    wkb.extend_from_slice(&f64::NAN.to_le_bytes());
+    wkb.extend_from_slice(&f64::NAN.to_le_bytes());
+    wkb
+}

Review Comment:
   We have a file sedona-testing/src/fixtures.rs where you can put the rendered version of this!



##########
.gitignore:
##########
@@ -36,3 +36,7 @@ coverage/
 
 # documentation
 site/
+
+# Python cache files
+__pycache__/
+benchmarks/__pycache__/

Review Comment:
   nit: I think this works:
   
   ```suggestion
   __pycache__
   ```



##########
rust/sedona-geo/src/st_centroid.rs:
##########
@@ -0,0 +1,155 @@
+// 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.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::ColumnarValue;
+use sedona_expr::scalar_udf::{ArgMatcher, ScalarKernelRef, SedonaScalarKernel};
+use sedona_functions::executor::WkbExecutor;
+use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY};
+use wkb::reader::Wkb;
+
+use crate::centroid::extract_centroid_2d;
+
+/// ST_Centroid() implementation using centroid extraction
+pub fn st_centroid_impl() -> ScalarKernelRef {
+    Arc::new(STCentroid {})
+}
+
+#[derive(Debug)]
+struct STCentroid {}
+
+impl SedonaScalarKernel for STCentroid {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY);
+
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[SedonaType],
+        args: &[ColumnarValue],
+    ) -> Result<ColumnarValue> {
+        let executor = WkbExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(executor.num_iterations(), 1024);
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    let centroid_wkb = invoke_scalar(&wkb)?;
+                    builder.append_value(&centroid_wkb);
+                }
+                _ => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(wkb: &Wkb) -> Result<Vec<u8>> {
+    let (x, y) = extract_centroid_2d(wkb)?;

Review Comment:
   One of the challeneges with centroid in particular is behaviour in 3D (the Z and/or M values is interpolated and possibly weighted by the length of the segment if I remember correctly, and I have no idea what happens for a Polygon).



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

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

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


Re: [PR] feat: Implement native Rust ST_Centroid and ST_Length functions [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #33:
URL: https://github.com/apache/sedona-db/pull/33#discussion_r2331065218


##########
rust/sedona-geometry/src/is_empty.rs:
##########
@@ -0,0 +1,153 @@
+// 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.
+
+use geo_traits::{
+    GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait, MultiPointTrait,
+    MultiPolygonTrait, PointTrait, PolygonTrait,
+};
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum IsEmptyError {
+    #[error("Invalid geometry type")]
+    InvalidGeometryType,
+}
+
+pub fn is_geometry_empty<G: GeometryTrait<T = f64>>(geometry: &G) -> Result<bool, IsEmptyError> {

Review Comment:
   Sorry I didn't catch this on the last round - we have `SedonaGeometryError` already and we should use that!



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

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

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