Skip to content

Allow short mmap reads - #8808

Closed
coszio wants to merge 2 commits into
devfrom
short-mmap-reads
Closed

coszio wants to merge 2 commits into
devfrom
short-mmap-reads

Conversation

@coszio

@coszio coszio commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

This PR enables mmap reads to not error when the end of a range goes beyond EOF.

When developing #8792, I enabled it to use a generic backend for reading a remote file. In linux, it uses io-uring with O_DIRECT flags, but in other systems it can default to use MmapFile. This introduces the same problem that was already solved for uring in #8466, but for mmap:

Since O_DIRECT requires reads to be page-aligned, if the size of the file is not page-aligned, we will end up requesting a read that goes beyond EOF. Returning a shorter read than requested if it stumbles with EOF is pretty canonical, so I think enabling the same mechanism for mmap is appropriate.

This is at the cost of an extra branching statement, but should be negligible.

Alternatively...

The alternative would be to take the length of the file in consideration at the moment of requesting the read, but it would mean that io-uring should need to allocate twice: one for the page-aligned buffer, and once again for the extracted output.

I think allowing a short mmap read makes sense in the context of general I/O reads

@coszio
coszio requested a review from xzfc April 27, 2026 22:09

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/common/common/src/universal_io/mmap.rs`:
- Around line 275-296: The read() implementation in MmapFile currently computes
requested_end via unchecked arithmetic (start + size_of::<T>() * items) which
can overflow; update MmapFile::read() to use checked_mul(size_of::<T>(), items)
and then checked_add(start, product) (or the equivalent on usize) and return a
suitable UniversalIoError (e.g., OutOfBounds or a new Overflow variant) when any
checked operation returns None; also ensure callers read_bytes() and
read_batch() either call validate_range() or perform the same checked arithmetic
before invoking MmapFile::read() (similar to read_bytes_stream()), so all entry
points validate ranges and prevent silent wrapping when computing requested_end.
🪄 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: d390cf6e-4ed5-4e9a-ac04-e62124e22efe

📥 Commits

Reviewing files that changed from the base of the PR and between 74881e6 and 07f84d9.

📒 Files selected for processing (2)
  • lib/common/common/src/universal_io/mmap.rs
  • src/tonic/api/storage_read_api/tests.rs

Comment on lines +275 to +296
let requested_end = start + size_of::<T>() * items as usize;

let bytes = bytes
.get(start..end)
.ok_or_else(|| UniversalIoError::OutOfBounds {
if start > bytes.len() {
return Err(UniversalIoError::OutOfBounds {
start: start as _,
end: end as _,
end: requested_end as _,
elements: bytes.len() / size_of::<T>(),
})?;
});
}

let range = if requested_end <= bytes.len() {
start..requested_end
} else {
// allow short reads, but align them to size of T
let avail_bytes = bytes.len() - start;
let truncated_items = avail_bytes / size_of::<T>() * size_of::<T>();
let end = start + truncated_items;

start..end
};

let bytes = &bytes[range];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C4 'struct ReadRange|ReadBytesRequest|ReadBatchRequest|ReadMultiRequest|byte_offset|length' src lib

Repository: qdrant/qdrant

Length of output: 50370


🏁 Script executed:

# Read the specific file and lines mentioned in the review
head -300 lib/common/common/src/universal_io/mmap.rs | tail -50

Repository: qdrant/qdrant

Length of output: 1412


🏁 Script executed:

# Get more context - read lines around 275-296
sed -n '250,310p' lib/common/common/src/universal_io/mmap.rs

Repository: qdrant/qdrant

Length of output: 1658


🏁 Script executed:

# Check all callers of MmapFile::read to see if they validate ranges
rg -n 'MmapFile.*read|\.read\(' lib/common/common/src/universal_io/mmap.rs -A2 -B2

Repository: qdrant/qdrant

Length of output: 217


🏁 Script executed:

# Search for all calls to the generic read() function or MmapFile::read
rg -n '\.read\s*<|MmapFile.*read|read::<' lib/common/common/src/universal_io/mmap.rs -B3 -A3

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check the public read method signature on MmapFile
sed -n '1,500p' lib/common/common/src/universal_io/mmap.rs | grep -A20 'pub.*fn read'

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Look for all callers of MmapFile::read in the entire codebase
rg -n '\.read::<|storage\.read::<|MmapFile' src lib --type rs | grep -i read | head -30

Repository: qdrant/qdrant

Length of output: 84


🏁 Script executed:

# Search for direct calls to read function in mmap.rs and callers
rg -n 'read::<|fn read' lib/common/common/src/universal_io/mmap.rs

Repository: qdrant/qdrant

Length of output: 258


🏁 Script executed:

# Check what's in the UniversalRead trait and its implementations
rg -n 'trait UniversalRead|impl.*UniversalRead' lib/common/common/src/universal_io/ -A10

Repository: qdrant/qdrant

Length of output: 12248


🏁 Script executed:

# Find where the inline read function is called
rg -n '\bread\s*::<|fn read<' lib/common/common/src/universal_io/mmap.rs -B5 -A15

Repository: qdrant/qdrant

Length of output: 1343


🏁 Script executed:

# Search in storage_read_api to understand how read() is invoked
sed -n '160,165p' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 345


🏁 Script executed:

# Check ReadRange::new to see if it does any validation
rg -n 'impl ReadRange|fn new|struct ReadRange' lib/common/common/src/universal_io/ -A5

Repository: qdrant/qdrant

Length of output: 6047


🏁 Script executed:

# Check what ReadRange is and whether it validates
sed -n '1,100p' lib/common/common/src/universal_io/read.rs

Repository: qdrant/qdrant

Length of output: 3343


🏁 Script executed:

# Verify that read_bytes in storage_read_api does NOT validate before calling read()
sed -n '139,166p' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 1101


🏁 Script executed:

# Check read_batch to see if it validates
sed -n '267,306p' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 1547


🏁 Script executed:

# Check if read_bytes validates ranges before calling storage.read
sed -n '139,170p' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 1237


🏁 Script executed:

# Check if there's validation happening in read() before the slice index
sed -n '265,296p' lib/common/common/src/universal_io/mmap.rs

Repository: qdrant/qdrant

Length of output: 925


🏁 Script executed:

# Search for any validation that happens to gRPC requests before they reach read functions
rg -n 'validate_range|check.*range|overflow' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 226


🏁 Script executed:

# Examine the specific paths: are read_bytes and read_batch without validate_range?
rg -B20 'storage.read::<Random>' src/tonic/api/storage_read_api/mod.rs | head -60

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check if read_bytes_stream always calls validate_range and if that's the only safe path
sed -n '175,215p' src/tonic/api/storage_read_api/mod.rs

Repository: qdrant/qdrant

Length of output: 1787


🏁 Script executed:

# Look more closely at validate_range implementation to confirm it uses checked_add properly
sed -n '198,220p' src/tonic/api/storage_read_api/helpers.rs

Repository: qdrant/qdrant

Length of output: 793


🏁 Script executed:

# Check if there are any other callers of the internal read() function that might bypass validation
rg -n 'fn read<' lib/common/common/src/universal_io/mmap.rs -A30 | grep -A30 'fn read<T>'

Repository: qdrant/qdrant

Length of output: 1018


🏁 Script executed:

# Check what the gRPC validate() function checks
rg -n 'fn validate' src/tonic/api/storage_read_api/ -A20

Repository: qdrant/qdrant

Length of output: 1635


🏁 Script executed:

# Check if there's any size_of multiplied by items that could overflow
rg -n 'size_of.*items|items.*size_of' lib/common/common/src/universal_io/mmap.rs

Repository: qdrant/qdrant

Length of output: 253


Add overflow protection for index computation in read().

The read() function at lines 265–296 performs unchecked arithmetic when computing requested_end (line 275: start + size_of::<T>() * items as usize) before any bounds check. The multiplication size_of::<T>() * items can overflow independently of the bounds comparison, causing requested_end to wrap to an incorrect value. This wrapped value may then appear to pass the bounds check and be used in slice indexing, potentially returning unintended data.

Additionally, read_bytes() and read_batch() invoke MmapFile::read() without calling validate_range(), leaving them completely unprotected. Only read_bytes_stream() validates ranges. Use checked_mul() and checked_add() to detect overflow and return an error instead of silently wrapping:

Suggested fix
-    let requested_end = start + size_of::<T>() * items as usize;
+    let item_bytes = size_of::<T>()
+        .checked_mul(items as usize)
+        .ok_or_else(|| UniversalIoError::OutOfBounds { /* ... */ })?;
+    let requested_end = start
+        .checked_add(item_bytes)
+        .ok_or_else(|| UniversalIoError::OutOfBounds { /* ... */ })?;
🤖 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 275 - 296, The
read() implementation in MmapFile currently computes requested_end via unchecked
arithmetic (start + size_of::<T>() * items) which can overflow; update
MmapFile::read() to use checked_mul(size_of::<T>(), items) and then
checked_add(start, product) (or the equivalent on usize) and return a suitable
UniversalIoError (e.g., OutOfBounds or a new Overflow variant) when any checked
operation returns None; also ensure callers read_bytes() and read_batch() either
call validate_range() or perform the same checked arithmetic before invoking
MmapFile::read() (similar to read_bytes_stream()), so all entry points validate
ranges and prevent silent wrapping when computing requested_end.

@generall

Copy link
Copy Markdown
Member

if the size of the file is not page-aligned, we will end up requesting a read that goes beyond EOF

I would expect O_DIRECT and page alignment to be an implementation detail, user should not know it is supposed to be requesting aligned memory, therefore we should never try to request EOF from MmapFile.
Where am I wrong?

Comment on lines +285 to +294
let range = if requested_end <= bytes.len() {
start..requested_end
} else {
// allow short reads, but align them to size of T
let avail_bytes = bytes.len() - start;
let truncated_items = avail_bytes / size_of::<T>() * size_of::<T>();
let end = start + truncated_items;

start..end
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think short reads should throw an error (by default), otherwise we'd have to add explicit checks at every callsite.

We have code that expects that requested_size_bytes == returned_size_bytes, e.g. here:

for result in S::read_multi_iter::<P, _>(reads)? {
let (offset, bytes) = result?;
if pages == 1 {
return Ok(bytes);
}
buffer[offset..offset + bytes.len()].write_copy_of_slice(&bytes);
}
Ok(Cow::Owned(unsafe { assume_init_vec(buffer) }))

Explicit parameter/separate method should be OK. Right now our io_uring impl allows short reads when OpenOptions::prevent_caching is enabled (tho perhaps we can make this flag more obvious).

@coszio

coszio commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

I would expect O_DIRECT and page alignment to be an implementation detail, user should not know it is supposed to be requesting aligned memory, therefore we should never try to request EOF from MmapFile.
Where am I wrong?

If we make it an implementation detail, it would mean io-uring would need 2 allocations. One to setup a buffer aligned with kernel page size, and another to return a buffer aligned for the requested type.

Overall I think it is possible but requires deeper refactoring on uring implementation.

@coszio

coszio commented Apr 28, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #8833

@coszio coszio closed this Apr 28, 2026
@qdrant qdrant deleted a comment from coderabbitai Bot Apr 29, 2026
@generall
generall deleted the short-mmap-reads branch May 30, 2026 21:23
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