Skip to content

universal io iterator - #8535

Merged
generall merged 13 commits into
devfrom
universal-io-iterator
Mar 31, 2026
Merged

generall merged 13 commits into
devfrom
universal-io-iterator

Conversation

@generall

@generall generall commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

During migration of mmap-hashmap into universal IO I have re-evaluated my decision about using iterators.

The problem is, that sometimes we need to read from multiple places within the same function, and one read depends on another.

For example, we might need to 1. read offsets 2. read data by offsets.

If we do it in 2 steps batch facion - we loose performace:

offsets file: *******           |                | *******
cpu         :        *****      | (1 batch done) |        *****
data    file:             ***** |                |             *****

What we want instead: continously read and process data like a conveyor belt.

Iterators seems to be just right interface for it. With iterators we can trivially implement callbacks, but we can't implement iterators with callbacks.

Iterators are unordered by design.

Iterators implementation should be backend-specific to extract max performance, but mmap implementation can be as trivial as for loop.

Best to review commit-by-commit.


Also condidered:

Making io_uring-style summit/read interface public. In this case we can continously push more requets depending on what we have read. But this interface might be the next step.

@generall
generall requested review from ffuugoo and xzfc and removed request for xzfc March 29, 2026 11:40
@generall
generall marked this pull request as ready for review March 29, 2026 11:40
coderabbitai[bot]

This comment was marked as resolved.

O_DIRECT bypasses the page cache, so reading the whole file to warm
it is pointless — return early as a no-op.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
coderabbitai[bot]

This comment was marked as resolved.

@ffuugoo ffuugoo 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.

Skimmed the PR, seems OK. My only significant comment so far would be to maybe try to "merge" ReadIter and ReadMultiIter? They do 90% the same thing, the only difference is callback have extra parameter.

I'd say we either make ReadIter a wrapper on top of ReadMultiIter (simply provide &[one_and_only_file] to ReadMultiIter) or abstract single/multi file logic into a trait and make ReadIter<SingleOrMulti> that can be parameterized with this logic.

@xzfc

xzfc commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

Benchmarked dev vs this PR vs #8507, and this change made the performance significantly worse.

Benchmark: iterate over all u64/[u64; 128] values in 512MiB file.


I think the main issue is that step/next doing a lot of things on each iteration:

  • submit_and_wait (a syscall)
  • let cqes: Vec<_> = ….collect(); (an allocation)
  • self.buffer.push_back (another allocation. Tho, it's amortized as the buffer would be reused between iterations. But still, it'll be an issue for tiny batches)

This PR approach is "next() kick-offs the background queue". Which is inverted compared to our current callback-based read_batch approach.

For comparison, previously, I've tried to implement a different approach: "override FallibleIterator::try_fold(), so it will be conceptually similar to read_batch". Tho, it's incomplete/untested. code (I'm not sure if it's a right/latest version of this commit as I salvaged it from my junk pile of abandoned commits)

Unless the performance fix for this PR is trivial, I want to discuss both of these approaches.

@generall

Copy link
Copy Markdown
Member Author

Benchmark: iterate over all u64/[u64; 128] values in 512MiB file.

I did have a little different use-case in mind. This is kind of a worst case: no read IO, everything is pretty much cached.

Running step every 2 / 4 / 8 iterations proportionally improves benchmarks up to performance of the original implementation. Also, I am pretty sure there will be a benchmark, which would show degradation in the opposite direction.

Made-with: Cursor

# Conflicts:
#	lib/common/common/src/universal_io/io_uring.rs

@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

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

174-177: Consider using checked multiplication to prevent potential overflow.

length * size_of::<T>() as u64 could overflow before reaching the try_from check. While unlikely given typical file sizes, defensive code would use checked_mul:

-        let byte_length = length * size_of::<T>() as u64;
-        let byte_length = u32::try_from(byte_length).expect("read buffer length fit within u32");
+        let byte_length = length
+            .checked_mul(size_of::<T>() as u64)
+            .and_then(|n| u32::try_from(n).ok())
+            .expect("read buffer length fit within u32");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/runtime.rs` around lines 174 -
177, Compute the buffer byte length using a checked multiplication instead of
direct `length * size_of::<T>() as u64` to avoid overflow: replace that
expression with a `checked_mul` call (e.g., `length.checked_mul(size_of::<T>()
as u64)`) and handle the `None` case with the same failure path you use for
`u32::try_from` (e.g., an `expect` or early error) before calling
`u32::try_from`; keep the existing `bytes_ptr` (from
`items.as_mut_ptr().cast()`) and `byte_length` variable names so the change is
localized to the computation and validation of the byte length.
🤖 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/io_uring/runtime.rs`:
- Around line 221-225: In finalize (fn finalize) the io::Error message uses a
literal "request {id} does not exist" so the RequestId value isn't interpolated;
change the error construction to include the id (e.g., use format!("request {}
does not exist", id) or format!("request {id} does not exist") depending on
trait bounds) when calling io::Error::other so the actual RequestId is shown;
ensure RequestId implements Display or Debug (use {:?} if only Debug) and update
the io::Error::other invocation accordingly.

---

Nitpick comments:
In `@lib/common/common/src/universal_io/io_uring/runtime.rs`:
- Around line 174-177: Compute the buffer byte length using a checked
multiplication instead of direct `length * size_of::<T>() as u64` to avoid
overflow: replace that expression with a `checked_mul` call (e.g.,
`length.checked_mul(size_of::<T>() as u64)`) and handle the `None` case with the
same failure path you use for `u32::try_from` (e.g., an `expect` or early error)
before calling `u32::try_from`; keep the existing `bytes_ptr` (from
`items.as_mut_ptr().cast()`) and `byte_length` variable names so the change is
localized to the computation and validation of the byte length.
🪄 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: da28c342-94f9-4b62-aaad-2e608e50ec84

📥 Commits

Reviewing files that changed from the base of the PR and between 9f2d5b1 and ebef853.

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

Comment on lines +221 to +225
pub fn finalize(&mut self, id: RequestId, byte_length: u32) -> io::Result<IoUringResponse<T>> {
let req = self
.requests
.remove(&id)
.ok_or_else(|| io::Error::other("request {id} does not exist"))?;

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

Bug: Error message doesn't interpolate the request ID.

Line 225 uses a string literal instead of a format string, so {id} is printed literally rather than being replaced with the actual ID value.

         let req = self
             .requests
             .remove(&id)
-            .ok_or_else(|| io::Error::other("request {id} does not exist"))?;
+            .ok_or_else(|| io::Error::other(format!("request {id} does not exist")))?;
📝 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
pub fn finalize(&mut self, id: RequestId, byte_length: u32) -> io::Result<IoUringResponse<T>> {
let req = self
.requests
.remove(&id)
.ok_or_else(|| io::Error::other("request {id} does not exist"))?;
pub fn finalize(&mut self, id: RequestId, byte_length: u32) -> io::Result<IoUringResponse<T>> {
let req = self
.requests
.remove(&id)
.ok_or_else(|| io::Error::other(format!("request {id} does not exist")))?;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/runtime.rs` around lines 221 -
225, In finalize (fn finalize) the io::Error message uses a literal "request
{id} does not exist" so the RequestId value isn't interpolated; change the error
construction to include the id (e.g., use format!("request {} does not exist",
id) or format!("request {id} does not exist") depending on trait bounds) when
calling io::Error::other so the actual RequestId is shown; ensure RequestId
implements Display or Debug (use {:?} if only Debug) and update the
io::Error::other invocation accordingly.

On older kernels, submit_and_wait may return before completions are
available. Apply the same retry loop to the iterator step() methods
to prevent premature iterator termination.

Made-with: Cursor

@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 (4)
lib/common/common/src/universal_io/io_uring/read_multi_iter.rs (4)

85-89: Expect message could be clearer.

The message "SQE is not full" describes the expected state but reads awkwardly. Consider rephrasing:

-                unsafe { sqe.push(&entry).expect("SQE is not full") };
+                unsafe { sqe.push(&entry).expect("SQE overflow check failed") };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/read_multi_iter.rs` around lines
85 - 89, The expect message on the sqe.push call is awkward; change the panic
string used on sqe.push(&entry).expect(...) to a clearer, actionable message
such as indicating that pushing the Submission Queue Entry failed because the
submission queue is full (e.g. "failed to push SQE: submission queue is full" or
similar). Locate the sqe.push(&entry).expect("SQE is not full") call in
read_multi_iter.rs (the block that creates entry via self.state.read and then
calls sqe.push) and replace the literal with a clearer failure message
referencing the push and full queue.

125-130: Use explicit UniversalIoError::from() instead of .into().

As per coding guidelines: "Prefer explicit SomeType::from(x) over implicit x.into() in Rust".

Proposed fix
-                return Err(io_error_context(
+                return Err(UniversalIoError::from(io_error_context(
                     io::Error::from_raw_os_error(-result),
                     format!("io_uring operation {id} failed"),
-                )
-                .into());
+                )));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/read_multi_iter.rs` around lines
125 - 130, The returned error currently uses implicit conversion with .into();
replace that with the explicit UniversalIoError::from(...) call: wrap the
io_error_context(...) result in UniversalIoError::from(...) instead of calling
.into() so the return becomes
Err(UniversalIoError::from(io_error_context(io::Error::from_raw_os_error(-result),
format!("io_uring operation {id} failed")))); locate this change around the
io_error_context usage in read_multi_iter.rs.

137-140: Consider explicit type annotation for result as _.

Using as _ relies on type inference which can obscure intent. An explicit cast (e.g., result as usize) would be clearer, especially since result is an i32 from the kernel and the target type matters for correctness.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/read_multi_iter.rs` around lines
137 - 140, The cast `result as _` is ambiguous; replace it with an explicit
target type to convey intent and ensure correctness—e.g., change the `length`
binding in the block around `let length = result as _;` to a clearly typed cast
such as `let length = result as usize;` (or another intended type) before
calling `self.state.finalize(id, length)?`, keeping the surrounding logic that
uses `id`, `file_idx`, `resp.expect_read()`, and `self.buffer.push_back((id as
usize, file_idx, items));` intact.

114-117: CQE collection allocates on every step() call.

This allocation per iteration contributes to the performance regression noted in the PR benchmarks. Consider reusing a pre-allocated buffer as a struct field to avoid repeated allocations in the hot path.

 pub(super) struct IoUringReadMultiIter<
     'a,
     T: bytemuck::Pod + 'static,
     I: Iterator<Item = (FileIndex, ReadRange)>,
 > {
     files: &'a [IoUringFile],
     guard: IoUringGuard,
     reads: std::iter::Enumerate<I>,
     buffer: VecDeque<(usize, FileIndex, Vec<T>)>,
     file_indices: AHashMap<RequestId, FileIndex>,
     state: IoUringState<'static, T>,
     in_progress: usize,
+    cqe_buffer: Vec<(u64, i32)>,
     _not_send: PhantomData<*const ()>,
 }

Then reuse it:

-        let cqes: Vec<_> = io_uring
-            .completion()
-            .map(|cqe: ::io_uring::cqueue::Entry| (cqe.user_data(), cqe.result()))
-            .collect();
-
-        for (id, result) in cqes {
+        self.cqe_buffer.clear();
+        self.cqe_buffer.extend(
+            io_uring
+                .completion()
+                .map(|cqe: ::io_uring::cqueue::Entry| (cqe.user_data(), cqe.result())),
+        );
+
+        for &(id, result) in &self.cqe_buffer {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/read_multi_iter.rs` around lines
114 - 117, The hot path allocates a new Vec for `cqes` on every `step()` call;
instead add a pre-allocated buffer field to the iterator struct (e.g., `cqes:
Vec<(u64, i32)>` with an appropriate initial capacity), initialize it once in
the struct constructor, and in `step()` replace the `.collect()` call with
reusing that buffer by calling `self.cqes.clear()` and then iterating over
`io_uring.completion()` and `push((cqe.user_data(), cqe.result()))` into
`self.cqes`; keep the element types matching `user_data()` and `result()` and
update any local uses to refer to `&self.cqes` (or drain/iterate as needed) so
no per-iteration allocation occurs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/common/common/src/universal_io/io_uring/read_multi_iter.rs`:
- Around line 85-89: The expect message on the sqe.push call is awkward; change
the panic string used on sqe.push(&entry).expect(...) to a clearer, actionable
message such as indicating that pushing the Submission Queue Entry failed
because the submission queue is full (e.g. "failed to push SQE: submission queue
is full" or similar). Locate the sqe.push(&entry).expect("SQE is not full") call
in read_multi_iter.rs (the block that creates entry via self.state.read and then
calls sqe.push) and replace the literal with a clearer failure message
referencing the push and full queue.
- Around line 125-130: The returned error currently uses implicit conversion
with .into(); replace that with the explicit UniversalIoError::from(...) call:
wrap the io_error_context(...) result in UniversalIoError::from(...) instead of
calling .into() so the return becomes
Err(UniversalIoError::from(io_error_context(io::Error::from_raw_os_error(-result),
format!("io_uring operation {id} failed")))); locate this change around the
io_error_context usage in read_multi_iter.rs.
- Around line 137-140: The cast `result as _` is ambiguous; replace it with an
explicit target type to convey intent and ensure correctness—e.g., change the
`length` binding in the block around `let length = result as _;` to a clearly
typed cast such as `let length = result as usize;` (or another intended type)
before calling `self.state.finalize(id, length)?`, keeping the surrounding logic
that uses `id`, `file_idx`, `resp.expect_read()`, and `self.buffer.push_back((id
as usize, file_idx, items));` intact.
- Around line 114-117: The hot path allocates a new Vec for `cqes` on every
`step()` call; instead add a pre-allocated buffer field to the iterator struct
(e.g., `cqes: Vec<(u64, i32)>` with an appropriate initial capacity), initialize
it once in the struct constructor, and in `step()` replace the `.collect()` call
with reusing that buffer by calling `self.cqes.clear()` and then iterating over
`io_uring.completion()` and `push((cqe.user_data(), cqe.result()))` into
`self.cqes`; keep the element types matching `user_data()` and `result()` and
update any local uses to refer to `&self.cqes` (or drain/iterate as needed) so
no per-iteration allocation occurs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5b3ef8ed-35ac-4a2b-bee7-a2b3642c5c74

📥 Commits

Reviewing files that changed from the base of the PR and between ebef853 and e915705.

📒 Files selected for processing (2)
  • lib/common/common/src/universal_io/io_uring/read_iter.rs
  • lib/common/common/src/universal_io/io_uring/read_multi_iter.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/common/common/src/universal_io/io_uring/read_iter.rs

@xzfc

xzfc commented Mar 31, 2026

Copy link
Copy Markdown
Member

This is kind of a worst case: no read IO, everything is pretty much cached.

It's still worse with constrained memory:

echo 3 | sudo tee /proc/sys/vm/drop_caches && systemd-run --user --scope -p MemoryMax=128M -- target/release/deps/io_uring_iter-99ba37d2ec386807 --bench --measurement-time 10

dev: 177ms
this PR: 2.4s


Also, I am pretty sure there will be a benchmark, which would show degradation in the opposite direction.

I disagree: see "doing a lot of things on each iteration" above. In dev, read_batch performs neither of these, so I expect it to be strictly not worse.

@qdrant qdrant deleted a comment from coderabbitai Bot Mar 31, 2026
@generall
generall requested a review from ffuugoo March 31, 2026 12:04
@coderabbitai

This comment was marked as resolved.

@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/io_uring/read_iter.rs (1)

296-322: Drop impl may hang on older kernels due to missing completion-ready check.

In step(), you handle the case where submit_and_wait returns before completions are ready (lines 240-244) with a retry loop. However, the Drop impl at lines 304-307 calls submit_and_wait(self.in_progress) without a similar check, then immediately collects completions.

On older kernels where submit_and_wait may return early, this could collect an empty Vec, leaving in_progress > 0, and re-enter the loop with the same state — potentially causing a spin or very slow cleanup.

♻️ Consider aligning drop behavior with step()
     fn drop(&mut self) {
         if self.in_progress == 0 {
             return;
         }
         let io_uring = self.guard.io_uring();
         while self.in_progress > 0 {
-            if io_uring.submit_and_wait(self.in_progress).is_err() {
-                break;
+            // Loop because `submit_and_wait` may return before completions
+            // are available on older kernels.
+            loop {
+                if io_uring.submit_and_wait(1).is_err() {
+                    return; // Best-effort cleanup; resources will be freed anyway
+                }
+                if !io_uring.completion().is_empty() {
+                    break;
+                }
             }
             let cqes: Vec<_> = io_uring
                 .completion()
                 .map(|cqe: ::io_uring::cqueue::Entry| (cqe.user_data(), cqe.result()))
                 .collect();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/io_uring/read_iter.rs` around lines 296 -
322, The Drop implementation for IoUringReadIterInner can spin on older kernels
because it calls io_uring.submit_and_wait(self.in_progress) and then immediately
reads completions without handling the case where submit_and_wait returned early
and no completions are ready; modify drop() to mirror the logic in step(): after
submit_and_wait succeeds, check whether the completion() iterator produced any
entries and, if it produced none, retry submit_and_wait (or continue the loop)
instead of proceeding to decrement in_progress; ensure you still handle
submit_and_wait errors by breaking, and keep using resolver.untrack_abort,
state.abort and state.finalize when real completions are observed so the cleanup
semantics match step().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/common/common/src/universal_io/io_uring/read_iter.rs`:
- Around line 296-322: The Drop implementation for IoUringReadIterInner can spin
on older kernels because it calls io_uring.submit_and_wait(self.in_progress) and
then immediately reads completions without handling the case where
submit_and_wait returned early and no completions are ready; modify drop() to
mirror the logic in step(): after submit_and_wait succeeds, check whether the
completion() iterator produced any entries and, if it produced none, retry
submit_and_wait (or continue the loop) instead of proceeding to decrement
in_progress; ensure you still handle submit_and_wait errors by breaking, and
keep using resolver.untrack_abort, state.abort and state.finalize when real
completions are observed so the cleanup semantics match step().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8e20d7f1-2862-4766-9964-87686c888e32

📥 Commits

Reviewing files that changed from the base of the PR and between ebef853 and 36351cc.

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

@ffuugoo ffuugoo 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.

It's OK-ish to merge, but I'll optimize this in a follow-up PR... 😅

@generall
generall merged commit f473e83 into dev Mar 31, 2026
15 checks passed
@generall
generall deleted the universal-io-iterator branch March 31, 2026 13:54
@xzfc xzfc mentioned this pull request Apr 1, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* [AI] Implement low-level iterator for universal-io implementation of io_uring

* [AI] io_uring pool

* fmt

* [AI] refactor io_uring into multiple files

* [AI] implement IoUringReadMultiIter

* [AI] replace file_indices Vec -> AHashMap to prevent memory growth

* fmt

* Guard populate() when file uses O_DIRECT

O_DIRECT bypasses the page cache, so reading the whole file to warm
it is pointless — return early as a no-op.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* Update comment about O_DIRECT in concurrent read iter test

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: apply submit_and_wait retry loop to read iterators

On older kernels, submit_and_wait may return before completions are
available. Apply the same retry loop to the iterator step() methods
to prevent premature iterator termination.

Made-with: Cursor

* do not step every time

* [AI] unify iterators

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Cursor Agent <[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.

4 participants