Skip to content

universal io mmap - #8196

Merged
generall merged 5 commits into
devfrom
universal-io-mmap
Feb 24, 2026
Merged

generall merged 5 commits into
devfrom
universal-io-mmap

Conversation

@generall

@generall generall commented Feb 22, 2026 •

Copy link
Copy Markdown
Member

Implementation of the Universal IO traits for mmap.

@generall
generall requested a review from ffuugoo February 22, 2026 21:32
@generall
generall marked this pull request as ready for review February 22, 2026 21:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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) } and unsafe { 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
lib/common/common/src/universal_io/mod.rs (1)

50-51: populate: Option<bool> — consider using plain bool.

All current and foreseeable implementations (as seen in mmap.rs) resolve this with populate.unwrap_or_default(), making None and Some(false) indistinguishable. A plain bool is 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.

@generall
generall requested a review from xzfc February 23, 2026 10:29
@qdrant qdrant deleted a comment from coderabbitai Bot Feb 23, 2026
@coderabbitai

coderabbitai Bot commented Feb 23, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes introduce a generic MmapUniversal<T> type that provides a unified memory-mapped I/O abstraction combining a primary read/write mmap and an optional read-only sequential mmap. The universal_io module traits are generalized to work with any Copy + 'static element type rather than just bytes. The module adds support for compile-time sequential read selection, new populate() method, structured error types with out-of-bounds context, and converts BytesRange from a tuple type to a struct. The OpenOptions structure gains a populate field for RAM cache control.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Universal I/O #8183 — Directly related as it establishes the foundation of the universal_io traits and types that this PR evolves to be generic and implements with the new MmapUniversal concrete type.

Suggested reviewers

  • xzfc
🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'universal io mmap' is vague and generic, using non-descriptive terms that don't convey what aspect of universal IO or mmap functionality is being implemented. Consider using a more specific title like 'Implement UniversalRead and UniversalWrite traits for mmap' to clearly indicate the main change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed The description 'Implementation of the Universal IO traits for mmap' is directly related to the changeset, which introduces MmapUniversal type and implements UniversalRead and UniversalWrite traits.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch universal-io-mmap

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
lib/common/common/src/universal_io/mmap.rs (1)

59-76: ⚠️ Potential issue | 🟡 Minor

Potential arithmetic overflow in index computation.

range.start as usize truncates on 32-bit targets, and start + range.length as usize (Line 65) can wrap in release mode. The same pattern appears in read_batch (Line 88) and write (Line 129). Consider using checked_add / usize::try_from with 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).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3021a9 and aeef746.

📒 Files selected for processing (2)
  • lib/common/common/src/universal_io/mmap.rs
  • lib/common/common/src/universal_io/mod.rs

Comment on lines +125 to +141
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(())
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

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

@generall
generall merged commit 949376f into dev Feb 24, 2026
15 checks passed
@generall
generall deleted the universal-io-mmap branch February 24, 2026 10:55
coszio pushed a commit to coszio/qdrant that referenced this pull request Mar 5, 2026
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
@coderabbitai coderabbitai Bot mentioned this pull request Mar 25, 2026
7 of 9 tasks
@generall generall added this to the Universal IO milestone Mar 26, 2026
generall added a commit that referenced this pull request Mar 26, 2026
* [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]>
KShivendu pushed a commit that referenced this pull request Mar 30, 2026
* [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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants