Repository navigation
impl UniversalRead for local disk cache - #8368
Conversation
UniversalReadUniversalRead
|
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 disk-backed block cache and a typed, block-backed view over files. Introduces CacheController (global initializer, mmap-backed hot storage, quick_cache lifecycle, file opening and block fetch APIs) and BlocksLifecycle for cache eviction. Adds CachedSlice offering typed element reads with single-block zero-copy and multi-block assembly (bytemuck-backed). Exposes these via a new disk_cache module and a disk_cached universal_io backend implementing UniversalRead/UniversalReadFileOps. Extends UniversalIoError with BytemuckCast and Uninitialized, updates OperationError conversions, and adds comprehensive unit and concurrency tests for cache and slice behavior. Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 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: 8
🧹 Nitpick comments (5)
lib/common/common/src/disk_cache/tests.rs (2)
95-99: Usebytemuck::cast_sliceinstead of unsafe raw pointer cast.The unsafe block manually casts
&[f32]to&[u8]using raw pointers. Per the coding guidelines, preferbytemuckover manual byte transmutation.♻️ Proposed fix using bytemuck
/// Write a flat slice of f32s to a binary file (little-endian, which is native on x86/ARM). fn write_vectors_to_file(path: &Path, data: &[f32]) { - let bytes: &[u8] = - unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), data.len() * 4) }; + let bytes: &[u8] = bytemuck::cast_slice(data); fs::write(path, bytes).unwrap(); }As per coding guidelines: "In new code, don't use
transmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/disk_cache/tests.rs` around lines 95 - 99, The unsafe raw pointer conversion in write_vectors_to_file should be replaced with bytemuck to safely cast &[f32] to &[u8]; import bytemuck::cast_slice and call cast_slice(data) to get a &[u8] and pass that to fs::write, and ensure the bytemuck crate is added to Cargo.toml if not present; update the write_vectors_to_file function to use cast_slice(data) instead of the unsafe std::slice::from_raw_parts.
11-45: Consider adding assertions totest_cacher.The test only prints debug output via
eprintln!but doesn't assert any expected values. While useful for manual debugging, tests should include assertions to catch regressions.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/disk_cache/tests.rs` around lines 11 - 45, The test_cacher currently only prints outputs; replace or supplement the eprintln! calls with assertions that validate the decoded slices returned by CachedSlice::<u8>::get_range (use fancy_decode on each get_range result) against the expected string contents for the created test file (created by create_test_file). Specifically, assert the values for the ranges used (BLOCK_SIZE * 3..BLOCK_SIZE * 3, BLOCK_SIZE * 3 + 3..BLOCK_SIZE * 3 + 14, BLOCK_SIZE * 3..BLOCK_SIZE * 4 - 1, BLOCK_SIZE * 3..BLOCK_SIZE * 4, BLOCK_SIZE * 3..BLOCK_SIZE * 4 + 1) using assert_eq! (or similar) so the test fails on regressions while keeping the same setup that constructs CacheController::new and opens the CachedSlice.lib/common/common/src/universal_io/disk_cached.rs (1)
44-52: Consider honoring thepopulateoption fromOpenOptions.The
populatefield fromOpenOptionsis explicitly ignored, but callers may expect the cache to be warmed on open whenpopulate: Some(true)is passed. This could lead to unexpected cold-cache performance in production.💡 Suggestion
If
populateisSome(true), consider pre-fetching blocks for the file into the cache duringopen(), or document that the disk cache does not support eager population.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/disk_cached.rs` around lines 44 - 52, OpenOptions.populate is currently ignored; update the open path that calls CachedSlice::open(controller, path.as_ref()) to honor populate: if options.populate == Some(true) pre-warm the cache by reading/prefetching the file's blocks into the disk-cache (e.g., call the controller/CachedSlice prefetch/populate API or read ranges after opening), otherwise leave behavior unchanged; ensure you reference OpenOptions.populate, CachedSlice::open and controller/path when implementing the prefetch so callers with populate: Some(true) get an eager-warmed cache (or alternatively add clear documentation on lack of support if prefetching isn’t feasible).lib/common/common/src/disk_cache/controller.rs (2)
239-247: Consider adding a timeout to prevent unbounded blocking.
pop_unused_blockwaits indefinitely viaCondvar::wait. If all blocks are pinned or a bug prevents eviction, this could hang a thread forever. A timeout with an error return (or at least a logged warning) would improve debuggability.Optional: Add timeout with diagnostic
fn pop_unused_block(&self) -> BlockOffset { let mut pool = self.unused_blocks.lock(); loop { if let Some(offset) = pool.pop() { return offset; } - self.blocks_available.wait(&mut pool); + let timed_out = self.blocks_available.wait_for(&mut pool, std::time::Duration::from_secs(30)).timed_out(); + if timed_out { + log::warn!("Waiting for free cache block for >30s, possible deadlock or cache exhaustion"); + } } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/disk_cache/controller.rs` around lines 239 - 247, The pop_unused_block method blocks indefinitely on blocks_available.wait; change it to use wait_timeout (on the same Condvar) and return a Result<BlockOffset, TimeoutError> or Option<BlockOffset> instead of unconditionally returning a BlockOffset, so callers can handle timeouts; inside pop_unused_block (and around unused_blocks and blocks_available) implement a reasonable timeout duration, log a diagnostic/warning when the timeout expires (including current pool length and whether blocks are pinned), and if timeout repeats return an explicit error or None rather than looping forever so callers can surface the failure or attempt recovery.
155-161: Borrowed slice may outlive cache entry (use-after-free risk).The
TODOcomment acknowledges this: the returnedCow::Borrowedslice references mmap data, but the block can be evicted while the borrow is still held. Sinceis_pinnedalways returnsfalse, nothing prevents eviction. This is a latent safety issue that should be tracked.Would you like me to open an issue to track implementing block pinning for safe borrowed returns?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/disk_cache/controller.rs` around lines 155 - 161, The returned Cow::Borrowed created from self.cache_mmap can outlive the cache entry and be used after the block is evicted because is_pinned always returns false; fix by ensuring borrowed views cannot outlive eviction—either copy the data into an owned buffer before returning (return Cow::Owned with a Vec<u8> constructed from the mmap slice in the function that currently returns Cow::Borrowed) or implement block pinning so that is_pinned reflects an active borrow; update the code paths around cache_mmap, the function that constructs the slice, and any eviction logic to honor pinning (refer to cache_mmap, Cow::Borrowed, is_pinned) so borrowed slices are safe.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/common/common/src/disk_cache/cached_slice.rs`:
- Around line 65-68: The call to controller.get_from_cache currently uses
.expect(...) which panics; change the cached_slice::get_range function to return
a Result (e.g., Result<Cow<'_, [T]>, YourErrorType>) and propagate errors from
controller.get_from_cache using the ? operator instead of expect; update the
function signature of get_range and any other methods that call it to
accept/return the Result, pick or define an appropriate error type (or convert
controller errors into the module's error enum), and replace the other expect
calls (the ones around lines 84–88) with ? propagation as well so cache I/O
errors bubble to callers for handling.
- Line 139: The assignment to BlockOffset currently casts block_offset to u32
with a plain as, which can silently truncate for very large files; update the
construction of BlockOffset(block_offset as u32) to perform a checked conversion
(e.g. use u32::try_from(block_offset).map_err/expect or an explicit assert) and
handle or propagate the error if block_offset exceeds u32::MAX so overflow
cannot silently occur; locate this change where BlockOffset is constructed from
the block_offset variable in cached_slice.rs and ensure callers/signatures
reflect any propagated error if you choose to return a Result.
- Around line 131-134: The code computes last_block and trailing_offset using
bytes_range.end - 1 which underflows for an empty range; update the logic in the
function handling bytes_range (references: bytes_range, first_block, last_block,
leading_offset, trailing_offset, BLOCK_SIZE) to guard against empty
ranges—either add a precondition like debug_assert!(!bytes_range.is_empty()) if
empty ranges are invalid, or handle emptiness explicitly by early-returning or
setting block/offset values appropriately before performing bytes_range.end - 1
to avoid underflow.
In `@lib/common/common/src/disk_cache/controller.rs`:
- Around line 73-75: The code silently truncates when casting size_blocks to u32
in the initialization of unused_blocks ((0..size_blocks as
u32).rev().map(BlockOffset).collect()), which can wrap BlockOffset values if
size_blocks > u32::MAX; add an explicit validation using try_into() or an if
check against u32::MAX to return an error (or panic) when size_blocks exceeds
u32::MAX, or change the BlockOffset and related logic to accept a larger integer
type; locate the initialization of unused_blocks and the use of BlockOffset to
implement the check or type change and ensure any callers that rely on u32-sized
block counts are updated accordingly.
- Around line 174-178: The current read path in controller.rs uses
file.read_at(...) which can return a short read without error and then copies
the full BLOCK_SIZE buffer into the mmap, risking silently corrupted cached
data; replace this by either (A) calling file.read_exact_at(&mut buf,
key.offset.bytes() as u64) unconditionally and explicitly handling
io::ErrorKind::UnexpectedEof to treat a partial final block (fill remaining
bytes with zeros or only copy the actual bytes), or (B) keep read_at but check
its returned usize n and only copy n bytes from buf into the mmap (leave the
rest zeroed); update the logic around range.len(), BLOCK_SIZE, buf, file.read_at
/ read_exact_at, and the mmap write so partial reads are detected and handled
rather than silently trusted.
- Around line 115-120: The fcntl call on macOS currently ignores its return
value; update the unsafe block that calls nix::libc::fcntl(f.as_raw_fd(),
nix::libc::F_NOCACHE, 1) to check the return value for -1 and handle errors
(e.g., convert errno to a rust error via std::io::Error::last_os_error() or
nix::errno::Errno and either log the failure or return Err from the surrounding
function). Ensure you reference the same call site (use of AsRawFd,
f.as_raw_fd(), nix::libc::fcntl, and nix::libc::F_NOCACHE) and make the function
propagate or report the error instead of silently ignoring it so failures to set
F_NOCACHE are detected.
- Line 122: The cast of f.metadata()?.len() to usize in open_file is unsafe on
32-bit targets and can silently truncate; update open_file to handle file length
safely by using u64-to-usize conversion with an explicit bounds check (e.g., use
usize::try_from or u64::try_into and return a clear error if it fails) or decide
to change the open_file API to return u64 instead of usize; modify the code
around the let len = ... expression to perform the conversion with
try_into()/try_from and propagate a descriptive error if the value does not fit
into usize (or change the function signature and related callers to use u64
consistently).
In `@lib/common/common/src/universal_io/disk_cached.rs`:
- Around line 84-90: The two methods populate() and clear_ram_cache() currently
call todo!() which panics; replace those panics with real behavior — either
implement the intended disk-cache logic (e.g., warm the cache/mmap pages or call
madvise/fadvise on the backing file) or, as an immediate safe stub, return
Ok(()) to satisfy the UniversalRead trait and avoid runtime panic; update the
bodies of the functions populate and clear_ram_cache in disk_cached.rs to return
crate::universal_io::Result<()> (Ok(())) or call the actual caching/madvise
helpers you have available so callers won’t hit todo!().
---
Nitpick comments:
In `@lib/common/common/src/disk_cache/controller.rs`:
- Around line 239-247: The pop_unused_block method blocks indefinitely on
blocks_available.wait; change it to use wait_timeout (on the same Condvar) and
return a Result<BlockOffset, TimeoutError> or Option<BlockOffset> instead of
unconditionally returning a BlockOffset, so callers can handle timeouts; inside
pop_unused_block (and around unused_blocks and blocks_available) implement a
reasonable timeout duration, log a diagnostic/warning when the timeout expires
(including current pool length and whether blocks are pinned), and if timeout
repeats return an explicit error or None rather than looping forever so callers
can surface the failure or attempt recovery.
- Around line 155-161: The returned Cow::Borrowed created from self.cache_mmap
can outlive the cache entry and be used after the block is evicted because
is_pinned always returns false; fix by ensuring borrowed views cannot outlive
eviction—either copy the data into an owned buffer before returning (return
Cow::Owned with a Vec<u8> constructed from the mmap slice in the function that
currently returns Cow::Borrowed) or implement block pinning so that is_pinned
reflects an active borrow; update the code paths around cache_mmap, the function
that constructs the slice, and any eviction logic to honor pinning (refer to
cache_mmap, Cow::Borrowed, is_pinned) so borrowed slices are safe.
In `@lib/common/common/src/disk_cache/tests.rs`:
- Around line 95-99: The unsafe raw pointer conversion in write_vectors_to_file
should be replaced with bytemuck to safely cast &[f32] to &[u8]; import
bytemuck::cast_slice and call cast_slice(data) to get a &[u8] and pass that to
fs::write, and ensure the bytemuck crate is added to Cargo.toml if not present;
update the write_vectors_to_file function to use cast_slice(data) instead of the
unsafe std::slice::from_raw_parts.
- Around line 11-45: The test_cacher currently only prints outputs; replace or
supplement the eprintln! calls with assertions that validate the decoded slices
returned by CachedSlice::<u8>::get_range (use fancy_decode on each get_range
result) against the expected string contents for the created test file (created
by create_test_file). Specifically, assert the values for the ranges used
(BLOCK_SIZE * 3..BLOCK_SIZE * 3, BLOCK_SIZE * 3 + 3..BLOCK_SIZE * 3 + 14,
BLOCK_SIZE * 3..BLOCK_SIZE * 4 - 1, BLOCK_SIZE * 3..BLOCK_SIZE * 4, BLOCK_SIZE *
3..BLOCK_SIZE * 4 + 1) using assert_eq! (or similar) so the test fails on
regressions while keeping the same setup that constructs CacheController::new
and opens the CachedSlice.
In `@lib/common/common/src/universal_io/disk_cached.rs`:
- Around line 44-52: OpenOptions.populate is currently ignored; update the open
path that calls CachedSlice::open(controller, path.as_ref()) to honor populate:
if options.populate == Some(true) pre-warm the cache by reading/prefetching the
file's blocks into the disk-cache (e.g., call the controller/CachedSlice
prefetch/populate API or read ranges after opening), otherwise leave behavior
unchanged; ensure you reference OpenOptions.populate, CachedSlice::open and
controller/path when implementing the prefetch so callers with populate:
Some(true) get an eager-warmed cache (or alternatively add clear documentation
on lack of support if prefetching isn’t feasible).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: feede4db-6395-403d-98fa-a3eedb68f5f2
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (9)
lib/common/common/Cargo.tomllib/common/common/src/disk_cache/cached_slice.rslib/common/common/src/disk_cache/controller.rslib/common/common/src/disk_cache/mod.rslib/common/common/src/disk_cache/tests.rslib/common/common/src/lib.rslib/common/common/src/universal_io/disk_cached.rslib/common/common/src/universal_io/mod.rslib/segment/src/common/operation_error.rs
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/common/common/src/disk_cache/controller.rs`:
- Around line 131-145: The current FileId increment uses
checked_add(...).unwrap_or_else(|| unimplemented!(...)) which panics on
overflow; replace this panic path with returning a proper error (e.g.,
Err(std::io::Error::new(io::ErrorKind::Other, "file id overflow"))) instead of
calling unimplemented!, so the function that creates file_id returns a
Result<FileId, io::Error> (or your crate's error type) and callers
propagate/handle it; update the block around self.file_id_counter.lock() and the
FileId(...) construction to map the checked_add None case into that error, and
update callsites to handle the Result accordingly.
In `@lib/common/common/src/disk_cache/tests.rs`:
- Around line 21-24: The test prints an empty slice because it calls
fd.get_range(BLOCK_SIZE * 3..BLOCK_SIZE * 3) (an empty range) likely due to
copy/paste; change the range to actually read bytes (e.g., BLOCK_SIZE *
3..BLOCK_SIZE * 4 or BLOCK_SIZE * 3..BLOCK_SIZE * 3 + N) so get_range on fd
returns the intended data, and update the corresponding fancy_decode call and
any expected test assertions to match the new non-empty slice.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 82f5c3cd-229e-429a-8f65-2f06fdb204ac
📒 Files selected for processing (3)
lib/common/common/src/disk_cache/cached_slice.rslib/common/common/src/disk_cache/controller.rslib/common/common/src/disk_cache/tests.rs
42b5be3 to
625aa8e
Compare
| #[derive(Debug)] | ||
| pub struct CacheController { | ||
| /// Mapping from the assigned file id, to its file descriptor | ||
| files: RwLock<HashMap<FileId, fs::File>>, |
There was a problem hiding this comment.
ToDo: map to universal IO reference?
|
|
||
| // TODO: Pin the block_id, track the lifetime of the borrow, | ||
| // then release the block_id when the borrow ends | ||
| let slice = unsafe { |
There was a problem hiding this comment.
consider callback to avoid data-race problem?
There was a problem hiding this comment.
Using a callback only makes sense if we have this callback usage all the way into interface, but we will lose the ability to return a slice when possible (e.g. for non-batched interface).
| mut callback: impl FnMut(usize, &[T]) -> crate::universal_io::Result<()>, | ||
| ) -> crate::universal_io::Result<()> { | ||
| for (i, range) in ranges.into_iter().enumerate() { | ||
| let data = self.read::<SEQUENTIAL>(range)?; |
There was a problem hiding this comment.
we want self.get_range_batch for this case, otherwise cold latency will be terrible
There was a problem hiding this comment.
I propose to do this once we add the support for io-uring for slow disk
UniversalReadUniversalRead for local disk cache
- log warning if long wait - Option for RequestState - clippy
| /// reference into the mmap. Otherwise, it will allocate a `Vec<T>` and copy | ||
| /// block data into it. Allocating as `Vec<T>` (rather than `Vec<u8>`) | ||
| /// guarantees correct alignment for any `T`. | ||
| pub fn get_range(&self, range: Range<usize>) -> io::Result<Cow<'_, [T]>> { |
There was a problem hiding this comment.
I think later we'd need to replace Range<usize> with ReadRange. Maybe after #8493.
There was a problem hiding this comment.
Yes, and will probably need a rename to DiskCached or smth
* checkout from `ssd-cache-wip` * impl UniversalRead for CachedFile * use `CachedSlice` for `UniversalRead` implementation * block exhaustion test * fix block exhaustion error * fix alignment on owned path * merge CachedFile into CachedSlice * propagate io errors * self-review - log warning if long wait - Option for RequestState - clippy * handle coderabbit's comments * fix num read bytes check * don't allocate twice for cache misses * not for windows, sorry * no more dead code * use atomic for file id * update cache controller description * rebase fixes * Self: Sized * Use imports * Remove with_global (unused) * Add TODO * move common::disk_cache -> universal_io::disk_cache --------- Co-authored-by: xzfc <[email protected]>
* checkout from `ssd-cache-wip` * impl UniversalRead for CachedFile * use `CachedSlice` for `UniversalRead` implementation * block exhaustion test * fix block exhaustion error * fix alignment on owned path * merge CachedFile into CachedSlice * propagate io errors * self-review - log warning if long wait - Option for RequestState - clippy * handle coderabbit's comments * fix num read bytes check * don't allocate twice for cache misses * not for windows, sorry * no more dead code * use atomic for file id * update cache controller description * rebase fixes * Self: Sized * Use imports * Remove with_global (unused) * Add TODO * move common::disk_cache -> universal_io::disk_cache --------- Co-authored-by: xzfc <[email protected]>
Takes #8109, but removes the WIP integration. Instead it implements
UniversalReadfor it.TODO
CachedSliceimplUniversalReadFuture work
CachedSlice#8462UniversalReadfor slow disk #8467