Repository navigation
UniversalReadPipeline - #8798
Conversation
5d744d7 to
479b82a
Compare
This comment was marked as resolved.
This comment was marked as resolved.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
lib/segment/src/common/operation_error.rs (1)
159-167: Considerservice_error_lightforQueueIsFullto avoid backtrace cost.
service_errorcallsBacktrace::force_capture()(line 87), which is expensive on Linux.QueueIsFullis expected to fire on hot backpressure paths, so paying for a captured backtrace on every occurrence is wasteful and skews flame graphs. The same likely applies toUninitialized, which represents a misconfiguration rather than a runtime invariant violation worthy of a backtrace.♻️ Proposed split
UniversalIoError::BytemuckCast(_) | UniversalIoError::ZerocopySize(_) | UniversalIoError::IoUringNotSupported(_) | UniversalIoError::NotFound { .. } | UniversalIoError::OutOfBounds { .. } - | UniversalIoError::InvalidFileIndex { .. } - | UniversalIoError::Uninitialized { .. } - | UniversalIoError::QueueIsFull => Self::service_error(err.to_string()), + | UniversalIoError::InvalidFileIndex { .. } => Self::service_error(err.to_string()), + + UniversalIoError::Uninitialized { .. } | UniversalIoError::QueueIsFull => { + Self::service_error_light(err.to_string()) + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/common/operation_error.rs` around lines 159 - 167, The match arm currently maps UniversalIoError::QueueIsFull (and possibly UniversalIoError::Uninitialized) to Self::service_error(err.to_string()), which forces a Backtrace capture; change these to use Self::service_error_light(err.to_string()) for QueueIsFull (and consider Uninitialized) so hot backpressure/misconfiguration paths don't pay the backtrace cost—locate the match handling UniversalIoError in operation_error.rs and replace QueueIsFull (and optionally Uninitialized) branch targets from service_error(...) to service_error_light(...), leaving other error variants mapped to service_error(...) unchanged.lib/common/common/src/universal_io/disk_cache/mod.rs (1)
125-151: Note:P: AccessPatternis silently ignored — fixed toRandom.The associated type
DiskCacheReadPipeline<'a, T, Meta>does not propagate theP: AccessPatternparameter fromUniversalRead::ReadPipeline<'a, P, Meta>to the underlying read; line 144 always usesfile.read::<Random>(range). This is fine for a small in-memory cache layer, but it means callers who build the pipeline throughread_batch::<Sequential, _>(or any otherP) won't get the access-pattern behavior they asked for.If the disk cache is ever extended with prefetch/readahead heuristics, you'll want to thread
Pthrough (e.g.DiskCacheReadPipeline<'a, T, P, Meta>carrying aPhantomData<P>and usingfile.read::<P>(range)). For now a brief comment documenting the intentional override would help future readers.🤖 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_cache/mod.rs` around lines 125 - 151, The code currently ignores the access-pattern type by hardcoding file.read::<Random>(range) in DiskCacheReadPipeline::schedule, so either thread the pattern through or explicitly document the override; to fix properly, add a generic P: AccessPattern to the DiskCacheReadPipeline definition (e.g., DiskCacheReadPipeline<'a, T, P, Meta>), store PhantomData<P> in the struct, update the impl to implement UniversalReadPipeline<'a, P, Meta> for DiskCacheReadPipeline<'a, T, P, Meta>, and replace file.read::<Random>(range) with file.read::<P>(range) in schedule so callers of read_batch::<Sequential, _> get the requested access pattern (alternatively, if intentional, add a concise comment next to the schedule implementation and the file.read::<Random> call explaining why Random is forced).lib/common/common/src/universal_io/io_uring/runtime.rs (1)
12-13: Tighten field visibility topub(super)(orpub(crate)).These fields only need to be reached from the sibling pipeline module in
io_uring/mod.rs. Exposing them as fullypubwidens the public API of thecommoncrate unnecessarily and makes future internal refactors harder.♻️ Proposed narrowing
pub struct IoUringRuntime<'data, T, Meta = u64> { - pub io_uring: IoUringGuard, - pub state: IoUringState<'data, T, Meta>, + pub(super) io_uring: IoUringGuard, + pub(super) state: IoUringState<'data, T, Meta>, pub in_progress: usize, }Note:
in_progress(alreadypub) likely deserves the same treatment if the same accessors are only needed by the pipeline.Based on learnings: "In the Qdrant codebase, using
pub(super)visibility is preferred when fields need to be accessed by sibling modules (particularly for index type conversions), as it provides the necessary access without bloating the interface with numerous getters." (timvisee, PR 6503).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/io_uring/runtime.rs` around lines 12 - 13, The two struct fields currently declared as `pub io_uring: IoUringGuard` and `pub state: IoUringState<'data, T, Meta>` should have their visibility narrowed to `pub(super)` (or `pub(crate)` if sibling module layout requires crate-level access) to avoid widening the public API; update the field declarations for `io_uring` and `state` accordingly and also evaluate `in_progress` (currently `pub`) and narrow it the same way if only accessed by the sibling pipeline module to keep the interface minimal.lib/common/common/src/universal_io/read.rs (1)
126-129: Document theOk(None)semantics onwait().The current doc only describes the "blocking until completed" path. Worth explicitly noting that
Ok(None)means there are no outstanding scheduled operations (which is what allows theread_multi_iterdriver to terminate the iterator).📝 Suggested doc
- /// Block until any of the scheduled operations is completed and consume its - /// result. + /// Block until any of the scheduled operations is completed and consume its + /// result. Returns `Ok(None)` when there are no outstanding scheduled + /// operations (i.e. nothing to wait for). fn wait(&mut self) -> Result<Option<(Meta, Cow<'a, [T]>)>>;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/read.rs` around lines 126 - 129, The docstring for the trait method wait (fn wait(&mut self) -> Result<Option<(Meta, Cow<'a, [T]>)>>) is missing the semantics for Ok(None); update the comment to explicitly state that Ok(None) indicates there are no outstanding scheduled operations (i.e., the scheduler is empty) and that callers such as the read_multi_iter driver should treat Ok(None) as the termination condition for the iterator. Mention that Ok(Some(...)) returns a completed operation's metadata and buffer and that Err(...) indicates an error.lib/common/common/src/universal_io/mmap.rs (1)
134-165: Synchronous "pipeline" — consider a brief doc comment.
MmapReadPipelineperforms the I/O synchronously insideschedule()(so read errors surface at schedule time, not atwait()). This is permitted by the trait contract but diverges from theIoUringPipelinebehavior, so a one-line doc on the type clarifying the semantics would help future readers (and anyone trying to compare error-timing across backends).📝 Suggested doc
+/// Mmap "pipeline": schedules at most one read at a time and performs +/// the read synchronously inside [`schedule`](Self::schedule). Read errors +/// are therefore reported by `schedule`, not by [`wait`](Self::wait). pub struct MmapReadPipeline<'a, T, P, Meta> { result: Option<(Meta, &'a [T])>, _phantom: PhantomData<P>, }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/mmap.rs` around lines 134 - 165, Add a one-line doc comment to the MmapReadPipeline type explaining that it performs reads synchronously inside schedule(), so read errors are returned at schedule time (not at wait()), and that this differs from async backends like IoUringPipeline; reference the struct name MmapReadPipeline and the methods schedule() and wait() in the comment so readers can quickly understand the differing error-timing semantics when comparing to implementations of the UniversalReadPipeline trait such as IoUringPipeline.lib/common/common/src/universal_io/io_uring/mod.rs (1)
137-182: Pipeline implementation looks correct.The
can_schedule/schedulepair correctly bounds the queue and the unsafepush().expect(...)is properly guarded by the explicit capacity check. One small observation onwait(): whencompletion_is_empty()isfalse, we return a completed entry without ever flushing entries staged insqueue. That isn't a correctness bug (the nextwait()with empty completion will submit), but it can leave staged entries unsubmitted longer than necessary when the previoussubmit_and_waitproduced multiple completions. Worth keeping in mind if you observe latency anomalies under steady-state load.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/universal_io/io_uring/mod.rs` around lines 137 - 182, The wait() path can return completed entries while leaving staged submission queue entries unflushed; update wait() so when completion_is_empty() is false you still flush any staged submissions before returning. Concretely, in UniversalReadPipeline::wait(), after checking completion_is_empty()/before returning a completed() entry, inspect self.runtime.io_uring.submission().len() (or equivalent) and if > 0 call the runtime method that submits staged entries (e.g., self.runtime.submit() or submit_and_wait(0) as appropriate) so staged entries are pushed to the kernel; keep the existing completed() return behavior otherwise.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/tonic/api/storage_read_api/helpers.rs`:
- Line 253: The mapping for UniversalIoError::QueueIsFull currently returns
Status::internal; change it to a retryable gRPC status such as
Status::resource_exhausted (or Status::unavailable) so the client sees this as
transient backpressure rather than an internal server error; update the match
arm handling UniversalIoError::QueueIsFull in the helper that produces
tonic::Status accordingly (replace Status::internal(e.to_string()) with
Status::resource_exhausted(e.to_string()) or
Status::unavailable(e.to_string())).
---
Nitpick comments:
In `@lib/common/common/src/universal_io/disk_cache/mod.rs`:
- Around line 125-151: The code currently ignores the access-pattern type by
hardcoding file.read::<Random>(range) in DiskCacheReadPipeline::schedule, so
either thread the pattern through or explicitly document the override; to fix
properly, add a generic P: AccessPattern to the DiskCacheReadPipeline definition
(e.g., DiskCacheReadPipeline<'a, T, P, Meta>), store PhantomData<P> in the
struct, update the impl to implement UniversalReadPipeline<'a, P, Meta> for
DiskCacheReadPipeline<'a, T, P, Meta>, and replace file.read::<Random>(range)
with file.read::<P>(range) in schedule so callers of read_batch::<Sequential, _>
get the requested access pattern (alternatively, if intentional, add a concise
comment next to the schedule implementation and the file.read::<Random> call
explaining why Random is forced).
In `@lib/common/common/src/universal_io/io_uring/mod.rs`:
- Around line 137-182: The wait() path can return completed entries while
leaving staged submission queue entries unflushed; update wait() so when
completion_is_empty() is false you still flush any staged submissions before
returning. Concretely, in UniversalReadPipeline::wait(), after checking
completion_is_empty()/before returning a completed() entry, inspect
self.runtime.io_uring.submission().len() (or equivalent) and if > 0 call the
runtime method that submits staged entries (e.g., self.runtime.submit() or
submit_and_wait(0) as appropriate) so staged entries are pushed to the kernel;
keep the existing completed() return behavior otherwise.
In `@lib/common/common/src/universal_io/io_uring/runtime.rs`:
- Around line 12-13: The two struct fields currently declared as `pub io_uring:
IoUringGuard` and `pub state: IoUringState<'data, T, Meta>` should have their
visibility narrowed to `pub(super)` (or `pub(crate)` if sibling module layout
requires crate-level access) to avoid widening the public API; update the field
declarations for `io_uring` and `state` accordingly and also evaluate
`in_progress` (currently `pub`) and narrow it the same way if only accessed by
the sibling pipeline module to keep the interface minimal.
In `@lib/common/common/src/universal_io/mmap.rs`:
- Around line 134-165: Add a one-line doc comment to the MmapReadPipeline type
explaining that it performs reads synchronously inside schedule(), so read
errors are returned at schedule time (not at wait()), and that this differs from
async backends like IoUringPipeline; reference the struct name MmapReadPipeline
and the methods schedule() and wait() in the comment so readers can quickly
understand the differing error-timing semantics when comparing to
implementations of the UniversalReadPipeline trait such as IoUringPipeline.
In `@lib/common/common/src/universal_io/read.rs`:
- Around line 126-129: The docstring for the trait method wait (fn wait(&mut
self) -> Result<Option<(Meta, Cow<'a, [T]>)>>) is missing the semantics for
Ok(None); update the comment to explicitly state that Ok(None) indicates there
are no outstanding scheduled operations (i.e., the scheduler is empty) and that
callers such as the read_multi_iter driver should treat Ok(None) as the
termination condition for the iterator. Mention that Ok(Some(...)) returns a
completed operation's metadata and buffer and that Err(...) indicates an error.
In `@lib/segment/src/common/operation_error.rs`:
- Around line 159-167: The match arm currently maps
UniversalIoError::QueueIsFull (and possibly UniversalIoError::Uninitialized) to
Self::service_error(err.to_string()), which forces a Backtrace capture; change
these to use Self::service_error_light(err.to_string()) for QueueIsFull (and
consider Uninitialized) so hot backpressure/misconfiguration paths don't pay the
backtrace cost—locate the match handling UniversalIoError in operation_error.rs
and replace QueueIsFull (and optionally Uninitialized) branch targets from
service_error(...) to service_error_light(...), leaving other error variants
mapped to service_error(...) unchanged.
🪄 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: d16fdaa6-6e89-4dd5-b50f-f78b951f0614
📒 Files selected for processing (14)
lib/common/common/src/universal_io/disk_cache/mod.rslib/common/common/src/universal_io/error.rslib/common/common/src/universal_io/io_uring/mod.rslib/common/common/src/universal_io/io_uring/read_iter.rslib/common/common/src/universal_io/io_uring/runtime.rslib/common/common/src/universal_io/mmap.rslib/common/common/src/universal_io/read.rslib/common/common/src/universal_io/wrappers/mod.rslib/common/common/src/universal_io/wrappers/read_only.rslib/common/common/src/universal_io/wrappers/typed.rslib/common/common/src/universal_io/wrappers/wrapped_pipeline.rslib/segment/src/common/operation_error.rslib/segment/src/index/field_index/numeric_index/tests.rssrc/tonic/api/storage_read_api/helpers.rs
💤 Files with no reviewable changes (1)
- lib/common/common/src/universal_io/io_uring/read_iter.rs
| fn read_batch<'a, P: AccessPattern, Meta: 'a>( | ||
| &'a self, | ||
| ranges: impl IntoIterator<Item = (Meta, ReadRange)>, | ||
| mut callback: impl FnMut(Meta, &[T]) -> Result<()>, | ||
| ) -> Result<()> { | ||
| let mmap = self.as_bytes::<P>(); | ||
|
|
||
| for (meta, range) in ranges { | ||
| let items = read(mmap, range)?; | ||
| callback(meta, items)?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| } |
There was a problem hiding this comment.
I think we can keep this custom impl. It would skip the Option from the pipeline.
There was a problem hiding this comment.
It will be optimized away anyway.
ffuugoo
left a comment
There was a problem hiding this comment.
This turned out waaaaaay nicer than I expected! Nice work!
| type ReadPipeline<'a, P: AccessPattern, Meta> | ||
| = WrappedReadPipeline<'a, T, S, P, Meta> | ||
| where | ||
| Self: 'a; |
There was a problem hiding this comment.
Can't we simply reuse S::ReadPipeline? 🤔
| type ReadPipeline<'a, P: AccessPattern, Meta> | |
| = WrappedReadPipeline<'a, T, S, P, Meta> | |
| where | |
| Self: 'a; | |
| type ReadPipeline<'a, P: AccessPattern, Meta> = S::ReadPipeline<'a, P, Meta> | |
| where | |
| Self: 'a; |
There was a problem hiding this comment.
ReadPipeline::schedule() wants outer file: &'a S, not inner file: &'a S::ReadPipeline<…>.
I didn't found any non-cursed way to get rid of WrappedReadPipeline.
There was a problem hiding this comment.
ReadPipeline::schedule()wants outerfile: &'a S...
Ah, yes, figured.
I didn't found any non-cursed way to get rid of WrappedReadPipeline
type File: UniversalRead<T> and declare as either type File = Self in native impls, or type File = Wrappee in wrappers? 🤔 Not 100% sure if it won't introduce more issues, though.
| type ReadPipeline<'a, P: AccessPattern, Meta> | ||
| = WrappedReadPipeline<'a, T, S, P, Meta> | ||
| where | ||
| Self: 'a; |
The previous commit removed `MmapFile::read_batch` method override. So,
`MmapFile` now re-uses the default `UniversalRead::read_batch` impl,
which is implemented using `UniversalReadPipeline` interface.
Unsurprisingly, it caused a slowdown in the benchmarks, particularly
this one:
cargo bench -p common --bench universal_io -- mmap/8bytes/read_batch_full
This commit reclaims the performance back.
* UniversalReadPipeline
* Performance: cache pointers in MmapFile
The previous commit removed `MmapFile::read_batch` method override. So,
`MmapFile` now re-uses the default `UniversalRead::read_batch` impl,
which is implemented using `UniversalReadPipeline` interface.
Unsurprisingly, it caused a slowdown in the benchmarks, particularly
this one:
cargo bench -p common --bench universal_io -- mmap/8bytes/read_batch_full
This commit reclaims the performance back.
* remove unfulfilled lint
* Review suggestions
---------
Co-authored-by: Luis Cossío <[email protected]>
Co-authored-by: Roman Titov <[email protected]>
This PR implements
io_uring-like interface forUniversalReadtraits. Basically, it allows callers to schedule reads, and wait for scheduled reads.Rationale
The current interator-based interface (e.g.
UniversalRead::read_iter) assumes two separate phases:Some callers might want to interleave decide/process actions. (e.g. graph traversals). The new
UniversalReadPipelineinterface allows such interleaving.Interface
Usage: call
can_schedule()first. If it istrue, you can callschedule().After that, call
wait().Default implementations for batch/iter methods
In this PR, all of the existing batch/iter methods (
read_batch,read_iter,read_multi,read_multi_iter) are implemented usingUniversalReadPipeline. I.e.IoUringFileandMmapFiledo not override these methods and implement onlyUniversalReadPipelinestuff.This is not necessary, but it works as a stress-test for the new implementation. If the Rust compiler can optimize away all these abstraction layers, then (I hope) the new
UniversalReadPipelineinterface is good enough for an arbitrary case.Benchmarks
The first commit made the performance of
MmapFileworse (why -- see previous section).The second commit adds an optimization that reclaims that performance back. (this optimization is not related to the new
UniversalReadPipelineinterface; but it matters when compiler inlines things)cargo bench -p common --bench universal_io -- --measurement-time 60(not in this PR) Better
scheduleinterfaceThe
can_schedule()+schedule()probably is not the safest interface as it's easy to misuse: the caller can callschedule()even when the buffer is not available. Maybe later we can replace it with an interface that can prevent it. Some potential alternatives:But for now I'd prefer to stick to
can_schedule(): boolas it's the simplest option.