Repository navigation
refactor: split geo_index/mod.rs into separate files - #9018
Conversation
The geo_index module was a single 2134-line file. Split it into focused files for better readability and maintainability: - mod.rs: GeoMapIndex enum definition and core methods (~290 lines) - builders.rs: GeoMapIndexMmapBuilder and GeoMapIndexGridstoreBuilder - payload_index.rs: ValueIndexer, PayloadFieldIndex, PayloadFieldIndexRead impls - tests.rs: all test code (~1340 lines) No logic changes; all 40 existing tests pass. Co-authored-by: Cursor <[email protected]>
📝 WalkthroughWalkthroughThis PR refactors the geo index module by extracting previously co-located code into separate files. GeoMapIndex methods are promoted to pub(crate) visibility to enable internal crate access. Two builder types are introduced (Mmap and Gridstore variants) implementing FieldIndexBuilderTrait for constructing geo indexes via different storage backends. A new payload_index module implements the full ValueIndexer, PayloadFieldIndex, and PayloadFieldIndexRead trait surface for GeoMapIndex, enabling geo-point ingestion, cardinality estimation with polygon interior support, and condition-based filtering. Comprehensive test coverage validates correctness across all three backends with 1330 lines of tests. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
lib/segment/src/index/field_index/geo_index/payload_index.rs (1)
44-56: ⚡ Quick winSpell out the non-object
Valuevariants.The
_ => Nonearm hides futureserde_json::Valuevariant additions from the compiler. Listing the other variants keeps this helper aligned with the repo’s exhaustive-match rule.♻️ Suggested change
fn get_value(value: &Value) -> Option<GeoPoint> { match value { Value::Object(obj) => { let lon_op = obj.get("lon").and_then(|x| x.as_f64()); let lat_op = obj.get("lat").and_then(|x| x.as_f64()); if let (Some(lon), Some(lat)) = (lon_op, lat_op) { return GeoPoint::new(lon, lat).ok(); } None } - _ => None, + Value::Null + | Value::Bool(_) + | Value::Number(_) + | Value::String(_) + | Value::Array(_) => None, } }As per coding guidelines,
Prefer explicit exhaustive matches over catch-all _ arm in Rust match expressions, so we don't miss handling new enum variants when they are added later.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lib/segment/src/index/field_index/geo_index/payload_index.rs` around lines 44 - 56, The match in get_value currently uses a catch-all `_ => None`, which violates the repo's exhaustive-match rule; replace the `_` arm with explicit serde_json::Value variants (e.g., Value::Null, Value::Bool(_), Value::Number(_), Value::String(_), Value::Array(_)) each returning None so the match is exhaustive and the compiler will warn if new variants are added; keep the existing Value::Object branch that parses "lon" and "lat" and returns GeoPoint::new(lon, lat).ok().lib/segment/src/index/field_index/geo_index/tests.rs (1)
228-229: ⚡ Quick winUse exact condition matches as the oracle here.
iterator(hashes)only gives geohash candidates, so border false positives and polygon-hole exclusions can still be present. These assertions can pass whileestimate_cardinalityis wrong for the actualFieldCondition.Also applies to: 302-303
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@lib/segment/src/index/field_index/geo_index/tests.rs` around lines 228 - 229, The test currently uses field_index.iterator(hashes) as the oracle, but that yields only geohash candidates and can include border false positives or polygon-hole exclusions; instead compute the true oracle by filtering those candidates with the exact FieldCondition predicate (i.e., iterate field_index.iterator(hashes).unwrap(), then keep only points where the FieldCondition actually matches the point—use the condition's match method or the point-level predicate your code exposes) and use that filtered count as real_cardinality to compare against estimate_cardinality for the FieldCondition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@lib/segment/src/index/field_index/geo_index/builders.rs`:
- Around line 66-76: The init method currently uses assert! to enforce a single
initialization which can panic; change this to return an appropriate
OperationResult error instead: check if self.index.is_some() and if so return
Err(OperationError::service_error("index must be initialized exactly once")) (or
a more specific OperationError), then proceed to call
GeoMapIndex::new_gridstore(...) and propagate its errors as before; mirror the
existing error-handling style used in add_point and finalize to keep consistent
behavior and use the same symbols (init, self.index, GeoMapIndex::new_gridstore,
OperationError::service_error).
In `@lib/segment/src/index/field_index/geo_index/payload_index.rs`:
- Around line 202-212: The subtraction of interior_estimation fields from
exterior_estimation (inside the loop over interior_hashes in payload_index.rs)
can underflow before max(...) clamps results; modify the updates to use
saturating_sub when reducing exterior_estimation.min, exterior_estimation.max,
and exterior_estimation.exp (i.e., replace direct `-` operations with
`.saturating_sub(...)` when subtracting interior_estimation.max/min/exp after
calling self.match_cardinality(interior, hw_counter)) so the arithmetic never
underflows prior to applying the max clamps.
---
Nitpick comments:
In `@lib/segment/src/index/field_index/geo_index/payload_index.rs`:
- Around line 44-56: The match in get_value currently uses a catch-all `_ =>
None`, which violates the repo's exhaustive-match rule; replace the `_` arm with
explicit serde_json::Value variants (e.g., Value::Null, Value::Bool(_),
Value::Number(_), Value::String(_), Value::Array(_)) each returning None so the
match is exhaustive and the compiler will warn if new variants are added; keep
the existing Value::Object branch that parses "lon" and "lat" and returns
GeoPoint::new(lon, lat).ok().
In `@lib/segment/src/index/field_index/geo_index/tests.rs`:
- Around line 228-229: The test currently uses field_index.iterator(hashes) as
the oracle, but that yields only geohash candidates and can include border false
positives or polygon-hole exclusions; instead compute the true oracle by
filtering those candidates with the exact FieldCondition predicate (i.e.,
iterate field_index.iterator(hashes).unwrap(), then keep only points where the
FieldCondition actually matches the point—use the condition's match method or
the point-level predicate your code exposes) and use that filtered count as
real_cardinality to compare against estimate_cardinality for the FieldCondition.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2d033e77-1fde-4c4a-befa-c1d3040d859f
📒 Files selected for processing (4)
lib/segment/src/index/field_index/geo_index/builders.rslib/segment/src/index/field_index/geo_index/mod.rslib/segment/src/index/field_index/geo_index/payload_index.rslib/segment/src/index/field_index/geo_index/tests.rs
| fn init(&mut self) -> OperationResult<()> { | ||
| assert!( | ||
| self.index.is_none(), | ||
| "index must be initialized exactly once", | ||
| ); | ||
| self.index.replace( | ||
| GeoMapIndex::new_gridstore(self.dir.clone(), true)?.ok_or_else(|| { | ||
| OperationError::service_error("Failed to open GeoMapIndex after creating it") | ||
| })?, | ||
| ); | ||
| Ok(()) |
There was a problem hiding this comment.
Return an error from init instead of panicking.
FieldIndexBuilderTrait::init already returns OperationResult, but a second call here aborts the process via assert!. This should stay on the normal error path like add_point and finalize.
🛠️ Suggested change
fn init(&mut self) -> OperationResult<()> {
- assert!(
- self.index.is_none(),
- "index must be initialized exactly once",
- );
+ if self.index.is_some() {
+ return Err(OperationError::service_error(
+ "GeoMapIndexGridstoreBuilder: init called more than once",
+ ));
+ }
self.index.replace(
GeoMapIndex::new_gridstore(self.dir.clone(), true)?.ok_or_else(|| {
OperationError::service_error("Failed to open GeoMapIndex after creating it")
})?,
);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lib/segment/src/index/field_index/geo_index/builders.rs` around lines 66 -
76, The init method currently uses assert! to enforce a single initialization
which can panic; change this to return an appropriate OperationResult error
instead: check if self.index.is_some() and if so return
Err(OperationError::service_error("index must be initialized exactly once")) (or
a more specific OperationError), then proceed to call
GeoMapIndex::new_gridstore(...) and propagate its errors as before; mirror the
existing error-handling style used in add_point and finalize to keep consistent
behavior and use the same symbols (init, self.index, GeoMapIndex::new_gridstore,
OperationError::service_error).
| for interior in &interior_hashes { | ||
| let interior_estimation = self.match_cardinality(interior, hw_counter)?; | ||
| exterior_estimation.min = max(0, exterior_estimation.min - interior_estimation.max); | ||
| exterior_estimation.max = max( | ||
| exterior_estimation.min, | ||
| exterior_estimation.max - interior_estimation.min, | ||
| ); | ||
| exterior_estimation.exp = max( | ||
| exterior_estimation.exp - interior_estimation.exp, | ||
| exterior_estimation.min, | ||
| ); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, check if the file exists and read the relevant section
cat -n lib/segment/src/index/field_index/geo_index/payload_index.rs | sed -n '195,225p'Repository: qdrant/qdrant
Length of output: 1929
🌐 Web query:
Qdrant payload_index.rs geo_index usize underflow saturating_sub
💡 Result:
No specific evidence found of a usize underflow vulnerability fixed or present in Qdrant's payload_index.rs related to geo_index using saturating_sub. Searches across GitHub, issues, PRs, and source code snippets show geo_index.rs exists in lib/segment/src/index/field_index/geo_index.rs as part of Qdrant's payload indexing for geo payloads [1][2][3][4]. StructPayloadIndex manages field indexes including GeoIndex [5]. Saturating arithmetic like saturating_sub appears in geo_index.rs cardinality estimation to prevent underflow: sum.saturating_sub(point_duplications) [3]. This safely handles potential underflow when calculating non-duplicated points estimate (point_duplications = total_values - total_points, where total_values >= total_points). General Rust usize underflow prevention uses saturating_sub [6], and Qdrant uses similar patterns elsewhere (e.g., query batch limits [7], group search capacities [8]). No explicit bug reports, fixes, or panics mention "payload_index.rs" (likely refers to payload indexing code), geo_index usize underflow. On-disk payload index is in development [9], but no underflow issues noted. Qdrant geo indexes use geohash for efficient geo filtering [1][4].
Citations:
- 1: index geo payload #366
- 2: https://github.com/qdrant/qdrant/blob/09f87abb/lib/segment/src/index/field_index/field_index_base.rs
- 3: https://github.com/qdrant/qdrant/blob/7aa164bd2dda1c0fc9bf3a0da42e656c95c2e52a/lib/segment/src/index/field_index/geo_index.rs
- 4: https://github.com/qdrant/qdrant/blob/09f87abb/lib/segment/src/index/field_index/geo_hash.rs
- 5: https://github.com/qdrant/qdrant/blob/09f87abb/lib/segment/src/index/struct_payload_index.rs
- 6: https://stackoverflow.com/questions/65643399/how-to-avoid-underflow-pitfalls-when-iterating-manually
- 7: [Bug] Integer Overflow in do_query_batch aggregation causes resource miscalculation #7949
- 8: Fix: Prevent panics in Point Group Search with large limits or group sizes #8533
- 9: [On disk payload index] Tracking issue #4502
Use saturating_sub to prevent underflow in cardinality estimates.
Subtracting interior_estimation values from exterior_estimation fields can underflow if interior estimates exceed current exterior bounds. Underflow happens before max(...) is applied, causing panics in debug/test builds and incorrect estimates in release builds.
🐛 Suggested fix
for interior in &interior_hashes {
let interior_estimation = self.match_cardinality(interior, hw_counter)?;
- exterior_estimation.min = max(0, exterior_estimation.min - interior_estimation.max);
+ exterior_estimation.min =
+ exterior_estimation.min.saturating_sub(interior_estimation.max);
exterior_estimation.max = max(
exterior_estimation.min,
- exterior_estimation.max - interior_estimation.min,
+ exterior_estimation
+ .max
+ .saturating_sub(interior_estimation.min),
);
exterior_estimation.exp = max(
- exterior_estimation.exp - interior_estimation.exp,
+ exterior_estimation
+ .exp
+ .saturating_sub(interior_estimation.exp),
exterior_estimation.min,
);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for interior in &interior_hashes { | |
| let interior_estimation = self.match_cardinality(interior, hw_counter)?; | |
| exterior_estimation.min = max(0, exterior_estimation.min - interior_estimation.max); | |
| exterior_estimation.max = max( | |
| exterior_estimation.min, | |
| exterior_estimation.max - interior_estimation.min, | |
| ); | |
| exterior_estimation.exp = max( | |
| exterior_estimation.exp - interior_estimation.exp, | |
| exterior_estimation.min, | |
| ); | |
| for interior in &interior_hashes { | |
| let interior_estimation = self.match_cardinality(interior, hw_counter)?; | |
| exterior_estimation.min = | |
| exterior_estimation.min.saturating_sub(interior_estimation.max); | |
| exterior_estimation.max = max( | |
| exterior_estimation.min, | |
| exterior_estimation | |
| .max | |
| .saturating_sub(interior_estimation.min), | |
| ); | |
| exterior_estimation.exp = max( | |
| exterior_estimation | |
| .exp | |
| .saturating_sub(interior_estimation.exp), | |
| exterior_estimation.min, | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@lib/segment/src/index/field_index/geo_index/payload_index.rs` around lines
202 - 212, The subtraction of interior_estimation fields from
exterior_estimation (inside the loop over interior_hashes in payload_index.rs)
can underflow before max(...) clamps results; modify the updates to use
saturating_sub when reducing exterior_estimation.min, exterior_estimation.max,
and exterior_estimation.exp (i.e., replace direct `-` operations with
`.saturating_sub(...)` when subtracting interior_estimation.max/min/exp after
calling self.match_cardinality(interior, hw_counter)) so the arithmetic never
underflows prior to applying the max clamps.
The geo_index module was a single 2134-line file. Split it into focused files for better readability and maintainability: - mod.rs: GeoMapIndex enum definition and core methods (~290 lines) - builders.rs: GeoMapIndexMmapBuilder and GeoMapIndexGridstoreBuilder - payload_index.rs: ValueIndexer, PayloadFieldIndex, PayloadFieldIndexRead impls - tests.rs: all test code (~1340 lines) No logic changes; all 40 existing tests pass. Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Cursor <[email protected]>
Summary
lib/segment/src/index/field_index/geo_index/mod.rsinto focused files for better readability and maintainabilitymod.rs(~290 lines):GeoMapIndexenum definition and core methods (constructors, builders, cardinality, telemetry, iterators)builders.rs(~100 lines):GeoMapIndexMmapBuilderandGeoMapIndexGridstoreBuilderwith theirFieldIndexBuilderTraitimplementationspayload_index.rs(~280 lines):ValueIndexer,PayloadFieldIndex, andPayloadFieldIndexReadtrait implementations plusvalue_retrievertests.rs(~1340 lines): all test code moved to a dedicated fileTest plan
cargo check -p segment— clean compilation, no warningscargo test -p segment --lib -- geo_index::tests— all 40 tests passcargo +nightly fmt --all -- --check— passesMade with Cursor