Skip to content

refactor mmap hashmap - #8405

Merged
xzfc merged 3 commits into
devfrom
refactor-mmap-hashmap
May 12, 2026
Merged

xzfc merged 3 commits into
devfrom
refactor-mmap-hashmap

Conversation

@generall

Copy link
Copy Markdown
Member
  • [manual] split mmap_hashmap into multilpe files
  • [AI] first iteration
  • [AI] impleent custor for each key

@generall
generall force-pushed the refactor-mmap-hashmap branch 2 times, most recently from 2f17e2a to ca0b66f Compare March 27, 2026 11:14
@xzfc xzfc self-assigned this Apr 8, 2026
@coszio coszio mentioned this pull request Apr 8, 2026
34 of 36 tasks
@xzfc
xzfc force-pushed the refactor-mmap-hashmap branch from e67945e to ecf41e4 Compare May 6, 2026 14:00
@coszio coszio added this to the Universal IO milestone May 6, 2026
@xzfc
xzfc force-pushed the refactor-mmap-hashmap branch from ecf41e4 to 62d1a52 Compare May 6, 2026 20:44
@xzfc
xzfc force-pushed the refactor-mmap-hashmap branch 3 times, most recently from 5cbe5bf to f28313b Compare May 8, 2026 02:37
@xzfc xzfc mentioned this pull request May 8, 2026
@xzfc
xzfc marked this pull request as ready for review May 8, 2026 02:39

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/common/common/src/persisted_hashmap/mmap.rs (1)

113-123: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

iter() silently swallows decode errors that keys() logs.

keys() distinguishes ReadResult::Invalid(error) (debug_assert + log::error!) from ReadResult::Incomplete (silent skip), but iter() collapses both into a silent return None; via the let-else. Corrupt entries will go entirely unnoticed here. Consider matching the error-reporting behavior of keys() so the two iterators stay in sync, and so corruption is surfaced consistently.

🐛 Proposed alignment with `keys()`
     pub fn iter(&self) -> impl Iterator<Item = (&K, &[V])> {
         (0..self.keys_count()).filter_map(|i| {
-            // NOTE: errors are discarded
-            let entry = self.get_entry(i).ok()?;
-            let ReadResult::Ok(key) = K::from_bytes(entry) else {
-                return None;
+            let entry = match self.get_entry(i) {
+                Ok(entry) => entry,
+                Err(err) => {
+                    debug_assert!(false, "Error reading entry for key {i}: {err}");
+                    log::error!("Error reading entry for key {i}: {err}");
+                    return None;
+                }
+            };
+            let key = match K::from_bytes(entry) {
+                ReadResult::Ok(key) => key,
+                ReadResult::Incomplete => return None,
+                ReadResult::Invalid(error) => {
+                    debug_assert!(false, "Error reading key for entry {i}: {error}");
+                    log::error!("Error reading key for entry {i}: {error}");
+                    return None;
+                }
             };
             let values = Self::get_values_from_entry(entry, key).ok()?;
             Some((key, values))
         })
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/mmap.rs` around lines 113 - 123, The
iter() implementation currently swallows all decode errors via the let-else,
unlike keys() which logs ReadResult::Invalid(error) and only silently skips
ReadResult::Incomplete; update iter() (the iter method that calls self.get_entry
and K::from_bytes) to match keys(): call K::from_bytes(entry) and match on the
ReadResult variants, log the error for ReadResult::Invalid using the same
logging pattern used in keys(), silently skip on ReadResult::Incomplete, and
only continue to get values (Self::get_values_from_entry) when
ReadResult::Ok(key) is returned so corrupt entries are surfaced consistently.
🧹 Nitpick comments (5)
lib/common/common/src/persisted_hashmap/uio/sparse_reader.rs (1)

232-248: 💤 Low value

Minor: bytes already read are kept on retry but byte_offset is not advanced.

When the parse doesn't satisfy entry_kind, the entry is re-queued with the same byte_offset but a larger expected_len. In schedule_next_entry (lines 135-139) the next read range is computed as byte_offset + buf.len() for expected_len - buf.len() bytes, which is correct as long as buf.len() faithfully tracks the absolute offset within the entry.

If data passed to process ever contains less than the requested chunk (e.g. a clamped range), buf.len() after extend_from_slice will be smaller than expected, and the next range calculation will still be correct — but consider asserting buf.len() <= expected_len_prev and adding a comment so the invariant is documented for future maintainers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/sparse_reader.rs` around lines
232 - 248, When re-queueing an entry in State::ReadingEntry (the block building
Entry with byte_offset, expected_len, buf, requested_key) ensure the invariant
that buf.len() never exceeds the previous expected_len is explicit: add an
assert (or debug_assert) that buf.len() <= expected_len_prev (or the previous
expected_len) and a short comment explaining that schedule_next_entry relies on
buf.len() being the absolute bytes already read so the next read is scheduled
from byte_offset + buf.len() for expected_len - buf.len() bytes; reference
parsed.satisfies_kind, schedule_next_entry, Entry, State::ReadingEntry,
expected_len, buf.len(), and byte_offset when adding the check/comment.
lib/common/common/src/universal_io/mod.rs (1)

109-114: 💤 Low value

Optional: avoid silently shifting byte_offset on overflow.

If self.byte_offset > max_end_offset, line 110 clamps the start of the read to max_end_offset rather than just zeroing the length. The downstream saturating_sub already produces max_len == 0 for this case without needing to mutate byte_offset, and leaving the start untouched makes accidental misuse (e.g. callers that don't check length == 0) less surprising. Not a correctness issue with the current callers (which always pass T = u8 and check length == 0), so feel free to ignore.

♻️ Proposed simplification
     pub fn clamp<T>(mut self, max_end_offset: u64) -> ReadRange {
-        self.byte_offset = self.byte_offset.min(max_end_offset);
         let max_len = max_end_offset.saturating_sub(self.byte_offset) / size_of::<T>() as u64;
         self.length = self.length.min(max_len);
         self
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/universal_io/mod.rs` around lines 109 - 114, The clamp
method on ReadRange currently mutates self.byte_offset when byte_offset >
max_end_offset; instead compute max_len using
max_end_offset.saturating_sub(self.byte_offset) / size_of::<T>() as u64 and only
update self.length = self.length.min(max_len) without changing self.byte_offset
so callers that rely on the original start aren’t surprised; update the clamp
function (referencing clamp, ReadRange, byte_offset, length, max_end_offset,
size_of::<T>()) to remove the byte_offset assignment and only adjust length
based on the computed max_len.
lib/common/common/src/persisted_hashmap/uio/mod.rs (2)

246-251: 💤 Low value

Optional: simplify parse_bucket_offset for an infallible call site.

The only caller (for_each_key, line 179) feeds it chunks_exact(size_of::<BucketOffset>()), so try_from can never fail, and the unwrap() reflects that. You could either inline the conversion at the call site (BucketOffset::from_ne_bytes(c.try_into().unwrap())) or change the helper to take [u8; size_of::<BucketOffset>()] directly and return BucketOffset (no Result). Purely a clarity nit.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/mod.rs` around lines 246 - 251,
The helper parse_bucket_offset currently returns Result<BucketOffset> using
try_from on a slice even though its sole caller for_each_key uses
chunks_exact(size_of::<BucketOffset>()) so the conversion is infallible;
simplify by changing parse_bucket_offset to accept a [u8;
size_of::<BucketOffset>()] (or a generic array parameter) and return
BucketOffset directly via BucketOffset::from_ne_bytes, or alternatively remove
parse_bucket_offset and inline the conversion at the call site as
BucketOffset::from_ne_bytes(c.try_into().unwrap()); update the signature/usages
accordingly to eliminate the unused Result and error path.

150-156: 💤 Low value

Nit: iter.next() inside debug_assert! is a side-effect that only runs in debug builds.

debug_assert! evaluates its condition (and consumes one chunk from iter) only in debug builds. Functionally this is fine because the function returns immediately afterwards, but folding a state-mutating call into an assertion is easy to misread. Consider extracting it to a separate debug_assert!(matches!(iter.next(), None)) after a comment, or dropping the iter check entirely (the entries_seen == entries_expected invariant + buf.is_empty() is already a strong post-condition).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/mod.rs` around lines 150 - 156,
The current debug_assert! calls iter.next() which has side effects only in debug
builds; change this by separating the checks: first assert buf.is_empty() with
debug_assert!(buf.is_empty(), "Trailing bytes left after parsing all entries"),
then add a separate debug-only check for the iterator like
debug_assert!(matches!(iter.next(), None), "Trailing chunks left after parsing
all entries") and add a short comment explaining we're avoiding side effects
inside assertions; reference the existing symbols entries_seen,
entries_expected, buf, iter and the debug_assert! call when making the change.
lib/common/common/src/aligned_buf.rs (1)

67-76: 💤 Low value

Optional: defensively guard remove_prefix against count exceeding the available data.

remove_prefix(..count) assumes count <= self.deref().len(). If a future caller violates that, self.offset advances past self.buf.len() and the subsequent copy_within / truncate will panic in a non-obvious place. Today the only caller (uio::for_each_entry) respects this, so this is purely defensive.

♻️ Suggested debug check
     pub fn remove_prefix(&mut self, range: RangeTo<usize>) {
         let RangeTo { end: count } = range;
+        debug_assert!(count <= self.deref().len(), "remove_prefix beyond available data");
         self.offset += count;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/aligned_buf.rs` around lines 67 - 76, Guard
remove_prefix against a caller passing a count larger than the buffer: inside
the aligned_buf::remove_prefix method compute the available length (e.g.,
self.deref().len() or self.buf.len() - self.offset) and clamp the extracted
count so it does not advance self.offset past the available bytes, then compute
to_drop = new_offset - new_offset % ALIGN and adjust self.offset %= ALIGN; if
clamped count is zero return early to avoid calling copy_within/truncate;
reference the remove_prefix method, self.offset, self.buf, and ALIGN when making
the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/common/common/src/persisted_hashmap/uio/mod.rs`:
- Around line 64-92: In open, validate and compute entries_start safely: use
checked_mul/checked_add on header.buckets_count and size_of::<BucketOffset>()
and return an io::Error if they overflow, then ensure entries_start <=
storage.len() (using storage.len()?); only then compute average_entry_size from
storage.len() - entries_start. This protects UniversalHashMap::open and later
consumers (e.g., for_each_entry which uses file_len - self.entries_start) from
overflow/truncation attacks by failing early when header.buckets_pos or
buckets_count produce an out-of-bounds entries_start.

---

Outside diff comments:
In `@lib/common/common/src/persisted_hashmap/mmap.rs`:
- Around line 113-123: The iter() implementation currently swallows all decode
errors via the let-else, unlike keys() which logs ReadResult::Invalid(error) and
only silently skips ReadResult::Incomplete; update iter() (the iter method that
calls self.get_entry and K::from_bytes) to match keys(): call
K::from_bytes(entry) and match on the ReadResult variants, log the error for
ReadResult::Invalid using the same logging pattern used in keys(), silently skip
on ReadResult::Incomplete, and only continue to get values
(Self::get_values_from_entry) when ReadResult::Ok(key) is returned so corrupt
entries are surfaced consistently.

---

Nitpick comments:
In `@lib/common/common/src/aligned_buf.rs`:
- Around line 67-76: Guard remove_prefix against a caller passing a count larger
than the buffer: inside the aligned_buf::remove_prefix method compute the
available length (e.g., self.deref().len() or self.buf.len() - self.offset) and
clamp the extracted count so it does not advance self.offset past the available
bytes, then compute to_drop = new_offset - new_offset % ALIGN and adjust
self.offset %= ALIGN; if clamped count is zero return early to avoid calling
copy_within/truncate; reference the remove_prefix method, self.offset, self.buf,
and ALIGN when making the change.

In `@lib/common/common/src/persisted_hashmap/uio/mod.rs`:
- Around line 246-251: The helper parse_bucket_offset currently returns
Result<BucketOffset> using try_from on a slice even though its sole caller
for_each_key uses chunks_exact(size_of::<BucketOffset>()) so the conversion is
infallible; simplify by changing parse_bucket_offset to accept a [u8;
size_of::<BucketOffset>()] (or a generic array parameter) and return
BucketOffset directly via BucketOffset::from_ne_bytes, or alternatively remove
parse_bucket_offset and inline the conversion at the call site as
BucketOffset::from_ne_bytes(c.try_into().unwrap()); update the signature/usages
accordingly to eliminate the unused Result and error path.
- Around line 150-156: The current debug_assert! calls iter.next() which has
side effects only in debug builds; change this by separating the checks: first
assert buf.is_empty() with debug_assert!(buf.is_empty(), "Trailing bytes left
after parsing all entries"), then add a separate debug-only check for the
iterator like debug_assert!(matches!(iter.next(), None), "Trailing chunks left
after parsing all entries") and add a short comment explaining we're avoiding
side effects inside assertions; reference the existing symbols entries_seen,
entries_expected, buf, iter and the debug_assert! call when making the change.

In `@lib/common/common/src/persisted_hashmap/uio/sparse_reader.rs`:
- Around line 232-248: When re-queueing an entry in State::ReadingEntry (the
block building Entry with byte_offset, expected_len, buf, requested_key) ensure
the invariant that buf.len() never exceeds the previous expected_len is
explicit: add an assert (or debug_assert) that buf.len() <= expected_len_prev
(or the previous expected_len) and a short comment explaining that
schedule_next_entry relies on buf.len() being the absolute bytes already read so
the next read is scheduled from byte_offset + buf.len() for expected_len -
buf.len() bytes; reference parsed.satisfies_kind, schedule_next_entry, Entry,
State::ReadingEntry, expected_len, buf.len(), and byte_offset when adding the
check/comment.

In `@lib/common/common/src/universal_io/mod.rs`:
- Around line 109-114: The clamp method on ReadRange currently mutates
self.byte_offset when byte_offset > max_end_offset; instead compute max_len
using max_end_offset.saturating_sub(self.byte_offset) / size_of::<T>() as u64
and only update self.length = self.length.min(max_len) without changing
self.byte_offset so callers that rely on the original start aren’t surprised;
update the clamp function (referencing clamp, ReadRange, byte_offset, length,
max_end_offset, size_of::<T>()) to remove the byte_offset assignment and only
adjust length based on the computed max_len.
🪄 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: 296d2c8c-b3fd-41f1-97d6-d04c4663f9f2

📥 Commits

Reviewing files that changed from the base of the PR and between edde26e and f28313b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • lib/common/common/Cargo.toml
  • lib/common/common/benches/mmap_hashmap.rs
  • lib/common/common/src/aligned_buf.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/persisted_hashmap/fixtures.rs
  • lib/common/common/src/persisted_hashmap/mmap.rs
  • lib/common/common/src/persisted_hashmap/mod.rs
  • lib/common/common/src/persisted_hashmap/structures.rs
  • lib/common/common/src/persisted_hashmap/tests.rs
  • lib/common/common/src/persisted_hashmap/uio/mod.rs
  • lib/common/common/src/persisted_hashmap/uio/sparse_reader.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/zeros.rs

Comment on lines +64 to +92
let phf_region_start = size_of::<Header>() as u64;
let phf_region_len = header
.buckets_pos
.checked_sub(phf_region_start)
.ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "buckets_pos before header end")
})?;
let phf_bytes = storage.read::<Sequential>(ReadRange {
byte_offset: phf_region_start,
length: phf_region_len,
})?;
let phf = Function::read(&mut Cursor::new(&*phf_bytes))?;

let entries_start =
header.buckets_pos + header.buckets_count * size_of::<BucketOffset>() as u64;

let average_entry_size = (storage.len()? - entries_start)
.checked_div(header.buckets_count)
.unwrap_or(0);

Ok(UniversalHashMap {
storage,
header,
phf,
entries_start,
average_entry_size,
phantom: PhantomData,
})
}

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 | ⚡ Quick win

Validate that entries_start fits within the file in open.

The header check on line 65–70 only ensures buckets_pos >= phf_region_start. It doesn't bound entries_start = buckets_pos + buckets_count * size_of::<BucketOffset>() against storage.len(). With a malformed/truncated file:

  • Line 78: buckets_pos + buckets_count * 8 can overflow u64 for a hostile header.
  • Line 80: storage.len()? - entries_start then panics in debug builds and wraps in release builds, producing a nonsensical average_entry_size.
  • Line 128 (length: file_len - self.entries_start in for_each_entry) inherits the same risk later at I/O time.

A cheap fix is to compute entries_start with checked_* and verify entries_start <= storage.len() once, in open, so all later arithmetic is sound.

🛡️ Suggested guard
-        let entries_start =
-            header.buckets_pos + header.buckets_count * size_of::<BucketOffset>() as u64;
-
-        let average_entry_size = (storage.len()? - entries_start)
-            .checked_div(header.buckets_count)
-            .unwrap_or(0);
+        let entries_start = header
+            .buckets_count
+            .checked_mul(size_of::<BucketOffset>() as u64)
+            .and_then(|bo| header.buckets_pos.checked_add(bo))
+            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "entries_start overflow"))?;
+
+        let file_len = storage.len()?;
+        if entries_start > file_len {
+            return Err(UniversalIoError::from(io::Error::new(
+                io::ErrorKind::InvalidData,
+                "entries_start beyond file end",
+            )));
+        }
+
+        let average_entry_size = (file_len - entries_start)
+            .checked_div(header.buckets_count)
+            .unwrap_or(0);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/mod.rs` around lines 64 - 92, In
open, validate and compute entries_start safely: use checked_mul/checked_add on
header.buckets_count and size_of::<BucketOffset>() and return an io::Error if
they overflow, then ensure entries_start <= storage.len() (using
storage.len()?); only then compute average_entry_size from storage.len() -
entries_start. This protects UniversalHashMap::open and later consumers (e.g.,
for_each_entry which uses file_len - self.entries_start) from
overflow/truncation attacks by failing early when header.buckets_pos or
buckets_count produce an out-of-bounds entries_start.

@xzfc
xzfc force-pushed the refactor-mmap-hashmap branch from f28313b to 3f6db26 Compare May 8, 2026 06:04
coderabbitai[bot]

This comment was marked as resolved.

@qdrant qdrant deleted a comment from coderabbitai Bot May 8, 2026
@xzfc
xzfc force-pushed the refactor-mmap-hashmap branch from 3f6db26 to fc66719 Compare May 12, 2026 03:13
@coderabbitai

coderabbitai Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces universal I/O support to the persisted hashmap module. It adds UniversalHashMap, a generic on-disk read-only hash map backed by pluggable storage (mmap, io_uring). The ReadResult<T> enum explicitly contracts key-parsing outcomes (complete, incomplete, invalid), updated to the Key trait. A new AlignedBuf wrapper preserves alignment invariants between file offsets and buffer indices. The crate gains an aligned-vec dependency and exposes both new and existing utilities. MmapHashMap iteration now handles ReadResult semantics. Tests are refactored into a generic harness exercising both backends against deterministic ground-truth data. Benchmarks are restructured for multi-scenario Criterion comparison with optional Linux low-memory profiling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • qdrant/qdrant#8685: Both PRs modify the universal_io API by introducing a UniversalKind and adding/implementing a UniversalRead::kind() method with corresponding implementations for io_uring, mmap, and disk cache.
  • qdrant/qdrant#8798: Both PRs modify the universal_io read pipeline by introducing/solidifying a UniversalReadPipeline-based API with corresponding ReadPipeline associated types and pipeline implementations.
  • qdrant/qdrant#8721: Both PRs add and refactor Universal IO-backed storage (UniversalHashMap/UniversalPostings) and touch universal_io error/zerocopy handling integration.

Suggested reviewers

  • xzfc
  • coszio
  • timvisee
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'refactor mmap hashmap' is vague and does not clearly convey the main changes in the pull request, which involve creating a new UniversalHashMap abstraction, adding AlignedBuf, introducing test fixtures, and significantly refactoring multiple modules. Make the title more specific by highlighting the primary objective, such as 'Introduce UniversalHashMap with io_uring support and refactor persisted hashmap infrastructure' or 'Add UniversalHashMap and refactor hashmap benchmarking and testing framework'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The description mentions splitting mmap_hashmap into files and implementing custom iteration, which relates to actual changes in the PR like the new UniversalHashMap, AlignedBuf, and refactored test fixtures.
Docstring Coverage ✅ Passed Docstring coverage is 82.05% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor-mmap-hashmap

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

🧹 Nitpick comments (1)
lib/common/common/src/persisted_hashmap/uio/random_reader.rs (1)

129-131: ⚡ Quick win

Use explicit field ignoring for ReadingOffset.

Please spell this as State::ReadingOffset { requested_key: _ } so a future field addition cannot be silently ignored here.

♻️ Proposed fix
-                State::ReadingOffset { .. } => unreachable!("we don't schedule ReadingOffset"),
+                State::ReadingOffset { requested_key: _ } => {
+                    unreachable!("we don't schedule ReadingOffset")
+                }

As per coding guidelines, "Prefer explicit field ignoring using : _ over using .. in Rust struct destructuring".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/random_reader.rs` around lines
129 - 131, The match arm in the pop handling uses a wildcard struct pattern
State::ReadingOffset { .. } which can silently ignore future fields; update the
pattern in the match on &entry.state (the branch inside the if let Some(entry) =
self.queue.pop()) to use explicit field ignoring like State::ReadingOffset {
requested_key: _ } so the current field is ignored explicitly and new fields
will cause compile errors if unhandled.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/common/common/src/persisted_hashmap/uio/random_reader.rs`:
- Around line 151-185: The code currently returns
range.clamp::<u8>(self.file_len) directly which can produce a zero-length read
for truncated files; before scheduling the read, compute let clamped =
range.clamp::<u8>(self.file_len) and if clamped.length == 0 call f(meta, None)?
and continue (reject the request) instead of returning/scheduling it, otherwise
return Ok(Some((entry, clamped))). Update the logic around Entry/State/ReadRange
and the return that uses range.clamp::<u8>(self.file_len) to use this
pre-checked clamped value and avoid enqueuing 0-byte reads.

---

Nitpick comments:
In `@lib/common/common/src/persisted_hashmap/uio/random_reader.rs`:
- Around line 129-131: The match arm in the pop handling uses a wildcard struct
pattern State::ReadingOffset { .. } which can silently ignore future fields;
update the pattern in the match on &entry.state (the branch inside the if let
Some(entry) = self.queue.pop()) to use explicit field ignoring like
State::ReadingOffset { requested_key: _ } so the current field is ignored
explicitly and new fields will cause compile errors if unhandled.
🪄 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: c5fc93c0-6482-4224-9907-fddbab2a24b4

📥 Commits

Reviewing files that changed from the base of the PR and between 3f6db26 and fc66719.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • lib/common/common/Cargo.toml
  • lib/common/common/benches/mmap_hashmap.rs
  • lib/common/common/src/aligned_buf.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/persisted_hashmap/fixtures.rs
  • lib/common/common/src/persisted_hashmap/mmap.rs
  • lib/common/common/src/persisted_hashmap/mod.rs
  • lib/common/common/src/persisted_hashmap/structures.rs
  • lib/common/common/src/persisted_hashmap/tests.rs
  • lib/common/common/src/persisted_hashmap/uio/mod.rs
  • lib/common/common/src/persisted_hashmap/uio/random_reader.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/zeros.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/common/common/src/zeros.rs
  • lib/common/common/src/lib.rs
🚧 Files skipped from review as they are similar to previous changes (9)
  • lib/common/common/Cargo.toml
  • lib/common/common/src/persisted_hashmap/mod.rs
  • lib/common/common/src/persisted_hashmap/mmap.rs
  • lib/common/common/src/aligned_buf.rs
  • lib/common/common/benches/mmap_hashmap.rs
  • lib/common/common/src/persisted_hashmap/tests.rs
  • lib/common/common/src/persisted_hashmap/uio/mod.rs
  • lib/common/common/src/persisted_hashmap/structures.rs
  • lib/common/common/src/persisted_hashmap/fixtures.rs

Comment on lines +151 to +185
for (meta, request) in requests.by_ref() {
let (state, range);
match request {
Request::Offset(offset) => {
let byte_offset = self.map.entries_start + offset;
state = State::ReadingEntry {
byte_offset,
buf: AlignedBuf::new_for_offset(byte_offset),
expected_len: self.entry_read_size_est,
requested_key: None,
};
range = ReadRange {
byte_offset,
length: self.entry_read_size_est,
};
}
Request::Key(requested_key) => {
// PHF miss: no stored entry; report immediately and continue.
let Some(hash) = self.map.phf.get(requested_key) else {
f(meta, None)?;
continue;
};
// PHF hit: schedule the bucket-offset read; transitions to
// Loading once the offset arrives.
let bucket_byte_offset =
self.map.header.buckets_pos + hash * size_of::<BucketOffset>() as u64;
state = State::ReadingOffset { requested_key };
range = ReadRange {
byte_offset: bucket_byte_offset,
length: size_of::<BucketOffset>() as u64,
};
}
}
let entry = Entry { meta, state };
return Ok(Some((entry, range.clamp::<u8>(self.file_len))));

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 | ⚡ Quick win

Reject zero-length clamped reads before scheduling them.

The fresh-request path returns range.clamp::<u8>(self.file_len) directly, so a truncated file can still enqueue a 0-byte read here. That bypasses the explicit unexpected eof handling you already added for queued entry re-reads and makes the first failure mode less consistent.

🛠️ Proposed fix
-            let entry = Entry { meta, state };
-            return Ok(Some((entry, range.clamp::<u8>(self.file_len))));
+            let range = range.clamp::<u8>(self.file_len);
+            if range.length == 0 {
+                return Err(E::from(UniversalIoError::Io(read_err("unexpected eof"))));
+            }
+
+            let entry = Entry { meta, state };
+            return Ok(Some((entry, range)));
📝 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
for (meta, request) in requests.by_ref() {
let (state, range);
match request {
Request::Offset(offset) => {
let byte_offset = self.map.entries_start + offset;
state = State::ReadingEntry {
byte_offset,
buf: AlignedBuf::new_for_offset(byte_offset),
expected_len: self.entry_read_size_est,
requested_key: None,
};
range = ReadRange {
byte_offset,
length: self.entry_read_size_est,
};
}
Request::Key(requested_key) => {
// PHF miss: no stored entry; report immediately and continue.
let Some(hash) = self.map.phf.get(requested_key) else {
f(meta, None)?;
continue;
};
// PHF hit: schedule the bucket-offset read; transitions to
// Loading once the offset arrives.
let bucket_byte_offset =
self.map.header.buckets_pos + hash * size_of::<BucketOffset>() as u64;
state = State::ReadingOffset { requested_key };
range = ReadRange {
byte_offset: bucket_byte_offset,
length: size_of::<BucketOffset>() as u64,
};
}
}
let entry = Entry { meta, state };
return Ok(Some((entry, range.clamp::<u8>(self.file_len))));
for (meta, request) in requests.by_ref() {
let (state, range);
match request {
Request::Offset(offset) => {
let byte_offset = self.map.entries_start + offset;
state = State::ReadingEntry {
byte_offset,
buf: AlignedBuf::new_for_offset(byte_offset),
expected_len: self.entry_read_size_est,
requested_key: None,
};
range = ReadRange {
byte_offset,
length: self.entry_read_size_est,
};
}
Request::Key(requested_key) => {
// PHF miss: no stored entry; report immediately and continue.
let Some(hash) = self.map.phf.get(requested_key) else {
f(meta, None)?;
continue;
};
// PHF hit: schedule the bucket-offset read; transitions to
// Loading once the offset arrives.
let bucket_byte_offset =
self.map.header.buckets_pos + hash * size_of::<BucketOffset>() as u64;
state = State::ReadingOffset { requested_key };
range = ReadRange {
byte_offset: bucket_byte_offset,
length: size_of::<BucketOffset>() as u64,
};
}
}
let range = range.clamp::<u8>(self.file_len);
if range.length == 0 {
return Err(E::from(UniversalIoError::Io(read_err("unexpected eof"))));
}
let entry = Entry { meta, state };
return Ok(Some((entry, range)));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/common/common/src/persisted_hashmap/uio/random_reader.rs` around lines
151 - 185, The code currently returns range.clamp::<u8>(self.file_len) directly
which can produce a zero-length read for truncated files; before scheduling the
read, compute let clamped = range.clamp::<u8>(self.file_len) and if
clamped.length == 0 call f(meta, None)? and continue (reject the request)
instead of returning/scheduling it, otherwise return Ok(Some((entry, clamped))).
Update the logic around Entry/State/ReadRange and the return that uses
range.clamp::<u8>(self.file_len) to use this pre-checked clamped value and avoid
enqueuing 0-byte reads.

@xzfc xzfc left a comment

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.

Reviewed with @generall.

@xzfc
xzfc merged commit 75b3c92 into dev May 12, 2026
15 checks passed
@xzfc
xzfc deleted the refactor-mmap-hashmap branch May 12, 2026 04:03
@coderabbitai coderabbitai Bot mentioned this pull request May 19, 2026
generall added a commit that referenced this pull request May 22, 2026
* AlignedBuf

* UniversalHashMap

* Update wording

---------

Co-authored-by: xzfc <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Jul 7, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jul 21, 2026
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