Repository navigation
universal io iterator - #8535
Conversation
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]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ffuugoo
left a comment
There was a problem hiding this comment.
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.
|
Benchmarked Benchmark: iterate over all
I think the main issue is that
This PR approach is " For comparison, previously, I've tried to implement a different approach: "override Unless the performance fix for this PR is trivial, I want to discuss both of these approaches. |
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
There was a problem hiding this comment.
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 u64could overflow before reaching thetry_fromcheck. While unlikely given typical file sizes, defensive code would usechecked_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
📒 Files selected for processing (2)
lib/common/common/src/universal_io/io_uring/mod.rslib/common/common/src/universal_io/io_uring/runtime.rs
| 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"))?; |
There was a problem hiding this comment.
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.
| 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
There was a problem hiding this comment.
🧹 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 explicitUniversalIoError::from()instead of.into().As per coding guidelines: "Prefer explicit
SomeType::from(x)over implicitx.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 forresult as _.Using
as _relies on type inference which can obscure intent. An explicit cast (e.g.,result as usize) would be clearer, especially sinceresultis ani32from 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 everystep()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
📒 Files selected for processing (2)
lib/common/common/src/universal_io/io_uring/read_iter.rslib/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
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 10dev: 177ms
I disagree: see "doing a lot of things on each iteration" above. In |
This comment was marked as resolved.
This comment was marked as resolved.
There was a problem hiding this comment.
🧹 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 wheresubmit_and_waitreturns before completions are ready (lines 240-244) with a retry loop. However, theDropimpl at lines 304-307 callssubmit_and_wait(self.in_progress)without a similar check, then immediately collects completions.On older kernels where
submit_and_waitmay return early, this could collect an empty Vec, leavingin_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
📒 Files selected for processing (2)
lib/common/common/src/universal_io/io_uring/mod.rslib/common/common/src/universal_io/io_uring/read_iter.rs
ffuugoo
left a comment
There was a problem hiding this comment.
It's OK-ish to merge, but I'll optimize this in a follow-up PR... 😅
* [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]>
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:
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.