Copilot commented on code in PR #645:
URL: https://github.com/apache/sedona-db/pull/645#discussion_r2875974912


##########
rust/sedona-spatial-join/src/index/spatial_index_builder.rs:
##########
@@ -87,241 +70,3 @@ impl SpatialJoinBuildMetrics {
         }
     }
 }

Review Comment:
   `SpatialJoinBuildMetrics` is declared `pub`, but after this refactor the 
`index` module is not exported from the crate root (and `lib.rs` no longer 
re-exports the type). This can cause `unreachable_pub` warnings and makes it 
ambiguous whether the metrics type is part of the public API. Either re-export 
it from `lib.rs` (and keep it `pub`) or downgrade it to `pub(crate)` if it’s 
internal.



##########
rust/sedona-spatial-join/src/index/default_spatial_index_builder.rs:
##########
@@ -0,0 +1,306 @@
+// 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 arrow::array::BooleanBufferBuilder;
+use arrow_schema::SchemaRef;
+use sedona_common::SpatialJoinOptions;
+use sedona_expr::statistics::GeoStatistics;
+use std::sync::Arc;
+
+use crate::index::spatial_index::SpatialIndexRef;
+use crate::index::spatial_index_builder::{SpatialIndexBuilder, 
SpatialJoinBuildMetrics};
+use crate::{
+    evaluated_batch::{evaluated_batch_stream::SendableEvaluatedBatchStream, 
EvaluatedBatch},
+    index::{default_spatial_index::DefaultSpatialIndex, 
knn_adapter::KnnComponents},
+    operand_evaluator::create_operand_evaluator,
+    refine::create_refiner,
+    spatial_predicate::SpatialPredicate,
+    utils::join_utils::need_produce_result_in_final,
+};
+use async_trait::async_trait;
+use datafusion_common::{utils::proxy::VecAllocExt, Result};
+use datafusion_expr::JoinType;
+use futures::StreamExt;
+use geo_index::rtree::{sort::HilbertSort, RTree, RTreeBuilder, RTreeIndex};
+use parking_lot::Mutex;
+use std::sync::atomic::AtomicUsize;
+
+// Type aliases for better readability
+type SpatialRTree = RTree<f32>;
+type DataIdToBatchPos = Vec<(i32, i32)>;
+type RTreeBuildResult = (SpatialRTree, DataIdToBatchPos);
+
+/// Rough estimate for in-memory size of the rtree per rect in bytes
+const RTREE_MEMORY_ESTIMATE_PER_RECT: usize = 60;
+
+/// Builder for constructing a SpatialIndex from geometry batches.
+///
+/// This builder handles:
+/// 1. Accumulating geometry batches to be indexed
+/// 2. Building the spatial R-tree index
+/// 3. Setting up memory tracking and visited bitmaps
+/// 4. Configuring prepared geometries based on execution mode
+pub struct DefaultSpatialIndexBuilder {
+    schema: SchemaRef,
+    spatial_predicate: SpatialPredicate,
+    options: SpatialJoinOptions,
+    join_type: JoinType,
+    probe_threads_count: usize,
+    metrics: SpatialJoinBuildMetrics,
+
+    /// Batches to be indexed
+    indexed_batches: Vec<EvaluatedBatch>,
+
+    /// Statistics for indexed geometries
+    stats: GeoStatistics,
+
+    /// Memory used by the spatial index
+    memory_used: usize,
+}
+
+impl DefaultSpatialIndexBuilder {
+    /// Create a new builder with the given configuration.
+    pub fn new(
+        schema: SchemaRef,
+        spatial_predicate: SpatialPredicate,
+        options: SpatialJoinOptions,
+        join_type: JoinType,
+        probe_threads_count: usize,
+        metrics: SpatialJoinBuildMetrics,
+    ) -> Result<Self> {
+        Ok(Self {

Review Comment:
   `DefaultSpatialIndexBuilder` (and its `new` ctor) are declared `pub` in a 
module that isn’t reachable from the crate root, which can trigger 
`unreachable_pub` warnings and makes API intent unclear. Consider switching the 
struct + ctor to `pub(crate)` if they’re internal implementation details, or 
re-export them from `lib.rs` if they’re meant to be part of the public API.



##########
rust/sedona-spatial-join/src/index.rs:
##########
@@ -25,8 +27,9 @@ pub(crate) mod spatial_index_builder;
 pub(crate) use build_side_collector::{
     BuildPartition, BuildSideBatchesCollector, CollectBuildSideMetrics,
 };
-pub use spatial_index::SpatialIndex;
-pub use spatial_index_builder::{SpatialIndexBuilder, SpatialJoinBuildMetrics};
+pub(crate) use spatial_index::SpatialIndex;
+
+pub use default_spatial_index_builder::DefaultSpatialIndexBuilder;

Review Comment:
   `DefaultSpatialIndexBuilder` is re-exported as `pub` from the (private) 
`index` module. This is likely to trigger the `unreachable_pub` lint (and makes 
API intent unclear). Consider changing this to `pub(crate) use ...` if it’s 
internal-only, or make the type reachable from the crate root (e.g., re-export 
from `lib.rs`) if it’s intended as public API.
   ```suggestion
   pub(crate) use default_spatial_index_builder::DefaultSpatialIndexBuilder;
   ```



##########
rust/sedona-spatial-join/src/lib.rs:
##########
@@ -33,8 +33,7 @@ pub use exec::SpatialJoinExec;
 // Re-export function for register the spatial join planner
 pub use planner::register_planner;
 
-// Re-export types needed for external usage (e.g., in Comet)
-pub use index::{SpatialIndex, SpatialJoinBuildMetrics};
+// pub use index::SpatialJoinBuildMetrics;
 pub use spatial_predicate::SpatialPredicate;

Review Comment:
   The public re-export of `SpatialJoinBuildMetrics` was replaced with a 
commented-out line. If downstream crates rely on these re-exports (the previous 
comment mentions external usage), this change is a breaking API change and 
isn’t reflected in the PR description. Either restore appropriate `pub use` 
exports (potentially for the new trait-based types) or remove the stale 
commented-out export + update the PR description to explicitly state the API 
change.



##########
rust/sedona-spatial-join/src/index/default_spatial_index.rs:
##########
@@ -0,0 +1,2032 @@
+// 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::{
+    ops::Range,
+    sync::{
+        atomic::{AtomicUsize, Ordering},
+        Arc,
+    },
+};
+
+use arrow_array::RecordBatch;
+use arrow_schema::SchemaRef;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_common_runtime::JoinSet;
+use float_next_after::NextAfter;
+use geo::BoundingRect;
+use geo_index::rtree::{
+    distance::{DistanceMetric, GeometryAccessor},
+    util::f64_box_to_f32,
+};
+use geo_index::rtree::{sort::HilbertSort, RTree, RTreeBuilder, RTreeIndex};
+use geo_index::IndexableNum;
+use geo_types::Rect;
+use parking_lot::Mutex;
+use sedona_expr::statistics::GeoStatistics;
+use sedona_geo::to_geo::item_to_geometry;
+use wkb::reader::Wkb;
+
+use crate::index::spatial_index::DISTANCE_TOLERANCE;
+use crate::index::SpatialIndex;
+use crate::{
+    evaluated_batch::EvaluatedBatch,
+    index::{
+        knn_adapter::{KnnComponents, SedonaKnnAdapter},
+        IndexQueryResult, QueryResultMetrics,
+    },
+    operand_evaluator::{create_operand_evaluator, distance_value_at, 
OperandEvaluator},
+    refine::{create_refiner, IndexQueryResultRefiner},
+    spatial_predicate::SpatialPredicate,
+};
+use arrow::array::BooleanBufferBuilder;
+use async_trait::async_trait;
+use sedona_common::{option::SpatialJoinOptions, sedona_internal_err, 
ExecutionMode};
+
+struct DefaultSpatialIndexInner {
+    pub(crate) schema: SchemaRef,
+    pub(crate) options: SpatialJoinOptions,
+
+    /// The spatial predicate evaluator for the spatial predicate.
+    pub(crate) evaluator: Arc<dyn OperandEvaluator>,
+
+    /// The refiner for refining the index query results.
+    pub(crate) refiner: Arc<dyn IndexQueryResultRefiner>,
+
+    /// R-tree index for the geometry batches. It takes MBRs as query windows 
and returns
+    /// data indexes. These data indexes should be translated using 
`data_id_to_batch_pos` to get
+    /// the original geometry batch index and row index, or translated using 
`prepared_geom_idx_vec`
+    /// to get the prepared geometries array index.
+    pub(crate) rtree: RTree<f32>,
+
+    /// Indexed batches containing evaluated geometry arrays. It contains the 
original record
+    /// batches and geometry arrays obtained by evaluating the geometry 
expression on the build side.
+    pub(crate) indexed_batches: Vec<EvaluatedBatch>,
+    /// An array for translating rtree data index to geometry batch index and 
row index
+    pub(crate) data_id_to_batch_pos: Vec<(i32, i32)>,
+
+    /// An array for translating rtree data index to consecutive index. Each 
geometry may be indexed by
+    /// multiple boxes, so there could be multiple data indexes for the same 
geometry. A mapping for
+    /// squashing the index makes it easier for persisting per-geometry 
auxiliary data for evaluating
+    /// the spatial predicate. This is extensively used by the spatial 
predicate evaluators for storing
+    /// prepared geometries.
+    pub(crate) geom_idx_vec: Vec<usize>,
+
+    /// Shared bitmap builders for visited build side indices, one per batch
+    pub(crate) visited_build_side: Option<Mutex<Vec<BooleanBufferBuilder>>>,
+
+    /// Counter of running probe-threads, potentially able to update `bitmap`.
+    /// Each time a probe thread finished probing the index, it will decrement 
the counter.
+    /// The last finished probe thread will produce the extra output batches 
for unmatched
+    /// build side when running left-outer joins. See also 
[`report_probe_completed`].
+    pub(crate) probe_threads_counter: AtomicUsize,
+
+    /// Shared KNN components (distance metrics and geometry cache) for 
efficient KNN queries
+    pub(crate) knn_components: Option<KnnComponents>,
+}
+
+#[derive(Clone)]
+pub struct DefaultSpatialIndex {
+    inner: Arc<DefaultSpatialIndexInner>,
+}
+
+impl DefaultSpatialIndex {
+    pub(crate) fn empty(
+        spatial_predicate: SpatialPredicate,
+        schema: SchemaRef,
+        options: SpatialJoinOptions,
+        probe_threads_counter: AtomicUsize,
+    ) -> Self {
+        let evaluator = create_operand_evaluator(&spatial_predicate, 
options.clone());
+        let refiner = create_refiner(
+            options.spatial_library,
+            &spatial_predicate,
+            options.clone(),
+            0,
+            GeoStatistics::empty(),
+        );
+        let rtree = RTreeBuilder::<f32>::new(0).finish::<HilbertSort>();
+        let knn_components = matches!(spatial_predicate, 
SpatialPredicate::KNearestNeighbors(_))
+            .then(|| KnnComponents::new(0, &[]).unwrap());
+        Self {
+            inner: Arc::new(DefaultSpatialIndexInner {
+                schema,
+                options,
+                evaluator,
+                refiner,
+                rtree,
+                data_id_to_batch_pos: Vec::new(),
+                indexed_batches: Vec::new(),
+                geom_idx_vec: Vec::new(),
+                visited_build_side: None,
+                probe_threads_counter,
+                knn_components,
+            }),
+        }
+    }
+    #[allow(clippy::too_many_arguments)]
+    pub fn new(
+        schema: SchemaRef,
+        options: SpatialJoinOptions,
+        evaluator: Arc<dyn OperandEvaluator>,
+        refiner: Arc<dyn IndexQueryResultRefiner>,
+        rtree: RTree<f32>,
+        indexed_batches: Vec<EvaluatedBatch>,
+        data_id_to_batch_pos: Vec<(i32, i32)>,
+        geom_idx_vec: Vec<usize>,
+        visited_build_side: Option<Mutex<Vec<BooleanBufferBuilder>>>,
+        probe_threads_counter: AtomicUsize,
+        knn_components: Option<KnnComponents>,
+    ) -> Self {
+        Self {

Review Comment:
   `DefaultSpatialIndex` is declared `pub` (and `new` is `pub`) but the 
surrounding module is `pub(crate)` under a private `index` module. Unless this 
is intended to be a public API type (in which case it should be re-exported 
from `lib.rs`), consider making the struct and constructor `pub(crate)` to 
avoid `unreachable_pub` warnings and to clarify that it’s an internal default 
implementation behind the `SpatialIndex` trait.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to