Skip to content

Move element type from UniversalRead trait to method generics - #8955

Merged
generall merged 4 commits into
devfrom
uio-method-level-generic
May 8, 2026
Merged

generall merged 4 commits into
devfrom
uio-method-level-generic

Conversation

@generall

@generall generall commented May 8, 2026 •

Copy link
Copy Markdown
Member

Move generic from trait into method in Universal IO

Motivation

Currently, we have trait UniversalRead<T>, which has generic param T that devines what type of structures we can read from file.

Knowing T we can properly allign in memory structures we read, especially in io_uring implementation of UniversalRead.

There is, however a problem in practice, that many structures expect different types stored in the same file.
As a result we had to use UniversalRead in a strange ways, like for examples S: UniversalRead<u8> + UniversalRead<u32>, which forces us to use turbo-fish and is overall inconvenient and ugly.

Proposal

Instead of using trait parameter T, move the parameter to the method level.

For example:

fn read<P: AccessPattern>(&self, range: ReadRange) -> Result<Cow<'_, [T]>>;

would become:

fn read<P: AccessPattern, T>(&self, range: ReadRange) -> Result<Cow<'_, [T]>>;

This way we can entirely avoid using trait parameters and use method generics instead.

Plan

Check the scope of refactoring and propose a plan.

If some components become obsolete after refactoring, include them in plan.

--- AI from here ---

Summary

  • Lifts T off trait UniversalRead<T> / UniversalWrite<T> and onto the read/write methods themselves; ReadPipeline becomes a GAT over T.
  • Callers reading several element types from one storage now write S: UniversalRead instead of stacking UniversalRead<u8> + UniversalRead<Counts> + ….
  • Deletes the workarounds the old shape required: TypedStorage<S, T>, UniversalReadFamily (HKT shim), the StoredGeoMapIndexStorage four-bound trait alias, and the <T> parameter on CachedSlice.

No runtime behavior change: alignment in IoUringRuntime and CachedSlice is preserved because T is still known at each call site.

Test plan

  • cargo check --workspace --tests --benches
  • cargo clippy --workspace --tests --benches -- -D warnings
  • cargo test -p common --lib universal_io — 17/17 (incl. direct-IO + EINTR alignment-sensitive cases)
  • cargo test -p segment --lib {numeric_index,geo_index,id_tracker,chunked,dense} — 26 + 40 + 37 + 4 + 33 pass
  • cargo test -p gridstore — 58 pass
  • cargo bench -p common --no-run

🤖 Generated with Claude Code

@generall
generall requested review from coszio and xzfc May 8, 2026 10:53
@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 94384992-42a0-4469-975d-1db11ef3c96b

📥 Commits

Reviewing files that changed from the base of the PR and between 7d51d65 and b3ca09d.

📒 Files selected for processing (1)
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs

📝 Walkthrough

Walkthrough

This PR moves element-type generics off UniversalRead/UniversalWrite into method-level generics (T: bytemuck::Pod), removes UniversalReadFamily, converts TypedStorage to inherent typed methods, updates backend impls (mmap, io_uring, disk_cache) to non-generic impls, and updates all callsites, tests, benchmarks, and API handlers to supply explicit T turbofish (e.g., read::<P, T>, len::, read_multi_iter::<P, T, _>).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • qdrant/qdrant#8894: Similar UniversalRead/UniversalWrite API-shape changes across backends and pipelines.
  • qdrant/qdrant#8915: Changes to chunked_vectors read/chunks APIs that align with TypedStorage/read signature updates.
  • qdrant/qdrant#8685: Overlapping modifications to universal_io trait/impl surface and backend implementations.

Suggested labels

release:1.18.0

Suggested reviewers

  • ffuugoo
  • xzfc
  • coszio
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main refactoring: moving the element type generic parameter from UniversalRead/UniversalWrite traits to method-level generics, which is the core change throughout the 38-file changeset.
Description check ✅ Passed The description provides comprehensive context for the refactoring: motivation (avoiding stacked bounds like UniversalRead + UniversalRead), the proposal (move T to method level), implementation summary, and test results confirming the changes compile and pass.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch uio-method-level-generic

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.

🧹 Nitpick comments (1)
lib/common/common/src/stored_bitslice.rs (1)

1-6: 💤 Low value

Outdated doc comment references old trait syntax.

The module doc references UniversalRead<u64> and UniversalWrite<u64>, but after this refactor these traits are no longer generic. Consider updating to reflect the new API.

📝 Suggested doc update
-//! Storage-agnostic bitslice backed by any [`UniversalRead<u64>`] /
-//! [`UniversalWrite<u64>`] backend.
+//! Storage-agnostic bitslice backed by any [`UniversalRead`] /
+//! [`UniversalWrite`] backend.

Similarly for the struct doc at lines 32-33.

🤖 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/stored_bitslice.rs` around lines 1 - 6, Update the
module and struct docs to use the current, non-generic trait names instead of
the old generic `UniversalRead<u64>` and `UniversalWrite<u64>` references:
change occurrences mentioning `UniversalRead<u64>` and `UniversalWrite<u64>` to
`UniversalRead` and `UniversalWrite`, and ensure the `BitSliceStorage` doc
comment describes that it wraps any `UniversalRead` / `UniversalWrite` backend
(no generic parameter). Keep wording consistent wherever those traits are
documented in this file.
🤖 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.

Nitpick comments:
In `@lib/common/common/src/stored_bitslice.rs`:
- Around line 1-6: Update the module and struct docs to use the current,
non-generic trait names instead of the old generic `UniversalRead<u64>` and
`UniversalWrite<u64>` references: change occurrences mentioning
`UniversalRead<u64>` and `UniversalWrite<u64>` to `UniversalRead` and
`UniversalWrite`, and ensure the `BitSliceStorage` doc comment describes that it
wraps any `UniversalRead` / `UniversalWrite` backend (no generic parameter).
Keep wording consistent wherever those traits are documented in this file.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7bf9d1e2-4f0d-491f-9812-2a880f7c58cc

📥 Commits

Reviewing files that changed from the base of the PR and between edde26e and e63e7bf.

📒 Files selected for processing (42)
  • lib/common/common/benches/universal_io.rs
  • lib/common/common/src/stored_bitslice.rs
  • lib/common/common/src/universal_io/disk_cache/cached_slice.rs
  • lib/common/common/src/universal_io/disk_cache/mod.rs
  • lib/common/common/src/universal_io/disk_cache/tests.rs
  • lib/common/common/src/universal_io/family.rs
  • lib/common/common/src/universal_io/io_uring/mod.rs
  • lib/common/common/src/universal_io/io_uring/tests.rs
  • lib/common/common/src/universal_io/mmap.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/read.rs
  • lib/common/common/src/universal_io/wrappers/buffered_update.rs
  • lib/common/common/src/universal_io/wrappers/mod.rs
  • lib/common/common/src/universal_io/wrappers/read_only.rs
  • lib/common/common/src/universal_io/wrappers/stored_struct.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/common/common/src/universal_io/wrappers/wrapped_pipeline.rs
  • lib/common/common/src/universal_io/write.rs
  • lib/gridstore/src/bitmask/gaps.rs
  • lib/gridstore/src/bitmask/mod.rs
  • lib/gridstore/src/gridstore/view.rs
  • lib/gridstore/src/pages.rs
  • lib/gridstore/src/tracker.rs
  • lib/segment/src/common/buffered_update_bitslice.rs
  • lib/segment/src/common/flags/dynamic_stored_flags.rs
  • lib/segment/src/id_tracker/immutable_id_tracker/mod.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/uio_postings.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rs
  • lib/segment/src/index/field_index/stored_point_to_values.rs
  • lib/segment/src/vector_storage/chunked_vectors/chunks.rs
  • lib/segment/src/vector_storage/chunked_vectors/read.rs
  • lib/segment/src/vector_storage/chunked_vectors/write.rs
  • lib/segment/src/vector_storage/dense/dense_vector_storage.rs
  • lib/segment/src/vector_storage/dense/immutable_dense_vectors.rs
  • lib/segment/src/vector_storage/dense/read_only/chucked_vector_storage.rs
  • lib/segment/src/vector_storage/multi_dense/appendable_mmap_multi_dense_vector_storage.rs
  • lib/segment/src/vector_storage/multi_dense/read_only/chunked_vector_storage.rs
  • lib/segment/src/vector_storage/read_only/mod.rs
  • src/tonic/api/storage_read_api/helpers.rs
  • src/tonic/api/storage_read_api/mod.rs
💤 Files with no reviewable changes (3)
  • lib/common/common/src/universal_io/wrappers/mod.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/common/common/src/universal_io/family.rs

Comment on lines +35 to +36
pub trait BitmaskStorage: UniversalWrite {}
impl<T> BitmaskStorage for T where T: UniversalWrite {}

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.

We don't need this trait now.

Suggested change
pub trait BitmaskStorage: UniversalWrite {}
impl<T> BitmaskStorage for T where T: UniversalWrite {}

Comment on lines -24 to -40
pub struct TypedStorage<S, T> {
pub inner: S,
_phantom: PhantomData<T>,
}

impl<S, T> TypedStorage<S, T> {
/// Approximate RAM usage in bytes. IO-backed storage has no significant
/// heap allocations; on-disk data is accounted via `files()`.
pub fn ram_usage_bytes(&self) -> usize {
0
}
}

impl<S, T> UniversalReadFileOps for TypedStorage<S, T>
where
S: UniversalReadFileOps,
{

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.

I'd keep TypedStorage<T>, but make it a 'generic structure' with 'non-generic methods' without implementing UniversalRead trait.

Like here: a76870eb9454#diff-28f9341127cf44ad2ea45a529c522cfcd043f00826820440387a45105fc1b458 (another commit that implements the same idea as this PR)

Why: to specify the type once, not at every .read() callsite.


Some ideas: it should be able to wrap both owned and non-owned UniversalRead implementations. E.g.

// to temporarily "lock" the type within local scope
let by_ref = TypedStorage::<&MmapFile, u32>(&file);
// to store in structures
let owned = TypedStorage::<MmapFile, u32>(file);

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.

it should be able to wrap both owned and non-owned UniversalRead implementations

impl<T: UniversalRead> UniversalRead for &T { ... }?

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.

I'd vote to keep too

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.

impl<T: UniversalRead> UniversalRead for &T { ... }?

Yep, like so.

Comment on lines +31 to +32
pub trait UioDynamicFlags: UniversalWrite + Send + 'static {}
impl<T> UioDynamicFlags for T where T: UniversalWrite + Send + 'static {}

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.

Probably we don't need this too (akin to BitmaskStorage).

counts_per_hash.ram_usage_bytes()
+ points_map.ram_usage_bytes()
+ points_map_ids.ram_usage_bytes()
+ point_to_values.ram_usage_bytes()

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.

Are these changes related to this PR?

(same question to let _ = pairs; // io-backed: no significant heap allocations below)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Unlike TypedStorage, UniversalRead doesn't have ram_usage_bytes, but TypedStorage hard-coded 0 as RAM usage, so this change is technically correct

Lifts the `T` parameter off `trait UniversalRead<T>` (and the matching
`UniversalWrite<T>`) and onto the read/write methods themselves. The
`ReadPipeline` associated type becomes a GAT over `T`. With per-method
generics, callers that need to read several element types from one storage
just write `S: UniversalRead` instead of stacking
`UniversalRead<u8> + UniversalRead<Counts> + ...`.

Removes the workarounds the old shape required:
- `TypedStorage<S, T>` newtype (sole purpose was disambiguating multi-bounds)
- `UniversalReadFamily` HKT shim
- `StoredGeoMapIndexStorage` four-bound trait alias
- `CachedSlice<T>` is now non-generic; `T` moves to `get_range`/`len`

No runtime behavior change: alignment in `IoUringRuntime` and `CachedSlice`
is preserved because `T` is still known at each call site.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@generall
generall force-pushed the uio-method-level-generic branch from e63e7bf to cde0a6f Compare May 8, 2026 12:35
Comment on lines -24 to -40
pub struct TypedStorage<S, T> {
pub inner: S,
_phantom: PhantomData<T>,
}

impl<S, T> TypedStorage<S, T> {
/// Approximate RAM usage in bytes. IO-backed storage has no significant
/// heap allocations; on-disk data is accounted via `files()`.
pub fn ram_usage_bytes(&self) -> usize {
0
}
}

impl<S, T> UniversalReadFileOps for TypedStorage<S, T>
where
S: UniversalReadFileOps,
{

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.

I'd vote to keep too

let bytes = self.storage.read::<Random, u8>(ReadRange {
byte_offset: start_offset as u64,
length: std::mem::size_of::<Optional<ValuePointer>>() as u64,
})?;

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.

I guess this is refactor for another PR

generall and others added 3 commits May 8, 2026 15:13
Reintroduces `TypedStorage<S, T>` as a transparent wrapper around
`UniversalRead`/`UniversalWrite` storage that fixes the element type to
`T`. With per-method generics on the underlying traits, callers can
otherwise read or write any `T` from the same handle; this wrapper
binds it at the type level so accidental cross-type access fails to
compile.

The wrapper exposes inherent typed methods (`read::<P>`, `read_iter`,
`write`, `len`, …) that delegate to the inner storage with `T` fixed.
It does not implement `UniversalRead`/`UniversalWrite` itself — those
are intentionally avoided to prevent the typed binding from being
bypassed via the generic trait methods.

Restores the wrapping at the previous call sites: `StoredStruct`'s
inner storage, `ImmutableIdTracker`'s version mmap, the geo and
numeric index storages, the chunked-vectors chunks, and the
immutable dense vector storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`TypedStorage::len` returns `Result<u64>` (a fallible byte length from
the underlying storage), so an `is_empty` companion would also be
fallible and offer nothing over `len()? == 0`. Suppress the lint at
the impl block, matching how the underlying `UniversalRead::len` is
already exempted.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
coderabbitai[bot]

This comment was marked as low quality.

@generall
generall merged commit 6424433 into dev May 8, 2026
15 checks passed
@generall
generall deleted the uio-method-level-generic branch May 8, 2026 15:37
coszio added a commit that referenced this pull request May 8, 2026
generall added a commit that referenced this pull request May 8, 2026
* derive bytemuck::Pod on `OptionalPointer`, get rid of legacy transmute

* remove one layer of Option in `get_raw`

* keep `UniversalRead<u8>` bound, do bytemuck conversion at call site (#8953)

Drop the `+ UniversalRead<OptionalPointer>` / `+ UniversalWrite<OptionalPointer>`
trait bounds added in the previous two commits. Reads and writes of
`OptionalPointer` and `TrackerHeader` now go through `bytemuck::from_bytes` /
`bytemuck::bytes_of` on the existing `u8` byte slices instead.

This keeps the unsafe-transmute removal but avoids the turbofish noise
(`UniversalWrite::<u8>::flusher(&self.storage)`, `<S as UniversalRead<u8>>::open`,
…) that two `T`s on `S` forced everywhere.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* extra refactoring after #8955

* explicit zeroed instantiation

---------

Co-authored-by: Andrey Vasnetsov <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced May 13, 2026
generall added a commit that referenced this pull request May 22, 2026
* Move element type from UniversalRead trait to method generics

Lifts the `T` parameter off `trait UniversalRead<T>` (and the matching
`UniversalWrite<T>`) and onto the read/write methods themselves. The
`ReadPipeline` associated type becomes a GAT over `T`. With per-method
generics, callers that need to read several element types from one storage
just write `S: UniversalRead` instead of stacking
`UniversalRead<u8> + UniversalRead<Counts> + ...`.

Removes the workarounds the old shape required:
- `TypedStorage<S, T>` newtype (sole purpose was disambiguating multi-bounds)
- `UniversalReadFamily` HKT shim
- `StoredGeoMapIndexStorage` four-bound trait alias
- `CachedSlice<T>` is now non-generic; `T` moves to `get_range`/`len`

No runtime behavior change: alignment in `IoUringRuntime` and `CachedSlice`
is preserved because `T` is still known at each call site.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Restore TypedStorage as a typed-access fail-safe

Reintroduces `TypedStorage<S, T>` as a transparent wrapper around
`UniversalRead`/`UniversalWrite` storage that fixes the element type to
`T`. With per-method generics on the underlying traits, callers can
otherwise read or write any `T` from the same handle; this wrapper
binds it at the type level so accidental cross-type access fails to
compile.

The wrapper exposes inherent typed methods (`read::<P>`, `read_iter`,
`write`, `len`, …) that delegate to the inner storage with `T` fixed.
It does not implement `UniversalRead`/`UniversalWrite` itself — those
are intentionally avoided to prevent the typed binding from being
bypassed via the generic trait methods.

Restores the wrapping at the previous call sites: `StoredStruct`'s
inner storage, `ImmutableIdTracker`'s version mmap, the geo and
numeric index storages, the chunked-vectors chunks, and the
immutable dense vector storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Silence clippy::len_without_is_empty on TypedStorage

`TypedStorage::len` returns `Result<u64>` (a fallible byte length from
the underlying storage), so an `is_empty` companion would also be
fallible and offer nothing over `len()? == 0`. Suppress the lint at
the impl block, matching how the underlying `UniversalRead::len` is
already exempted.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fmt

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
generall added a commit that referenced this pull request May 22, 2026
* derive bytemuck::Pod on `OptionalPointer`, get rid of legacy transmute

* remove one layer of Option in `get_raw`

* keep `UniversalRead<u8>` bound, do bytemuck conversion at call site (#8953)

Drop the `+ UniversalRead<OptionalPointer>` / `+ UniversalWrite<OptionalPointer>`
trait bounds added in the previous two commits. Reads and writes of
`OptionalPointer` and `TrackerHeader` now go through `bytemuck::from_bytes` /
`bytemuck::bytes_of` on the existing `u8` byte slices instead.

This keeps the unsafe-transmute removal but avoids the turbofish noise
(`UniversalWrite::<u8>::flusher(&self.storage)`, `<S as UniversalRead<u8>>::open`,
…) that two `T`s on `S` forced everywhere.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>

* extra refactoring after #8955

* explicit zeroed instantiation

---------

Co-authored-by: Andrey Vasnetsov <[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.

4 participants