Repository navigation
refactor mmap hashmap - #8405
Conversation
generall
commented
Mar 15, 2026
- [manual] split mmap_hashmap into multilpe files
- [AI] first iteration
- [AI] impleent custor for each key
2f17e2a to
ca0b66f
Compare
e67945e to
ecf41e4
Compare
ecf41e4 to
62d1a52
Compare
5cbe5bf to
f28313b
Compare
There was a problem hiding this comment.
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 thatkeys()logs.
keys()distinguishesReadResult::Invalid(error)(debug_assert +log::error!) fromReadResult::Incomplete(silent skip), butiter()collapses both into a silentreturn None;via the let-else. Corrupt entries will go entirely unnoticed here. Consider matching the error-reporting behavior ofkeys()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 valueMinor: bytes already read are kept on retry but
byte_offsetis not advanced.When the parse doesn't satisfy
entry_kind, the entry is re-queued with the samebyte_offsetbut a largerexpected_len. Inschedule_next_entry(lines 135-139) the next read range is computed asbyte_offset + buf.len()forexpected_len - buf.len()bytes, which is correct as long asbuf.len()faithfully tracks the absolute offset within the entry.If
datapassed toprocessever contains less than the requested chunk (e.g. a clamped range),buf.len()afterextend_from_slicewill be smaller than expected, and the next range calculation will still be correct — but consider assertingbuf.len() <= expected_len_prevand 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 valueOptional: avoid silently shifting
byte_offseton overflow.If
self.byte_offset > max_end_offset, line 110 clamps the start of the read tomax_end_offsetrather than just zeroing the length. The downstreamsaturating_subalready producesmax_len == 0for this case without needing to mutatebyte_offset, and leaving the start untouched makes accidental misuse (e.g. callers that don't checklength == 0) less surprising. Not a correctness issue with the current callers (which always passT = u8and checklength == 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 valueOptional: simplify
parse_bucket_offsetfor an infallible call site.The only caller (
for_each_key, line 179) feeds itchunks_exact(size_of::<BucketOffset>()), sotry_fromcan never fail, and theunwrap()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 returnBucketOffset(noResult). 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 valueNit:
iter.next()insidedebug_assert!is a side-effect that only runs in debug builds.
debug_assert!evaluates its condition (and consumes one chunk fromiter) 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 separatedebug_assert!(matches!(iter.next(), None))after a comment, or dropping theitercheck entirely (theentries_seen == entries_expectedinvariant +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 valueOptional: defensively guard
remove_prefixagainstcountexceeding the available data.
remove_prefix(..count)assumescount <= self.deref().len(). If a future caller violates that,self.offsetadvances pastself.buf.len()and the subsequentcopy_within/truncatewill 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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (13)
lib/common/common/Cargo.tomllib/common/common/benches/mmap_hashmap.rslib/common/common/src/aligned_buf.rslib/common/common/src/lib.rslib/common/common/src/persisted_hashmap/fixtures.rslib/common/common/src/persisted_hashmap/mmap.rslib/common/common/src/persisted_hashmap/mod.rslib/common/common/src/persisted_hashmap/structures.rslib/common/common/src/persisted_hashmap/tests.rslib/common/common/src/persisted_hashmap/uio/mod.rslib/common/common/src/persisted_hashmap/uio/sparse_reader.rslib/common/common/src/universal_io/mod.rslib/common/common/src/zeros.rs
| 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, | ||
| }) | ||
| } |
There was a problem hiding this comment.
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 * 8can overflowu64for a hostile header. - Line 80:
storage.len()? - entries_startthen panics in debug builds and wraps in release builds, producing a nonsensicalaverage_entry_size. - Line 128 (
length: file_len - self.entries_startinfor_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.
f28313b to
3f6db26
Compare
3f6db26 to
fc66719
Compare
📝 WalkthroughWalkthroughThis PR introduces universal I/O support to the persisted hashmap module. It adds Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
lib/common/common/src/persisted_hashmap/uio/random_reader.rs (1)
129-131: ⚡ Quick winUse 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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (13)
lib/common/common/Cargo.tomllib/common/common/benches/mmap_hashmap.rslib/common/common/src/aligned_buf.rslib/common/common/src/lib.rslib/common/common/src/persisted_hashmap/fixtures.rslib/common/common/src/persisted_hashmap/mmap.rslib/common/common/src/persisted_hashmap/mod.rslib/common/common/src/persisted_hashmap/structures.rslib/common/common/src/persisted_hashmap/tests.rslib/common/common/src/persisted_hashmap/uio/mod.rslib/common/common/src/persisted_hashmap/uio/random_reader.rslib/common/common/src/universal_io/mod.rslib/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
| 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)))); |
There was a problem hiding this comment.
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.
| 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.
* AlignedBuf * UniversalHashMap * Update wording --------- Co-authored-by: xzfc <[email protected]>