Skip to content

Segment Read View - #8841

Merged
generall merged 30 commits into
devfrom
read-only-segment-step-1
May 4, 2026
Merged

generall merged 30 commits into
devfrom
read-only-segment-step-1

Conversation

@generall

Copy link
Copy Markdown
Member

No description provided.

@timvisee timvisee changed the title Read Only Sement (step 1) Read Only Segment (step 1) Apr 30, 2026
@generall
generall force-pushed the read-only-segment-step-1 branch 2 times, most recently from 424aaa9 to 13974a3 Compare April 30, 2026 19:22
generall and others added 19 commits May 4, 2026 13:08
… and lookup_internal_id

Step 1 of the SegmentReadView migration.

* `SegmentReadView` is expanded to its final field set, parameterised over
  four read-only traits (`IdTrackerRead`, `PayloadIndexRead`,
  `PayloadStorageRead`, `VectorDataRead`). A `SegmentReadViewFor<'s>` type
  alias hides the verbosity at call sites for `Segment`. Steps 2-11 only
  add `impl` methods; the struct shape is now frozen.
* `Segment::with_view` borrows the three `AtomicRefCell`-wrapped storages
  up front and populates every view field; closure bound relaxed
  `Fn` -> `FnOnce`.
* `lookup_internal_id` (Option -> PointIdError conversion) and
  `read_range` (iterator + take_while) are migrated to the view. The
  previous Segment-side helpers become thin `with_view` delegators where
  external callers still rely on them.
* Trivial id-tracker getters (`has_point`, `is_empty`,
  `available_point_count`, `deleted_point_count`, `total_point_count`)
  stay implemented directly on `Segment` -- one-liners that
  `ReadOnlySegment` will reimplement just as cheaply, no shared logic to
  factor out.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 2 of the SegmentReadView migration.

Move the five composition-style deferred-point methods onto the view:
`deferred_point_count`, `has_deferred_points`, `point_is_deferred`,
`deferred_point_ids`, `available_point_count_without_deferred`. Each
combines the deferred-point status with id-tracker reads, so they are
real shared logic — not trivial getters.

The Segment-side trait method bodies in `entry.rs` collapse to
`self.with_view(|v| v.foo(...))` delegators.

`deferred_internal_id` and `deferred_deleted_count` are one-line
field accessors on `DeferredPointStatus`, so they stay direct on
`Segment`. The view has its own private helpers with the same
one-liner shape — duplicated only at the access-path level.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…/deferred.rs

Move the six deferred-point methods (deferred_internal_id /
deferred_deleted_count helpers + deferred_point_count, has_deferred_points,
point_is_deferred, deferred_point_ids, available_point_count_without_deferred)
out of read_view/segment_ops.rs into their own read_view/deferred.rs module.
Keeps each read_view file focused on a single concern.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 3 of the SegmentReadView migration.

Move the vector-access logic onto the view in a new
`read_view/vectors.rs` module:
* `vector_by_offset`, `vectors_by_offsets` (was `pub(super)` on Segment)
* `read_vectors` (was `pub(crate)` on Segment in the now-deleted
  `segment/vectors.rs`)
* `vector` and `available_vectors_size_in_bytes` (`ReadSegmentEntry`
  trait methods)

`Segment::vector` and `Segment::available_vectors_size_in_bytes`
collapse to `with_view` delegators. The `retrieve` trait method now
calls `view.read_vectors(...)` inside per-name `with_view` closures.

Removed entirely:
* `segment/vectors.rs` (its only function moved to the view)
* `Segment::vector_by_offset` and `Segment::vectors_by_offsets`
  in `segment_ops.rs`

Kept on Segment:
* `vector_names` — trivial `vector_data.keys().cloned().collect()`,
  no shared logic to factor out.
* `all_vectors` — invariant `NamedVectors<'_>` lifetime fights the
  view borrow, and the body is a 6-line iteration over `self.vector`
  (which is itself now a view delegator). ReadOnlySegment will write
  the same trivial loop.

Tests in `segment/tests/mod.rs` that exercised
`segment.vector_by_offset(...)` now go through
`segment.with_view(|v| v.vector_by_offset(...))`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 4 of the SegmentReadView migration.

New `read_view/payload.rs` module hosts:
* `payload_by_offset` (was `pub(super)` on Segment in `segment_ops.rs`)
* `payload` (`ReadSegmentEntry` trait method, real composition:
  `lookup_internal_id` + `payload_by_offset`)
* `estimate_point_count` (`ReadSegmentEntry` trait method, composes
  filter handling, payload-index cardinality and deferred-point
  adjustment)

The corresponding Segment-side trait methods become `with_view`
delegators, and `Segment::payload_by_offset` is deleted.

`Segment::lookup_internal_id` (a transitional `with_view` delegator
introduced in step 1) is now unused after `vector` and `payload`
moved off of it; deleted as well. Tests that called it now go
through `with_view`.

`get_indexed_fields` stays direct on Segment — single-line
`payload_index.borrow().indexed_fields()`, no shared logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 5 of the SegmentReadView migration.

New `read_view/scroll.rs` module hosts:
* `should_pre_filter` — payload-index cardinality estimation,
  used by all three scroll-shaped trait methods (read_filtered,
  read_ordered_filtered, read_random_filtered).
* `read_by_id_stream` — streamed enumeration of visible points.
* `filtered_read_by_id_stream` — streamed enumeration with a
  payload-filter context applied.

`Segment`-side `read_filtered` collapses to a `with_view` orchestrator
(except for the `filtered_read_by_index` branch, see below).
`read_ordered_filtered` and `read_random_filtered` now route their
`should_pre_filter` calls through `with_view` (their own bodies migrate
in steps 6 and 7).

`filtered_read_by_index` stays on `Segment` for now: it depends on
`StructPayloadIndex::iter_filtered_points`, which is an inherent method
that takes the concrete `&IdTrackerEnum` and returns `impl Iterator`.
Migrating it cleanly requires extending `PayloadIndexRead` with a
trait-object-friendly version of that method, which is the same
prerequisite Steps 6/7/8 will need (sampling, order_by, facet all use
`iter_filtered_points`). I will do that as a focused pre-step before
Step 6.

`deferred_internal_id` / `deferred_deleted_count` view helpers bumped
from private to `pub(super)` so the new `scroll` module can call them.

`scroll_filtering_test.rs` integration test updated to call
`filtered_read_by_id_stream` via `with_view`.

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

Prerequisite for migrating order_by, sampling, facet, and scroll's
`filtered_read_by_index` to `SegmentReadView`. Both methods existed only
as inherent methods / public field access on `StructPayloadIndex`; the
view holds a generic `&TPI: PayloadIndexRead` reference and so can
only call trait methods.

* `iter_filtered_points` is now a trait method, generic over
  `I: IdTrackerRead` for the id_tracker parameter and using `impl Iterator`
  in return position (RPITIT). Each impl keeps its own zero-cost concrete
  iterator chain — no boxed dyn-iterator allocation. The trait becomes
  non-object-safe, which is fine because nothing currently uses
  `dyn PayloadIndexRead`.
* `numeric_index_for(key) -> Option<NumericFieldIndex<'_>>` exposes the
  per-key numeric-index lookup that ordered reads rely on, replacing
  direct access to `StructPayloadIndex::field_indexes`.
* Implementations on `StructPayloadIndex` (real) and `PlainPayloadIndex`
  (the latter has no numeric indexes, so `numeric_index_for` returns
  `None`).
* Existing internal callers (hnsw, scroll, sampling, order_by, facet)
  now pass `&*id_tracker` to fully deref `AtomicRef<IdTrackerEnum>` to
  `&IdTrackerEnum` for the generic-param inference.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 6 of the SegmentReadView migration.

Move `lib/segment/src/segment/order_by.rs` into
`read_view/order_by.rs`:
* `filtered_read_by_index_ordered` — uses
  `payload_index.iter_filtered_points` (now on trait, see prior commit)
  and `numeric_index_for` (also now on trait).
* `filtered_read_by_value_stream` — uses `numeric_index_for` and
  `filter_context` (already on trait).
* `read_ordered_filtered` — `ReadSegmentEntry` orchestrator, also moved
  to the view.

`Segment::read_ordered_filtered` collapses to a single
`with_view(|v| v.read_ordered_filtered(...))` delegator. The legacy
`segment/order_by.rs` file is deleted entirely; `mod order_by;` removed
from `segment/mod.rs`.

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

Step 5 leftover: with PayloadIndexRead.iter_filtered_points now on the
trait, filtered_read_by_index can move to the view alongside the other
three scroll helpers.

* `read_view/scroll.rs` gains `filtered_read_by_index` and the
  `read_filtered` orchestrator.
* `segment/scroll.rs` is deleted entirely; `mod scroll;` removed from
  `segment/mod.rs`.
* `Segment::read_filtered` collapses to a single
  `with_view(|v| v.read_filtered(...))` delegator.
* `scroll_filtering_test.rs` integration test calls
  `filtered_read_by_index` via `with_view`.

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

A read-only payload index implementation will have its own concrete
numeric-index type that doesn't fit the appendable
\`NumericFieldIndex<'a>\` enum. So PayloadIndexRead can't return that
concrete type directly.

Introduce \`NumericFieldIndexRead\` trait exposing only what ordered
reads consume (\`get_ordering_values\`, \`stream_range\`). Implement it
for the existing \`NumericFieldIndex<'a>\` (delegates to the inherent
methods + \`StreamRange\`).

\`PayloadIndexRead::numeric_index_for\` now returns
\`Option<impl NumericFieldIndexRead + '_>\` (RPITIT). Each
implementation picks its own concrete return type:
- \`StructPayloadIndex\` returns \`Option<NumericFieldIndex<'_>>\`.
- \`PlainPayloadIndex\` always returns \`None\` (it has no field
  indexes); the explicit \`None::<NumericFieldIndex<'_>>\` turbofish
  just supplies a placeholder type tag — no value is constructed.

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

Both \`StreamRange<T>::stream_range\` and the new
\`NumericFieldIndexRead\` trait now return \`impl Iterator\` /
\`impl DoubleEndedIterator\` directly. No more boxed trait-object
allocations in the order-by hot path.

Mechanism:
* \`NumericIndexInner::stream_range\` has 4-way branching
  (empty / mutable / immutable / mmap), all with different concrete
  iterator types. Unified via a new 4-arm \`NumericRangeIter\` enum that
  delegates \`Iterator\` and \`DoubleEndedIterator\` to its variants.
* \`NumericFieldIndex::stream_range\` and \`get_ordering_values\` have
  2-way branching (Int / Float). Unified via \`itertools::Either\`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Drop the bespoke 4-arm \`NumericRangeIter\` enum introduced in the prior
commit. The existing \`common::either_variant::EitherVariant\` is the
same shape and already has \`Iterator\` plus all the standard adapter
specializations.

Adds a \`DoubleEndedIterator\` impl to \`EitherVariant\` (\`next_back\`,
\`nth_back\`, \`rfold\`, \`rfind\`) so it can be used in this position.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 7 of the SegmentReadView migration.

Move \`segment/sampling.rs\` → \`read_view/sampling.rs\`:
* \`read_by_random_id\`
* \`filtered_read_by_index_shuffled\`
* \`filtered_read_by_random_stream\`
* \`read_random_filtered\` orchestrator

\`Segment::read_random_filtered\` collapses to a single
\`with_view(|v| v.read_random_filtered(...))\` delegator. The legacy
\`segment/sampling.rs\` is deleted; \`mod sampling;\` removed from
\`segment/mod.rs\`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Same shape as the numeric_index_for change in the previous PR: a
read-only segment will have its own per-key facet-index type, so
PayloadIndexRead can't return the concrete \`FacetIndexEnum<'a>\`.

* New \`FacetIndexRead\` trait in \`field_index/facet_index.rs\` mirrors
  the inherent methods of \`FacetIndexEnum\` (\`for_points_values\`,
  \`for_each_value\`, \`for_each_value_map\`, \`for_each_count_per_value\`).
* Implemented for \`FacetIndexEnum<'a>\` by delegating to the inherent
  methods.
* \`PayloadIndexRead::facet_index_for(key) -> Option<impl FacetIndexRead + '_>\`
  added (RPITIT, no boxing). Each impl picks its own concrete return
  type:
  - \`StructPayloadIndex\` returns \`Option<FacetIndexEnum<'_>>\`.
  - \`PlainPayloadIndex\` always returns \`None\`; the explicit
    \`None::<FacetIndexEnum<'_>>\` turbofish supplies a placeholder
    type tag.
* \`FacetIndexRead\` re-exported from \`field_index/mod.rs\` (the
  \`facet_index\` submodule itself stays \`pub(super)\`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Step 8 of the SegmentReadView migration.

Move \`segment/facet.rs\` → \`read_view/facet.rs\`:
* \`approximate_facet\`
* \`facet_values\`

Both now go through the trait-method \`facet_index_for\` (added in the
prior commit) and the existing trait-method \`filter_context\` instead
of the previous inherent \`get_facet_index\` and
\`struct_filtered_context\` calls.

\`Segment::unique_values\` and \`Segment::facet\` (the \`ReadSegmentEntry\`
trait orchestrators) collapse to single \`with_view\` delegators. The
legacy \`segment/facet.rs\` is deleted; \`mod facet;\` removed from
\`segment/mod.rs\`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The introduced \`FacetIndexRead\` trait was almost identical to the
existing \`FacetIndex\` trait — the only difference was the augmented
\`for_each_value\` signature on \`FacetIndexEnum\` that took
\`hw_counter\` and \`deferred_internal_id\` to skip values whose only
points are deferred.

* Move that "skip deferred" logic onto \`FacetIndex\` itself as a default
  method \`for_each_visible_value\` — implemented in terms of the
  existing \`for_each_value\` and \`for_each_value_map\`. All
  \`FacetIndex\` impls (MapIndex, BoolIndex, FacetIndexEnum) get it for
  free.
* Make \`FacetIndexEnum\` impl \`FacetIndex\` directly (delegating to the
  inner index's \`FacetIndex\` impl). The augmented inherent
  \`for_each_value\` is gone.
* \`PayloadIndexRead::facet_index_for\` now returns
  \`Option<impl FacetIndex + '_>\` (no separate \`FacetIndexRead\` trait).
* View facet code uses \`for_each_visible_value\` instead of the old
  augmented \`for_each_value\`.

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

Adds \`fill_idf_statistics\` to the \`VectorIndexRead\` trait with a
no-op default (only sparse-vector indexes track IDF). \`VectorIndexEnum\`
overrides it with the per-variant dispatch that previously lived as an
inherent method.

The inherent \`indexed_vectors\` is removed: it returned the same value
as the trait method \`indexed_vector_count\` for every variant
(sparse's \`indexed_vector_count\` is itself
\`inverted_index.vector_count()\`). The remaining caller in
\`fill_query_context\` will use \`indexed_vector_count\` after the next
commit moves it to the view.

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

Step 9 of the SegmentReadView migration.

New \`read_view/search.rs\` hosts:
* \`retrieve\` — full body (deferred filtering, vector enrichment, payload
  attachment).
* \`process_search_result\` — converts internal \`ScoredPointOffset\`s into
  user-facing \`ScoredPoint\`s; calls the new \`view.retrieve\`.
* \`search_batch\` — \`ReadSegmentEntry\` orchestrator.
* \`fill_query_context\` — uses the trait \`VectorIndexRead::fill_idf_statistics\`
  (added in the prior commit) and the existing \`indexed_vector_count\`.

The \`Segment\`-side trait method bodies for \`search_batch\`, \`retrieve\`,
and \`fill_query_context\` collapse to single \`with_view\` delegators.
\`rescore_with_formula\` (whose body still uses Segment-side
\`do_rescore_with_formula\`, migrated in step 11) routes its
\`process_search_result\` call through \`with_view\`.

\`segment/search.rs\` is trimmed to just the
\`#[cfg(feature = "testing")] pub fn search\` helper, which calls
\`search_batch\` (now a \`with_view\` delegator) — no migration needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
generall and others added 2 commits May 4, 2026 13:08
Leftovers from moving \`StructPayloadIndex::formula_scorer\` out of this
file. Caught by clippy.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…w (step 11) (#8882)

* refactor(index): extend VectorIndexRead and PayloadIndexRead for telemetry/info

Two trait extensions (no defaults — every implementor must opt in):

* \`VectorIndexRead::is_index\` — distinguishes a real index from a plain
  full-scan one. Used by reporting code. Moved out of inherent
  \`VectorIndexEnum::is_index\` into the trait. Explicit impls on Plain
  (false), HNSW (true), Sparse* (true).
* \`PayloadIndexRead::get_telemetry_data\` — per-field-index telemetry.
  Moved out of inherent \`StructPayloadIndex::get_telemetry_data\` into
  the trait impl. \`PlainPayloadIndex\` returns an empty Vec.

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

* refactor(segment): migrate info/size_info/telemetry to SegmentReadView

Step 11 of the SegmentReadView migration — the final logical step.

New \`read_view/info.rs\` exposes builder methods:
* \`build_size_info(uuid, segment_type, is_appendable)\`
* \`build_info(uuid, segment_type, is_appendable)\` — same plus
  \`index_schema\`
* \`build_telemetry(uuid, segment_type, is_appendable, config, detail)\`

The trivial segment-level fields (\`uuid\`, \`segment_type\`,
\`is_appendable\`, \`config\`) are passed in by the caller — they stay
direct on each segment-type rather than going through the view.
Everything else (vector data breakdown, payloads size, deferred
counts, vector-index telemetry, payload-field telemetry, …) is
computed once inside the view through the read traits.

\`Segment::size_info\`, \`info\`, and \`get_telemetry_data\` collapse to
one-line \`with_view\` delegators that pass in the trivial fields.

Cleanup: \`Segment::deferred_deleted_count\` is now unused (the view
has its own equivalent helper); deleted.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@generall
generall marked this pull request as ready for review May 4, 2026 11:09
@generall generall changed the title Read Only Segment (step 1) Segment Read View May 4, 2026
@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a major refactoring of segment read-path architecture by creating a generic SegmentReadView abstraction that encapsulates read-only segment operations. It moves substantial read logic from Segment impl blocks to SegmentReadView, updates trait hierarchies to separate read-only from mutable capabilities (e.g., ReadSegmentEntry no longer inherits SnapshotEntry; StorageSegmentEntry now inherits both), expands PayloadIndexRead with new accessors for field indexes and filtered point iteration, replaces boxed dynamic iterators with impl return types and callbacks, adds fill_idf_statistics and is_index requirements to VectorIndexRead, and refactors formula scoring into a trait-driven constructor pattern.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • qdrant/qdrant#8764: Refactors FacetIndex traversal API from iterator-returning methods to callback-based for_each_* visitors, including changes to FacetIndexEnum and value/map/count traversal methods.
  • qdrant/qdrant#8858: Introduces/updates PayloadIndexRead trait to split read-only payload API, which this PR builds upon extensively by adding and implementing new methods across multiple modules.
  • qdrant/qdrant#8826: Splits IdTracker into IdTrackerRead/IdTracker traits; this PR adopts IdTrackerRead as a trait bound throughout the new read-view layer.

Suggested labels

release:1.18.0

Suggested reviewers

  • dancixx
  • xzfc
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.01% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive No pull request description was provided by the author; the description field is empty. Add a description explaining the purpose, motivation, and scope of the Segment Read View refactoring to help reviewers understand the architectural changes.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The PR title 'Read Only Segment (step 1)' clearly indicates the main objective of this changeset: implementing read-only segment functionality as part of a multi-step refactoring.

✏️ 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 read-only-segment-step-1

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: 4

🧹 Nitpick comments (5)
lib/segment/src/segment/read_view/mod.rs (1)

29-29: 💤 Low value

#[allow(unused, dead_code)] should be removed before merge.

Both the struct definition (line 29) and the impl block (line 52) carry #[allow(unused, dead_code)]. This is fine as a transitional marker in a draft PR, but track removal once downstream consumers (entry.rs, read-view submodules) are wired up.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/read_view/mod.rs` at line 29, Remove the temporary
#[allow(unused, dead_code)] attributes applied to the read-view type and its
impl block in mod.rs: delete the attribute on the struct declaration (the
read-view type defined near the top of the file) and the attribute on its
corresponding impl block (the impl around the mid of the file) so compiler lints
are enforced once downstream consumers (entry.rs and read-view submodules) are
wired up.
lib/segment/src/segment/tests/mod.rs (2)

922-924: ⚡ Quick win

Use a checked conversion before calling payload_by_offset.

i as u32 - 1 silently truncates if this helper ever gets exercised past u32::MAX. Converting through PointOffsetType::try_from(i - 1) keeps the helper aligned with the repo's offset-cast invariant. You'll also need a use common::types::PointOffsetType; import at the top of the file.

♻️ Suggested change
-        let is_deferred_payload = segment
-            .with_view(|v| v.payload_by_offset(i as u32 - 1, &hw_counter))
+        let point_offset = PointOffsetType::try_from(i - 1).unwrap();
+        let is_deferred_payload = segment
+            .with_view(|v| v.payload_by_offset(point_offset, &hw_counter))
             .unwrap()

Based on learnings, "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"

Also applies to: 939-941

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/tests/mod.rs` around lines 922 - 924, Replace
unchecked cast usage like `i as u32 - 1` before calling `segment.with_view(|v|
v.payload_by_offset(..., &hw_counter))` with a checked conversion: call
`PointOffsetType::try_from(i - 1)` and handle the Result (propagate or unwrap
with a clear message) so the offset cast cannot silently truncate; add `use
common::types::PointOffsetType;` to the imports and apply the same replacement
for the other occurrences around `payload_by_offset` at the later block (lines
noted in the comment).

356-358: ⚡ Quick win

Use explicit PointIdType::from(...) in the new lookup calls.

These new lookup_internal_id call sites switched back to implicit .into(). Please spell the conversion out explicitly here.

♻️ Suggested change
-    let internal_id = segment
-        .with_view(|v| v.lookup_internal_id(6.into()))
+    let internal_id = segment
+        .with_view(|v| v.lookup_internal_id(PointIdType::from(6_u64)))
         .unwrap();
-    let internal_8 = segment
-        .with_view(|v| v.lookup_internal_id(8.into()))
+    let internal_8 = segment
+        .with_view(|v| v.lookup_internal_id(PointIdType::from(8_u64)))
         .unwrap();

As per coding guidelines, **/*.rs: Prefer explicit SomeType::from(x) over implicit x.into() in Rust

Also applies to: 520-522

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/tests/mod.rs` around lines 356 - 358, Replace the
implicit .into() conversions when calling lookup_internal_id with an explicit
PointIdType::from(...) to match the coding guideline; specifically change calls
like segment.with_view(|v| v.lookup_internal_id(6.into())) to use
PointIdType::from(6) (and likewise update the other occurrences around the later
test block), keeping the call sites (segment, with_view, lookup_internal_id,
internal_id) unchanged except for the explicit conversion.
lib/segment/tests/integration/scroll_filtering_test.rs (1)

31-50: ⚡ Quick win

Use the concrete constructor instead of .into() for the new scroll offsets.

Line 33 and Line 43 introduce new implicit conversions again. Please switch both call sites to the explicit ID/offset constructor that filtered_read_* expects so this test stays aligned with the repo's Rust style rule.

As per coding guidelines, **/*.rs: Prefer explicit SomeType::from(x) over implicit x.into() in Rust

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/tests/integration/scroll_filtering_test.rs` around lines 31 - 50,
The test is using implicit conversions via Some(random_offset.into()) when
calling filtered_read_by_index and filtered_read_by_id_stream; replace those
.into() calls with the explicit constructor that the filtered_read_* functions
expect (use the concrete ID/offset constructor for the scroll offset) so both
call sites—filtered_read_by_index(...) and filtered_read_by_id_stream(...)
passing random_offset—use Some(ExplicitOffsetType::from(...)) (or the module's
concrete constructor) instead of .into() to comply with the project Rust style
rule.
lib/segment/src/segment/read_view/vectors.rs (1)

93-127: 💤 Low value

Deferred error pattern silently continues after first lookup failure.

The current implementation stores the first lookup_internal_id error and continues processing remaining IDs. This is a valid design choice for partial results, but the callback at line 118 silently skips points where external_id returns None without any debug assertion—unlike process_search_result in search.rs which includes a debug_assert! for this case.

Consider adding a debug_assert! for consistency with the search path, or document why silent skipping is intentional here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/read_view/vectors.rs` around lines 93 - 127,
read_vectors currently defers lookup_internal_id errors but silently skips
entries when id_tracker.external_id returns None; add a debug_assert (similar to
process_search_result in search.rs) inside the closure passed to
vectors_by_offsets to assert that external_id(Some) holds for any visited
point_offset, or alternatively add a comment documenting why silent skipping is
intentional. Locate the closure in read_vectors (the one invoking
id_tracker.external_id(point_offset) and calling callback) and insert a
debug_assert! referencing id_tracker.external_id and point_offset, or add a
clear comment above that closure explaining the design choice.
🤖 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/plain_payload_index.rs`:
- Around line 184-193: The formula_scorer in PlainPayloadIndex currently returns
an OperationError which causes formula/rescore queries to fail for unindexed
segments; replace the error path in PlainPayloadIndex::formula_scorer with a
non-index-backed fallback that constructs and returns an on-the-fly
FormulaScorer (i.e., a scorer that evaluates ParsedFormula against payloads at
query time using available prefetches_scores and hw_counter) instead of
Err(OperationError::service_error); locate the formula_scorer function and
instantiate/return the appropriate FormulaScorer<'q> (or a lightweight wrapper
implementing the same trait expected by callers) wrapped in Ok(...) so plain
segments can perform rescore without payload indexes.

In `@lib/segment/src/segment/read_view/deferred.rs`:
- Around line 36-39: has_deferred_points() currently checks deferred_internal_id
against id_tracker.total_point_count which can be true even when all deferred
points were deleted; change it to mirror the other helpers by returning whether
any deferred points actually exist. Replace the body of has_deferred_points() to
use the existing deferred_point_count() (or, if it returns Option<usize>,
map_or(false, |c| c > 0)) so the function returns true only when
deferred_point_count() > 0; keep references to deferred_point_count(),
deferred_point_ids(), deferred_internal_id(), and id_tracker.total_point_count()
in mind when locating the implementation.

In `@lib/segment/src/segment/read_view/payload.rs`:
- Around line 23-29: The new payload_by_offset now routes to
payload_index.get_payload which will hit the unreachable!() implementations in
PlainPayloadIndex; revert routing so payload reads come from the payload storage
or make the plain index delegate to storage. Specifically, change
payload_by_offset to call the payload storage accessor (e.g., use
self.payload_storage.get_payload/ payload(...) equivalent) instead of
payload_index.get_payload, or implement PlainPayloadIndex::get_payload to
forward to the underlying payload_storage so payload(), retrieve(...,
with_payload) and payload_by_offset all return stored payloads rather than
panicking.

In `@lib/segment/src/segment/read_view/search.rs`:
- Around line 183-190: The error message passed to OperationError::service_error
in the block that obtains point_version from self.id_tracker.internal_version
contains a typo ("Corrupter"); update the string to "Corrupted" so the message
reads "Corrupted id_tracker, no version for point {point_id}". Locate the call
inside the search/read view code where point_version is set (the
self.id_tracker.internal_version(...).ok_or_else(...) closure) and change the
message there.

---

Nitpick comments:
In `@lib/segment/src/segment/read_view/mod.rs`:
- Line 29: Remove the temporary #[allow(unused, dead_code)] attributes applied
to the read-view type and its impl block in mod.rs: delete the attribute on the
struct declaration (the read-view type defined near the top of the file) and the
attribute on its corresponding impl block (the impl around the mid of the file)
so compiler lints are enforced once downstream consumers (entry.rs and read-view
submodules) are wired up.

In `@lib/segment/src/segment/read_view/vectors.rs`:
- Around line 93-127: read_vectors currently defers lookup_internal_id errors
but silently skips entries when id_tracker.external_id returns None; add a
debug_assert (similar to process_search_result in search.rs) inside the closure
passed to vectors_by_offsets to assert that external_id(Some) holds for any
visited point_offset, or alternatively add a comment documenting why silent
skipping is intentional. Locate the closure in read_vectors (the one invoking
id_tracker.external_id(point_offset) and calling callback) and insert a
debug_assert! referencing id_tracker.external_id and point_offset, or add a
clear comment above that closure explaining the design choice.

In `@lib/segment/src/segment/tests/mod.rs`:
- Around line 922-924: Replace unchecked cast usage like `i as u32 - 1` before
calling `segment.with_view(|v| v.payload_by_offset(..., &hw_counter))` with a
checked conversion: call `PointOffsetType::try_from(i - 1)` and handle the
Result (propagate or unwrap with a clear message) so the offset cast cannot
silently truncate; add `use common::types::PointOffsetType;` to the imports and
apply the same replacement for the other occurrences around `payload_by_offset`
at the later block (lines noted in the comment).
- Around line 356-358: Replace the implicit .into() conversions when calling
lookup_internal_id with an explicit PointIdType::from(...) to match the coding
guideline; specifically change calls like segment.with_view(|v|
v.lookup_internal_id(6.into())) to use PointIdType::from(6) (and likewise update
the other occurrences around the later test block), keeping the call sites
(segment, with_view, lookup_internal_id, internal_id) unchanged except for the
explicit conversion.

In `@lib/segment/tests/integration/scroll_filtering_test.rs`:
- Around line 31-50: The test is using implicit conversions via
Some(random_offset.into()) when calling filtered_read_by_index and
filtered_read_by_id_stream; replace those .into() calls with the explicit
constructor that the filtered_read_* functions expect (use the concrete
ID/offset constructor for the scroll offset) so both call
sites—filtered_read_by_index(...) and filtered_read_by_id_stream(...) passing
random_offset—use Some(ExplicitOffsetType::from(...)) (or the module's concrete
constructor) instead of .into() to comply with the project Rust style rule.
🪄 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: c68b68b5-055e-496d-a9c8-6479c2106764

📥 Commits

Reviewing files that changed from the base of the PR and between cdc3a21 and 645a1a5.

📒 Files selected for processing (37)
  • lib/collection/src/shards/local_shard/snapshot.rs
  • lib/common/common/src/either_variant.rs
  • lib/segment/src/entry/entry_point.rs
  • lib/segment/src/index/field_index/facet_index.rs
  • lib/segment/src/index/field_index/field_index_base.rs
  • lib/segment/src/index/field_index/mod.rs
  • lib/segment/src/index/field_index/numeric_index/mod.rs
  • lib/segment/src/index/hnsw_index/hnsw.rs
  • lib/segment/src/index/payload_index_base.rs
  • lib/segment/src/index/plain_payload_index.rs
  • lib/segment/src/index/plain_vector_index.rs
  • lib/segment/src/index/query_optimization/rescore_formula/formula_scorer.rs
  • lib/segment/src/index/query_optimization/rescore_formula/mod.rs
  • lib/segment/src/index/query_optimization/rescore_formula/value_retriever.rs
  • lib/segment/src/index/sparse_index/sparse_vector_index.rs
  • lib/segment/src/index/struct_payload_index.rs
  • lib/segment/src/index/vector_index_base.rs
  • lib/segment/src/segment/as_view.rs
  • lib/segment/src/segment/entry.rs
  • lib/segment/src/segment/mod.rs
  • lib/segment/src/segment/read_view/deferred.rs
  • lib/segment/src/segment/read_view/facet.rs
  • lib/segment/src/segment/read_view/formula_rescore.rs
  • lib/segment/src/segment/read_view/info.rs
  • lib/segment/src/segment/read_view/mod.rs
  • lib/segment/src/segment/read_view/order_by.rs
  • lib/segment/src/segment/read_view/payload.rs
  • lib/segment/src/segment/read_view/sampling.rs
  • lib/segment/src/segment/read_view/scroll.rs
  • lib/segment/src/segment/read_view/search.rs
  • lib/segment/src/segment/read_view/segment_ops.rs
  • lib/segment/src/segment/read_view/vectors.rs
  • lib/segment/src/segment/search.rs
  • lib/segment/src/segment/segment_ops.rs
  • lib/segment/src/segment/tests/mod.rs
  • lib/segment/src/segment/vectors.rs
  • lib/segment/tests/integration/scroll_filtering_test.rs
💤 Files with no reviewable changes (1)
  • lib/segment/src/segment/vectors.rs

Comment on lines +184 to +193
fn formula_scorer<'q>(
&'q self,
_parsed_formula: &'q ParsedFormula,
_prefetches_scores: &'q [AHashMap<PointOffsetType, ScoreType>],
_hw_counter: &'q HardwareCounterCell,
) -> OperationResult<FormulaScorer<'q>> {
Err(OperationError::service_error(
"Formula scoring is not supported by PlainPayloadIndex",
))
}

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't make formula scoring fail on plain segments.

PlainPayloadIndex is the normal read path for small/unindexed segments, so returning a hard error here makes formula/rescore queries fail for those segments outright. This needs a non-index-backed scorer fallback instead of OperationError, otherwise behavior now depends on whether the segment happened to build payload indexes.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/plain_payload_index.rs` around lines 184 - 193, The
formula_scorer in PlainPayloadIndex currently returns an OperationError which
causes formula/rescore queries to fail for unindexed segments; replace the error
path in PlainPayloadIndex::formula_scorer with a non-index-backed fallback that
constructs and returns an on-the-fly FormulaScorer (i.e., a scorer that
evaluates ParsedFormula against payloads at query time using available
prefetches_scores and hw_counter) instead of Err(OperationError::service_error);
locate the formula_scorer function and instantiate/return the appropriate
FormulaScorer<'q> (or a lightweight wrapper implementing the same trait expected
by callers) wrapped in Ok(...) so plain segments can perform rescore without
payload indexes.

Comment on lines +36 to +39
pub fn has_deferred_points(&self) -> bool {
self.deferred_internal_id().is_some_and(|deferred_from| {
self.id_tracker.total_point_count() > deferred_from as usize
})

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make has_deferred_points() match the other deferred helpers.

If all deferred points have been deleted, total_point_count() > deferred_from is still true, so this returns true while deferred_point_count() and deferred_point_ids() are already empty. That makes the API inconsistent and can trigger unnecessary deferred-point handling.

Suggested fix
     pub fn has_deferred_points(&self) -> bool {
-        self.deferred_internal_id().is_some_and(|deferred_from| {
-            self.id_tracker.total_point_count() > deferred_from as usize
-        })
+        self.deferred_point_count() > 0
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/read_view/deferred.rs` around lines 36 - 39,
has_deferred_points() currently checks deferred_internal_id against
id_tracker.total_point_count which can be true even when all deferred points
were deleted; change it to mirror the other helpers by returning whether any
deferred points actually exist. Replace the body of has_deferred_points() to use
the existing deferred_point_count() (or, if it returns Option<usize>,
map_or(false, |c| c > 0)) so the function returns true only when
deferred_point_count() > 0; keep references to deferred_point_count(),
deferred_point_ids(), deferred_internal_id(), and id_tracker.total_point_count()
in mind when locating the implementation.

Comment on lines +23 to +29
pub fn payload_by_offset(
&self,
point_offset: PointOffsetType,
hw_counter: &HardwareCounterCell,
) -> OperationResult<Payload> {
self.payload_index.get_payload(point_offset, hw_counter)
}

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Don't route payload reads through PayloadIndexRead yet.

This now calls payload_index.get_payload(...), but PlainPayloadIndex still implements both payload getters as unreachable!() in lib/segment/src/index/plain_payload_index.rs:153-167. Any payload()/retrieve(..., with_payload) on a plain segment will panic instead of returning stored payloads. Please keep this on payload_storage, or make the plain index delegate payload reads correctly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/read_view/payload.rs` around lines 23 - 29, The new
payload_by_offset now routes to payload_index.get_payload which will hit the
unreachable!() implementations in PlainPayloadIndex; revert routing so payload
reads come from the payload storage or make the plain index delegate to storage.
Specifically, change payload_by_offset to call the payload storage accessor
(e.g., use self.payload_storage.get_payload/ payload(...) equivalent) instead of
payload_index.get_payload, or implement PlainPayloadIndex::get_payload to
forward to the underlying payload_storage so payload(), retrieve(...,
with_payload) and payload_by_offset all return stored payloads rather than
panicking.

Comment on lines +183 to +190
let point_version =
self.id_tracker
.internal_version(point_offset)
.ok_or_else(|| {
OperationError::service_error(format!(
"Corrupter id_tracker, no version for point {point_id}"
))
})?;

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Typo in error message: "Corrupter" should be "Corrupted".

📝 Proposed fix
             let point_version =
                 self.id_tracker
                     .internal_version(point_offset)
                     .ok_or_else(|| {
                         OperationError::service_error(format!(
-                            "Corrupter id_tracker, no version for point {point_id}"
+                            "Corrupted id_tracker, no version for point {point_id}"
                         ))
                     })?;
📝 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.

Suggested change
let point_version =
self.id_tracker
.internal_version(point_offset)
.ok_or_else(|| {
OperationError::service_error(format!(
"Corrupter id_tracker, no version for point {point_id}"
))
})?;
let point_version =
self.id_tracker
.internal_version(point_offset)
.ok_or_else(|| {
OperationError::service_error(format!(
"Corrupted id_tracker, no version for point {point_id}"
))
})?;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/read_view/search.rs` around lines 183 - 190, The
error message passed to OperationError::service_error in the block that obtains
point_version from self.id_tracker.internal_version contains a typo
("Corrupter"); update the string to "Corrupted" so the message reads "Corrupted
id_tracker, no version for point {point_id}". Locate the call inside the
search/read view code where point_version is set (the
self.id_tracker.internal_version(...).ok_or_else(...) closure) and change the
message there.

@timvisee timvisee left a comment

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 evaluated and approved the general concept of this PR in a call.

@generall
generall merged commit 81ea504 into dev May 4, 2026
15 checks passed
@generall
generall deleted the read-only-segment-step-1 branch May 4, 2026 11:31
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.

2 participants