Skip to content

refactor: split geo_index/mod.rs into separate files - #9018

Merged
generall merged 1 commit into
devfrom
refactor/split-geo-index-module
May 12, 2026
Merged

generall merged 1 commit into
devfrom
refactor/split-geo-index-module

Conversation

@qdrant-cloud-bot

Copy link
Copy Markdown
Contributor

Summary

  • Split the 2134-line lib/segment/src/index/field_index/geo_index/mod.rs into focused files for better readability and maintainability
  • mod.rs (~290 lines): GeoMapIndex enum definition and core methods (constructors, builders, cardinality, telemetry, iterators)
  • builders.rs (~100 lines): GeoMapIndexMmapBuilder and GeoMapIndexGridstoreBuilder with their FieldIndexBuilderTrait implementations
  • payload_index.rs (~280 lines): ValueIndexer, PayloadFieldIndex, and PayloadFieldIndexRead trait implementations plus value_retriever
  • tests.rs (~1340 lines): all test code moved to a dedicated file

Test plan

  • cargo check -p segment — clean compilation, no warnings
  • cargo test -p segment --lib -- geo_index::tests — all 40 tests pass
  • cargo +nightly fmt --all -- --check — passes

Made with Cursor

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]>
@coderabbitai

coderabbitai Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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

  • qdrant/qdrant#8965: Adds concrete GeoMapIndex builder types and FieldIndexBuilderTrait implementations required by this refactoring.
  • qdrant/qdrant#8507: Modifies geo_index internals and APIs (method visibility and mmap-backed storage behavior) in the same module.
  • qdrant/qdrant#8996: Implements field-index trait surface (condition_checker and value_retriever) that interacts directly with these changes.

Suggested labels

release:1.18.0

Suggested reviewers

  • xzfc
  • ffuugoo
  • coszio
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: refactoring a large monolithic geo_index module file into separate focused files for better organization and maintainability.
Description check ✅ Passed The description is directly related to the changeset, providing clear details about the refactoring: how the 2134-line file was split into four focused files (mod.rs, builders.rs, payload_index.rs, tests.rs) with line counts and responsibilities for each.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/split-geo-index-module

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
lib/segment/src/index/field_index/geo_index/payload_index.rs (1)

44-56: ⚡ Quick win

Spell out the non-object Value variants.

The _ => None arm hides future serde_json::Value variant 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 win

Use 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 while estimate_cardinality is wrong for the actual FieldCondition.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f99a0b and d131957.

📒 Files selected for processing (4)
  • lib/segment/src/index/field_index/geo_index/builders.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/payload_index.rs
  • lib/segment/src/index/field_index/geo_index/tests.rs

Comment on lines +66 to +76
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(())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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).

Comment on lines +202 to +212
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,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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:


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.

Suggested change
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.

@generall
generall merged commit 3fca28c into dev May 12, 2026
15 checks passed
@generall
generall deleted the refactor/split-geo-index-module branch May 12, 2026 18:57
@coderabbitai coderabbitai Bot mentioned this pull request May 13, 2026
6 of 9 tasks
generall pushed a commit that referenced this pull request May 22, 2026
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]>
@coderabbitai coderabbitai Bot mentioned this pull request Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants