Skip to content

refactor(index): drop PayloadIndex: PayloadIndexRead super-trait - #8969

Merged
generall merged 2 commits into
devfrom
generall/payload-index-trait-split
May 9, 2026
Merged

generall merged 2 commits into
devfrom
generall/payload-index-trait-split

Conversation

@generall

@generall generall commented May 9, 2026

Copy link
Copy Markdown
Member

Summary

  • Drops the PayloadIndex: PayloadIndexRead super-trait at lib/segment/src/index/payload_index_base.rs:149. The two traits are now siblings: PayloadIndex for writes, PayloadIndexRead for reads.
  • Adds a doc comment on PayloadIndex directing callers to bring PayloadIndexRead into scope explicitly when they also need reads.
  • One-line code change; no consumer updates required.

Why

This unblocks a future StructPayloadIndexReadView<'a, P: PayloadStorageRead> (mirror of SegmentReadView) that implements PayloadIndexRead but should not implement the writable PayloadIndex -- the view is borrow-based and has no mutating semantics. Today the super-trait would force any PayloadIndex impl to also be PayloadIndexRead, but it does not force the converse, which is what we actually need: read-only impls without a write surface.

Audit

Pre-merge grep:

  • grep "PayloadIndex\b" filtered for trait usage (excluding PayloadIndexInfo, PayloadIndexParams, FullPayloadIndexType, StructPayloadIndex, PlainPayloadIndex, etc.) returned no generic bound sites in the workspace.
  • The only consumers are the two impl PayloadIndex for ... blocks (StructPayloadIndex, PlainPayloadIndex) and a handful of use imports in tests / fixtures / benches.
  • Both impl blocks already have an independent impl PayloadIndexRead for ... companion, so dropping the super-trait does not leave them in an inconsistent state.

Test plan

  • cargo build --workspace --tests --benches -- green, no consumer changes needed
  • cargo test -p segment --lib -- 665 passed, 0 failed
  • cargo test -p segment --tests -- 120 passed, 0 failed (integration tests)
  • cargo test -p storage --lib -- 44 passed
  • cargo test -p collection --lib -- 197 passed
  • cargo clippy -p segment --tests --benches -- clean

🤖 Generated with Claude Code

`PayloadIndex` now only declares the mutating surface; reads live on
the sibling `PayloadIndexRead` trait. The previous super-trait
relationship forced any type that implemented `PayloadIndex` to also
implement `PayloadIndexRead`, blocking a future `PayloadIndexRead`-only
view that doesn't (and shouldn't) own the writable index machinery.

No behavioural change. Audit before committing showed no generic
bound site on `PayloadIndex` exists in the workspace, and every
caller that uses read methods already imports `PayloadIndexRead`
explicitly (the trait was already used as a generic bound on
`SegmentReadView`'s `TPayloadIndex` parameter and on
`iter_filtered_points`). The full workspace builds clean and all
segment / storage / collection tests pass without any consumer
update.

Doc comment on `PayloadIndex` updated to point readers at
`PayloadIndexRead` for the read surface.

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

coderabbitai Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change removes the PayloadIndex: PayloadIndexRead supertrait relationship and documents that read operations require PayloadIndexRead in scope. A new read-only wrapper type StructPayloadIndexReadView was added and re-exported; read-only implementations (PayloadIndexRead), condition conversion, filtering, optimizer, and variable retriever logic were moved onto that view. StructPayloadIndex::with_view was added and many call sites (HNSW, plain/sparse vector indexes, segment builder, tests, benches) were updated to use .with_view(|v| ...) for read operations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • qdrant/qdrant#8967: Changes to types that implement both PayloadIndex and PayloadIndexRead traits, affected by the trait relationship modification.
  • qdrant/qdrant#8858: Earlier trait refactoring in the same file that introduced PayloadIndexRead and established the supertrait relationship now being reversed.
  • qdrant/qdrant#8965: File-level edits in the same payload_index_base.rs touching the trait declaration area.

Suggested labels

release:1.18.0

Suggested reviewers

  • dancixx
  • xzfc
  • coszio
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main architectural change: removing the super-trait relationship between PayloadIndex and PayloadIndexRead, making them sibling traits instead.
Description check ✅ Passed The description is comprehensive and directly related to the changeset. It explains the why (unblocking read-only view implementations), the what (dropping the super-trait), and provides audit/testing evidence.
Docstring Coverage ✅ Passed Docstring coverage is 91.30% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch generall/payload-index-trait-split

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.

Move the read surface of `StructPayloadIndex` onto a new borrowed view
struct generic over `<P: PayloadStorageRead, I: IdTrackerRead, V: VectorStorageRead>`.
The view holds exactly the fields that `PayloadIndexRead` requires --
no more, no less:

    pub struct StructPayloadIndexReadView<'a, P, I, V> {
        payload:         &'a Arc<AtomicRefCell<P>>,
        id_tracker:      &'a I,
        vector_storages: &'a HashMap<VectorNameBuf, Arc<AtomicRefCell<V>>>,
        field_indexes:   &'a IndexesMap,
        config:          &'a PayloadConfig,
        visited_pool:    &'a VisitedPool,
    }

`StructPayloadIndex` now exposes a `with_view(|v| ...)` accessor that
borrows `id_tracker` once at the top and constructs the view for the
closure scope. All read-method bodies move onto the view, which is the
sole `PayloadIndexRead` implementor for this index.

Why three generics
==================
- `P: PayloadStorageRead` -- already generic via PR #8968.
- `I: IdTrackerRead` -- direct method calls; held as `&I` (not
  `&Arc<AtomicRefCell<I>>`) because the cell is collapsed at the
  `with_view` boundary, saving a per-method `borrow()` atomic op.
  `dyn IdTrackerRead` does not satisfy `I: IdTrackerRead` bounds in
  Rust without an explicit blanket impl, so generic is the only
  consistent option here.
- `V: VectorStorageRead` -- the only access site is
  `available_vector_count()` for the `HasVector` cardinality branch
  (`condition_cardinality` in `read_view/filtering.rs`).

Why `payload` keeps the `Arc`
=============================
`PayloadProvider<P>::new(...)` (introduced in PR #8968) takes
`Arc<AtomicRefCell<P>>` so that the returned `FormulaScorer<'q>` /
`Box<dyn FilterContext + 'a>` can outlive the caller frame. The view
therefore holds `&'a Arc<AtomicRefCell<P>>` (asymmetric vs the bare
`&I` for `id_tracker`). Switching to a borrow-based provider would
require reworking `formula_scorer` / `filter_context` to callback
style; deferred to a follow-up if needed.

What does NOT move
==================
- `build_field_indexes` and `clear_index_for_point` stay on
  `StructPayloadIndex`. `build_field_indexes` is read-shaped but only
  has write-side callers, and pulls in the `selector` machinery which
  uses `path` + `storage_type`. Keeping it on the writable struct
  means `path` and `is_appendable` do not need to leak into the view.
- The `selector` / `selector_with_type` helpers stay on the writable
  struct for the same reason.
- The free helpers in `query_optimization/condition_converter.rs`
  (range / geo / null / is-empty checkers) stay where they are; their
  visibility is bumped from `fn` to `pub(in crate::index)` so the view
  can still call them.

Module layout
=============
    lib/segment/src/index/struct_payload_index/
        mod.rs                          # owning struct + with_view
        build.rs                        # write-side build coordination
        payload_index.rs                # impl PayloadIndex (mutating only)
        tests.rs
        read_view/
            mod.rs                      # view struct + module wiring
            payload_index_read.rs       # impl PayloadIndexRead for view
            filtering.rs                # struct_filtered_context, condition_cardinality, query_field, estimate_field_condition
            condition_converter.rs      # impl block from query_optimization/
            optimizer.rs                # impl block from query_optimization/
            value_retriever.rs          # impl block from query_optimization/
            tests.rs                    # smoke test that builds the view directly

Consumer migration
==================
- `Segment::with_view` nests the new `StructPayloadIndex::with_view`
  inside it; `SegmentReadViewFor<'s>` uses the view as its
  `TPayloadIndex` parameter.
- HNSW (`hnsw.rs`), sparse (`sparse_vector_index.rs`), plain
  (`plain_vector_index.rs`) call sites wrap their read-method calls in
  `payload_index.borrow().with_view(|v| ...)`.
- `Segment::get_indexed_fields`, `update_all_field_indices`, and
  `SegmentBuilder::build` switch to `with_view` for `indexed_fields()`
  / `get_payload_sequential()`.
- Integration tests and benches similarly migrate.
- `set_payload` (still on `PayloadIndex` write impl) inlines its
  former `self.get_payload(...)` call as `self.payload.borrow().get(...)`
  to avoid going through `with_view` from a `&mut self` write path.

Smoke test (`read_view/tests.rs`) constructs the view directly over
`InMemoryPayloadStorage` + `InMemoryIdTracker` + an empty vector-storage
map, and exercises `indexed_fields()`, `query_points()`, and
`available_point_count()` -- proving the view is genuinely decoupled
from `StructPayloadIndex`. This is the abstraction PR 4 will use to
wire a read-only segment.

Verified
========
- `cargo build --workspace --tests --benches` -- green
- `cargo test -p segment --lib` -- 666 passed (665 + 1 new smoke test), 0 failed
- `cargo test -p segment --tests` -- 120 integration tests pass
- `cargo test -p storage --lib` -- 44 passed
- `cargo test -p collection --lib` -- 197 passed
- `cargo clippy -p segment --tests --benches` -- clean

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
lib/segment/src/index/struct_payload_index/read_view/tests.rs (1)

25-63: ⚡ Quick win

Exercise a non-empty filtered path in this smoke test.

All assertions currently run against empty/default state, so this still passes if direct view construction breaks payload-backed filtering or value retrieval. Seeding one point plus a simple filter would cover the code that was actually moved onto the view.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/index/struct_payload_index/read_view/tests.rs` around lines
25 - 63, The test currently only exercises empty/default paths so it won't catch
regressions in filtered queries or value retrieval on
StructPayloadIndexReadView; seed one point into the in-memory backends (use
InMemoryPayloadStorage via payload and register its ID in
InMemoryIdTracker/id_tracker), add a simple Filter that matches the seeded
payload, call view.query_points(&filter, &hw_counter, &is_stopped, None) and
assert the returned point ID set contains the seeded ID and that
view.available_point_count() reflects the tracker, so the test verifies
non-empty filtered behavior rather than only empty-state behavior.
lib/segment/src/index/struct_payload_index/read_view/optimizer.rs (1)

116-138: ⚡ Quick win

Replace the catch-all _ arm with explicit Condition variant matching.

The _ arm silently sends any unhandled Condition variant (including future ones) through the generic checker path, bypassing optimizer-specific logic. Explicitly enumerate all supported non-Filter variants to enforce compile-time completeness when new variants are added to the Condition enum.

♻️ Suggested change
         conditions
             .iter()
             .map(|condition| match condition {
                 Condition::Filter(filter) => {
                     let (optimized_filter, estimation) =
                         self.optimize_filter(filter, payload_provider.clone(), total, hw_counter)?;
                     Ok((OptimizedCondition::Filter(optimized_filter), estimation))
                 }
-                _ => {
+                Condition::Field(_)
+                | Condition::IsEmpty(_)
+                | Condition::IsNull(_)
+                | Condition::HasId(_)
+                | Condition::HasVector(_)
+                | Condition::Nested(_)
+                | Condition::CustomIdChecker(_) => {
                     let estimation = self.condition_cardinality(condition, None, hw_counter)?;
                     let condition_checker =
                         self.condition_converter(condition, payload_provider.clone(), hw_counter);
                     Ok((OptimizedCondition::Checker(condition_checker), estimation))
                 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/index/struct_payload_index/read_view/optimizer.rs` around
lines 116 - 138, In convert_conditions, avoid the catch-all `_` arm and instead
explicitly match every non-Filter Condition variant (e.g., list each current
variants such as Condition::IsNull, Condition::Match, Condition::Range, etc.)
and for each variant perform the same logic currently in the `_` arm: call
self.condition_cardinality(condition, None, hw_counter)? and build the
condition_checker via self.condition_converter(condition,
payload_provider.clone(), hw_counter) then return
Ok((OptimizedCondition::Checker(condition_checker), estimation)). This makes the
match exhaustive so adding new Condition variants will force you to handle them
at compile time; keep references to OptimizedCondition, condition_cardinality,
condition_converter, and convert_conditions when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/segment/benches/conditional_search.rs`:
- Around line 178-182: The struct benchmark currently uses .count() which
removes the allocation cost while the plain benchmark still uses
collect_vec().len(); make both measure identical work by updating the plain
benchmark to use iteration counting instead of collecting (or alternatively
revert this block to use sample.into_iter().collect_vec().len()); locate the
plain benchmark code that computes its filtered_count (the one calling
collect_vec().len()) and replace that collection-based measurement with the same
iteration-based approach used here (i.e., use .into_iter().filter(|id|
context.check(*id)).count()), ensuring the symbols struct_index.with_view,
filter_context, context.check and sample are used consistently across both
benches.

In `@lib/segment/tests/integration/nested_filtering_test.rs`:
- Around line 147-156: The test uses unchecked casts like NUM_POINTS as
PointOffsetType when building ranges for check_res0; change this to compute a
single validated value with
PointOffsetType::try_from(NUM_POINTS).expect("NUM_POINTS fits PointOffsetType")
and reuse that variable for all range boundaries (the construction of check_res0
and the similar check_res* ranges), replacing all direct `as PointOffsetType`
casts to prevent silent truncation; update references in the closure passed to
index.with_view and any other occurrences in nested_filtering_test.rs (e.g.,
where check_res0 is built) to use the validated value.

---

Nitpick comments:
In `@lib/segment/src/index/struct_payload_index/read_view/optimizer.rs`:
- Around line 116-138: In convert_conditions, avoid the catch-all `_` arm and
instead explicitly match every non-Filter Condition variant (e.g., list each
current variants such as Condition::IsNull, Condition::Match, Condition::Range,
etc.) and for each variant perform the same logic currently in the `_` arm: call
self.condition_cardinality(condition, None, hw_counter)? and build the
condition_checker via self.condition_converter(condition,
payload_provider.clone(), hw_counter) then return
Ok((OptimizedCondition::Checker(condition_checker), estimation)). This makes the
match exhaustive so adding new Condition variants will force you to handle them
at compile time; keep references to OptimizedCondition, condition_cardinality,
condition_converter, and convert_conditions when making the change.

In `@lib/segment/src/index/struct_payload_index/read_view/tests.rs`:
- Around line 25-63: The test currently only exercises empty/default paths so it
won't catch regressions in filtered queries or value retrieval on
StructPayloadIndexReadView; seed one point into the in-memory backends (use
InMemoryPayloadStorage via payload and register its ID in
InMemoryIdTracker/id_tracker), add a simple Filter that matches the seeded
payload, call view.query_points(&filter, &hw_counter, &is_stopped, None) and
assert the returned point ID set contains the seeded ID and that
view.available_point_count() reflects the tracker, so the test verifies
non-empty filtered behavior rather than only empty-state behavior.
🪄 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: 51b8c523-d69c-4041-95fd-a2d54cf26653

📥 Commits

Reviewing files that changed from the base of the PR and between 368c203 and 0c37fe8.

📒 Files selected for processing (30)
  • lib/segment/benches/boolean_filtering.rs
  • lib/segment/benches/conditional_search.rs
  • lib/segment/benches/range_filtering.rs
  • lib/segment/src/index/hnsw_index/hnsw.rs
  • lib/segment/src/index/plain_vector_index.rs
  • lib/segment/src/index/query_optimization/condition_converter.rs
  • lib/segment/src/index/query_optimization/mod.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/mod.rs
  • lib/segment/src/index/struct_payload_index/payload_index.rs
  • lib/segment/src/index/struct_payload_index/read_view/condition_converter.rs
  • lib/segment/src/index/struct_payload_index/read_view/filtering.rs
  • lib/segment/src/index/struct_payload_index/read_view/mod.rs
  • lib/segment/src/index/struct_payload_index/read_view/optimizer.rs
  • lib/segment/src/index/struct_payload_index/read_view/payload_index_read.rs
  • lib/segment/src/index/struct_payload_index/read_view/tests.rs
  • lib/segment/src/index/struct_payload_index/read_view/value_retriever.rs
  • lib/segment/src/segment/as_view.rs
  • lib/segment/src/segment/entry.rs
  • lib/segment/src/segment/read_view/mod.rs
  • lib/segment/src/segment/segment_ops.rs
  • lib/segment/src/segment_constructor/segment_builder.rs
  • lib/segment/tests/integration/exact_search_test.rs
  • lib/segment/tests/integration/filtering_context_check.rs
  • lib/segment/tests/integration/filtrable_hnsw_test.rs
  • lib/segment/tests/integration/nested_filtering_test.rs
  • lib/segment/tests/integration/payload_index_test.rs
  • lib/segment/tests/integration/sparse_vector_index_search_tests.rs
💤 Files with no reviewable changes (1)
  • lib/segment/src/index/query_optimization/mod.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/segment/src/index/query_optimization/rescore_formula/mod.rs
  • lib/segment/src/segment/entry.rs

Comment on lines +178 to +182
let filtered_count = struct_index.with_view(|v| {
let context = v.filter_context(&filter, &hw_counter).unwrap();
sample.into_iter().filter(|id| context.check(*id)).count()
});
result_size += filtered_count;

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

Keep the plain and struct context-check benchmarks measuring the same work.

This branch now uses .count() while the plain benchmark still pays for collect_vec().len(), so any delta between the two benches now includes an unrelated allocation change. Either update the plain benchmark the same way or keep the old collection cost here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/benches/conditional_search.rs` around lines 178 - 182, The struct
benchmark currently uses .count() which removes the allocation cost while the
plain benchmark still uses collect_vec().len(); make both measure identical work
by updating the plain benchmark to use iteration counting instead of collecting
(or alternatively revert this block to use
sample.into_iter().collect_vec().len()); locate the plain benchmark code that
computes its filtered_count (the one calling collect_vec().len()) and replace
that collection-based measurement with the same iteration-based approach used
here (i.e., use .into_iter().filter(|id| context.check(*id)).count()), ensuring
the symbols struct_index.with_view, filter_context, context.check and sample are
used consistently across both benches.

Comment on lines +147 to +156
let (res0, check_res0) = index.with_view(|v| {
let res0 = v
.query_points(&nested_filter_0, &hw_counter, &is_stopped, None)
.unwrap();
let filter_context = v.filter_context(&nested_filter_0, &hw_counter).unwrap();
let check_res0: Vec<_> = (0..NUM_POINTS as PointOffsetType)
.filter(|point_id| filter_context.check(*point_id as PointOffsetType))
.collect();
(res0, check_res0)
});

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

Guard the usize → PointOffsetType conversion.

NUM_POINTS as PointOffsetType is fine with the current fixture size, but it becomes a silent truncating cast if this test grows later. Please convert once with PointOffsetType::try_from(NUM_POINTS).expect(...) and reuse that value for the repeated check_res* ranges below.

Suggested change
         let (res0, check_res0) = index.with_view(|v| {
+            let num_points = PointOffsetType::try_from(NUM_POINTS)
+                .expect("NUM_POINTS must fit into PointOffsetType");
             let res0 = v
                 .query_points(&nested_filter_0, &hw_counter, &is_stopped, None)
                 .unwrap();
             let filter_context = v.filter_context(&nested_filter_0, &hw_counter).unwrap();
-            let check_res0: Vec<_> = (0..NUM_POINTS as PointOffsetType)
+            let check_res0: Vec<_> = (0..num_points)
                 .filter(|point_id| filter_context.check(*point_id as PointOffsetType))
                 .collect();
             (res0, check_res0)
         });

Based on learnings: "In code that computes offsets or casts counts to PointOffsetType (u32), avoid unsafe or unchecked casts from usize to PointOffsetType... validate the bound first and add an explicit assertion or guard."

📝 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 (res0, check_res0) = index.with_view(|v| {
let res0 = v
.query_points(&nested_filter_0, &hw_counter, &is_stopped, None)
.unwrap();
let filter_context = v.filter_context(&nested_filter_0, &hw_counter).unwrap();
let check_res0: Vec<_> = (0..NUM_POINTS as PointOffsetType)
.filter(|point_id| filter_context.check(*point_id as PointOffsetType))
.collect();
(res0, check_res0)
});
let (res0, check_res0) = index.with_view(|v| {
let num_points = PointOffsetType::try_from(NUM_POINTS)
.expect("NUM_POINTS must fit into PointOffsetType");
let res0 = v
.query_points(&nested_filter_0, &hw_counter, &is_stopped, None)
.unwrap();
let filter_context = v.filter_context(&nested_filter_0, &hw_counter).unwrap();
let check_res0: Vec<_> = (0..num_points)
.filter(|point_id| filter_context.check(*point_id as PointOffsetType))
.collect();
(res0, check_res0)
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/tests/integration/nested_filtering_test.rs` around lines 147 -
156, The test uses unchecked casts like NUM_POINTS as PointOffsetType when
building ranges for check_res0; change this to compute a single validated value
with PointOffsetType::try_from(NUM_POINTS).expect("NUM_POINTS fits
PointOffsetType") and reuse that variable for all range boundaries (the
construction of check_res0 and the similar check_res* ranges), replacing all
direct `as PointOffsetType` casts to prevent silent truncation; update
references in the closure passed to index.with_view and any other occurrences in
nested_filtering_test.rs (e.g., where check_res0 is built) to use the validated
value.

@generall
generall merged commit 8de9c11 into dev May 9, 2026
15 checks passed
@generall
generall deleted the generall/payload-index-trait-split branch May 9, 2026 21:39
generall added a commit that referenced this pull request May 22, 2026
* refactor(index): drop PayloadIndex: PayloadIndexRead super-trait

`PayloadIndex` now only declares the mutating surface; reads live on
the sibling `PayloadIndexRead` trait. The previous super-trait
relationship forced any type that implemented `PayloadIndex` to also
implement `PayloadIndexRead`, blocking a future `PayloadIndexRead`-only
view that doesn't (and shouldn't) own the writable index machinery.

No behavioural change. Audit before committing showed no generic
bound site on `PayloadIndex` exists in the workspace, and every
caller that uses read methods already imports `PayloadIndexRead`
explicitly (the trait was already used as a generic bound on
`SegmentReadView`'s `TPayloadIndex` parameter and on
`iter_filtered_points`). The full workspace builds clean and all
segment / storage / collection tests pass without any consumer
update.

Doc comment on `PayloadIndex` updated to point readers at
`PayloadIndexRead` for the read surface.

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

* refactor(index): introduce StructPayloadIndexReadView<P, I, V> (#8970)

Move the read surface of `StructPayloadIndex` onto a new borrowed view
struct generic over `<P: PayloadStorageRead, I: IdTrackerRead, V: VectorStorageRead>`.
The view holds exactly the fields that `PayloadIndexRead` requires --
no more, no less:

    pub struct StructPayloadIndexReadView<'a, P, I, V> {
        payload:         &'a Arc<AtomicRefCell<P>>,
        id_tracker:      &'a I,
        vector_storages: &'a HashMap<VectorNameBuf, Arc<AtomicRefCell<V>>>,
        field_indexes:   &'a IndexesMap,
        config:          &'a PayloadConfig,
        visited_pool:    &'a VisitedPool,
    }

`StructPayloadIndex` now exposes a `with_view(|v| ...)` accessor that
borrows `id_tracker` once at the top and constructs the view for the
closure scope. All read-method bodies move onto the view, which is the
sole `PayloadIndexRead` implementor for this index.

Why three generics
==================
- `P: PayloadStorageRead` -- already generic via PR #8968.
- `I: IdTrackerRead` -- direct method calls; held as `&I` (not
  `&Arc<AtomicRefCell<I>>`) because the cell is collapsed at the
  `with_view` boundary, saving a per-method `borrow()` atomic op.
  `dyn IdTrackerRead` does not satisfy `I: IdTrackerRead` bounds in
  Rust without an explicit blanket impl, so generic is the only
  consistent option here.
- `V: VectorStorageRead` -- the only access site is
  `available_vector_count()` for the `HasVector` cardinality branch
  (`condition_cardinality` in `read_view/filtering.rs`).

Why `payload` keeps the `Arc`
=============================
`PayloadProvider<P>::new(...)` (introduced in PR #8968) takes
`Arc<AtomicRefCell<P>>` so that the returned `FormulaScorer<'q>` /
`Box<dyn FilterContext + 'a>` can outlive the caller frame. The view
therefore holds `&'a Arc<AtomicRefCell<P>>` (asymmetric vs the bare
`&I` for `id_tracker`). Switching to a borrow-based provider would
require reworking `formula_scorer` / `filter_context` to callback
style; deferred to a follow-up if needed.

What does NOT move
==================
- `build_field_indexes` and `clear_index_for_point` stay on
  `StructPayloadIndex`. `build_field_indexes` is read-shaped but only
  has write-side callers, and pulls in the `selector` machinery which
  uses `path` + `storage_type`. Keeping it on the writable struct
  means `path` and `is_appendable` do not need to leak into the view.
- The `selector` / `selector_with_type` helpers stay on the writable
  struct for the same reason.
- The free helpers in `query_optimization/condition_converter.rs`
  (range / geo / null / is-empty checkers) stay where they are; their
  visibility is bumped from `fn` to `pub(in crate::index)` so the view
  can still call them.

Module layout
=============
    lib/segment/src/index/struct_payload_index/
        mod.rs                          # owning struct + with_view
        build.rs                        # write-side build coordination
        payload_index.rs                # impl PayloadIndex (mutating only)
        tests.rs
        read_view/
            mod.rs                      # view struct + module wiring
            payload_index_read.rs       # impl PayloadIndexRead for view
            filtering.rs                # struct_filtered_context, condition_cardinality, query_field, estimate_field_condition
            condition_converter.rs      # impl block from query_optimization/
            optimizer.rs                # impl block from query_optimization/
            value_retriever.rs          # impl block from query_optimization/
            tests.rs                    # smoke test that builds the view directly

Consumer migration
==================
- `Segment::with_view` nests the new `StructPayloadIndex::with_view`
  inside it; `SegmentReadViewFor<'s>` uses the view as its
  `TPayloadIndex` parameter.
- HNSW (`hnsw.rs`), sparse (`sparse_vector_index.rs`), plain
  (`plain_vector_index.rs`) call sites wrap their read-method calls in
  `payload_index.borrow().with_view(|v| ...)`.
- `Segment::get_indexed_fields`, `update_all_field_indices`, and
  `SegmentBuilder::build` switch to `with_view` for `indexed_fields()`
  / `get_payload_sequential()`.
- Integration tests and benches similarly migrate.
- `set_payload` (still on `PayloadIndex` write impl) inlines its
  former `self.get_payload(...)` call as `self.payload.borrow().get(...)`
  to avoid going through `with_view` from a `&mut self` write path.

Smoke test (`read_view/tests.rs`) constructs the view directly over
`InMemoryPayloadStorage` + `InMemoryIdTracker` + an empty vector-storage
map, and exercises `indexed_fields()`, `query_points()`, and
`available_point_count()` -- proving the view is genuinely decoupled
from `StructPayloadIndex`. This is the abstraction PR 4 will use to
wire a read-only segment.

Verified
========
- `cargo build --workspace --tests --benches` -- green
- `cargo test -p segment --lib` -- 666 passed (665 + 1 new smoke test), 0 failed
- `cargo test -p segment --tests` -- 120 integration tests pass
- `cargo test -p storage --lib` -- 44 passed
- `cargo test -p collection --lib` -- 197 passed
- `cargo clippy -p segment --tests --benches` -- clean

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant