Repository navigation
refactor: read only geoindex - #9033
Conversation
71d8591 to
8b1693e
Compare
📝 WalkthroughWalkthroughThis PR refactors the geo-index read path by introducing Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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.
🧹 Nitpick comments (2)
lib/segment/src/index/field_index/geo_index/read_ops.rs (1)
155-157: 💤 Low valueConsider bounds validation for cardinality estimate cast.
The
round() as usizecast could theoretically produce incorrect results if the floating-point value exceedsusize::MAXor 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 valueDocument or log serialization failures in
value_retriever.The
filter_map(|v| serde_json::to_value(v).ok())silently drops anyGeoPointvalues that fail JSON serialization. While serialization should always succeed for the simpleGeoPointstruct, 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
📒 Files selected for processing (12)
lib/segment/src/index/field_index/field_index_base/field_index.rslib/segment/src/index/field_index/field_index_base/field_index_read_impl.rslib/segment/src/index/field_index/field_index_base/read_only/mod.rslib/segment/src/index/field_index/field_index_base/read_only/read_ops.rslib/segment/src/index/field_index/geo_index/immutable_geo_index.rslib/segment/src/index/field_index/geo_index/mmap_geo_index.rslib/segment/src/index/field_index/geo_index/mod.rslib/segment/src/index/field_index/geo_index/mutable_geo_index.rslib/segment/src/index/field_index/geo_index/payload_index.rslib/segment/src/index/field_index/geo_index/read_only_geo_index.rslib/segment/src/index/field_index/geo_index/read_ops.rslib/segment/src/index/field_index/geo_index/tests.rs
generall
left a comment
There was a problem hiding this comment.
Please address the comment and apply the same file structure as in map_index
There was a problem hiding this comment.
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 winHandle upserts in
add_many_geo_pointsbefore incrementing counters.When
idxalready has geo values, this path overwrites values but still incrementspoints_countand 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 liftDo not silently convert storage errors into
falseincheck_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 winReplace 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
ascasts fromusizetou32/PointOffsetType. On 64-bit systems whereusizecan exceedu32::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
📒 Files selected for processing (15)
lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rslib/segment/src/index/field_index/geo_index/immutable_geo_index/mod.rslib/segment/src/index/field_index/geo_index/immutable_geo_index/read_ops.rslib/segment/src/index/field_index/geo_index/mmap_geo_index/lifecycle.rslib/segment/src/index/field_index/geo_index/mmap_geo_index/mod.rslib/segment/src/index/field_index/geo_index/mmap_geo_index/read_ops.rslib/segment/src/index/field_index/geo_index/mod.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/lifecycle.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/mod.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/mod.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/read_ops.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/read_ops.rslib/segment/src/index/field_index/geo_index/read_only/mod.rslib/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
| // 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) | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 winValidate bounds before casting to
u32.Lines 47 and 61 cast
points_map_ids.len()fromusizetou32without validation. Sincepoints_map_idsaccumulates point IDs across all geohashes and can contain duplicates (the same point appearing in multiple hashes), the total length could theoretically exceedu32::MAXon 64-bit systems with large datasets, causing silent overflow and index corruption.Based on learnings, casts from
usizetou32(orPointOffsetType) 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
📒 Files selected for processing (5)
lib/segment/src/index/field_index/geo_index/immutable_geo_index/lifecycle.rslib/segment/src/index/field_index/geo_index/immutable_geo_index/mod.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rslib/segment/src/index/field_index/geo_index/mutable_geo_index/read_only/read_ops.rslib/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
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
lib/segment/src/index/field_index/geo_index/mutable_geo_index/inner.rs
| 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}")), | ||
| )?; |
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
…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]>
* 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
…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]>
All Submissions:
devbranch (notmaster) and my branch was created fromdev.New Feature Submissions:
cargo +nightly fmt --allcommand prior to submission?cargo clippy --workspace --all-featurescommand?Changes to Core Features: