Repository navigation
Refactor PointToValues to use UniversalRead - #8298
Conversation
It includes a significant change to `MmapValue` trait to be able to handle Cow reads, instead of just references.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
lib/segment/src/index/field_index/map_index/immutable_map_index.rs (1)
429-429: Prefer direct count lookup instead of iterating forvalues_count.
get_values(idx)?.count()is O(n) per call; use the direct count API for O(1) if available.♻️ Suggested change
pub fn values_count(&self, idx: PointOffsetType) -> Option<usize> { - Some(self.point_to_values.get_values(idx)?.count()) + self.point_to_values.get_values_count(idx) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/map_index/immutable_map_index.rs` at line 429, The current implementation calls self.point_to_values.get_values(idx)?.count(), which iterates O(n); change it to use the direct O(1) count API on point_to_values (e.g., a method like get_values_count(idx) or values_count(idx)) instead of retrieving the iterator and counting. Locate the expression using point_to_values.get_values and replace it with the direct-count accessor on the point_to_values struct so values_count returns the count without iterating.lib/segment/src/index/field_index/mmap_point_to_values.rs (1)
288-295: Consider addressing the TODO comment.The TODO at line 292 indicates the hardware counter should be propagated upwards. This could affect IO measurement accuracy.
Do you want me to help propagate the hardware counter through the call chain?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` around lines 288 - 295, The TODO indicates values_iter should propagate a hardware IO counter instead of creating a never counter; modify values_iter to accept a &ConditionedCounter (or an owned counter param) and pass it into self.values(point_id, counter) so the measurement propagates; update the signature of values_iter (and any callers) to accept the counter and return OperationResult<Option<impl Iterator<Item = Cow<'a, T>>>>, ensuring references to ConditionedCounter, values_iter, and values are adjusted consistently through the call chain so IO counters are recorded and not dropped.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 64-92: The string parsing in read_from_mmap uses incorrect slice
bounds and start advancement: when you call u32::read_from_prefix to get len,
len is the string length and the 4-byte prefix must be skipped; replace
occurrences of slice.get(start..len as usize) and vec.get(start..len as usize)
with slices that begin at start + size_of::<u32>() and end at start +
size_of::<u32>() + len as usize, and then advance start by size_of::<u32>() +
len as usize (instead of Self::mmapped_size(string) if that relied on old
offsets) so mmapped_size/next-offset calculations use the correct total bytes
consumed; update both the Cow::Borrowed and Cow::Owned branches and keep
references to read_from_mmap, CowValues, mmapped_size and u32::read_from_prefix
to locate the changes.
In `@lib/segment/src/index/field_index/numeric_index/mod.rs`:
- Around line 289-292: The mmap branch is swallowing I/O/storage errors by
calling unwrap_or(false) on NumericIndexInner::Mmap.index.check_values_any;
update the code to propagate the underlying error instead of returning false —
have the call return a Result and use the ? operator (or map_err and return Err)
so check_values_any errors bubble up, and adjust the enclosing function
signature (and callers) to return a Result as needed (refer to
NumericIndexInner::Mmap and the check_values_any invocation).
---
Nitpick comments:
In `@lib/segment/src/index/field_index/map_index/immutable_map_index.rs`:
- Line 429: The current implementation calls
self.point_to_values.get_values(idx)?.count(), which iterates O(n); change it to
use the direct O(1) count API on point_to_values (e.g., a method like
get_values_count(idx) or values_count(idx)) instead of retrieving the iterator
and counting. Locate the expression using point_to_values.get_values and replace
it with the direct-count accessor on the point_to_values struct so values_count
returns the count without iterating.
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 288-295: The TODO indicates values_iter should propagate a
hardware IO counter instead of creating a never counter; modify values_iter to
accept a &ConditionedCounter (or an owned counter param) and pass it into
self.values(point_id, counter) so the measurement propagates; update the
signature of values_iter (and any callers) to accept the counter and return
OperationResult<Option<impl Iterator<Item = Cow<'a, T>>>>, ensuring references
to ConditionedCounter, values_iter, and values are adjusted consistently through
the call chain so IO counters are recorded and not dropped.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 11132cbe-aab8-445c-97dc-7004b38a5caf
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (18)
Cargo.tomllib/common/common/src/cow.rslib/common/common/src/ext.rslib/segment/benches/numeric_index_check_values.rslib/segment/src/data_types/facets.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/index_selector.rslib/segment/src/index/field_index/map_index/immutable_map_index.rslib/segment/src/index/field_index/map_index/mmap_map_index.rslib/segment/src/index/field_index/map_index/mod.rslib/segment/src/index/field_index/map_index/mutable_map_index.rslib/segment/src/index/field_index/mmap_point_to_values.rslib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rslib/segment/src/index/field_index/numeric_index/mod.rslib/segment/src/segment_constructor/segment_builder.rslib/segment/src/types.rs
| // FIXME: don't silently ignore error, change output of this function and propagate | ||
| NumericIndexInner::Mmap(index) => index | ||
| .check_values_any(idx, check_fn, hw_counter) | ||
| .unwrap_or(false), |
There was a problem hiding this comment.
Don’t silently convert mmap index errors to false.
At Line 289, unwrap_or(false) hides storage/I/O failures and can silently drop valid matches from filtered queries. This should propagate an error (preferred) instead of being treated as “no match”.
Suggested direction
- ) -> bool {
+ ) -> OperationResult<bool> {
match self {
- NumericIndexInner::Mutable(index) => index.check_values_any(idx, check_fn),
- NumericIndexInner::Immutable(index) => index.check_values_any(idx, check_fn),
- NumericIndexInner::Mmap(index) => index
- .check_values_any(idx, check_fn, hw_counter)
- .unwrap_or(false),
+ NumericIndexInner::Mutable(index) => Ok(index.check_values_any(idx, check_fn)),
+ NumericIndexInner::Immutable(index) => Ok(index.check_values_any(idx, check_fn)),
+ NumericIndexInner::Mmap(index) => index.check_values_any(idx, check_fn, hw_counter),
}
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/segment/src/index/field_index/numeric_index/mod.rs` around lines 289 -
292, The mmap branch is swallowing I/O/storage errors by calling
unwrap_or(false) on NumericIndexInner::Mmap.index.check_values_any; update the
code to propagate the underlying error instead of returning false — have the
call return a Result and use the ? operator (or map_err and return Err) so
check_values_any errors bubble up, and adjust the enclosing function signature
(and callers) to return a Result as needed (refer to NumericIndexInner::Mmap and
the check_values_any invocation).
There was a problem hiding this comment.
Already acknowledged it :)
There was a problem hiding this comment.
@coszio, fair enough — the // FIXME comment already captures the intent to address this properly later. I'll defer to that. Thanks for noting it!
🧠 Learnings used
Learnt from: coszio
Repo: qdrant/qdrant PR: 8196
File: lib/common/common/src/universal_io/mmap.rs:63-65
Timestamp: 2026-02-23T18:49:18.575Z
Learning: In `lib/common/common/src/universal_io/mmap.rs`, for index computations like `start + range.length as usize` used with `slice.get(start..end)`, relying on the bounds checking of `get()` rather than explicit overflow protection with `checked_add` is acceptable. The bounds check gracefully handles overflow cases by returning `None`, which gets propagated as an error.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR `#7048`, using checked_mul with u64 casting to prevent silent overflow.
Learnt from: generall
Repo: qdrant/qdrant PR: 8287
File: lib/gridstore/src/gridstore/mod.rs:145-149
Timestamp: 2026-03-04T16:22:16.230Z
Learning: In `lib/gridstore/src/gridstore/mod.rs`, the maintainer (generall) intentionally treats any mismatch between `loaded_pages` (from `Pages::open`) and `num_pages` (inferred from bitmask) as a hard error (`GridstoreError::service_error`), including the case where `loaded_pages > num_pages`. Extra trailing page files not covered by the bitmask are considered evidence of storage corruption, not a recoverable warning condition.
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7520
File: lib/quantization/src/p_square.rs:41-49
Timestamp: 2025-11-18T18:20:20.021Z
Learning: In lib/quantization/src/p_square.rs, IvanPleshkov prefers using defensive double-checks (e.g., `let Ok(x) = NotNan::new(x) else { return; }`) over `.unwrap()` even when a prior check guarantees success, to avoid panic-causing code and maintain defensive programming practices.
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Learnt from: coszio
Repo: qdrant/qdrant PR: 6528
File: lib/posting_list/src/view.rs:118-118
Timestamp: 2025-05-19T14:40:20.068Z
Learning: In the bitpacking crate, the BitPacker::decompress_strictly_sorted function takes an Option<PointOffsetType> as its first parameter, which means using checked_sub(1) without unwrapping is intentional and correct.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Learnt from: coszio
Repo: qdrant/qdrant PR: 8287
File: lib/gridstore/src/tracker.rs:285-292
Timestamp: 2026-03-04T17:03:23.486Z
Learning: In `lib/gridstore/src/tracker.rs`, the use of `transmute_from_u8` with `#[expect(deprecated, reason = "legacy code")]` in functions like `read_header` and `get_raw` is a known existing issue acknowledged by the maintainer (coszio). It should not be flagged as a new violation in code reviews for this file.
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6444
File: lib/segment/src/index/field_index/map_index/immutable_map_index.rs:373-375
Timestamp: 2025-05-08T10:34:42.223Z
Learning: In the Qdrant codebase, storage backends may have different error handling approaches. Specifically, the mmap variant of `remove_point` method does not return errors, while the RocksDB variant does propagate errors using the `?` operator. These differences are intentional by design.
Learnt from: coszio
Repo: qdrant/qdrant PR: 6768
File: lib/collection/src/collection/mmr.rs:90-95
Timestamp: 2025-07-01T17:12:27.967Z
Learning: In the Qdrant codebase, the user coszio mistakenly believed that triple question mark `???` syntax was valid Rust, when it is actually invalid syntax. The codebase uses standard Rust error propagation with `?` and `??` operators only.
Learnt from: KShivendu
Repo: qdrant/qdrant PR: 6352
File: lib/segment/src/id_tracker/immutable_id_tracker.rs:379-393
Timestamp: 2025-05-07T09:13:47.781Z
Learning: In the Qdrant codebase, prefer fail-fast error handling by returning explicit errors rather than silently continuing with potentially corrupted state, especially in components like ID trackers that are fundamental to data integrity.
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: For Rust code review, checking whether code compiles is out of scope, including: missing imports for `size_of` or `align_of` (included in Rust 1.80+ prelude), methods not implemented for types, different method names across `rand` crate versions (e.g., `random_range` vs `gen_range`), and other compiler errors or warnings
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 8246
File: lib/segment/src/segment/segment_ops.rs:691-696
Timestamp: 2026-02-27T19:23:23.760Z
Learning: In code that computes offsets or casts counts to PointOffsetType (u32), avoid unsafe or unchecked casts from usize to PointOffsetType. Do not cast unless you can guarantee the value is < PointOffsetType::MAX, for example by assertions or by design constraints (as in versions_store.rs and segment internal IDs). When such a cast is necessary, validate the bound first and add an explicit assertion or guard, documenting the invariant to prevent overflow and maintain correctness across segments.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs (1)
349-349: Prefer explicit error conversion inmap_err.Use an explicit converter (
OperationError::fromor concrete error mapping) instead ofInto::intoto match repo style.♻️ Proposed fix
- self.store.populate().map_err(Into::into) + self.store.populate().map_err(OperationError::from)As per coding guidelines,
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` at line 349, The map_err call on self.store.populate() uses the implicit Into::into conversion; replace it with an explicit converter matching repo style (e.g., map_err(OperationError::from) or the concrete error type's from) so the error is converted explicitly—update the expression around self.store.populate() to call the appropriate ::from function instead of Into::into and run tests/request_verification.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/segment/src/index/field_index/map_index/mmap_map_index.rs`:
- Around line 218-223: The code currently uses .ok()? on
self.storage.point_to_values.values_iter(idx), which hides storage errors;
change this to explicitly match the Result from values_iter, returning
Some(Box::new(iter) ...) on Ok and logging the Err before returning None so
errors are not silently dropped; locate the call to
self.storage.point_to_values.values_iter in mmap_map_index.rs (and the similar
occurrence around the other instance) and replace .ok()? with a match or
.map(...).map_err(|e| { process_logger/error!(...) ; e }).ok() pattern that logs
the error (include error details) before yielding None to preserve the Option
API.
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Line 199: from_iter is passing a full file path into open which then appends
"point_to_values.bin" again, producing
"<dir>/point_to_values.bin/point_to_values.bin"; change from_iter so it passes
the directory root (e.g. the parent directory of file_name or the original
directory path) into Self::open instead of the full file path, or alternatively
pass the correct base path string that does not include "point_to_values.bin";
update references to file_name in from_iter accordingly so open builds exactly
"<dir>/point_to_values.bin" once.
- Around line 43-47: In read_from_mmap (returning Option<Self::CowValues<'_>>),
replace the infallible bytemuck::cast_slice/cast_vec calls with the fallible
bytemuck::try_cast_slice and bytemuck::try_cast_vec, handling the Result by
returning None on Err so malformed or misaligned mmap bytes do not panic; ensure
you still construct Cow::Borrowed(...) or Cow::Owned(...) with the successfully
casted slice/vec and keep the function signature and CowValues usage unchanged.
---
Nitpick comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Line 349: The map_err call on self.store.populate() uses the implicit
Into::into conversion; replace it with an explicit converter matching repo style
(e.g., map_err(OperationError::from) or the concrete error type's from) so the
error is converted explicitly—update the expression around self.store.populate()
to call the appropriate ::from function instead of Into::into and run
tests/request_verification.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: dbf55e5d-dd1e-4a33-8deb-94b9c89ad003
📒 Files selected for processing (2)
lib/segment/src/index/field_index/map_index/mmap_map_index.rslib/segment/src/index/field_index/mmap_point_to_values.rs
| self.storage | ||
| .point_to_values | ||
| .values_iter(idx) | ||
| .ok()? | ||
| .map(|iter| Box::new(iter) as Box<dyn Iterator<Item = Cow<'_, N>>>) | ||
| }) |
There was a problem hiding this comment.
Avoid silently downgrading storage errors to None.
Using .ok()? here makes corruption/read failures indistinguishable from “no values,” which can silently skew filter/count results.
🔍 Proposed fix (log on error while preserving current Option API)
pub fn get_values(
&self,
idx: PointOffsetType,
) -> Option<Box<dyn Iterator<Item = Cow<'_, N>> + '_>> {
self.storage
.deleted
.get(idx as usize)
.filter(|b| !b)
.and_then(|_| {
- self.storage
- .point_to_values
- .values_iter(idx)
- .ok()?
- .map(|iter| Box::new(iter) as Box<dyn Iterator<Item = Cow<'_, N>>>)
+ match self.storage.point_to_values.values_iter(idx) {
+ Ok(Some(iter)) => Some(Box::new(iter) as Box<dyn Iterator<Item = Cow<'_, N>>>),
+ Ok(None) => None,
+ Err(err) => {
+ log::error!("Failed to read point_to_values for point {idx}: {err:?}");
+ None
+ }
+ }
})
}
@@
pub fn values_count(&self, idx: PointOffsetType) -> Option<usize> {
self.storage
.deleted
.get(idx as usize)
.filter(|b| !b)
- .and_then(|_| self.storage.point_to_values.get_values_count(idx).ok()?)
+ .and_then(|_| match self.storage.point_to_values.get_values_count(idx) {
+ Ok(v) => v,
+ Err(err) => {
+ log::error!("Failed to read value count for point {idx}: {err:?}");
+ None
+ }
+ })
}Also applies to: 231-231
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/segment/src/index/field_index/map_index/mmap_map_index.rs` around lines
218 - 223, The code currently uses .ok()? on
self.storage.point_to_values.values_iter(idx), which hides storage errors;
change this to explicitly match the Result from values_iter, returning
Some(Box::new(iter) ...) on Ok and logging the Err before returning None so
errors are not silently dropped; locate the call to
self.storage.point_to_values.values_iter in mmap_map_index.rs (and the similar
occurrence around the other instance) and replace .ok()? with a match or
.map(...).map_err(|e| { process_logger/error!(...) ; e }).ok() pattern that logs
the error (include error details) before yielding None to preserve the Option
API.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe patch refactors mmap-backed index storage to a universal I/O abstraction and Cow-based value semantics. It introduces a generic MmapPointToValues<T, S: UniversalRead>, a new MmapValue trait with Cow-backed iterators (and CowSlice/CowSliceIter), propagates OperationResult through open/populate/check APIs, updates many map/numeric/geo index modules to use MmapUniversal and Cow, changes MapIndexKey/owned-associated-type usage across map indices, adds ResultOptionExt, derives bytemuck Pod/Zeroable and #[repr(C)] for GeoPoint, and enables ordered-float's bytemuck feature in Cargo.toml. Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs). Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs (1)
348-350: Prefer explicit error conversion inpopulate.Use explicit
OperationError::frominstead ofInto::intofor consistency with repo Rust style.Proposed fix
pub fn populate(&self) -> OperationResult<()> { - self.store.populate().map_err(Into::into) + self.store.populate().map_err(OperationError::from) }As per coding guidelines "Prefer explicit
SomeType::from(x)over implicitx.into()in Rust".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` around lines 348 - 350, The populate method currently maps errors using Into::into; change it to use the explicit conversion OperationError::from by replacing .map_err(Into::into) with .map_err(OperationError::from) so populate() returns an OperationResult<()> with errors converted via OperationError::from when calling self.store.populate().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 43-48: read_from_mmap currently ignores the provided count and
decodes the entire byte buffer, which can hide corruption; change it to validate
that bytes.len() equals count * size_of::<ElementType>() before casting.
Specifically, in read_from_mmap check the expected byte length
(count.checked_mul(std::mem::size_of::<YourValueType>()) and ensure it matches
the slice/vec length), return None on mismatch, and only then call
bytemuck::cast_slice or bytemuck::cast_vec and wrap in CowSlice; update
references to CowSlice and the Cow<'_, [u8]> branches (Borrowed/Owned)
accordingly.
---
Nitpick comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 348-350: The populate method currently maps errors using
Into::into; change it to use the explicit conversion OperationError::from by
replacing .map_err(Into::into) with .map_err(OperationError::from) so populate()
returns an OperationResult<()> with errors converted via OperationError::from
when calling self.store.populate().
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a4215b6a-b4e4-4a65-8aed-aa73e6043910
📒 Files selected for processing (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs
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/mmap_point_to_values.rs (1)
149-154:⚠️ Potential issue | 🟠 MajorGuard
from_itersize math against overflow.Line 152 and Line 153 use unchecked arithmetic for file sizing. In overflow cases this can produce undersized files and late write failures/corruption-like behavior.
Proposed fix
- let ranges_size = points_count * std::mem::size_of::<MmapRange>(); - let file_size = PADDING_SIZE + ranges_size + values_size; + let ranges_size = points_count + .checked_mul(std::mem::size_of::<MmapRange>()) + .ok_or_else(|| OperationError::service_error("points-to-values size overflow"))?; + let file_size = PADDING_SIZE + .checked_add(ranges_size) + .and_then(|v| v.checked_add(values_size)) + .ok_or_else(|| OperationError::service_error("points-to-values size overflow"))?;Based on learnings, overflow-sensitive storage sizing in this codebase is expected to use checked arithmetic to avoid silent overflow.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` around lines 149 - 154, The size computations in from_iter (points_count, values_size, ranges_size, file_size) use unchecked arithmetic and can overflow; update calculations to use checked operations (checked_add, checked_mul, checked_sum where available) for points_count accumulation and for values_size, then compute ranges_size = points_count.checked_mul(size_of::<MmapRange>()) and file_size = PADDING_SIZE.checked_add(ranges_size)?.checked_add(values_size)?; if any checked operation returns None, return an error (or propagate a Result) instead of continuing, so the function fails safely on overflow. Ensure you reference and protect the computations involving points_count, values_size, MmapRange size, PADDING_SIZE, and the final file_size in from_iter.
♻️ Duplicate comments (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs (1)
43-48:⚠️ Potential issue | 🟠 MajorValidate decoded length against
countfor POD values.Line 43 currently ignores
count, so corrupted range metadata can still decode “extra” values from raw bytes instead of failing fast.Proposed fix
- fn read_from_mmap(bytes: Cow<'_, [u8]>, _count: usize) -> Option<Self::CowValues<'_>> { + fn read_from_mmap(bytes: Cow<'_, [u8]>, count: usize) -> Option<Self::CowValues<'_>> { let cow = match bytes { - Cow::Borrowed(slice) => Cow::Borrowed(bytemuck::try_cast_slice(slice).ok()?), - Cow::Owned(vec) => Cow::Owned(bytemuck::try_cast_vec(vec).ok()?), + Cow::Borrowed(slice) => { + let casted: &[Self] = bytemuck::try_cast_slice(slice).ok()?; + if casted.len() != count { + return None; + } + Cow::Borrowed(casted) + } + Cow::Owned(vec) => { + let casted: Vec<Self> = bytemuck::try_cast_vec(vec).ok()?; + if casted.len() != count { + return None; + } + Cow::Owned(casted) + } }; Some(CowSlice(cow)) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` around lines 43 - 48, The read_from_mmap implementation for POD values must validate that the number of decoded elements matches the supplied count: in read_from_mmap (and where CowSlice is constructed) call bytemuck::try_cast_slice / try_cast_vec as before, then check the resulting slice/vec length against the provided _count (convert types safely) and return None if they differ; only return Some(CowSlice(cow)) when decoded_len == count to fail fast on corrupted metadata.
🧹 Nitpick comments (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs (1)
349-349: Use explicit conversion instead ofInto::into.Line 349 uses
map_err(Into::into). Please switch to explicitOperationError::from(...)conversion to match repository Rust style rules.Proposed fix
- self.store.populate().map_err(Into::into) + self.store.populate().map_err(OperationError::from)As per coding guidelines,
**/*.rs: “Prefer explicitSomeType::from(x)over implicitx.into()in Rust”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` at line 349, Replace the implicit conversion map_err(Into::into) on the result of self.store.populate() with an explicit OperationError::from(...) call; specifically change the closure passed to map_err so it calls OperationError::from(error) (i.e., map_err(|e| OperationError::from(e))) to follow the repository Rust style for explicit conversions, ensuring OperationError is in scope or imported if necessary.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 149-154: The size computations in from_iter (points_count,
values_size, ranges_size, file_size) use unchecked arithmetic and can overflow;
update calculations to use checked operations (checked_add, checked_mul,
checked_sum where available) for points_count accumulation and for values_size,
then compute ranges_size = points_count.checked_mul(size_of::<MmapRange>()) and
file_size = PADDING_SIZE.checked_add(ranges_size)?.checked_add(values_size)?; if
any checked operation returns None, return an error (or propagate a Result)
instead of continuing, so the function fails safely on overflow. Ensure you
reference and protect the computations involving points_count, values_size,
MmapRange size, PADDING_SIZE, and the final file_size in from_iter.
---
Duplicate comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 43-48: The read_from_mmap implementation for POD values must
validate that the number of decoded elements matches the supplied count: in
read_from_mmap (and where CowSlice is constructed) call bytemuck::try_cast_slice
/ try_cast_vec as before, then check the resulting slice/vec length against the
provided _count (convert types safely) and return None if they differ; only
return Some(CowSlice(cow)) when decoded_len == count to fail fast on corrupted
metadata.
---
Nitpick comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Line 349: Replace the implicit conversion map_err(Into::into) on the result of
self.store.populate() with an explicit OperationError::from(...) call;
specifically change the closure passed to map_err so it calls
OperationError::from(error) (i.e., map_err(|e| OperationError::from(e))) to
follow the repository Rust style for explicit conversions, ensuring
OperationError is in scope or imported if necessary.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2aa5b7eb-9f93-4e49-8f45-5e9987fd335a
📒 Files selected for processing (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs`:
- Around line 335-341: The code in mmap_point_to_values.rs computes point_id + 1
unsafely which overflows when point_id == u32::MAX; change the logic in the
method (around the get_range call) to use checked arithmetic or an explicit
bounds check: if point_id == u32::MAX then treat there being no next point and
set end = self.store.len()?, otherwise call
self.get_range(point_id.checked_add(1).unwrap()).map_some(...). Ensure you
reference the get_range call and the end calculation so the path that returns
None falls back to store.len() without ever wrapping the u32.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ff233087-32b7-4784-b4df-cec677c8370c
📒 Files selected for processing (1)
lib/segment/src/index/field_index/mmap_point_to_values.rs
| let end = match self.get_range(point_id + 1).map_some(|range| range.start)? { | ||
| Some(end) => end, | ||
| None => { | ||
| // if there is no next point, then use end of file | ||
| self.store.len()? | ||
| } | ||
| }; |
There was a problem hiding this comment.
Potential overflow in point_id + 1 calculation.
If point_id == u32::MAX, the addition wraps to 0 in release mode, causing get_range(0) to return the first point's range instead of None. This would produce an incorrect byte range.
Proposed fix using checked arithmetic
- let end = match self.get_range(point_id + 1).map_some(|range| range.start)? {
+ let end = match point_id
+ .checked_add(1)
+ .and_then(|next_id| self.get_range(next_id).transpose())
+ .transpose()?
+ .and_then(|range| range.map(|r| r.start))
+ {
Some(end) => end,
None => {
// if there is no next point, then use end of file
self.store.len()?
}
};Or simpler:
- let end = match self.get_range(point_id + 1).map_some(|range| range.start)? {
+ let next_point_start = point_id
+ .checked_add(1)
+ .map(|next_id| self.get_range(next_id))
+ .transpose()?
+ .flatten()
+ .map(|range| range.start);
+ let end = match next_point_start {
Some(end) => end,Based on learnings: "In code that computes offsets or casts counts to PointOffsetType (u32), avoid unsafe or unchecked casts... validate the bound first."
📝 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.
| let end = match self.get_range(point_id + 1).map_some(|range| range.start)? { | |
| Some(end) => end, | |
| None => { | |
| // if there is no next point, then use end of file | |
| self.store.len()? | |
| } | |
| }; | |
| let end = match point_id | |
| .checked_add(1) | |
| .and_then(|next_id| self.get_range(next_id)) | |
| .map(|range| range.start)? | |
| { | |
| Some(end) => end, | |
| None => { | |
| // if there is no next point, then use end of file | |
| self.store.len()? | |
| } | |
| }; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/segment/src/index/field_index/mmap_point_to_values.rs` around lines 335 -
341, The code in mmap_point_to_values.rs computes point_id + 1 unsafely which
overflows when point_id == u32::MAX; change the logic in the method (around the
get_range call) to use checked arithmetic or an explicit bounds check: if
point_id == u32::MAX then treat there being no next point and set end =
self.store.len()?, otherwise call
self.get_range(point_id.checked_add(1).unwrap()).map_some(...). Ensure you
reference the get_range call and the end calculation so the path that returns
None falls back to store.len() without ever wrapping the u32.
| let bytes = self.store.read::<false>(bytes_range)?; | ||
| let count = self.get_values_count(point_id)?.unwrap_or(0); | ||
|
|
||
| let cow_values = T::read_from_mmap(bytes, count) |
There was a problem hiding this comment.
proposal for next PR: for hot path in check_values_any we can use callback, other uses seems to be less hot, so collect is fine
this also makes it so that borrowed strs can keep happening :heart-eyes:
| pub fn values_iter<'a>( | ||
| &'a self, | ||
| point_id: PointOffsetType, | ||
| ) -> Option<impl Iterator<Item = T::Referenced<'a>> + 'a> { | ||
| hw_counter: ConditionedCounter, // TODO: make it by reference | ||
| ) -> OperationResult<Option<impl Iterator<Item = Cow<'a, T>>>> { | ||
| let hw_cell = hw_counter.payload_index_io_read_counter(); | ||
|
|
||
| // first, get range of values for point | ||
| let range = self.get_range(point_id)?; | ||
|
|
||
| // second, define iteration step for values | ||
| // iteration step gets remainder range from memmapped file and returns left range | ||
| let bytes: &[u8] = self.mmap.as_ref(); | ||
| let read_value = move |range: MmapRange| -> Option<(T::Referenced<'a>, MmapRange)> { | ||
| if range.count > 0 { | ||
| let bytes = bytes.get(range.start as usize..)?; | ||
| T::read_from_mmap(bytes).map(|value| { | ||
| let range = MmapRange { | ||
| start: range.start + T::mmapped_size(value.clone()) as u64, | ||
| count: range.count - 1, | ||
| }; | ||
| (value, range) | ||
| }) | ||
| } else { | ||
| None | ||
| } | ||
| let Some(bytes_range) = self.get_bytes_range(point_id)?.map(|range| { | ||
| let range = universal_io::ElementsRange { | ||
| start: range.start, | ||
| length: range.end - range.start, | ||
| }; | ||
| // Measure IO overhead of `self.get_bytes_range()` and the length of the values | ||
| hw_cell.incr_delta(MMAP_PTV_ACCESS_OVERHEAD + range.length as usize); | ||
|
|
||
| range | ||
| }) else { | ||
| return Ok(None); | ||
| }; |
There was a problem hiding this comment.
value_iter returns Option<impl Iterator>. Would it make sense to return an empty iterator instead of None? Do we explicitly rely on this Option anywhere?
There was a problem hiding this comment.
Well, it could always be an ExactSizeIterator but it makes handling None values easier with a ?
Maybe rename |
I can handle renames in the following PR |
* refactor PointToValues to use UniversalRead It includes a significant change to `MmapValue` trait to be able to handle Cow reads, instead of just references. * fix str parsing * fix incorrect path * use fallible casting * clippy * No eager allocation this also makes it so that borrowed strs can keep happening :heart-eyes: * Lifetime cleanup --------- Co-authored-by: Roman Titov <[email protected]>
* refactor PointToValues to use UniversalRead It includes a significant change to `MmapValue` trait to be able to handle Cow reads, instead of just references. * fix str parsing * fix incorrect path * use fallible casting * clippy * No eager allocation this also makes it so that borrowed strs can keep happening :heart-eyes: * Lifetime cleanup --------- Co-authored-by: Roman Titov <[email protected]>
Since the reads in new
universal_ioreturnCow, we need to change how we deal with each set of values for a particular point. Previously, it was "deserialized" iteratively, but this PR changes it to be done at onceWhat I tried
Naively, the change would be to just hold the
Cow<[u8]>of the read bytes in an iterator, and hand out references to it, so that callers can decide what to do with the reference.But the trait definition of
Iteratordoes not allow to define theItemas a reference to an owned section of the slice. It doesn't work because it would mean that in the case of owned bytes (Vec<u8>), would need to live as long as the mmap itself, which is not true.The idea of handing out references to things owned by the iterator is not wrong though. It can work, if only the
Iteratortrait could have GAT (type Item<'a>) such that the lifetime can be tied to thenext()function, not to the iterator itself.There are crates that solve this, but it is not super elegant and drifts from well known patterns. It would also make all upstream code aware of this pattern, so it wouldn't be self-contained.
What this PR does
To solve this more ergonomically, I have:
MmapValuetrait to convert the bytes of ALL the values of a particular point at once, and collect them into an associated type container.str, which is implemented separatelyThe other changes are necessary propagation of these changes, which includes:
OperationResultFacetValueRefnow takes copy types by value, and onlyKeywordvariant isCowMapIndexKey::OwnedandToOwned::Owned, so we need to specify<N as MapIndexKey>::Ownedeverywhere.bytemuck::PodforGeoPointand included"bytemuck"feature forOrderedFloat