Repository navigation
Introduce simple disk cache - #8792
Conversation
195f20c to
149e31d
Compare
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a new simple_disk_cache backend to universal_io with submodules: config, file, pipeline, and tests. Introduces DiskCacheConfig to map remote paths to local mirror paths, DiskCache which lazily initializes a local mmap-backed cache and tracks fetched 16 KiB blocks with a RoaringBitmap, and DiskCachePipeline that coordinates block-aligned remote reads and local mmap writes. Extends UniversalKind with a SimpleDiskCache variant and adds dependencies Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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: 2
♻️ Duplicate comments (1)
lib/common/common/src/universal_io/simple_disk_cache/file.rs (1)
51-58:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
read_mmap_bytesfabricates a slice over the entire mmap, aliasing concurrent writes.
std::slice::from_raw_parts(self.mmap.as_ptr(), self.mmap.len())produces a&[u8]covering the whole mapping; meanwhilewrite_mmap_bytesmutates other regions of that same mapping concurrently (only thefetchedlock is held, not all readers). Under Stacked/Tree Borrows this is UB even when the byte ranges don't overlap. Narrow the raw-parts slice to justbyte_range.🛡️ Proposed narrower slice
pub(super) unsafe fn read_mmap_bytes(&self, byte_range: Range<u64>) -> &[u8] { - let bytes = unsafe { std::slice::from_raw_parts(self.mmap.as_ptr(), self.mmap.len()) }; - &bytes[byte_range.start as usize..byte_range.end as usize] + let start = byte_range.start as usize; + let len = (byte_range.end - byte_range.start) as usize; + debug_assert!(start + len <= self.mmap.len()); + // SAFETY: caller guarantees `byte_range` is populated and within the mmap. + unsafe { std::slice::from_raw_parts(self.mmap.as_ptr().add(start), len) } }🤖 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/simple_disk_cache/file.rs` around lines 51 - 58, read_mmap_bytes currently fabricates a slice covering the entire mmap which can alias concurrent mutable writes; change it to create the raw-parts slice only for the requested Range by using a pointer offset at byte_range.start and a length of (byte_range.end - byte_range.start) so the returned &[u8] covers only the requested region; update the safety comment to state that the caller must ensure byte_range bounds and that self.fetched references that exact region; reference: LocalState::read_mmap_bytes and related write_mmap_bytes/fetched lock usage.
🧹 Nitpick comments (12)
lib/common/common/src/universal_io/simple_disk_cache/file.rs (4)
264-268: 💤 Low value
to_block_rangesilently truncates files larger than ~64 TiB.The casts
as u32will wrap silently ifrange.end / BLOCK_SIZEexceedsu32::MAX(i.e., a remote file >u32::MAX * 16 KiB ≈ 64 TiB). That's far beyond current expectations, but a wraparound here would silently corrupt the cache state (fetchedwould record bogus blocks). Adebug_assert!or explicit error would protect against future surprises.♻️ Proposed defensive check
pub(super) fn to_block_range(range: Range<u64>) -> Range<u32> { - let start = (range.start / BLOCK_SIZE as u64) as u32; - let end = range.end.div_ceil(BLOCK_SIZE as u64) as u32; - start..end + let start = range.start / BLOCK_SIZE as u64; + let end = range.end.div_ceil(BLOCK_SIZE as u64); + debug_assert!(end <= u32::MAX as u64, "block index overflow (file > 64 TiB)"); + start as u32..end as u32 }🤖 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/simple_disk_cache/file.rs` around lines 264 - 268, The to_block_range function currently casts computed block indices to u32 which silently wraps for ranges that exceed u32::MAX; add a defensive check in to_block_range (function name) to ensure both start and end block indices fit in u32 (e.g., compare start_blocks and end_blocks against u32::MAX) and either debug_assert! or return a clear error/panic if they don’t, so the casts to u32 cannot silently truncate and corrupt fetched block state.
26-27: 🏗️ Heavy liftDoc warns about single-instance requirement but nothing enforces it.
The
WARNblock calls out that multipleDiskCacheinstances per path will not share an mmap and can cause UB, yetopen_with_configdoes no registration / dedup. WithOpenOptionspaths flowing in from many call sites, this is easy to violate accidentally (especially since the globalDiskCacheConfigmakesDiskCache::openambient). Consider either:
- A process-wide registry (
HashMap<PathBuf, Weak<...>>) that hands out shared instances, or- A debug-only check that fails loudly when a duplicate is opened.
Even just promoting the warning to module-level docs and the
DiskCache::opendoc would help discoverability.🤖 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/simple_disk_cache/file.rs` around lines 26 - 27, The docs warn that multiple DiskCache instances per path are unsafe but open_with_config (and DiskCache::open governed by DiskCacheConfig) does not enforce this; add a process-wide registry keyed by PathBuf (e.g., a static Mutex<HashMap<PathBuf, Weak<DiskCache>>> or similar) used by open_with_config/DiskCache::open to return a shared Arc if an instance already exists, or at minimum add a debug-only check that panics/logs loudly when open_with_config attempts to create a second instance for the same path; also update the module- and DiskCache::open-level docs to mention the enforced singleton behavior.
218-229: 💤 Low value
len()silently truncates when remote size isn't a multiple ofsize_of::<T>().
bytes_len / t_size as u64rounds down, so a partial trailing element is invisible to callers. If aDiskCache<R>is opened with aTthat doesn't evenly divide the remote length (e.g., misaligned schema, reading a small header file asu32), the missing tail will go unnoticed. Either validate alignment at open time (bytes_len % t_size == 0) ordebug_assert!it here.🤖 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/simple_disk_cache/file.rs` around lines 218 - 229, The len() method currently truncates partial trailing elements by dividing bytes_len by size_of::<T>(); change it to validate alignment before dividing: compute bytes_len (as currently), then assert or return an error if bytes_len % t_size as u64 != 0 (e.g., debug_assert!(bytes_len % t_size as u64 == 0, "unaligned storage for T") or convert to a Result::Err with a clear message). Update the len() implementation in the same function (len) that references size_of::<T>() and self.local/self.remote so callers cannot silently lose a partial tail element.
60-86: 💤 Low value
write_mmap_bytesre-checkscontains_rangebut doesn't validatebytes.len()matches under contention.The
assert!at line 75 enforcesbytes.len() == max_len.min(blocks_range.len() * BLOCK_SIZE). If two threads scheduled overlapping ranges and both arrive here, the second one would be skipped by the earlycontains_rangereturn — good. But the assertion runs after the early return only whencontains_rangeis false, and it's a hardassert!(notdebug_assert!). A caller bug or remote returning short bytes will abort the process rather than surface asUniversalIoError. Consider returning an error or downgrading todebug_assert!with a recoverable error path.🤖 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/simple_disk_cache/file.rs` around lines 60 - 86, The write_mmap_bytes function currently uses a hard assert! to validate bytes.len(), which can abort the process; replace this panic with a runtime check and surface a recoverable error: compute let expected_len = max_len.min(blocks_range.len() * BLOCK_SIZE) and if bytes.len() != expected_len then return a Result::Err(UniversalIoError::InvalidWriteLength { expected: expected_len, got: bytes.len() }) (or, if changing the API is undesirable, use debug_assert! and return early with Ok(()) or log and clamp the copy length to the min of expected_len and bytes.len()); update the write_mmap_bytes signature to return Result<(), UniversalIoError> and adjust callers (or choose the debug_assert!/clamp path) and keep the existing fetched.contains_range early-return and the ptr::copy_nonoverlapping logic intact (function name: write_mmap_bytes, checks: fetched.contains_range, assertion: assert! on bytes.len()).lib/common/common/src/universal_io/simple_disk_cache/tests.rs (2)
75-102: ⚡ Quick winTests will not exercise the cache hit path on the second read.
Both
basic_read_returns_remote_bytesandpopulate_fetches_every_blockonly verify the contents returned, not that the second access avoids the remote. Consider using a counting/wrappingR(or assertinglocal.fetcheddirectly) to assert that subsequent reads of the same range hit the local mmap path inDiskCachePipeline::schedule(thecontains_rangeshort-circuit). This would protect the actual caching behavior — currently the tests pass even if every read silently re-fetched from remote.🤖 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/simple_disk_cache/tests.rs` around lines 75 - 102, Tests currently only validate returned bytes but don't assert cache hits; update the tests (e.g., basic_read_returns_remote_bytes and populate_fetches_every_block) to verify the cache short-circuit by wrapping or instrumenting the remote reader type R to count fetches (or by asserting a field like local.fetched) and then assert that after the first read a subsequent UniversalRead::read::<Sequential>(&file, ReadRange{...}) does not increment the remote fetch count. Specifically, instrument the Scenario::open::<R>() / R wrapper to expose a counter, call UniversalRead::read twice for the same range, and assert that DiskCachePipeline::schedule's contains_range short-circuit path was taken (no additional remote fetch) by checking the counter or local.fetched remains unchanged on the second call.
64-74: 💤 Low valueGenerated test modules end up nested as
tests::tests_mmap/tests::tests_uring.The outer file is already included via
#[cfg(test)] mod tests;fromsimple_disk_cache::mod.rs, andduplicate_itemthen generates innermod tests_mmap/mod tests_uring. The structure works but the extra nesting (and the per-arm#[cfg(test)]on each inner module) is redundant. If you'd like flatter test paths and slightly faster compile times, consider hoisting theduplicate_itemdirectly onto the test functions instead of an entire module wrapper. Non-blocking.🤖 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/simple_disk_cache/tests.rs` around lines 64 - 74, The generated tests are nested under mod tests::tests_mmap and tests::tests_uring due to applying duplicate::duplicate_item to the entire tests_mod; to flatten them, remove the duplicate_item attribute from the tests_mod wrapper and instead apply duplicate::duplicate_item to each test function (or to a smaller helper block) so the duplicate arms produce top-level items inside the existing tests module; update references to R, MmapFile, and IoUringFile accordingly and remove per-arm #[cfg(test)] on the inner modules (the outer mod tests from simple_disk_cache::mod.rs already provides the test cfg).lib/common/common/src/universal_io/simple_disk_cache/pipeline.rs (3)
57-76: 💤 Low valueSlot-not-found should be unreachable, not an
io::Error.The slot id is produced by
Slab::insertinscheduleand removed exactly once here. A missing slot indicates an internal pipeline bug (e.g., double-wait or a remote returning a fabricated slot id) rather than an I/O failure — surfacing it asio::Error::other("file slot not found")makes diagnosis harder and obscures the true class of bug. Preferunreachable!(or a dedicated invariant error) so the violation is loud.🤖 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/simple_disk_cache/pipeline.rs` around lines 57 - 76, The removal of the PipelinedMeta via self.pipelined_metas.try_remove(slot_id) represents an invariant (the slot was created by Slab::insert in schedule and must be removed exactly once), so replace the ok_or_else(|| io::Error::other("file slot not found"))? with an assertion/fatal (e.g., unreachable! or panic!("file slot not found: invariant violated")) so missing slots are treated as internal bugs; update the code around the PipelinedMeta destructuring (the let PipelinedMeta { ... } = self.pipelined_metas.try_remove(slot_id) ... ) to unwrap with unreachable!/panic and keep the rest of the function (local.write_mmap_bytes, local.read_mmap_bytes, and the Ok(Some((meta, bytemuck::cast_slice(mmap_bytes))))) unchanged.
162-170: 💤 Low value
wait()always drainsresultfirst regardless of remote completion order.If a caller schedules a cache-miss read (slot inserted, remote pending) and then a cache-hit read (sets
self.result),wait()will return the cache-hit result first — even though the consumer might be polling on the order of completion. BecauseMetadistinguishes the calls this is functionally correct, but it makes scheduling order ≠ completion order in a non-obvious way. Worth a brief doc note onwait()clarifying the returned ordering, or an explicit policy decision.🤖 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/simple_disk_cache/pipeline.rs` around lines 162 - 170, The current wait() implementation always drains self.result before checking wait_for_remote(), which returns in-memory cache-hit results ahead of in-flight remote completions; decide and implement the intended policy: to preserve completion order call self.wait_for_remote() first and if it yields None then take self.result, or if you prefer the existing behavior add a concise doc comment on the wait() method explaining that in-memory results are prioritized over remote completions; update the wait() function (and its docstring) accordingly, referencing the wait(), self.result, and wait_for_remote() symbols.
69-73: 💤 Low valueCombine SAFETY rationale with each unsafe call.
Two distinct unsafe operations (
write_mmap_bytesandread_mmap_bytes) live inside a singleunsafe { … }block with no SAFETY comment explaining why each is sound here. Each unsafe call has different invariants —writerequires the byte slice covers the full block range,readrequires the bytes were populated and within bounds. Consider splitting into two separateunsafeblocks, each preceded by a// SAFETY:comment, so future readers can audit them independently.🤖 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/simple_disk_cache/pipeline.rs` around lines 69 - 73, The combined unsafe block around local.write_mmap_bytes(&bytes, blocks_range) and local.read_mmap_bytes(read_range.into_byte_range::<T>()) should be split into two distinct unsafe blocks and each preceded by a clear "// SAFETY:" comment describing the required invariants: for the write (local.write_mmap_bytes) state that the provided byte slice covers the entire blocks_range, the mmap is writable and aligned for the write, and no other concurrent mutation occurs; for the read (local.read_mmap_bytes) state that the target range is in-bounds, the bytes have been fully populated by the prior write, and the returned reference lifetime and aliasing rules are respected. Reference the symbols local.write_mmap_bytes, local.read_mmap_bytes, bytes, blocks_range, read_range, and T when adding the SAFETY notes.lib/common/common/src/universal_io/simple_disk_cache/config.rs (2)
36-42: ⚡ Quick win
initialize_globalpanics on second call — consider returning aResult.The current
expectonGLOBAL.set(cfg)will abort the process if any caller (or test) accidentally invokesinitialize_globaltwice. Since the construction step is also fallible, returningResult<(), UniversalIoError>(orResult<&'static DiskCacheConfig>) gives callers control over the failure mode and makes test setups much easier. Tests in particular often need idempotent global init — consider exposing an idempotent variant (e.g.,get_or_init) or at least propagating the error.🤖 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/simple_disk_cache/config.rs` around lines 36 - 42, Change initialize_global to return a Result instead of panicking: have it call DiskCacheConfig::new(...) and propagate its error (use ? to return UniversalIoError), then attempt to set GLOBAL via GLOBAL.set(cfg) but handle the case where GLOBAL is already set by returning an appropriate Result (either Ok(&'static DiskCacheConfig) or a specific error variant) instead of expect/panic; alternatively add an idempotent helper get_or_init that returns the existing &'static DiskCacheConfig when GLOBAL is already initialized. Ensure you reference initialize_global, DiskCacheConfig::new, GLOBAL.set, and (optionally) add get_or_init and return Result types such as Result<&'static DiskCacheConfig, UniversalIoError>.
54-67: 💤 Low valueMisleading
NotFoundmapping for paths outsideremote_dir.When
strip_prefixfails the path actually exists (canonicalize succeeded) but is simply outside the configuredremote_dir. ReturningUniversalIoError::NotFoundfor that case is semantically misleading — callers checking "does this remote file exist?" will get a false negative. A dedicated error variant (e.g.,OutsideRemoteRoot/InvalidPath) or at least a different existing variant would convey the situation more accurately. The existing test only asserts the variant type, so the user-visible distinction is currently lost.🤖 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/simple_disk_cache/config.rs` around lines 54 - 67, The mapping in local_path_for incorrectly converts a strip_prefix failure (path canonicalized but outside self.remote_dir) into UniversalIoError::NotFound; change the error to a dedicated variant (e.g., UniversalIoError::OutsideRemoteRoot or UniversalIoError::InvalidPath) and return that from the strip_prefix map_err in the local_path_for function so callers can distinguish "exists but outside remote root" from true not-found errors; add the new enum variant to UniversalIoError (and implement Display/serialization if required) and update any tests that asserted the previous NotFound variant to expect the new variant.lib/common/common/src/universal_io/mod.rs (1)
108-122: ⚡ Quick win
into_byte_rangepanics on overflow rather than surfacing an error.Both
checked_mulandchecked_addpaths useexpect, which means malformed callers (or arithmetic that exceedsu64::MAX) abort the process instead of returning aUniversalIoError. Since the surrounding code already returnsResulteverywhere, prefer propagating an error here too — for example a dedicated overflow variant or reusingOutOfBounds. Also, the secondexpectmessage says"byte offset overflow"but it's actually the end-of-range that overflows; consider"byte range end overflow"for clarity.♻️ Possible signature change
- fn into_byte_range<T: bytemuck::Pod>(self) -> std::ops::Range<u64> { + fn into_byte_range<T: bytemuck::Pod>(self) -> Result<std::ops::Range<u64>> { let ReadRange { byte_offset, length, } = self; let t_size = size_of::<T>() as u64; - let byte_len = length.checked_mul(t_size).expect("length overflow"); - let byte_end = byte_offset - .checked_add(byte_len) - .expect("byte offset overflow"); - - byte_offset..byte_end + let byte_len = length + .checked_mul(t_size) + .ok_or_else(|| UniversalIoError::other("ReadRange length overflow"))?; + let byte_end = byte_offset + .checked_add(byte_len) + .ok_or_else(|| UniversalIoError::other("ReadRange byte end overflow"))?; + + Ok(byte_offset..byte_end) }🤖 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 108 - 122, into_byte_range currently panics on arithmetic overflow via expect; change its signature to return Result<std::ops::Range<u64>, UniversalIoError> and replace the two expect() calls with checked arithmetic that returns an appropriate UniversalIoError (either reuse OutOfBounds or add a new Overflow/RangeOverflow variant) when checked_mul or checked_add returns None; also correct the second error text to something like "byte range end overflow" so the returned error message accurately reflects the failing step; update callers of ReadRange::into_byte_range to propagate the Result accordingly.
🤖 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/universal_io/simple_disk_cache/file.rs`:
- Around line 95-101: The condition in the file opening logic is inverted:
change the check on options.writeable in the function that returns
UniversalIoError::Uninitialized so that writable=true is rejected (use if
options.writeable rather than if !options.writeable), update the error message
to match (e.g., "DiskCache only supports immutable files, writeable option is
not allowed"), and consider replacing the returned variant
UniversalIoError::Uninitialized with a more appropriate configuration error
variant such as UniversalIoError::Unsupported (or similarly named) to better
reflect an unsupported configuration; ensure you update any callsites/tests if
they depend on the specific error variant.
In `@lib/common/common/src/universal_io/simple_disk_cache/pipeline.rs`:
- Around line 148-160: The slab leak happens because
pipelined_metas.insert(pipelined_meta) is called before
remote_pipeline.schedule::<P>(slot_id, &file.remote, blocks_byte_range) so a
scheduling failure leaves the slot occupied; fix by deferring the insert until
after schedule succeeds (move pipelined_metas.insert after
get_or_init_remote_pipeline().schedule) or, if you must insert early, ensure you
remove the slot on any Err returned from remote_pipeline.schedule (call
pipelined_metas.remove(slot_id) in the error path); update the code paths around
PipelinedMeta creation, pipelined_metas.insert, get_or_init_remote_pipeline, and
remote_pipeline.schedule to implement one of these fixes.
---
Duplicate comments:
In `@lib/common/common/src/universal_io/simple_disk_cache/file.rs`:
- Around line 51-58: read_mmap_bytes currently fabricates a slice covering the
entire mmap which can alias concurrent mutable writes; change it to create the
raw-parts slice only for the requested Range by using a pointer offset at
byte_range.start and a length of (byte_range.end - byte_range.start) so the
returned &[u8] covers only the requested region; update the safety comment to
state that the caller must ensure byte_range bounds and that self.fetched
references that exact region; reference: LocalState::read_mmap_bytes and related
write_mmap_bytes/fetched lock usage.
---
Nitpick comments:
In `@lib/common/common/src/universal_io/mod.rs`:
- Around line 108-122: into_byte_range currently panics on arithmetic overflow
via expect; change its signature to return Result<std::ops::Range<u64>,
UniversalIoError> and replace the two expect() calls with checked arithmetic
that returns an appropriate UniversalIoError (either reuse OutOfBounds or add a
new Overflow/RangeOverflow variant) when checked_mul or checked_add returns
None; also correct the second error text to something like "byte range end
overflow" so the returned error message accurately reflects the failing step;
update callers of ReadRange::into_byte_range to propagate the Result
accordingly.
In `@lib/common/common/src/universal_io/simple_disk_cache/config.rs`:
- Around line 36-42: Change initialize_global to return a Result instead of
panicking: have it call DiskCacheConfig::new(...) and propagate its error (use ?
to return UniversalIoError), then attempt to set GLOBAL via GLOBAL.set(cfg) but
handle the case where GLOBAL is already set by returning an appropriate Result
(either Ok(&'static DiskCacheConfig) or a specific error variant) instead of
expect/panic; alternatively add an idempotent helper get_or_init that returns
the existing &'static DiskCacheConfig when GLOBAL is already initialized. Ensure
you reference initialize_global, DiskCacheConfig::new, GLOBAL.set, and
(optionally) add get_or_init and return Result types such as Result<&'static
DiskCacheConfig, UniversalIoError>.
- Around line 54-67: The mapping in local_path_for incorrectly converts a
strip_prefix failure (path canonicalized but outside self.remote_dir) into
UniversalIoError::NotFound; change the error to a dedicated variant (e.g.,
UniversalIoError::OutsideRemoteRoot or UniversalIoError::InvalidPath) and return
that from the strip_prefix map_err in the local_path_for function so callers can
distinguish "exists but outside remote root" from true not-found errors; add the
new enum variant to UniversalIoError (and implement Display/serialization if
required) and update any tests that asserted the previous NotFound variant to
expect the new variant.
In `@lib/common/common/src/universal_io/simple_disk_cache/file.rs`:
- Around line 264-268: The to_block_range function currently casts computed
block indices to u32 which silently wraps for ranges that exceed u32::MAX; add a
defensive check in to_block_range (function name) to ensure both start and end
block indices fit in u32 (e.g., compare start_blocks and end_blocks against
u32::MAX) and either debug_assert! or return a clear error/panic if they don’t,
so the casts to u32 cannot silently truncate and corrupt fetched block state.
- Around line 26-27: The docs warn that multiple DiskCache instances per path
are unsafe but open_with_config (and DiskCache::open governed by
DiskCacheConfig) does not enforce this; add a process-wide registry keyed by
PathBuf (e.g., a static Mutex<HashMap<PathBuf, Weak<DiskCache>>> or similar)
used by open_with_config/DiskCache::open to return a shared Arc if an instance
already exists, or at minimum add a debug-only check that panics/logs loudly
when open_with_config attempts to create a second instance for the same path;
also update the module- and DiskCache::open-level docs to mention the enforced
singleton behavior.
- Around line 218-229: The len() method currently truncates partial trailing
elements by dividing bytes_len by size_of::<T>(); change it to validate
alignment before dividing: compute bytes_len (as currently), then assert or
return an error if bytes_len % t_size as u64 != 0 (e.g., debug_assert!(bytes_len
% t_size as u64 == 0, "unaligned storage for T") or convert to a Result::Err
with a clear message). Update the len() implementation in the same function
(len) that references size_of::<T>() and self.local/self.remote so callers
cannot silently lose a partial tail element.
- Around line 60-86: The write_mmap_bytes function currently uses a hard assert!
to validate bytes.len(), which can abort the process; replace this panic with a
runtime check and surface a recoverable error: compute let expected_len =
max_len.min(blocks_range.len() * BLOCK_SIZE) and if bytes.len() != expected_len
then return a Result::Err(UniversalIoError::InvalidWriteLength { expected:
expected_len, got: bytes.len() }) (or, if changing the API is undesirable, use
debug_assert! and return early with Ok(()) or log and clamp the copy length to
the min of expected_len and bytes.len()); update the write_mmap_bytes signature
to return Result<(), UniversalIoError> and adjust callers (or choose the
debug_assert!/clamp path) and keep the existing fetched.contains_range
early-return and the ptr::copy_nonoverlapping logic intact (function name:
write_mmap_bytes, checks: fetched.contains_range, assertion: assert! on
bytes.len()).
In `@lib/common/common/src/universal_io/simple_disk_cache/pipeline.rs`:
- Around line 57-76: The removal of the PipelinedMeta via
self.pipelined_metas.try_remove(slot_id) represents an invariant (the slot was
created by Slab::insert in schedule and must be removed exactly once), so
replace the ok_or_else(|| io::Error::other("file slot not found"))? with an
assertion/fatal (e.g., unreachable! or panic!("file slot not found: invariant
violated")) so missing slots are treated as internal bugs; update the code
around the PipelinedMeta destructuring (the let PipelinedMeta { ... } =
self.pipelined_metas.try_remove(slot_id) ... ) to unwrap with unreachable!/panic
and keep the rest of the function (local.write_mmap_bytes,
local.read_mmap_bytes, and the Ok(Some((meta,
bytemuck::cast_slice(mmap_bytes))))) unchanged.
- Around line 162-170: The current wait() implementation always drains
self.result before checking wait_for_remote(), which returns in-memory cache-hit
results ahead of in-flight remote completions; decide and implement the intended
policy: to preserve completion order call self.wait_for_remote() first and if it
yields None then take self.result, or if you prefer the existing behavior add a
concise doc comment on the wait() method explaining that in-memory results are
prioritized over remote completions; update the wait() function (and its
docstring) accordingly, referencing the wait(), self.result, and
wait_for_remote() symbols.
- Around line 69-73: The combined unsafe block around
local.write_mmap_bytes(&bytes, blocks_range) and
local.read_mmap_bytes(read_range.into_byte_range::<T>()) should be split into
two distinct unsafe blocks and each preceded by a clear "// SAFETY:" comment
describing the required invariants: for the write (local.write_mmap_bytes) state
that the provided byte slice covers the entire blocks_range, the mmap is
writable and aligned for the write, and no other concurrent mutation occurs; for
the read (local.read_mmap_bytes) state that the target range is in-bounds, the
bytes have been fully populated by the prior write, and the returned reference
lifetime and aliasing rules are respected. Reference the symbols
local.write_mmap_bytes, local.read_mmap_bytes, bytes, blocks_range, read_range,
and T when adding the SAFETY notes.
In `@lib/common/common/src/universal_io/simple_disk_cache/tests.rs`:
- Around line 75-102: Tests currently only validate returned bytes but don't
assert cache hits; update the tests (e.g., basic_read_returns_remote_bytes and
populate_fetches_every_block) to verify the cache short-circuit by wrapping or
instrumenting the remote reader type R to count fetches (or by asserting a field
like local.fetched) and then assert that after the first read a subsequent
UniversalRead::read::<Sequential>(&file, ReadRange{...}) does not increment the
remote fetch count. Specifically, instrument the Scenario::open::<R>() / R
wrapper to expose a counter, call UniversalRead::read twice for the same range,
and assert that DiskCachePipeline::schedule's contains_range short-circuit path
was taken (no additional remote fetch) by checking the counter or local.fetched
remains unchanged on the second call.
- Around line 64-74: The generated tests are nested under mod tests::tests_mmap
and tests::tests_uring due to applying duplicate::duplicate_item to the entire
tests_mod; to flatten them, remove the duplicate_item attribute from the
tests_mod wrapper and instead apply duplicate::duplicate_item to each test
function (or to a smaller helper block) so the duplicate arms produce top-level
items inside the existing tests module; update references to R, MmapFile, and
IoUringFile accordingly and remove per-arm #[cfg(test)] on the inner modules
(the outer mod tests from simple_disk_cache::mod.rs already provides the test
cfg).
🪄 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: 3c100c38-0b88-4d50-ab5e-b4e5a0183968
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (7)
lib/common/common/Cargo.tomllib/common/common/src/universal_io/mod.rslib/common/common/src/universal_io/simple_disk_cache/config.rslib/common/common/src/universal_io/simple_disk_cache/file.rslib/common/common/src/universal_io/simple_disk_cache/mod.rslib/common/common/src/universal_io/simple_disk_cache/pipeline.rslib/common/common/src/universal_io/simple_disk_cache/tests.rs
✅ Files skipped from review due to trivial changes (1)
- lib/common/common/Cargo.toml
2d4d428 to
88e7dc9
Compare
|
|
||
| fn can_schedule(&mut self) -> bool { | ||
| self.result.is_none() | ||
| && self |
There was a problem hiding this comment.
sanity check: this can actually be OR instead of AND, right?
There was a problem hiding this comment.
we don't know whether the item to schedule is going to be already cached or not, so to be safe, I made it an AND.
Currently we don't have a way to tell that it is able to schedule only if it exists in mmap.
pass meta to remote pipeline
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Heads up: I am merging this without |
* [AI + manual] initial impl [AI] read_batch which actually batches manual nits [AI] better handling of local and remote paths manual refactor, respect open options don't delete local file dumbify read_batch we want to refactor it anyway simplify rename to `DiskCache` in `simple_disk_cache` module * refactor to use always use ReadPipeline pass meta to remote pipeline * nits * run tests for more Remotes * fix no more <T> in UniversalRead * fmt * chore(deps): unify roaring as workspace dep, move duplicate to dev-deps Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: generall <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
As a simpler alternative to
CachedSlice, which can work when the local disk is smaller than the remote disk, this PR introducessimple_disk_cache::DiskCache, which assumes a large-enough local disk.This is basically a local copy of the given file, with a bitmask on top. The local file gets initialized lazily with the length of the upstream file, and the contents --chunked in 16KB blocks-- get pulled lazily as they get requested.
This PR already implements the
ReadPipelinetrait, and every read is funneled through this.There are a few limitations, that can be addressed later:
&ref, soMmapRawmakes it easier without a lock.