Repository navigation
universal io mmap - #8196
universal io mmap#8196
Conversation
…tead of `pub type UniversalIoError = std::io::Error;` and implement all `todo!()` in MmapUniversal
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
lib/common/common/src/universal_io/mmap.rs (1)
40-42: Add inline// SAFETY:comments at unsafe MmapSlice/MmapSliceReadOnly construction sites.Lines 42 and 47 call
unsafe { MmapSlice::try_from(mmap) }andunsafe { MmapSliceReadOnly::try_from(mmap_seq) }. While the underlying functions document their safety requirements (alignment, valid type representation, proper size), the call sites lack comments explaining why these invariants are upheld. Add brief// SAFETY:comments at each site to clarify that the mmap sources satisfy the required invariants.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/mmap.rs` around lines 40 - 42, Add a brief inline "// SAFETY:" comment immediately above each unsafe block that calls MmapSlice::try_from(mmap) and MmapSliceReadOnly::try_from(mmap_seq), stating why the required invariants (alignment, valid type representation, and correct size) hold: e.g., note that mmap/mmap_seq come from open_write_mmap/open_read_mmap which return properly aligned, correctly sized memory mappings matching the expected element type and length (and any other preconditions like populated pages or file-backed size), so it is safe to call the unsafe conversions. Reference the variables mmap and mmap_seq and the conversion functions MmapSlice::try_from and MmapSliceReadOnly::try_from in the comment.
🤖 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/common/common/src/universal_io/mmap.rs`:
- Around line 63-65: The index computation using start + range.length as usize
can overflow; in as_slice::<SEQUENTIAL>() usage compute end via checked_add
(e.g., let end = (start).checked_add(range.length as usize)) and handle the None
case by returning an explicit error so you never form a backwards or incorrect
range; apply the same pattern to the other occurrences in read_batch and write
(replace the direct addition with checked_add and propagate/return a clear error
if overflow occurs) and then use get(start..end) only after the checked_add
succeeds.
In `@lib/common/common/src/universal_io/mod.rs`:
- Around line 80-85: The OutOfBounds error message in the OutOfBounds variant
(fields start, end, data_length) incorrectly refers to bytes; update the
#[error(...)] string on the OutOfBounds enum variant in mod.rs to use
element-aware wording (e.g., "Byte range {start}..{end} is out of bounds (data
length: {data_length})" or "Element range {start}..{end} is out of bounds
(elements: {data_length})") so it no longer misleadingly claims "bytes" when
start/end and data_length are element indices used by mmap.rs.
- Around line 66-69: BytesRange currently lacks common derives; update its
declaration to derive Copy, Clone, and Debug (matching other types like
OpenOptions) so callers can copy values and see debug output. Locate the struct
BytesRange { pub start: ByteOffset, pub length: u64 } and add the derives
attribute (Copy, Clone, Debug) to the struct definition; ensure ByteOffset is a
Copy-able type or adjust accordingly.
---
Nitpick comments:
In `@lib/common/common/src/universal_io/mmap.rs`:
- Around line 40-42: Add a brief inline "// SAFETY:" comment immediately above
each unsafe block that calls MmapSlice::try_from(mmap) and
MmapSliceReadOnly::try_from(mmap_seq), stating why the required invariants
(alignment, valid type representation, and correct size) hold: e.g., note that
mmap/mmap_seq come from open_write_mmap/open_read_mmap which return properly
aligned, correctly sized memory mappings matching the expected element type and
length (and any other preconditions like populated pages or file-backed size),
so it is safe to call the unsafe conversions. Reference the variables mmap and
mmap_seq and the conversion functions MmapSlice::try_from and
MmapSliceReadOnly::try_from in the comment.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
lib/common/common/src/universal_io/mod.rs (1)
50-51:populate: Option<bool>— consider using plainbool.All current and foreseeable implementations (as seen in
mmap.rs) resolve this withpopulate.unwrap_or_default(), makingNoneandSome(false)indistinguishable. A plainboolis simpler and equally expressive here. If "use implementation default" semantics are genuinely needed in the future, it can be re-introduced then (YAGNI).♻️ Proposed simplification
pub struct OpenOptions { pub need_sequential: bool, pub disk_parallel: Option<usize>, - /// Populate RAM cache on open, if applicable for this implementation. - pub populate: Option<bool>, + /// Populate RAM cache on open, if applicable for this implementation. + pub populate: bool, } impl Default for OpenOptions { fn default() -> Self { Self { need_sequential: true, disk_parallel: None, - populate: None, + populate: false, } } }And in
mmap.rs:-let mmap = open_write_mmap(mmap_file, advice, populate.unwrap_or_default())?; +let mmap = open_write_mmap(mmap_file, advice, populate)?;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/mod.rs` around lines 50 - 51, The populate field is currently declared as pub populate: Option<bool> but all usages call populate.unwrap_or_default(), making None equivalent to Some(false); change the field to pub populate: bool instead, update all places that construct the containing type to provide a bool default (false) and remove unwrap_or_default() calls (e.g., in mmap.rs where populate.unwrap_or_default() is used, replace with populate), and adjust any tests or callers to pass a concrete bool.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@lib/common/common/src/universal_io/mod.rs`:
- Around line 66-69: BytesRange is missing common trait derives; update the
BytesRange struct (fields start: ByteOffset and length: u64) to derive Copy,
Clone, and Debug so callers can copy ranges without moving them and so the
struct formats with {:?} (used e.g. in mmap.rs OutOfBounds error context). Add
the derives to the BytesRange declaration (derive Copy, Clone, Debug) and ensure
ByteOffset is also Copy/Clone-compatible if needed.
- Around line 64-69: The public types ByteOffset and BytesRange currently
advertise byte semantics but mmap.rs treats them as element indices; update the
mmap read/write code that uses as_slice::<SEQUENTIAL>(), BytesRange.start, and
offset indexing into mmap (the calls that compute start/end and call
get()/get_mut() on &[T]/&mut [T]) to convert byte offsets to element indices by
dividing start and length by std::mem::size_of::<T>(), validate that start and
length are multiples of the element size (or return an error), compute
elem_start and elem_count, and then index the slices using
elem_start..elem_start+elem_count so the API semantics match
ByteOffset/BytesRange.
---
Nitpick comments:
In `@lib/common/common/src/universal_io/mod.rs`:
- Around line 50-51: The populate field is currently declared as pub populate:
Option<bool> but all usages call populate.unwrap_or_default(), making None
equivalent to Some(false); change the field to pub populate: bool instead,
update all places that construct the containing type to provide a bool default
(false) and remove unwrap_or_default() calls (e.g., in mmap.rs where
populate.unwrap_or_default() is used, replace with populate), and adjust any
tests or callers to pass a concrete bool.
📝 WalkthroughWalkthroughThe changes introduce a generic Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
lib/common/common/src/universal_io/mmap.rs (1)
59-76:⚠️ Potential issue | 🟡 MinorPotential arithmetic overflow in index computation.
range.start as usizetruncates on 32-bit targets, andstart + range.length as usize(Line 65) can wrap in release mode. The same pattern appears inread_batch(Line 88) andwrite(Line 129). Consider usingchecked_add/usize::try_fromwith an explicit error to make this robust.Proposed fix (read; apply similarly to read_batch and write)
let data_slice = self.as_slice::<SEQUENTIAL>(); - let start = range.start as usize; - let end = start + range.length as usize; + let start = usize::try_from(range.start).map_err(|_| UniversalIoError::OutOfBounds { + start: range.start, + end: range.start.saturating_add(range.length), + data_length: data_slice.len(), + })?; + let end = start.checked_add( + usize::try_from(range.length).map_err(|_| UniversalIoError::OutOfBounds { + start: range.start, + end: range.start.saturating_add(range.length), + data_length: data_slice.len(), + })?, + ).ok_or(UniversalIoError::OutOfBounds { + start: range.start, + end: range.start.saturating_add(range.length), + data_length: data_slice.len(), + })?;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/mmap.rs` around lines 59 - 76, The index computations in read (and similarly in read_batch and write) use direct casts like range.start as usize and start + range.length as usize which can truncate or overflow on some targets; convert range.start and range.length from u64 using usize::try_from and use checked_add (or checked_mul where applicable) to compute end, returning the UniversalIoError::OutOfBounds (or a new explicit conversion error) when try_from or checked_add fails; update as_slice::<SEQUENTIAL>() usage to only proceed after successful conversions so you avoid panics and ensure the same pattern is applied in read_batch and write (referencing the read, read_batch, and write functions).
🤖 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/common/common/src/universal_io/mmap.rs`:
- Around line 125-141: The OutOfBounds error construction in write (fn write,
type ByteOffset) can itself overflow when computing offset + data.len() as u64;
update the error report to compute the end using a non-wrapping operation (e.g.,
offset.saturating_add(data.len() as u64) or use checked_add and handle the None
case) before creating UniversalIoError::OutOfBounds so the reported end is
correct and cannot wrap when offset is near u64::MAX.
---
Duplicate comments:
In `@lib/common/common/src/universal_io/mmap.rs`:
- Around line 59-76: The index computations in read (and similarly in read_batch
and write) use direct casts like range.start as usize and start + range.length
as usize which can truncate or overflow on some targets; convert range.start and
range.length from u64 using usize::try_from and use checked_add (or checked_mul
where applicable) to compute end, returning the UniversalIoError::OutOfBounds
(or a new explicit conversion error) when try_from or checked_add fails; update
as_slice::<SEQUENTIAL>() usage to only proceed after successful conversions so
you avoid panics and ensure the same pattern is applied in read_batch and write
(referencing the read, read_batch, and write functions).
| fn write(&mut self, offset: ByteOffset, data: &[T]) -> crate::universal_io::Result<()> { | ||
| let mmap_slice: &mut [T] = &mut self.mmap; | ||
| let data_length = mmap_slice.len(); | ||
| let start = offset as usize; | ||
| let end = start + data.len(); | ||
|
|
||
| let target = mmap_slice | ||
| .get_mut(start..end) | ||
| .ok_or(UniversalIoError::OutOfBounds { | ||
| start: offset, | ||
| end: offset + data.len() as u64, | ||
| data_length, | ||
| })?; | ||
|
|
||
| target.copy_from_slice(data); | ||
| Ok(()) | ||
| } |
There was a problem hiding this comment.
offset + data.len() as u64 in the error path (Line 135) can also overflow.
If offset is near u64::MAX, this addition wraps silently, producing a misleading OutOfBounds error. Use offset.saturating_add(data.len() as u64) (or checked_add) for the error report to stay consistent with the defensive intent.
Proposed fix
.ok_or(UniversalIoError::OutOfBounds {
start: offset,
- end: offset + data.len() as u64,
+ end: offset.saturating_add(data.len() as u64),
data_length,
})?;📝 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.
| fn write(&mut self, offset: ByteOffset, data: &[T]) -> crate::universal_io::Result<()> { | |
| let mmap_slice: &mut [T] = &mut self.mmap; | |
| let data_length = mmap_slice.len(); | |
| let start = offset as usize; | |
| let end = start + data.len(); | |
| let target = mmap_slice | |
| .get_mut(start..end) | |
| .ok_or(UniversalIoError::OutOfBounds { | |
| start: offset, | |
| end: offset + data.len() as u64, | |
| data_length, | |
| })?; | |
| target.copy_from_slice(data); | |
| Ok(()) | |
| } | |
| fn write(&mut self, offset: ByteOffset, data: &[T]) -> crate::universal_io::Result<()> { | |
| let mmap_slice: &mut [T] = &mut self.mmap; | |
| let data_length = mmap_slice.len(); | |
| let start = offset as usize; | |
| let end = start + data.len(); | |
| let target = mmap_slice | |
| .get_mut(start..end) | |
| .ok_or(UniversalIoError::OutOfBounds { | |
| start: offset, | |
| end: offset.saturating_add(data.len() as u64), | |
| data_length, | |
| })?; | |
| target.copy_from_slice(data); | |
| Ok(()) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/common/common/src/universal_io/mmap.rs` around lines 125 - 141, The
OutOfBounds error construction in write (fn write, type ByteOffset) can itself
overflow when computing offset + data.len() as u64; update the error report to
compute the end using a non-wrapping operation (e.g.,
offset.saturating_add(data.len() as u64) or use checked_add and handle the None
case) before creating UniversalIoError::OutOfBounds so the reported end is
correct and cannot wrap when offset is near u64::MAX.
Introduce a universal I/O abstraction layer (following upstream qdrant/qdrant PRs qdrant#8196, qdrant#8251, qdrant#8292) that decouples data access from storage backends. Key components: - UniversalRead<T> / UniversalWrite<T> traits for backend-agnostic I/O - MmapUniversal<T>: mmap-based implementation with optional sequential read mmap - BitSliceReader<S>: storage-agnostic bitslice reader that works over any UniversalRead<u8> backend, supporting: - read_bitslice(): read entire storage as a BitSlice (zero-copy for mmap) - get_bit(): single-bit access translating bit offset to a 1-byte read - read_bit_range(): partial bit range reads with byte-aligned backend access https://claude.ai/code/session_01X9Bnj9Gooxh5bxkhbFmnGx
* [manunal] WIP: universal mmap interface * [AI + manual] implement proper error handelling, with `thiserror` instead of `pub type UniversalIoError = std::io::Error;` and implement all `todo!()` in MmapUniversal * [AI] implement UniversalWrite for MmapUniversal * review fix: error wording * review nits --------- Co-authored-by: Luis Cossío <[email protected]>
* [manunal] WIP: universal mmap interface * [AI + manual] implement proper error handelling, with `thiserror` instead of `pub type UniversalIoError = std::io::Error;` and implement all `todo!()` in MmapUniversal * [AI] implement UniversalWrite for MmapUniversal * review fix: error wording * review nits --------- Co-authored-by: Luis Cossío <[email protected]>
Implementation of the Universal IO traits for mmap.