Repository navigation
uio mmap posting - #8721
uio mmap posting#8721
Conversation
…ocopyPostingValue
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
lib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rs (1)
488-517:⚠️ Potential issue | 🟡 Minor
TryFromsilently tolerates missing postings fromall_postings().
UniversalPostings::all_postingsis implemented on top ofwith_existing_postings, which silently drops token ids whose posting list is missing. The resultingImmutablePostingscould therefore be shorter thanvocab.len(), and the only check (Line 506-509) is adebug_assert!— release builds would build a misaligned index (token ids pointing at the wrong posting) instead of failing.In practice
all_postingsqueries0..posting_count, so each header is in-range and nothing should be dropped, but switchingall_postingsto the all-or-none variant (or converting thedebug_assert!to a real length check returningOperationError) would make the invariant enforceable at the type boundary.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rs` around lines 488 - 517, The TryFrom implementation for ImmutableInvertedIndex currently uses UniversalPostings::all_postings (via postings.all_postings()?) which can silently drop missing posting lists, and only a debug_assert checks postings.len() == vocab.len(); change this to a strict runtime validation: after building postings (from MmapPostingsEnum::Ids/WithPositions) verify postings.len() == vocab.len() and return an OperationError when they differ (instead of debug_assert!), or alternatively call an all-or-none variant of all_postings (or with_existing_postings that returns an error) so that missing postings are propagated as OperationError; update the try_from function (impl TryFrom<&MmapInvertedIndex> for ImmutableInvertedIndex) to perform the real length check and return Err(OperationError) on mismatch.
🧹 Nitpick comments (2)
lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/uio_postings.rs (1)
126-173:get_header/posting_lengo throughheaders_iterfor a single id — minor, butCowreturn is no longer useful.
get_headeralways producesCow::Owned(the header is decoded from bytes insideheaders_iter), so theCow<'_, PostingListHeader>return is effectively always owned. ReturningOption<PostingListHeader>directly would simplify the signature without any functional change;raw_postingalready clones intoCow::Owned(header)when buildingRawPostingList.lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs (1)
494-505: Only MmapInvertedIndex materializes—Mutable and Immutable variants use lazy iteration.The observation is accurate but applies only to
MmapInvertedIndex. Thefilter_has_all,filter_has_phrase, andfilter_has_anymethods in that implementation returnVec<PointOffsetType>and materialize results via.collect()before being wrapped in an iterator. The docstring already acknowledges this: "Pre-collected upfront becauseUniversalPostingsexposes posting views via aFnOncecallback. Acceptable since this index lives on disk."By contrast,
MutableInvertedIndexandImmutableInvertedIndexreturn lazy iterators from their respectivefilter_has_*methods, preserving short-circuit benefits for early-terminating consumers.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs` around lines 494 - 505, The comment wrongly implies all implementations materialize results; update the wording and/or docstring around the filter implementation and the MmapInvertedIndex-specific methods to state that only MmapInvertedIndex's filter_has_all, filter_has_phrase, and filter_has_any materialize into Vec (because UniversalPostings requires FnOnce callbacks and the index is on-disk), while MutableInvertedIndex and ImmutableInvertedIndex return lazy iterators that preserve short-circuiting; locate the generic filter function (fn filter(...)) and the MmapInvertedIndex implementations of filter_has_all/filter_has_phrase/filter_has_any and change the documentation/comments to clarify this distinction.
🤖 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/universal_io/error.rs`:
- Around line 15-16: The error enum is double debug-formatting the stored
zerocopy string; update the display formatting to use {0} instead of {0:?} so
the stored message isn't quoted/escaped when UniversalIoError is displayed.
Change the #[error("Zerocopy size error: {0:?}")] on the ZerocopySize variant
(and the similar attribute usages around the other zerocopy-related variants
mentioned) to #[error("Zerocopy size error: {0}")] (and the analogous
replacement for the other variants) so the stored string is rendered as-is.
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs`:
- Around line 515-527: vocab_with_postings_len_iter currently yields Err items
mid-stream and keeps iterating; change it to short-circuit on the first Err by
replacing the filter_map closure with an iterator using scan (or an equivalent
stateful adaptor) over self.iter_vocab() that calls
self.storage.postings.posting_len(token_id), yields Ok((token, posting_len)) for
Ok(Some(...)), skips for Ok(None), but when Err(err) is encountered yields
Some(Err(err)) and sets internal state so subsequent calls return None (stopping
the iterator); update the implementation around vocab_with_postings_len_iter /
self.iter_vocab() / storage.postings.posting_len to implement this
early-termination behavior.
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/raw_posting_list.rs`:
- Around line 33-38: The current parsing uses unchecked split_at/slicing on
self.header.ids_data_bytes_count, var_size_data_bytes_count, and
alignment_bytes_count which will panic on truncated buffers; change the code in
raw_posting_list.rs to perform bounds checks against bytes.len() before each
split/slice (check ids_data_bytes_count <= bytes.len(), then
var_size_data_bytes_count <= remaining.len(), then alignment_bytes_count <=
remaining.len()) and return the parser's OperationResult error (e.g., an
Err(OperationResult::TruncatedData) or the crate's equivalent) instead of
panicking; update the code paths that use ids_data_bytes_count,
var_size_data_bytes_count, and alignment_bytes_count so they only call
split_at/slice after these checks succeed.
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/uio_postings.rs`:
- Around line 255-268: all_postings currently does a truncating cast from
self.header.posting_count to TokenId and uses with_existing_postings which
silently skips missing entries; change it to first check if
self.header.posting_count > TokenId::MAX and return an OperationError on
overflow, then build the token id range safely (no unchecked usize→TokenId cast)
and call with_all_or_none_postings instead of with_existing_postings so any
missing/out-of-range header read yields an error that propagates to the caller
(affecting TryFrom<&MmapInvertedIndex> for ImmutableInvertedIndex); ensure you
reference the TokenId type and return OperationError when overflow or
with_all_or_none_postings fails, then collect and return the posting lists.
- Around line 179-219: In with_posting_views: stop using header_err Cell and
skipping failed headers; instead propagate the first Err from header_iter
synchronously so we don't issue self.storage.read_iter when a header failed.
Replace the filter_map that creates range_iter with a fallible mapping that
returns Result<((TokenId, Header), ReadRange), UniversalIoError> and either (a)
collect/try_fold those into a Vec and return Err immediately on the first error,
or (b) create a fused iterator that yields Err as soon as a header fails and
short-circuits before calling self.storage.read_iter; remove header_err and
ensure raw_postings/read_iter only runs after successful header collection so
errors from header_iter are returned directly from with_posting_views.
In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs`:
- Line 297: The closure currently collapsing errors via .map(|r|
r.unwrap_or(false)) must stop turning read/cast failures from
point_to_values.check_values_any into false negatives; modify the iterator/map
chain to propagate the OperationResult<bool> instead of unwrapping, by changing
the surrounding function signature to return OperationResult<...> (or otherwise
passing an OperationResult<bool> through), replace the .map that uses
unwrap_or(false) with a fallible map that returns Err when
point_to_values.check_values_any returns Err, and update any downstream callers
to handle the propagated error (use the existing OperationResult<bool> type and
any helper combinators to convert/aggregate results rather than silencing them).
Ensure references to point_to_values.check_values_any and the closure that
currently does unwrap_or(false) are updated accordingly.
In
`@lib/segment/src/index/query_optimization/condition_converter/match_converter.rs`:
- Around line 283-287: The closure used for full-text matching currently
swallows errors via unwrap_or(false); change the ConditionCheckerFn type and
callers to be fallible (return OperationResult<bool> or Result<bool, E>) and
propagate the error from full_text_index.check_match(&parsed_query, point_id)
instead of converting it to false; update the closure (the Box::new(move
|point_id: PointOffsetType| { ... })) to return the Result from check_match,
adjust any code expecting a plain bool to handle the Result (or map/flatten
where appropriate), and ensure error propagation up the call chain so
storage/IO/cancellation errors are surfaced rather than treated as misses.
In `@src/tonic/api/storage_read_api/helpers.rs`:
- Line 215: The match arm handling UniversalIoError::ZerocopySize currently
returns Status::internal(e) without preserving the error category; update the
conversion in the helpers where UniversalIoError is mapped to tonic::Status (the
match arm for UniversalIoError::ZerocopySize) to include a descriptive prefix
(e.g. "zerocopy size: ") before the error message so the resulting Status
clearly identifies it as a zerocopy size failure, matching the pattern used by
the neighboring variants.
---
Outside diff comments:
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rs`:
- Around line 488-517: The TryFrom implementation for ImmutableInvertedIndex
currently uses UniversalPostings::all_postings (via postings.all_postings()?)
which can silently drop missing posting lists, and only a debug_assert checks
postings.len() == vocab.len(); change this to a strict runtime validation: after
building postings (from MmapPostingsEnum::Ids/WithPositions) verify
postings.len() == vocab.len() and return an OperationError when they differ
(instead of debug_assert!), or alternatively call an all-or-none variant of
all_postings (or with_existing_postings that returns an error) so that missing
postings are propagated as OperationError; update the try_from function (impl
TryFrom<&MmapInvertedIndex> for ImmutableInvertedIndex) to perform the real
length check and return Err(OperationError) on mismatch.
---
Nitpick comments:
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs`:
- Around line 494-505: The comment wrongly implies all implementations
materialize results; update the wording and/or docstring around the filter
implementation and the MmapInvertedIndex-specific methods to state that only
MmapInvertedIndex's filter_has_all, filter_has_phrase, and filter_has_any
materialize into Vec (because UniversalPostings requires FnOnce callbacks and
the index is on-disk), while MutableInvertedIndex and ImmutableInvertedIndex
return lazy iterators that preserve short-circuiting; locate the generic filter
function (fn filter(...)) and the MmapInvertedIndex implementations of
filter_has_all/filter_has_phrase/filter_has_any and change the
documentation/comments to clarify this distinction.
🪄 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: e780a5e2-17ad-4c91-bbf5-14ae5345f574
📒 Files selected for processing (22)
lib/common/common/src/universal_io/error.rslib/posting_list/src/lib.rslib/posting_list/src/view.rslib/segment/src/common/operation_error.rslib/segment/src/index/field_index/full_text_index/immutable_text_index.rslib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mmap_postings.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mmap_postings_enum.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/raw_posting_list.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/types.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/uio_postings.rslib/segment/src/index/field_index/full_text_index/inverted_index/mod.rslib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rslib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rslib/segment/src/index/field_index/full_text_index/mmap_text_index.rslib/segment/src/index/field_index/full_text_index/tests/mod.rslib/segment/src/index/field_index/full_text_index/tests/test_congruence.rslib/segment/src/index/field_index/full_text_index/text_index.rslib/segment/src/index/field_index/geo_index/mmap_geo_index.rslib/segment/src/index/query_optimization/condition_converter/match_converter.rssrc/tonic/api/storage_read_api/helpers.rs
💤 Files with no reviewable changes (1)
- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mmap_postings.rs
| #[error("Zerocopy size error: {0:?}")] | ||
| ZerocopySize(String), |
There was a problem hiding this comment.
Avoid debug-formatting the stored zerocopy error twice.
format!("{err:?}") already stores a debug-formatted message; #[error(... {0:?})] will add quotes/escaping when UniversalIoError is displayed. Prefer {0} for the stored string.
🧹 Proposed formatting fix
- #[error("Zerocopy size error: {0:?}")]
+ #[error("Zerocopy size error: {0}")]
ZerocopySize(String),Also applies to: 66-69
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/common/common/src/universal_io/error.rs` around lines 15 - 16, The error
enum is double debug-formatting the stored zerocopy string; update the display
formatting to use {0} instead of {0:?} so the stored message isn't
quoted/escaped when UniversalIoError is displayed. Change the #[error("Zerocopy
size error: {0:?}")] on the ZerocopySize variant (and the similar attribute
usages around the other zerocopy-related variants mentioned) to
#[error("Zerocopy size error: {0}")] (and the analogous replacement for the
other variants) so the stored string is rendered as-is.
| Some(Box::new(move |point_id: PointOffsetType| { | ||
| full_text_index.check_match(&parsed_query, point_id) | ||
| // FIXME: don't silently ignore errors. Log error? Update ConditionCheckerFn? | ||
| full_text_index | ||
| .check_match(&parsed_query, point_id) | ||
| .unwrap_or(false) |
There was a problem hiding this comment.
Propagate full-text check errors instead of treating them as misses.
check_match can now fail for storage/IO/corruption/cancellation paths; unwrap_or(false) silently drops matching points and hides the underlying service error. Please make ConditionCheckerFn fallible, or route this path through an error-propagating/fallback mechanism instead of returning false.
I can help sketch the ConditionCheckerFn -> OperationResult<bool> migration if useful.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@lib/segment/src/index/query_optimization/condition_converter/match_converter.rs`
around lines 283 - 287, The closure used for full-text matching currently
swallows errors via unwrap_or(false); change the ConditionCheckerFn type and
callers to be fallible (return OperationResult<bool> or Result<bool, E>) and
propagate the error from full_text_index.check_match(&parsed_query, point_id)
instead of converting it to false; update the closure (the Box::new(move
|point_id: PointOffsetType| { ... })) to return the Result from check_match,
adjust any code expecting a plain bool to handle the Result (or map/flatten
where appropriate), and ensure error propagation up the call chain so
storage/IO/cancellation errors are surfaced rather than treated as misses.
There was a problem hiding this comment.
Yes, this is planned in another issue. Currently, is doesn't introduce any new errors, as we only use Mmap and it is exactly same backend as used before.
There was a problem hiding this comment.
@generall, understood — since the Mmap backend is unchanged and check_match errors on this path were never surfaced before, unwrap_or(false) maintains existing behavior without regressing. The FIXME comment already tracks this for the follow-up. I'll note this for future reviews.
✏️ Learnings added
Learnt from: generall
Repo: qdrant/qdrant PR: 8721
File: lib/segment/src/index/query_optimization/condition_converter/match_converter.rs:283-287
Timestamp: 2026-04-19T22:08:03.881Z
Learning: In `lib/segment/src/index/query_optimization/condition_converter/match_converter.rs`, the `unwrap_or(false)` in the `FullTextIndex` branch of `get_match_text_checker` is intentional for now. Making `ConditionCheckerFn` fallible to propagate `check_match` errors is planned in a separate follow-up issue. The current Mmap backend is identical to the pre-PR backend, so no new errors are introduced by this pattern. Do not flag this as a blocking issue.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6444
File: lib/segment/src/index/field_index/map_index/immutable_map_index.rs:373-375
Timestamp: 2025-05-08T10:34:42.223Z
Learning: In the Qdrant codebase, storage backends may have different error handling approaches. Specifically, the mmap variant of `remove_point` method does not return errors, while the RocksDB variant does propagate errors using the `?` operator. These differences are intentional by design.
Learnt from: generall
Repo: qdrant/qdrant PR: 8287
File: lib/gridstore/src/gridstore/mod.rs:145-149
Timestamp: 2026-03-04T16:22:20.875Z
Learning: In `lib/gridstore/src/gridstore/mod.rs`, the maintainer (generall) intentionally treats any mismatch between `loaded_pages` (from `Pages::open`) and `num_pages` (inferred from bitmask) as a hard error (`GridstoreError::service_error`), including the case where `loaded_pages > num_pages`. Extra trailing page files not covered by the bitmask are considered evidence of storage corruption, not a recoverable warning condition.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 8329
File: lib/segment/src/segment/segment_ops.rs:656-660
Timestamp: 2026-03-10T00:21:55.747Z
Learning: In `lib/segment/src/segment/segment_ops.rs`, `has_deferred_points()` intentionally uses `total_point_count()` (the count of all assigned internal IDs, including deleted ones) rather than the count of live mappings to check against `deferred_internal_id`. This is by design because `deferred_internal_id` is not persistent across restarts and must remain stable between runs even when points are deleted.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR `#7048`, using checked_mul with u64 casting to prevent silent overflow.
Learnt from: coszio
Repo: qdrant/qdrant PR: 8196
File: lib/common/common/src/universal_io/mmap.rs:63-65
Timestamp: 2026-02-23T18:49:18.575Z
Learning: In `lib/common/common/src/universal_io/mmap.rs`, for index computations like `start + range.length as usize` used with `slice.get(start..end)`, relying on the bounds checking of `get()` rather than explicit overflow protection with `checked_add` is acceptable. The bounds check gracefully handles overflow cases by returning `None`, which gets propagated as an error.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 8686
File: lib/collection/src/operations/conversions.rs:375-379
Timestamp: 2026-04-16T07:20:00.603Z
Learning: In qdrant/qdrant, TurboQuant API conversion branches (e.g., `Quantization::Turboquant` → `Self::Turbo` in `lib/collection/src/operations/conversions.rs`) are intentionally added before the full load/create implementation is ready. The `todo!()` placeholders in the backend are acceptable as part of the incremental rollout plan tracked in https://github.com/qdrant/qdrant/issues/8670. Do not flag these conversion branches as needing early rejection guards.
Learnt from: KShivendu
Repo: qdrant/qdrant PR: 6352
File: lib/segment/src/id_tracker/immutable_id_tracker.rs:379-393
Timestamp: 2025-05-07T09:13:47.781Z
Learning: In the Qdrant codebase, prefer fail-fast error handling by returning explicit errors rather than silently continuing with potentially corrupted state, especially in components like ID trackers that are fundamental to data integrity.
Learnt from: coszio
Repo: qdrant/qdrant PR: 8287
File: lib/gridstore/src/tracker.rs:285-292
Timestamp: 2026-03-04T17:03:25.836Z
Learning: In `lib/gridstore/src/tracker.rs`, the use of `transmute_from_u8` with `#[expect(deprecated, reason = "legacy code")]` in functions like `read_header` and `get_raw` is a known existing issue acknowledged by the maintainer (coszio). It should not be flagged as a new violation in code reviews for this file.
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 8246
File: lib/segment/src/segment/segment_ops.rs:691-696
Timestamp: 2026-02-27T19:23:23.760Z
Learning: In code that computes offsets or casts counts to PointOffsetType (u32), avoid unsafe or unchecked casts from usize to PointOffsetType. Do not cast unless you can guarantee the value is < PointOffsetType::MAX, for example by assertions or by design constraints (as in versions_store.rs and segment internal IDs). When such a cast is necessary, validate the bound first and add an explicit assertion or guard, documenting the invariant to prevent overflow and maintain correctness across segments.
Learnt from: generall
Repo: qdrant/qdrant PR: 8322
File: lib/edge/src/lib.rs:213-237
Timestamp: 2026-03-08T01:28:03.360Z
Learning: Use SaveOnDisk<T> from common::save_on_disk for atomic persist-then-swap semantics when a config or in-memory struct must be kept in memory and persisted atomically on mutation. Prefer SaveOnDisk<T> over combining parking_lot::RwLock<T> with manual save() calls. Note: write_optional (returns Option<T>) is appropriate for fallible mutations where returning None skips both save and swap. In the qdrant/qdrant repo, the type is located at lib/common/common/src/save_on_disk.rs; migrate relevant in-memory config mutations to use SaveOnDisk<T> to ensure atomic persistence.
Learnt from: generall
Repo: qdrant/qdrant PR: 8368
File: lib/common/common/src/disk_cache/controller.rs:129-129
Timestamp: 2026-03-17T19:36:24.259Z
Learning: In this repository, all builds target 64-bit systems. Do not flag casts from u64 to usize (for example file length via f.metadata()?.len() as usize) as potentially unsafe. These casts are acceptable because 32-bit targets are not supported. Apply this guidance across all Rust sources in the codebase unless explicit overrides exist.
| #[error("Zerocopy size error: {0:?}")] | ||
| ZerocopySize(String), |
There was a problem hiding this comment.
If you think we should switch to BytemuckCast here, I propose to postpone it for another PR
|
|
||
| impl<Src, Dst: ?Sized> From<zerocopy::SizeError<Src, Dst>> for UniversalIoError { | ||
| fn from(err: zerocopy::SizeError<Src, Dst>) -> Self { | ||
| Self::ZerocopySize(format!("{err:?}")) |
There was a problem hiding this comment.
string because of generics
| } | ||
|
|
||
| impl<'a> RawPostingList<'a> { | ||
| pub fn as_view<V: ZerocopyPostingValue>(&'a self) -> OperationResult<PostingListView<'a, V>> { |
There was a problem hiding this comment.
this function can happen if:
- alignment is broken
- size is wrong
Both are only possible here if code is wrong, not because of hardware failure.
There was a problem hiding this comment.
this fine is simply moved during initial refactoring
| Some(((token_id, header), range)) | ||
| } | ||
| Err(err) => { | ||
| header_err.set(Some(err)); |
There was a problem hiding this comment.
didn't find a better way to return error only once.
| let raw = postings.get(token_id).unwrap()?; | ||
| let view = raw.as_view::<()>().unwrap(); | ||
| view.into_iter().map(|elem| elem.id).collect() |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs`:
- Around line 45-46: The diagram comment incorrectly annotates the chunks line
as "chunks_count * chunks_count"; update the right-hand annotation to accurately
reflect serialized size by replacing that with "chunks_count *
size_of::<PostingChunk<Sized<V>>>()" (or a clear equivalent such as
"chunks_count × size_of::<PostingChunk<...>>()") where the diagram references
PostingChunk<Sized<V>> and chunks_count.
- Around line 136-140: The code currently panics via expect when last_id is
None; instead return an io::Error from the fallible function. Replace the expect
call on last_id in the bufw.write_all call by converting the Option to a Result
(e.g. last_id.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData,
"posting must have at least one element"))?) and then call as_bytes() and
bufw.write_all(...)? to propagate the error; update the surrounding expression
to use the ? operator so the function returns the io::Error rather than
panicking in create_postings.rs (the last_id usage in the bufw.write_all
invocation).
- Around line 106-123: The code writes id_data_len and var_size_data_len into
PostingListHeader using unchecked casts and advances posting_offset without
overflow checks; validate and prevent truncation by converting sizes with
u32::try_from(id_data_len) and u32::try_from(var_size_data_len) (returning an
error on overflow) and use checked_add when updating posting_offset (e.g.,
posting_offset =
posting_offset.checked_add(posting_list_header.posting_size::<V>() as
usize).ok_or(...) ), and apply the same u32/checked_add validation when
computing/writing alignment padding and advancing offsets (symbols: id_data_len,
var_size_data_len, alignment_len, PostingListHeader, posting_offset,
posting_list_header.posting_size::<V>(), remainders, and bufw.write_all).
🪄 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: dfe1bf6d-c034-4426-b1a9-4cefed229eca
📒 Files selected for processing (1)
lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs
| let id_data_len = id_data.len(); | ||
| let var_size_data_len = var_size_data.len(); | ||
| let data_len = id_data_len + var_size_data_len; | ||
| let alignment_len = data_len.next_multiple_of(ALIGNMENT) - data_len; | ||
|
|
||
| let posting_list_header = PostingListHeader { | ||
| offset: posting_offset as u64, | ||
| chunks_count: chunks.len() as u32, | ||
| ids_data_bytes_count: id_data_len as u32, | ||
| var_size_data_bytes_count: var_size_data_len as u32, | ||
| alignment_bytes_count: alignment_len as u8, | ||
| remainder_count: remainders.len() as u8, | ||
| _reserved: [0; 2], | ||
| }; | ||
|
|
||
| bufw.write_all(posting_list_header.as_bytes())?; | ||
|
|
||
| posting_offset += posting_list_header.posting_size::<V>(); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check for unchecked narrow casts and unchecked offset increments in the postings serializer.
rg -n -C3 'as u(32|8)|posting_offset\s*\+=' -- \
lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rsRepository: qdrant/qdrant
Length of output: 724
🏁 Script executed:
# Get full context of the create_postings.rs file around the flagged lines
wc -l lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rsRepository: qdrant/qdrant
Length of output: 164
🏁 Script executed:
# Read the full create_postings.rs file to understand context
cat -n lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs | head -160Repository: qdrant/qdrant
Length of output: 7618
🏁 Script executed:
# Check PostingListHeader definition
rg -A 15 "struct PostingListHeader" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/Repository: qdrant/qdrant
Length of output: 2238
🏁 Script executed:
# Check posting_size method
rg -B 2 -A 8 "fn posting_size" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/Repository: qdrant/qdrant
Length of output: 1566
🏁 Script executed:
# Check the second location mentioned (lines 152-154)
sed -n '150,160p' lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rsRepository: qdrant/qdrant
Length of output: 384
🏁 Script executed:
# Check ALIGNMENT value
rg -n "const ALIGNMENT|ALIGNMENT\s*=" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/Repository: qdrant/qdrant
Length of output: 184
🏁 Script executed:
# Check CHUNK_LEN and any bounds on chunks/remainders
rg -n "CHUNK_LEN|pub const" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/types.rs | head -20Repository: qdrant/qdrant
Length of output: 263
🏁 Script executed:
# Check PostingChunk and RemainderPosting structs
rg -B 2 -A 5 "struct PostingChunk|struct RemainderPosting" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check how compressed_postings is created and what creates the components
rg -n "PostingListComponents" -- lib/segment/src/index/field_index/full_text_index/inverted_index/ | head -10Repository: qdrant/qdrant
Length of output: 505
🏁 Script executed:
# Look at the PostingList view() and components() methods
rg -B 3 -A 10 "fn components\(\)" -- lib/posting_list/src/Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check if there are tests or related code that show expected bounds
rg -n "PostingListHeader|create_postings_file" -- lib/segment/src/index/field_index/full_text_index/inverted_index/ | head -20Repository: qdrant/qdrant
Length of output: 3498
🏁 Script executed:
# Check the mmap reader to understand how it uses these header fields
rg -B 5 -A 10 "fn read|from_bytes" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/ | head -60Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check if there's any validation or clamping when reading these header values
rg -n "ids_data_bytes_count|chunks_count" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/Repository: qdrant/qdrant
Length of output: 2025
🏁 Script executed:
# Check how PostingList is created and what constrains its size
rg -n "impl.*PostingList|fn new" -- lib/posting_list/src/lib.rs | head -20Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check if there are any limits on posting data size in the code
rg -n "u32::MAX|4.*GB|overflow" -- lib/segment/src/index/field_index/full_text_index/inverted_index/Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Look for any documentation about limits on posting data
rg -B 5 "id_data|var_size_data" -- lib/posting_list/src/ | grep -A 3 -B 3 "limit\|max\|bound\|size" | head -40Repository: qdrant/qdrant
Length of output: 2242
🏁 Script executed:
# Check the actual implementation - how big can id_data actually get?
cat -n lib/posting_list/src/view.rs | head -80Repository: qdrant/qdrant
Length of output: 3031
🏁 Script executed:
# Check the reader code that uses these header values - how does it parse the data?
cat -n lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/raw_posting_list.rsRepository: qdrant/qdrant
Length of output: 2327
🏁 Script executed:
# Check if there's any size validation when creating PostingList
rg -B 5 -A 10 "fn view|pub fn new" -- lib/posting_list/src/lib.rs | head -50Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Look for any tests that create large postings
rg -n "create_postings_file|PostingListHeader" -- lib/segment/src/index/field_index/full_text_index/inverted_index/tests/ 2>/dev/null | head -20Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check test files for this module
find lib/segment/src/index/field_index/full_text_index/inverted_index/ -name "*test*" -o -name "*tests*"Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check what creates the id_data and var_size_data - are there any bounds?
rg -B 5 -A 10 "struct PostingList|id_data.*Vec" -- lib/posting_list/src/lib.rs | head -60Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Check if there's validation at creation time
rg -n "PostingList::new|push|add" -- lib/posting_list/src/ | head -20Repository: qdrant/qdrant
Length of output: 957
🏁 Script executed:
# See what the maximum realistic size of id_data could be
rg -B 3 -A 8 "fn builder|struct.*Builder" -- lib/posting_list/src/ | head -40Repository: qdrant/qdrant
Length of output: 734
🏁 Script executed:
# Check the exact bounds - what limits the size of posting lists?
rg -n "PointOffsetType::MAX|u32::MAX" -- lib/segment/src/index/field_index/full_text_index/inverted_index/Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Look at bitpacker to understand CHUNK_LEN and chunk creation
rg -n "CHUNK_LEN|const" -- lib/posting_list/src/ | grep -i chunkRepository: qdrant/qdrant
Length of output: 3416
🏁 Script executed:
# Check if there are any assertions or guards elsewhere in the pipeline
rg -B 3 -A 3 "create_postings_file" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mod.rsRepository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# What's the actual value of CHUNK_LEN?
grep -n "const CHUNK_LEN" lib/posting_list/src/lib.rsRepository: qdrant/qdrant
Length of output: 93
🏁 Script executed:
# Check what the practical maximum is for a single segment
rg -n "PointOffsetType|u32::MAX" -- lib/common/src/types.rs | head -10Repository: qdrant/qdrant
Length of output: 120
🏁 Script executed:
# Check if there's any documentation about segment size limits
rg -n "segment.*size|max.*points|4.*GB|overflow" -- lib/segment/src/ | grep -i "limit\|max\|size" | head -20Repository: qdrant/qdrant
Length of output: 2225
🏁 Script executed:
# Verify the actual risk - can these values realistically overflow?
# Check the builder to see what the maximum reasonable id_data size would be
cat -n lib/posting_list/src/builder.rs | sed -n '40,100p'Repository: qdrant/qdrant
Length of output: 3023
🏁 Script executed:
# Check the key insight - what's the maximum id_data_size that could be created?
# With CHUNK_LEN=128, and max points = u32::MAX
python3 << 'EOF'
CHUNK_LEN = 128
MAX_POINTS = 2**32 - 1
# Maximum chunks
max_chunks = MAX_POINTS // CHUNK_LEN
print(f"Max chunks: {max_chunks:,} (fits in u32: {max_chunks < 2**32})")
# In the worst case, each chunk needs to store bit-packed IDs
# The compressed block size depends on value range, but let's estimate
# BitPacker worst case is about CHUNK_LEN bytes per chunk
max_id_data_size = max_chunks * CHUNK_LEN # pessimistic estimate
print(f"Pessimistic id_data size: {max_id_data_size:,} bytes ({max_id_data_size / 1e9:.2f} GB)")
print(f"Fits in u32 (4GB): {max_id_data_size < 2**32}")
# Check alignment_len
ALIGNMENT = 4
max_alignment_len = ALIGNMENT - 1 # worst case: need 3 bytes padding
print(f"\nMax alignment_len: {max_alignment_len} (fits in u8: True)")
# Check remainders
max_remainders = CHUNK_LEN - 1 # all remainder IDs for last chunk
print(f"Max remainder_count: {max_remainders} (fits in u8: {max_remainders < 2**8})")
EOFRepository: qdrant/qdrant
Length of output: 264
🏁 Script executed:
# Check if there are any segment size limits that would constrain this further
rg -n "max.*segment|segment.*limit" -- lib/segment/src/segment/mod.rs | head -10Repository: qdrant/qdrant
Length of output: 39
🏁 Script executed:
# Most importantly: check if there's any validation in the reader when it reads these headers
rg -B 5 -A 10 "as_view.*PostingListView" -- lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/raw_posting_list.rsRepository: qdrant/qdrant
Length of output: 692
🏁 Script executed:
# Final check: Does create_postings_file have any guards before these casts?
cat -n lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs | sed -n '74,125p'Repository: qdrant/qdrant
Length of output: 2439
🏁 Script executed:
# Check if there are any integration tests that validate posting file round-trip
find lib/segment/src -name "*.rs" -type f -exec grep -l "create_postings_file\|UniversalPostings" {} \;Repository: qdrant/qdrant
Length of output: 460
Add overflow validation for persisted header fields.
The unchecked casts at lines 113–117 can silently truncate id_data_len and var_size_data_len if they exceed u32::MAX (~4 GB). Since these values are written into the on-disk PostingListHeader, truncation will cause the mmap reader to split the payload at wrong byte offsets, corrupting posting-list reconstruction. Use u32::try_from() for narrowing casts and checked_add() for offset arithmetic on line 123, similar to the validation already present in the posting list builder (lib/posting_list/src/builder.rs:68–69). The same issue occurs at lines 152–154 when writing alignment padding.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs`
around lines 106 - 123, The code writes id_data_len and var_size_data_len into
PostingListHeader using unchecked casts and advances posting_offset without
overflow checks; validate and prevent truncation by converting sizes with
u32::try_from(id_data_len) and u32::try_from(var_size_data_len) (returning an
error on overflow) and use checked_add when updating posting_offset (e.g.,
posting_offset =
posting_offset.checked_add(posting_list_header.posting_size::<V>() as
usize).ok_or(...) ), and apply the same u32/checked_add validation when
computing/writing alignment padding and advancing offsets (symbols: id_data_len,
var_size_data_len, alignment_len, PostingListHeader, posting_offset,
posting_list_header.posting_size::<V>(), remainders, and bufw.write_all).
| bufw.write_all( | ||
| last_id | ||
| .expect("posting must have at least one element") | ||
| .as_bytes(), | ||
| )?; |
There was a problem hiding this comment.
Return an error instead of panicking on an empty posting list.
This function is fallible already, so an invariant violation should surface as io::Error rather than crashing the process with expect.
🛡️ Proposed fix
- bufw.write_all(
- last_id
- .expect("posting must have at least one element")
- .as_bytes(),
- )?;
+ let last_id = last_id.ok_or_else(|| {
+ io::Error::new(
+ io::ErrorKind::InvalidData,
+ "posting list must have at least one element",
+ )
+ })?;
+ bufw.write_all(last_id.as_bytes())?;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| bufw.write_all( | |
| last_id | |
| .expect("posting must have at least one element") | |
| .as_bytes(), | |
| )?; | |
| let last_id = last_id.ok_or_else(|| { | |
| io::Error::new( | |
| io::ErrorKind::InvalidData, | |
| "posting list must have at least one element", | |
| ) | |
| })?; | |
| bufw.write_all(last_id.as_bytes())?; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/create_postings.rs`
around lines 136 - 140, The code currently panics via expect when last_id is
None; instead return an io::Error from the fallible function. Replace the expect
call on last_id in the bufw.write_all call by converting the Option to a Result
(e.g. last_id.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData,
"posting must have at least one element"))?) and then call as_bytes() and
bufw.write_all(...)? to propagate the error; update the surrounding expression
to use the ? operator so the function returns the io::Error rather than
panicking in create_postings.rs (the last_id usage in the bufw.write_all
invocation).
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis pull request refactors the full-text inverted index infrastructure by replacing the existing Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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 |
coszio
left a comment
There was a problem hiding this comment.
Thanks for including the layout description here 🙌
The refactor looks good. I am only concerned that prefetching is also doing the work of preprocessing everything.
I tried giving Claude a chance to make evaluation lazy, and came up with a nice usage of self_cell to solve it.
For now, I think this one is fine to merge as-is.
| // Deduplicate phrase tokens: repeated tokens (e.g. "zn zn") must | ||
| // not fetch the same posting list twice, otherwise positions get | ||
| // added twice in `phrase_in_all_postings`. | ||
| let unique_tokens = phrase.to_token_set(); |
* [AI] update docstrings * move support strucutres from mmap_posting.rs * rename and simplify: MmapPostingValue -> PersistedPostingValue -> ZerocopyPostingValue * implement `with_view` method for UniversalPostings * WIP: RawPOstingList + AsPostingListView * wip: bathcing and pre-collection of posting lists * wip: batch reading in UniversalPostings * [AI] implement with_existing_postings * fmt * pre-collect in check_compressed_postings_phrase * batch pre-collect for check_any and check_intersection * get rid of iter_postings which is collected anyway * all_postings in UniversalPostings * missing unique for tokens in phrases * [AI] replace MmapPostings with UniversalPostings * mising file * cfg(test) * unnecessary Cow --------- Co-authored-by: Luis Cossío <[email protected]>
* [AI] update docstrings * move support strucutres from mmap_posting.rs * rename and simplify: MmapPostingValue -> PersistedPostingValue -> ZerocopyPostingValue * implement `with_view` method for UniversalPostings * WIP: RawPOstingList + AsPostingListView * wip: bathcing and pre-collection of posting lists * wip: batch reading in UniversalPostings * [AI] implement with_existing_postings * fmt * pre-collect in check_compressed_postings_phrase * batch pre-collect for check_any and check_intersection * get rid of iter_postings which is collected anyway * all_postings in UniversalPostings * missing unique for tokens in phrases * [AI] replace MmapPostings with UniversalPostings * mising file * cfg(test) * unnecessary Cow --------- Co-authored-by: Luis Cossío <[email protected]>
This is a Universal IO implementation of MmapPostings - a storage of posting lists for text index.
PR have the following stages:
MmapPostings- it moves and splits structures into dedicated files, so it is easier to work with. There is also a detailed diagram of persisted format now.MmapPostingsmethods. To make it more compatible with Universal IO, some of the methods ofMmapPostingsare updates to resemble batch operations better. Some non-needed iterators are replaces with pre-collection approach.UniversalPostingsis implemented. It have similar methods asMmapPostings. It is done to gradully verify that we can migrate to universal IO, and not all at once.As a last step, we replace
MmapPostingswithUniversalPostings, which should be not so hard, as we were adjusting the intefaces along the way