Skip to content

refactor: read only geoindex - #9033

Merged
dancixx merged 7 commits into
devfrom
refactor/read-only-geoindex
May 14, 2026
Merged

dancixx merged 7 commits into
devfrom
refactor/read-only-geoindex

Conversation

@dancixx

@dancixx dancixx commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

All Submissions:

⚠️ PRs must target the dev branch. If your PR targets master, please change the base branch to dev before requesting a review.

  • My PR targets the dev branch (not master) and my branch was created from dev.
  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?

New Feature Submissions:

  1. Does your submission pass tests?
  2. Have you formatted your code locally using cargo +nightly fmt --all command prior to submission?
  3. Have you checked your code using cargo clippy --workspace --all-features command?

Changes to Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

@dancixx
dancixx force-pushed the refactor/read-only-geoindex branch from 71d8591 to 8b1693e Compare May 13, 2026 15:58
@dancixx
dancixx marked this pull request as ready for review May 13, 2026 15:59
@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors the geo-index read path by introducing GeoMapIndexRead, a shared trait that abstracts read operations across concrete geo-index variants (mutable, immutable, mmap-backed, appendable). It adds read_ops helper functions (filter, estimate_cardinality, for_each_payload_block, condition_checker) with default trait methods for cardinality and telemetry, creates ReadOnlyGeoMapIndex<S> (Appendable | Immutable) and a read-only appendable wrapper, implements GeoMapIndexRead for all variants, and wires ReadOnlyFieldIndex and payload_index to delegate geo queries to the new trait and helpers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~65 minutes

Possibly related PRs

  • qdrant/qdrant#8975: Introduces the FieldIndexRead trait that this PR extends with ReadOnlyFieldIndex::GeoIndex variant support and geo read dispatch wiring.
  • qdrant/qdrant#9025: Related refactor of ReadOnlyFieldIndex shared plumbing for other index types using similar trait-dispatch patterns.
  • qdrant/qdrant#9018: Earlier module refactor that separated mutable and immutable geo-index types; this PR builds on that structure by unifying their read interface.

Suggested labels

release:1.18.0

Suggested reviewers

  • generall
  • ffuugoo
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.95% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description includes contribution checklist confirmations and process validations but provides no substantive explanation of the refactoring changes, rationale, or technical details of the geo index modifications. Add a clear explanation of the refactoring objectives, what the read-only geoindex changes accomplish, and why this architectural change improves the codebase.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: read only geoindex' directly relates to the main changeset, which refactors the geo index system to introduce read-only variants and trait-based abstractions across multiple backend types.
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/read-only-geoindex

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.

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

155-157: 💤 Low value

Consider bounds validation for cardinality estimate cast.

The round() as usize cast could theoretically produce incorrect results if the floating-point value exceeds usize::MAX or results in precision loss for very large cardinality estimates. While unlikely in practice for point counts, consider adding a .min(usize::MAX as f64) guard or a debug assertion to document the expected range.

🤖 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/read_ops.rs` around lines 155 -
157, The computed estimation_exp in the geo index read path (where
estimate_multi_value_selection_cardinality(total_points, total_values,
sum).round() as usize is used) can overflow or lose precision when casting from
f64 to usize; clamp or validate the floating result before casting—e.g., compute
the f64 result, apply .min(usize::MAX as f64) (or add a debug_assert that it is
<= usize::MAX) and then round and cast to usize—so update the code around
estimation_exp to bound the value and/or assert expected range using the
identifiers estimation_exp, estimate_multi_value_selection_cardinality,
total_points, total_values, and sum.
lib/segment/src/index/field_index/geo_index/read_only_geo_index.rs (1)

52-58: 💤 Low value

Document or log serialization failures in value_retriever.

The filter_map(|v| serde_json::to_value(v).ok()) silently drops any GeoPoint values that fail JSON serialization. While serialization should always succeed for the simple GeoPoint struct, silent error swallowing could mask data corruption or unexpected structure changes. Consider either:

  • Adding a debug assertion or log warning for serialization failures, or
  • Documenting that serialization failures are intentionally ignored and why.
🤖 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/read_only_geo_index.rs` around
lines 52 - 58, The value_retriever closure silently drops serialization failures
due to filter_map(|v| serde_json::to_value(v).ok()); modify the closure in the
value_retriever so that when serde_json::to_value(v) returns Err you either (a)
log a debug/warn message including the PointOffsetType and the failed GeoPoint
(or at least an identifier) using the crate logger, or (b) add a debug_assert
with a clear message that serialization must succeed for GeoPoint; locate this
change around the closure that calls GeoMapIndexRead::get_values and touches
types GeoPoint, PointOffsetType and MultiValue<Value>, and ensure the code still
returns only successful serde_json::to_value results.
🤖 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.

Nitpick comments:
In `@lib/segment/src/index/field_index/geo_index/read_only_geo_index.rs`:
- Around line 52-58: The value_retriever closure silently drops serialization
failures due to filter_map(|v| serde_json::to_value(v).ok()); modify the closure
in the value_retriever so that when serde_json::to_value(v) returns Err you
either (a) log a debug/warn message including the PointOffsetType and the failed
GeoPoint (or at least an identifier) using the crate logger, or (b) add a
debug_assert with a clear message that serialization must succeed for GeoPoint;
locate this change around the closure that calls GeoMapIndexRead::get_values and
touches types GeoPoint, PointOffsetType and MultiValue<Value>, and ensure the
code still returns only successful serde_json::to_value results.

In `@lib/segment/src/index/field_index/geo_index/read_ops.rs`:
- Around line 155-157: The computed estimation_exp in the geo index read path
(where estimate_multi_value_selection_cardinality(total_points, total_values,
sum).round() as usize is used) can overflow or lose precision when casting from
f64 to usize; clamp or validate the floating result before casting—e.g., compute
the f64 result, apply .min(usize::MAX as f64) (or add a debug_assert that it is
<= usize::MAX) and then round and cast to usize—so update the code around
estimation_exp to bound the value and/or assert expected range using the
identifiers estimation_exp, estimate_multi_value_selection_cardinality,
total_points, total_values, and sum.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1e464af0-f1ee-4529-8dc3-097b9ec29445

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed3057 and 8b1693e.

📒 Files selected for processing (12)
  • lib/segment/src/index/field_index/field_index_base/field_index.rs
  • lib/segment/src/index/field_index/field_index_base/field_index_read_impl.rs
  • lib/segment/src/index/field_index/field_index_base/read_only/mod.rs
  • lib/segment/src/index/field_index/field_index_base/read_only/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/payload_index.rs
  • lib/segment/src/index/field_index/geo_index/read_only_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/tests.rs

@dancixx
dancixx requested a review from generall May 13, 2026 16:10

@generall generall left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please address the comment and apply the same file structure as in map_index

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs (1)

153-159: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle upserts in add_many_geo_points before incrementing counters.

When idx already has geo values, this path overwrites values but still increments points_count and hash counters as if it were a fresh insert. That drifts all aggregate stats.

🔧 Suggested fix (replace-then-add semantics)
     pub fn add_many_geo_points(
         &mut self,
         idx: PointOffsetType,
         values: &[GeoPoint],
         hw_counter: &HardwareCounterCell,
     ) -> OperationResult<()> {
         if values.is_empty() {
             return Ok(());
         }
+
+        if self
+            .point_to_values
+            .get(idx as usize)
+            .is_some_and(|existing| !existing.is_empty())
+        {
+            self.remove_point(idx)?;
+        }

         if self.point_to_values.len() <= idx as usize {
             // That's a smart reallocation
             self.point_to_values.resize_with(idx as usize + 1, Vec::new);
         }

Also applies to: 177-189

🤖 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/mutable_geo_index/inner.rs`
around lines 153 - 159, The current assignment to self.point_to_values[idx as
usize] blindly overwrites existing geo values but still increases points_count
and the hash counters as if inserting new points, causing aggregate stats drift;
change add_many_geo_points to implement replace-then-add semantics: if
self.point_to_values[idx as usize] exists and is non-empty, first decrement
points_count and the associated hash counters for the existing values (reverse
whatever increment logic uses), then assign the new values
(self.point_to_values[idx as usize] = values.to_vec()), and finally increment
points_count and hash counters for the newly added values; apply the same
replace-then-add fix to the other code path referenced around the 177-189 block
so both branches handle upserts symmetrically.
lib/segment/src/index/field_index/geo_index/mmap_geo_index/lifecycle.rs (2)

213-226: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Do not silently convert storage errors into false in check_values_any.

unwrap_or(false) masks IO/data errors as a negative match, which can silently drop valid hits and obscure index corruption. This should be propagated (preferred) or at least surfaced explicitly.

🤖 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/mmap_geo_index/lifecycle.rs`
around lines 213 - 226, The method check_values_any currently swallows storage
errors by calling unwrap_or(false) on point_to_values.check_values_any, which
masks IO/data errors; change it to propagate the error instead of converting it
to false—update check_values_any to return a Result<bool, E> (or propagate the
point_to_values.check_values_any's error via ?), remove unwrap_or(false), and
adjust callers accordingly (or if changing the signature is infeasible, map the
error to a logged/explicit error state rather than returning false). Relevant
symbols: check_values_any, make_conditioned_counter, storage.deleted,
point_to_values.check_values_any, and the current unwrap_or(false) call. Ensure
errors from point_to_values.check_values_any are not silently ignored.

53-54: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace unchecked narrowing casts with bounds-checked conversions to prevent silent overflow of persisted index data.

Lines 53, 80, 81, 84, 109, and 110 contain unchecked as casts from usize to u32/PointOffsetType. On 64-bit systems where usize can exceed u32::MAX, these casts silently overflow and corrupt on-disk index structures (ids_start, ids_end, point/value counts). PointOffsetType::MAX is reserved as DELETED_SENTINEL, making the effective capacity strictly less than u32::MAX.

🔧 Suggested hardening
-                .map(|(idx, values)| (idx as PointOffsetType, values.iter())),
+                .map(|(idx, values)| {
+                    let idx = PointOffsetType::try_from(idx).map_err(|_| {
+                        OperationError::service_error("point_to_values index exceeds PointOffsetType")
+                    })?;
+                    Ok((idx, values.iter()))
+                })
+                .collect::<Result<Vec<_>, _>>()?
+                .into_iter(),
-                points_map[i].ids_start = ids_offset as u32;
-                points_map[i].ids_end = (ids_offset + ids.len()) as u32;
+                points_map[i].ids_start = u32::try_from(ids_offset).map_err(|_| {
+                    OperationError::service_error("ids_start exceeds u32 range")
+                })?;
+                points_map[i].ids_end = u32::try_from(ids_offset + ids.len()).map_err(|_| {
+                    OperationError::service_error("ids_end exceeds u32 range")
+                })?;
-                    dst.points = *points as u32;
-                    dst.values = *values as u32;
+                    dst.points = u32::try_from(*points).map_err(|_| {
+                        OperationError::service_error("points count exceeds u32 range")
+                    })?;
+                    dst.values = u32::try_from(*values).map_err(|_| {
+                        OperationError::service_error("values count exceeds u32 range")
+                    })?;
🤖 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/mmap_geo_index/lifecycle.rs`
around lines 53 - 54, The unchecked `as` casts from usize to u32/PointOffsetType
(e.g., the closure mapping `(idx as PointOffsetType, ...)` and other casts
around `ids_start`, `ids_end`, and point/value counts) can silently overflow on
64-bit and corrupt persisted index data; replace them with bounds-checked
conversions (u32::try_from or TryInto) and explicitly verify the value is less
than PointOffsetType::MAX (since MAX is reserved as DELETED_SENTINEL) before
converting, returning a clear error if out-of-range; propagate a descriptive
error from the functions that perform these conversions (e.g., the iterator
mapping closure and wherever `ids_start`/`ids_end` and counts are computed)
instead of using `as`.
🤖 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/mutable_geo_index/lifecycle.rs`:
- Around line 155-177: The current flow persists to storage (storage.put_value /
storage.delete_value) before mutating memory, which can leave storage and
in_memory_index inconsistent if in_memory_index.add_many_geo_points fails;
change the order to update in_memory_index first via
in_memory_index.add_many_geo_points(idx, values, hw_counter) and then persist
with storage.put_value (or delete_value for empty), and if persistence fails
roll back the memory change by calling the corresponding in-memory removal/undo
(e.g., in_memory_index.remove_many_geo_points or an equivalent rollback method)
so that either both steps succeed or state is reverted; ensure error handling
wraps storage.put_value/map_err and calls the rollback on failure, and include
hw_counter_ref when calling storage.put_value as before.

---

Outside diff comments:
In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index/lifecycle.rs`:
- Around line 213-226: The method check_values_any currently swallows storage
errors by calling unwrap_or(false) on point_to_values.check_values_any, which
masks IO/data errors; change it to propagate the error instead of converting it
to false—update check_values_any to return a Result<bool, E> (or propagate the
point_to_values.check_values_any's error via ?), remove unwrap_or(false), and
adjust callers accordingly (or if changing the signature is infeasible, map the
error to a logged/explicit error state rather than returning false). Relevant
symbols: check_values_any, make_conditioned_counter, storage.deleted,
point_to_values.check_values_any, and the current unwrap_or(false) call. Ensure
errors from point_to_values.check_values_any are not silently ignored.
- Around line 53-54: The unchecked `as` casts from usize to u32/PointOffsetType
(e.g., the closure mapping `(idx as PointOffsetType, ...)` and other casts
around `ids_start`, `ids_end`, and point/value counts) can silently overflow on
64-bit and corrupt persisted index data; replace them with bounds-checked
conversions (u32::try_from or TryInto) and explicitly verify the value is less
than PointOffsetType::MAX (since MAX is reserved as DELETED_SENTINEL) before
converting, returning a clear error if out-of-range; propagate a descriptive
error from the functions that perform these conversions (e.g., the iterator
mapping closure and wherever `ids_start`/`ids_end` and counts are computed)
instead of using `as`.

In `@lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs`:
- Around line 153-159: The current assignment to self.point_to_values[idx as
usize] blindly overwrites existing geo values but still increases points_count
and the hash counters as if inserting new points, causing aggregate stats drift;
change add_many_geo_points to implement replace-then-add semantics: if
self.point_to_values[idx as usize] exists and is non-empty, first decrement
points_count and the associated hash counters for the existing values (reverse
whatever increment logic uses), then assign the new values
(self.point_to_values[idx as usize] = values.to_vec()), and finally increment
points_count and hash counters for the newly added values; apply the same
replace-then-add fix to the other code path referenced around the 177-189 block
so both branches handle upserts symmetrically.
🪄 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: 0e16b8b6-1d54-4905-9ce3-3fa99bf17014

📥 Commits

Reviewing files that changed from the base of the PR and between 8b1693e and 7d01231.

📒 Files selected for processing (15)
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index/lifecycle.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/lifecycle.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/mod.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/read_only/mod.rs
  • lib/segment/src/index/field_index/geo_index/read_only/read_ops.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/field_index/geo_index/mod.rs

Comment on lines +155 to +177
// Update persisted storage
if values.is_empty() {
// We cannot store empty value, then delete instead
self.storage.delete_value(idx)?;
} else {
let hw_counter_ref = hw_counter.ref_payload_index_io_write_counter();
let raw_values = values
.iter()
.cloned()
.map(RawGeoPoint::from)
.collect::<Vec<_>>();
self.storage
.put_value(idx, &raw_values, hw_counter_ref)
.map_err(|err| {
OperationError::service_error(format!(
"failed to put value in mutable geo index gridstore: {err}"
))
})?;
}

self.in_memory_index
.add_many_geo_points(idx, values, hw_counter)
}

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

Avoid partial writes between Gridstore and in-memory index.

This method persists first and mutates memory second. If in_memory_index.add_many_geo_points fails (e.g., invalid coordinates during geohash encoding), storage is already updated and state diverges.

🔧 Suggested safeguard
     pub fn add_many_geo_points(
         &mut self,
         idx: PointOffsetType,
         values: &[GeoPoint],
         hw_counter: &HardwareCounterCell,
     ) -> OperationResult<()> {
+        // Validate geohash encodability before mutating either storage.
+        for geo_point in values {
+            encode_max_precision(geo_point.lon.0, geo_point.lat.0).map_err(|e| {
+                OperationError::service_error(format!("Malformed geo points: {e}"))
+            })?;
+        }
+
         // Update persisted storage
         if values.is_empty() {
             // We cannot store empty value, then delete instead
             self.storage.delete_value(idx)?;
         } else {
🤖 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/mutable_geo_index/lifecycle.rs`
around lines 155 - 177, The current flow persists to storage (storage.put_value
/ storage.delete_value) before mutating memory, which can leave storage and
in_memory_index inconsistent if in_memory_index.add_many_geo_points fails;
change the order to update in_memory_index first via
in_memory_index.add_many_geo_points(idx, values, hw_counter) and then persist
with storage.put_value (or delete_value for empty), and if persistence fails
roll back the memory change by calling the corresponding in-memory removal/undo
(e.g., in_memory_index.remove_many_geo_points or an equivalent rollback method)
so that either both steps succeed or state is reverted; ensure error handling
wraps storage.put_value/map_err and calls the rollback on failure, and include
hw_counter_ref when calling storage.put_value as before.

@dancixx
dancixx requested review from generall May 14, 2026 07:09

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rs (1)

37-62: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Validate bounds before casting to u32.

Lines 47 and 61 cast points_map_ids.len() from usize to u32 without validation. Since points_map_ids accumulates point IDs across all geohashes and can contain duplicates (the same point appearing in multiple hashes), the total length could theoretically exceed u32::MAX on 64-bit systems with large datasets, causing silent overflow and index corruption.

Based on learnings, casts from usize to u32 (or PointOffsetType) must be validated or guaranteed to be within bounds.

🛡️ Proposed fix using safe conversion
            |i, ids| {
                points_map_hashes.push(points_map_entries[i].hash.normalize());
-               points_map_offsets.push(points_map_ids.len() as u32);
+               points_map_offsets.push(
+                   u32::try_from(points_map_ids.len())
+                       .map_err(|_| OperationError::service_error(
+                           "Geo index too large: points_map_ids exceeds u32::MAX"
+                       ))?
+               );
                for &id in ids {
                    if !index
                        .storage
                        .deleted
                        .get_bit(id as usize)
                        .unwrap_or_default()
                    {
                        points_map_ids.push(id);
                    }
                }
                Ok(())
            },
        )?;
-       points_map_offsets.push(points_map_ids.len() as u32);
+       points_map_offsets.push(
+           u32::try_from(points_map_ids.len())
+               .map_err(|_| OperationError::service_error(
+                   "Geo index too large: points_map_ids exceeds u32::MAX"
+               ))?
+       );
🤖 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/immutable_geo_index/lifecycle.rs`
around lines 37 - 62, points_map_offsets is pushing points_map_ids.len() cast to
u32 without bounds checking, which can overflow; before each cast (both places
where points_map_ids.len() is cast and pushed), validate the length with a
checked conversion (e.g., use u32::try_from(points_map_ids.len()) or
TryFrom<usize> for PointOffsetType) and return/propagate an error if it exceeds
the target type; update the two pushes that currently do
points_map_offsets.push(points_map_ids.len() as u32) to perform the try_from
conversion and push the converted value (or convert to PointOffsetType after
checking) so overflow cannot silently occur.
🤖 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.

Outside diff comments:
In
`@lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rs`:
- Around line 37-62: points_map_offsets is pushing points_map_ids.len() cast to
u32 without bounds checking, which can overflow; before each cast (both places
where points_map_ids.len() is cast and pushed), validate the length with a
checked conversion (e.g., use u32::try_from(points_map_ids.len()) or
TryFrom<usize> for PointOffsetType) and return/propagate an error if it exceeds
the target type; update the two pushes that currently do
points_map_offsets.push(points_map_ids.len() as u32) to perform the try_from
conversion and push the converted value (or convert to PointOffsetType after
checking) so overflow cannot silently occur.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 48f35c64-5acb-4892-8c8b-ec3621b94cdf

📥 Commits

Reviewing files that changed from the base of the PR and between 7d01231 and 49d3b89.

📒 Files selected for processing (5)
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index/mod.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/read_ops.rs
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/read_ops.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs

@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

🤖 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/mutable_geo_index/inner.rs`:
- Around line 73-87: The code currently mutates state (takes
self.point_to_values, decrements self.points_count and self.points_values_count,
and later writes new values) before calling encode_max_precision which may fail;
instead, first iterate over the to-be-removed points and to-be-inserted points
and attempt to encode all their GeoHash values (use encode_max_precision)
collecting results into local vectors/sets (e.g., build removed_geo_hashes and
new_geo_hashes) and return early on any encode error, and only after all
encodings succeed perform the state mutations: replace self.point_to_values[idx
as usize], update self.points_count and self.points_values_count, and update
self.points_map accordingly. Ensure you reference and validate both the removal
path (removed_geo_points → removed_geo_hashes) and the insertion path (new
points used around where values are stored) before touching state.
- Around line 83-110: The loop currently only calls decrement_hash_value_counts
once per unique geohash, which miscounts when duplicate geo points are removed;
modify the loop in remove_point (in inner.rs) so
decrement_hash_value_counts(removed_geo_hash) is invoked for every
removed_geo_point before/independent of the removed_geo_hashes.insert(...)
uniqueness check, and keep the removed_geo_hashes set logic unchanged so
decrement_hash_point_counts still receives unique hashes; ensure ownership/copy
of removed_geo_hash is handled correctly when calling both insert and the
decrement function.
🪄 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: c0a2c42d-ce75-4dc3-941d-f624b5c32528

📥 Commits

Reviewing files that changed from the base of the PR and between 49d3b89 and dc3fb6f.

📒 Files selected for processing (1)
  • lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs

Comment on lines +73 to +87
let removed_geo_points = std::mem::take(&mut self.point_to_values[idx as usize]);

if removed_geo_points.is_empty() {
return Ok(());
}

self.points_count -= 1;
self.points_values_count -= removed_geo_points.len();
let mut removed_geo_hashes = AHashSet::with_capacity(removed_geo_points.len());

for removed_geo_point in removed_geo_points {
let removed_geo_hash: GeoHash =
encode_max_precision(removed_geo_point.lon.0, removed_geo_point.lat.0).map_err(
|e| OperationError::service_error(format!("Malformed geo points: {e}")),
)?;

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 | 🔴 Critical | ⚡ Quick win

Validate and encode geohashes before mutating the index state.

Line 73 empties point_to_values[idx] and Line 79 updates counters before encode_max_precision can fail. Line 129 likewise stores the new values before validating them. If encoding returns Err, the method exits with a partially mutated in-memory index.

Please collect/validate all hashes first, then update point_to_values, points_map, and the aggregate counters.

Also applies to: 124-141

🤖 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/mutable_geo_index/inner.rs`
around lines 73 - 87, The code currently mutates state (takes
self.point_to_values, decrements self.points_count and self.points_values_count,
and later writes new values) before calling encode_max_precision which may fail;
instead, first iterate over the to-be-removed points and to-be-inserted points
and attempt to encode all their GeoHash values (use encode_max_precision)
collecting results into local vectors/sets (e.g., build removed_geo_hashes and
new_geo_hashes) and return early on any encode error, and only after all
encodings succeed perform the state mutations: replace self.point_to_values[idx
as usize], update self.points_count and self.points_values_count, and update
self.points_map accordingly. Ensure you reference and validate both the removal
path (removed_geo_points → removed_geo_hashes) and the insertion path (new
points used around where values are stored) before touching state.

Comment on lines +83 to +110
for removed_geo_point in removed_geo_points {
let removed_geo_hash: GeoHash =
encode_max_precision(removed_geo_point.lon.0, removed_geo_point.lat.0).map_err(
|e| OperationError::service_error(format!("Malformed geo points: {e}")),
)?;
if !removed_geo_hashes.insert(removed_geo_hash) {
continue;
}

let is_last = if let Some(hash_ids) = self.points_map.get_mut(&removed_geo_hash) {
hash_ids.remove(&idx);
hash_ids.is_empty()
} else {
debug_assert!(
false,
"Geo index error: no points for hash {removed_geo_hash} was found",
);
false
};

if is_last {
self.points_map.remove(&removed_geo_hash);
}

self.decrement_hash_value_counts(removed_geo_hash);
}

self.decrement_hash_point_counts(removed_geo_hashes);

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

Keep values_per_hash decrements per value, not per unique geohash.

add_many_geo_points increments values_per_hash once for every input value, but remove_point only calls decrement_hash_value_counts for the first occurrence of each full geohash. A point with duplicate geo values will therefore leave values_per_hash permanently overstated after deletion.

Suggested fix
         for removed_geo_point in removed_geo_points {
             let removed_geo_hash: GeoHash =
                 encode_max_precision(removed_geo_point.lon.0, removed_geo_point.lat.0).map_err(
                     |e| OperationError::service_error(format!("Malformed geo points: {e}")),
                 )?;
+            self.decrement_hash_value_counts(removed_geo_hash);
             if !removed_geo_hashes.insert(removed_geo_hash) {
                 continue;
             }

             let is_last = if let Some(hash_ids) = self.points_map.get_mut(&removed_geo_hash) {
                 hash_ids.remove(&idx);
                 hash_ids.is_empty()
             } else {
                 debug_assert!(
                     false,
                     "Geo index error: no points for hash {removed_geo_hash} was found",
                 );
                 false
             };

             if is_last {
                 self.points_map.remove(&removed_geo_hash);
             }
-
-            self.decrement_hash_value_counts(removed_geo_hash);
         }
🤖 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/mutable_geo_index/inner.rs`
around lines 83 - 110, The loop currently only calls decrement_hash_value_counts
once per unique geohash, which miscounts when duplicate geo points are removed;
modify the loop in remove_point (in inner.rs) so
decrement_hash_value_counts(removed_geo_hash) is invoked for every
removed_geo_point before/independent of the removed_geo_hashes.insert(...)
uniqueness check, and keep the removed_geo_hashes set logic unchanged so
decrement_hash_point_counts still receives unique hashes; ensure ownership/copy
of removed_geo_hash is handled correctly when calling both insert and the
decrement function.

@dancixx
dancixx merged commit 00195ae into dev May 14, 2026
12 checks passed
@dancixx
dancixx deleted the refactor/read-only-geoindex branch May 14, 2026 12:12
generall added a commit that referenced this pull request May 14, 2026
…emoval (#9043)

* test: add failing test for values_per_hash drift on duplicate geo point removal

Reproduces the bug where `remove_point` only calls `decrement_hash_value_counts`
once per unique geohash, while `add_many_geo_points` increments it once per value.
When a point has duplicate geo coordinates (same geohash), the counters drift
upward permanently after removal.

Ref: #9033 (comment)
Co-authored-by: Cursor <[email protected]>

* fix: decrement values_per_hash once per value on geo point removal

`add_many_geo_points` increments `values_per_hash` once per value, but
`remove_point` deduplicated geohashes with a HashSet + `continue` that
also skipped the per-value decrement. A point with duplicate geo
coordinates (same geohash) therefore left the counters drifted upward
permanently after removal.

Move `decrement_hash_value_counts` above the dedup guard so it runs once
per value, matching the increment side. `points_map` and
`points_per_hash` track points, not values, so they stay deduplicated.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: generall <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
generall pushed a commit that referenced this pull request May 22, 2026
* refactor: read only geo index

* fix: linter

* fix: drop open temp

* fix: read_ops

* fix: address review fixes and use same file structure like map index

* fix: review comments

* fix: linter
generall added a commit that referenced this pull request May 22, 2026
…emoval (#9043)

* test: add failing test for values_per_hash drift on duplicate geo point removal

Reproduces the bug where `remove_point` only calls `decrement_hash_value_counts`
once per unique geohash, while `add_many_geo_points` increments it once per value.
When a point has duplicate geo coordinates (same geohash), the counters drift
upward permanently after removal.

Ref: #9033 (comment)
Co-authored-by: Cursor <[email protected]>

* fix: decrement values_per_hash once per value on geo point removal

`add_many_geo_points` increments `values_per_hash` once per value, but
`remove_point` deduplicated geohashes with a HashSet + `continue` that
also skipped the per-value decrement. A point with duplicate geo
coordinates (same geohash) therefore left the counters drifted upward
permanently after removal.

Move `decrement_hash_value_counts` above the dedup guard so it runs once
per value, matching the increment side. `points_map` and
`points_per_hash` track points, not values, so they stay deduplicated.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: generall <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 29, 2026
9 tasks
@generall generall added this to the Live-reload milestone May 30, 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.

2 participants