Skip to content

Introduce simple disk cache - #8792

Merged
coszio merged 7 commits into
devfrom
on-demand-file
May 19, 2026
Merged

coszio merged 7 commits into
devfrom
on-demand-file

Conversation

@coszio

@coszio coszio commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

As a simpler alternative to CachedSlice, which can work when the local disk is smaller than the remote disk, this PR introduces simple_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 ReadPipeline trait, and every read is funneled through this.

There are a few limitations, that can be addressed later:

  • The local file is hardcoded to be mmap, but we may want to use universal io there too. Not easy since we need to be able to write to it under & ref, so MmapRaw makes it easier without a lock.
  • The bitmask lives entirely in memory, we cannot reuse anything on restart.

@coszio
coszio requested a review from xzfc April 24, 2026 22:45
coderabbitai[bot]

This comment was marked as outdated.

@coszio
coszio marked this pull request as draft April 27, 2026 13:59
@coszio coszio changed the title Introduce OnDemandFile Introduce simple disk cache Apr 27, 2026
@coszio coszio mentioned this pull request Apr 27, 2026
@coszio
coszio changed the base branch from dev to proper-odirect-uring April 29, 2026 15:50
@qdrant qdrant deleted a comment from coderabbitai Bot Apr 30, 2026
Base automatically changed from proper-odirect-uring to dev May 5, 2026 15:07
@coszio
coszio force-pushed the on-demand-file branch 2 times, most recently from 195f20c to 149e31d Compare May 5, 2026 15:59
@coszio
coszio marked this pull request as ready for review May 5, 2026 16:18
@coszio
coszio requested a review from xzfc May 5, 2026 16:18
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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 duplicate and roaring.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~65 minutes

Possibly related PRs

  • qdrant/qdrant#8894: DiskCachePipeline implementation directly depends on and exercises the UniversalRead and UniversalReadPipeline trait contracts being defined.
  • qdrant/qdrant#8850: UniversalReadPipeline trait signature and semantics changes directly affect the DiskCachePipeline implementation in this PR.
  • qdrant/qdrant#8961: Changes to UniversalRead/trait bounds interact with DiskCachePipeline's generic constraints and usage.

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Introduce simple disk cache' directly describes the main change: adding a new DiskCache implementation to the simple_disk_cache module.
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.
Description check ✅ Passed The PR description clearly explains the purpose (simpler disk cache alternative), implementation approach (lazy-initialized mmap with in-memory block bitmask), and limitations for future work.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch on-demand-file

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: 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_bytes fabricates 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; meanwhile write_mmap_bytes mutates other regions of that same mapping concurrently (only the fetched lock 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 just byte_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_range silently truncates files larger than ~64 TiB.

The casts as u32 will wrap silently if range.end / BLOCK_SIZE exceeds u32::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 (fetched would record bogus blocks). A debug_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 lift

Doc warns about single-instance requirement but nothing enforces it.

The WARN block calls out that multiple DiskCache instances per path will not share an mmap and can cause UB, yet open_with_config does no registration / dedup. With OpenOptions paths flowing in from many call sites, this is easy to violate accidentally (especially since the global DiskCacheConfig makes DiskCache::open ambient). 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::open doc 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 of size_of::<T>().

bytes_len / t_size as u64 rounds down, so a partial trailing element is invisible to callers. If a DiskCache<R> is opened with a T that doesn't evenly divide the remote length (e.g., misaligned schema, reading a small header file as u32), the missing tail will go unnoticed. Either validate alignment at open time (bytes_len % t_size == 0) or debug_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_bytes re-checks contains_range but doesn't validate bytes.len() matches under contention.

The assert! at line 75 enforces bytes.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 early contains_range return — good. But the assertion runs after the early return only when contains_range is false, and it's a hard assert! (not debug_assert!). A caller bug or remote returning short bytes will abort the process rather than surface as UniversalIoError. Consider returning an error or downgrading to debug_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 win

Tests will not exercise the cache hit path on the second read.

Both basic_read_returns_remote_bytes and populate_fetches_every_block only verify the contents returned, not that the second access avoids the remote. Consider using a counting/wrapping R (or asserting local.fetched directly) to assert that subsequent reads of the same range hit the local mmap path in DiskCachePipeline::schedule (the contains_range short-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 value

Generated test modules end up nested as tests::tests_mmap / tests::tests_uring.

The outer file is already included via #[cfg(test)] mod tests; from simple_disk_cache::mod.rs, and duplicate_item then generates inner mod 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 the duplicate_item directly 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 value

Slot-not-found should be unreachable, not an io::Error.

The slot id is produced by Slab::insert in schedule and 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 as io::Error::other("file slot not found") makes diagnosis harder and obscures the true class of bug. Prefer unreachable! (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 drains result first 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. Because Meta distinguishes the calls this is functionally correct, but it makes scheduling order ≠ completion order in a non-obvious way. Worth a brief doc note on wait() 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 value

Combine SAFETY rationale with each unsafe call.

Two distinct unsafe operations (write_mmap_bytes and read_mmap_bytes) live inside a single unsafe { … } block with no SAFETY comment explaining why each is sound here. Each unsafe call has different invariants — write requires the byte slice covers the full block range, read requires the bytes were populated and within bounds. Consider splitting into two separate unsafe blocks, 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_global panics on second call — consider returning a Result.

The current expect on GLOBAL.set(cfg) will abort the process if any caller (or test) accidentally invokes initialize_global twice. Since the construction step is also fallible, returning Result<(), UniversalIoError> (or Result<&'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 value

Misleading NotFound mapping for paths outside remote_dir.

When strip_prefix fails the path actually exists (canonicalize succeeded) but is simply outside the configured remote_dir. Returning UniversalIoError::NotFound for 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_range panics on overflow rather than surfacing an error.

Both checked_mul and checked_add paths use expect, which means malformed callers (or arithmetic that exceeds u64::MAX) abort the process instead of returning a UniversalIoError. Since the surrounding code already returns Result everywhere, prefer propagating an error here too — for example a dedicated overflow variant or reusing OutOfBounds. Also, the second expect message 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

📥 Commits

Reviewing files that changed from the base of the PR and between 646b459 and ff176ef.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • lib/common/common/Cargo.toml
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/simple_disk_cache/config.rs
  • lib/common/common/src/universal_io/simple_disk_cache/file.rs
  • lib/common/common/src/universal_io/simple_disk_cache/mod.rs
  • lib/common/common/src/universal_io/simple_disk_cache/pipeline.rs
  • lib/common/common/src/universal_io/simple_disk_cache/tests.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/common/common/Cargo.toml

coderabbitai[bot]

This comment was marked as low quality.


fn can_schedule(&mut self) -> bool {
self.result.is_none()
&& self

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.

sanity check: this can actually be OR instead of AND, right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@coszio

coszio commented May 19, 2026

Copy link
Copy Markdown
Contributor Author

Heads up: I am merging this without mod simple_disk_cache; statement, so it won't even be checked by compiler. However, it will make review of next changes (cache prefilling) easier.

@coszio
coszio merged commit 9e32c94 into dev May 19, 2026
15 checks passed
@coszio
coszio deleted the on-demand-file branch May 19, 2026 17:11
generall added a commit that referenced this pull request May 22, 2026
* [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]>
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