Skip to content

IoUringState: replace HashMap with flat slice - #8599

Merged
xzfc merged 1 commit into
devfrom
uio-uring-flat-state
Apr 7, 2026
Merged

xzfc merged 1 commit into
devfrom
uio-uring-flat-state

Conversation

@xzfc

@xzfc xzfc commented Apr 3, 2026 •

Copy link
Copy Markdown
Member

Replace HashMap with flat slice

 pub struct IoUringState<T> {
-    requests: ahash::HashMap<
-        RequestId,
-        IoUringRequest<T>,
-    >,
+    requests: Vec<Option<
+       (RequestId, IoUringRequest<T>)
+   >>,
 }

(in this PR it's more sophisticated than Vec<Option<…>>, but the idea is the same)

Currently, we use HashMap to store requests. Performance-wise that means we need to hash RequestId on each io_uring request/response, and also probably do allocations.
But since io_uring has fixed size queue, we can improve the performance by storing requests in a flat fixed-size array instead of HashMap:

io_uring/8bytes/read_batch_small_sequential
                        time:   [1.2550 µs 1.2566 µs 1.2583 µs]
                        change: [−7.8385% −7.6725% −7.5137%] (p = 0.00 < 0.05)
                        Performance has improved.
io_uring/1KiB/read_batch_small_sequential
                        time:   [1.8207 µs 1.8251 µs 1.8293 µs]
                        change: [−6.0646% −5.7986% −5.5121%] (p = 0.00 < 0.05)
                        Performance has improved.

Make RequestId to be a generic parameter

(this change removed from this PR; it will go into #8601)

Details
-pub struct IoUringState<T> {
+pub struct IoUringState<T, RequestId> {

Previously, we were passing RequestId into io_uring's user_data. In this PR we pass slot number (aka index within IoUringState::request).
Thus, now we don't need to check RequestId for uniqueness. (collisions won't break the logic)
Thus, now we can make RequestId to be generic parameter and let callers decide which RequestId to use:

  • If order is important, RequestId = usize.
  • If order is not important, RequestId = ().
  • Later, callers can use domain-specific RequestId, e.g.:
    // not in this PR
    enum UniversalHashmapRequestId {
        BucketOffset(usize),
        EntryHeader(usize),
        Value(usize),
    }

@xzfc
xzfc requested review from Copilot, ffuugoo and generall and removed request for Copilot April 3, 2026 06:15
@generall

generall commented Apr 3, 2026

Copy link
Copy Markdown
Member

There are a lot of unsafe and panics, so why not Vec<Option<…>>?

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

Neat idea, though I'm not a huge fan of this overall, because of added complexity. I'd prefer to keep io_uring code "as simple as reasonably possible". 😬

I see that generic RequestId might be useful in the future, but not yet convinced it will be.

For the fixed-sized State, I dunno. I'd say if we can "freeze" the capacity of HashMap (so there's no realloc), it's fine to just use a HashMap.

pub struct IoUringState<'data, T> {
requests: ahash::HashMap<RequestId, IoUringRequest<'data, T>>,
pub struct IoUringState<'data, T, RequestId> {
requests: UninitSlice<(RequestId, IoUringRequest<'data, T>)>,

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.

I'd just use Vec. I don't see what we gain by using boxed slice. inb4: saving usize worth of stack space, but come on...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's more about communication/intent, rather than about performance.

Box<[T]> means "not supposed to be resized", and Vec<T> means "maybe we will resize it, maybe not".


Tho, I plan to move this code away. I need experimenting, but it'll be either of these:

  • I'll use slab, stable-vec, slotmap, or whatever, as this idea is not new.
  • Or move this data structure into separate module like common::slotmap to keep these unsafes away from IoUringState.
  • Or just use Vec<Option<…>>.

@xzfc

xzfc commented Apr 3, 2026

Copy link
Copy Markdown
Member Author

Neat idea, though I'm not a huge fan of this overall, because of added complexity. I'd prefer to keep io_uring code "as simple as reasonably possible". 😬

See next PR #8601. Generic RequestId removed far more complexity than added. Particularly because now we don't use RequestId as hashmap key and don't care about collisions.

@xzfc
xzfc force-pushed the uio-uring-flat-state branch 2 times, most recently from b52ae31 to d3c2d82 Compare April 7, 2026 08:52
@xzfc
xzfc force-pushed the uio-uring-flat-state branch from d3c2d82 to 522b6a2 Compare April 7, 2026 08:57
@qdrant qdrant deleted a comment from coderabbitai Bot Apr 7, 2026
@coderabbitai

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@xzfc

xzfc commented Apr 7, 2026

Copy link
Copy Markdown
Member Author

Update: replaced my unsafe thingy with slab::Slab.
This is not a new dependency as we already (indirectly) depend on it.
It's used in the tokio uring driver for the exactly the same purpose: https://github.com/tokio-rs/tokio/blob/tokio-1.51.0/tokio/src/runtime/io/driver/uring.rs#L17

@xzfc
xzfc requested review from ffuugoo and generall April 7, 2026 09:11

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

♻️ Duplicate comments (2)
lib/common/common/src/universal_io/io_uring/runtime.rs (2)

19-23: ⚠️ Potential issue | 🟠 Major

Use the kernel-reported SQ size in enqueue_while, too.

new() now pulls the actual submission capacity, but enqueue_while still caps against IO_URING_QUEUE_LENGTH and then expects push() to succeed. If the SQ is smaller than that constant, this still panics.

Suggested shape
-        if self.in_progress + squeue.len() >= IO_URING_QUEUE_LENGTH as _ {
+        squeue.sync();
+        if self.in_progress + squeue.len() >= squeue.capacity() {
             return Ok(());
         }

         while let Some(entry) = entries(&mut self.state)? {
-            unsafe { squeue.push(&entry).expect("submission queue is not full") };
+            if squeue.is_full() {
+                break;
+            }
+            unsafe { squeue.push(&entry).expect("checked with squeue.is_full") };

-            if self.in_progress + squeue.len() >= IO_URING_QUEUE_LENGTH as _ {
+            if self.in_progress + squeue.len() >= squeue.capacity() {
                 break;
             }
         }
For the Rust `io-uring` crate, does `SubmissionQueue::capacity()` reflect the kernel-reported SQ size, and should `push()` be guarded with `sq.is_full()` / `sq.capacity()` (with `sq.sync()` if needed) instead of a separate configured constant?

Also applies to: 38-46

🤖 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 19 - 23,
The code currently caps enqueue_while against the static IO_URING_QUEUE_LENGTH
and calls push().expect(...), which can panic if the kernel SQ is smaller;
change enqueue_while to use the runtime submission capacity from
io_uring.submission().capacity() (the same value passed into
IoUringState::with_capacity via get_io_uring()), and replace unconditional
push().expect with a guarded loop that checks sq.is_full() or compares against
sq.capacity() (and calls sq.sync()/sleep/wake as appropriate) before attempting
push, handling the full case without panicking; apply the same fix to the other
occurrence around the 38-46 block so all enqueues respect
SubmissionQueue::capacity() rather than IO_URING_QUEUE_LENGTH.

104-113: ⚠️ Potential issue | 🟠 Major

Make the abort path return the logical RequestId.

abort(slot) currently drops the entry and swallows missing slots, so failed CQEs only report an internal slot number and state mismatches slip by silently. Returning io::Result<RequestId> here keeps the error actionable and preserves the same invariant check finalize already has.

Suggested shape
-    pub fn abort(&mut self, slot: usize) {
-        self.requests.try_remove(slot);
+    pub fn abort(&mut self, slot: usize) -> io::Result<RequestId> {
+        let (id, _) = self
+            .requests
+            .try_remove(slot)
+            .ok_or_else(|| io::Error::other(format!("request in slot {slot} does not exist")))?;
+        Ok(id)
     }
-                self.state.abort(slot);
+                let id = self.state.abort(slot)?;

                 return Err(io_error_context(
                     io::Error::from_raw_os_error(-result),
-                    format!("io_uring operation in slot {slot} failed"),
+                    format!("io_uring request {id} failed"),
                 ));

Also applies to: 266-267

🤖 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/io_uring/runtime.rs`:
- Around line 19-23: The code currently caps enqueue_while against the static
IO_URING_QUEUE_LENGTH and calls push().expect(...), which can panic if the
kernel SQ is smaller; change enqueue_while to use the runtime submission
capacity from io_uring.submission().capacity() (the same value passed into
IoUringState::with_capacity via get_io_uring()), and replace unconditional
push().expect with a guarded loop that checks sq.is_full() or compares against
sq.capacity() (and calls sq.sync()/sleep/wake as appropriate) before attempting
push, handling the full case without panicking; apply the same fix to the other
occurrence around the 38-46 block so all enqueues respect
SubmissionQueue::capacity() rather than IO_URING_QUEUE_LENGTH.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5c6d2c9e-9be1-481f-b17f-fa512b2d3d6e

📥 Commits

Reviewing files that changed from the base of the PR and between b52ae31 and 522b6a2.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • lib/common/common/Cargo.toml
  • lib/common/common/src/universal_io/io_uring/mod.rs
  • lib/common/common/src/universal_io/io_uring/read_iter.rs
  • lib/common/common/src/universal_io/io_uring/runtime.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/common/common/Cargo.toml

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

Very nice, thanks!

@xzfc
xzfc merged commit 8e07ccb into dev Apr 7, 2026
15 checks passed
@xzfc
xzfc deleted the uio-uring-flat-state branch April 7, 2026 12:31
@coderabbitai coderabbitai Bot mentioned this pull request Jun 18, 2026
9 tasks done
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