Skip to content

Callback-based FacetIndex - #8764

Merged
xzfc merged 3 commits into
devfrom
uio-FacetIndex-callbacks
Apr 24, 2026
Merged

xzfc merged 3 commits into
devfrom
uio-FacetIndex-callbacks

Conversation

@xzfc

@xzfc xzfc commented Apr 22, 2026

Copy link
Copy Markdown
Member

Preparation for MmapHashMap UIO migration.

Goal: in MmapMapIndex, get rid of methods that require MmapHashMap to return an iterator.
Implementing some calback-based interface for UniversalHashMap is easier than keeping MmapHashMap-like iterator-based interface.
This PR is first part of doing so.

@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: 3

🧹 Nitpick comments (1)
lib/segment/src/index/field_index/map_index/mod.rs (1)

1260-1302: Prefer FacetValueRef::from(v) over .into() (style nit).

Per repo guideline, new code should prefer explicit SomeType::from(x). The new callback adapters use implicit .into() in several spots (e.g. v.borrow().into(), v.into(), value.into()). Note this requires flipping the FacetIndex-impl bounds from Into<FacetValueRef<'a>> to FacetValueRef<'a>: From<&'a N> / From<Cow<'a, N>> so FacetValueRef::from(...) is callable, so happy to defer if you'd rather keep this strictly additive.

Illustrative diff (also requires updating the two `Into>` bounds at lines 1251–1252)
-            MapIndex::Mutable(index) => index.for_points_values(points, |idx, slice| {
-                f(idx, &mut slice.iter().map(|v| v.borrow().into()));
-            }),
-            MapIndex::Immutable(index) => index.for_points_values(points, |idx, slice| {
-                f(idx, &mut slice.iter().map(|v| v.borrow().into()));
-            }),
-            MapIndex::Mmap(index) => index.for_points_values(points, hw_counter, |idx, vals| {
-                f(idx, &mut vals.map(|v| v.into()));
-            })?,
+            MapIndex::Mutable(index) => index.for_points_values(points, |idx, slice| {
+                f(idx, &mut slice.iter().map(|v| FacetValueRef::from(v.borrow())));
+            }),
+            MapIndex::Immutable(index) => index.for_points_values(points, |idx, slice| {
+                f(idx, &mut slice.iter().map(|v| FacetValueRef::from(v.borrow())));
+            }),
+            MapIndex::Mmap(index) => index.for_points_values(points, hw_counter, |idx, vals| {
+                f(idx, &mut vals.map(FacetValueRef::from));
+            })?,

As per coding guideline: "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/src/index/field_index/map_index/mod.rs` around lines 1260 - 1302,
Replace the implicit .into() conversions with explicit FacetValueRef::from(...)
calls and update the generic trait bounds on the FacetIndex impls so the
convertibility is expressed as FacetValueRef<'a>: From<&'a N> and/or
From<Cow<'a, N>> instead of Into<FacetValueRef<'a>>; specifically change the
closures in MapIndex::Mutable/Immutable/ Mmap invocations (the closures passed
to for_points_values that currently use v.borrow().into(), v.into(), and
vals.map(|v| v.into())), the adapter in for_each_value (the inner call
f(v.into())), for_each_value_map (f(value.into(), ...)), and
for_each_count_per_value (value.into()) to call FacetValueRef::from(...) so all
conversions are explicit and the trait bounds on FacetIndex are adjusted to
enable FacetValueRef::from(...) calls.
🤖 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/facet_index.rs`:
- Around line 81-85: The code uses id_iter.take_while(|&id| id <
deferred_internal_id).next().is_some() inside self.for_each_value_map which
wrongly assumes id_iter is sorted; replace that take_while chain with a full
scan that checks any id is less than deferred_internal_id (e.g.,
id_iter.any(|&id| id < deferred_internal_id) or id_iter.find(|&id| id <
deferred_internal_id).is_some()) in the closure (the one receiving facet_value
and id_iter) so deferred visibility is detected correctly regardless of
ordering.

In `@lib/segment/src/index/field_index/map_index/mmap_map_index.rs`:
- Around line 246-249: for_points_values is yielding values for points that may
have been soft-deleted by remove_point; before calling
self.storage.point_to_values.values_iter(...) skip any point that is marked
deleted (mirror the same deleted check used by get_values/values_count). Modify
the closure in points.try_for_each to first check the storage deleted marker
(e.g., call the existing is_deleted/is_point_deleted method or inspect
self.storage.deleted bitset) for idx and return Ok(()) early for deleted points,
then proceed to call point_to_values.values_iter(idx, hw_counter) and f(idx,
iter).

In `@lib/segment/src/segment/facet.rs`:
- Around line 86-102: The debug-only sorted iterator logic and the use of
dedup()/take_while assume the iterator is sorted, which is false for mmap-backed
for_each_value_map; this can trigger the debug_assert and incorrectly drop later
IDs. Replace the debug prev_id/inspect block and the dedup() + take_while
sequence in the counting code that references iter, dedup(), take_while,
deferred_internal_id(), PointOffsetType::MAX and context.check with a full
deferred filter that explicitly filters out IDs >= deferred_internal_id() and
then applies a uniqueness pass (e.g., unique() over the whole stream rather than
dedup()) before applying context.check and count(), ensuring correct behavior
for unsorted value-point lists.

---

Nitpick comments:
In `@lib/segment/src/index/field_index/map_index/mod.rs`:
- Around line 1260-1302: Replace the implicit .into() conversions with explicit
FacetValueRef::from(...) calls and update the generic trait bounds on the
FacetIndex impls so the convertibility is expressed as FacetValueRef<'a>:
From<&'a N> and/or From<Cow<'a, N>> instead of Into<FacetValueRef<'a>>;
specifically change the closures in MapIndex::Mutable/Immutable/ Mmap
invocations (the closures passed to for_points_values that currently use
v.borrow().into(), v.into(), and vals.map(|v| v.into())), the adapter in
for_each_value (the inner call f(v.into())), for_each_value_map (f(value.into(),
...)), and for_each_count_per_value (value.into()) to call
FacetValueRef::from(...) so all conversions are explicit and the trait bounds on
FacetIndex are adjusted to enable FacetValueRef::from(...) calls.
🪄 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: 0c7a0daf-ffe8-44d0-9f93-c7fd7ccc9888

📥 Commits

Reviewing files that changed from the base of the PR and between 35ee534 and c90ee2d.

📒 Files selected for processing (9)
  • lib/segment/src/index/field_index/bool_index/mod.rs
  • lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs
  • lib/segment/src/index/field_index/facet_index.rs
  • lib/segment/src/index/field_index/immutable_point_to_values.rs
  • lib/segment/src/index/field_index/map_index/immutable_map_index.rs
  • lib/segment/src/index/field_index/map_index/mmap_map_index.rs
  • lib/segment/src/index/field_index/map_index/mod.rs
  • lib/segment/src/index/field_index/map_index/mutable_map_index.rs
  • lib/segment/src/segment/facet.rs

Comment thread lib/segment/src/segment/facet.rs Resolved
@qdrant qdrant deleted a comment from coderabbitai Bot Apr 22, 2026
Comment on lines 9 to 31
pub trait FacetIndex {
/// Get all values for a point
fn get_point_values(
/// Call a closure on value->point_ids mapping for specified `points`.
fn for_points_values(
&self,
point_id: PointOffsetType,
points: impl Iterator<Item = PointOffsetType>,
hw_counter: &HardwareCounterCell,
) -> impl Iterator<Item = FacetValueRef<'_>> + '_;
f: impl FnMut(PointOffsetType, &mut dyn Iterator<Item = FacetValueRef<'_>>),
) -> OperationResult<()>;

/// Get all values in the index
fn iter_values(&self) -> impl Iterator<Item = FacetValueRef<'_>> + '_;
/// Call a closure on each value in the index.
fn for_each_value(
&self,
f: impl FnMut(FacetValueRef<'_>) -> OperationResult<()>,
) -> OperationResult<()>;

/// Get all value->point_ids mappings
fn iter_values_map<'a>(
&'a self,
hw_acc: &'a HardwareCounterCell,
) -> impl Iterator<Item = (FacetValueRef<'a>, IdIter<'a>)> + 'a;
/// Call a closure on each value->point_ids mapping.
fn for_each_value_map(
&self,
hw_acc: &HardwareCounterCell,
f: impl FnMut(
FacetValueRef<'_>,
&mut dyn Iterator<Item = PointOffsetType>,
) -> OperationResult<()>,
) -> OperationResult<()>;

/// Get all value->count mappings
fn iter_counts_per_value(
/// Call a closure on each value->count mapping.
fn for_each_count_per_value(
&self,
deferred_internal_id: Option<PointOffsetType>,
) -> impl Iterator<Item = FacetHit<FacetValueRef<'_>>> + '_;
f: impl FnMut(FacetHit<FacetValueRef<'_>>) -> OperationResult<()>,
) -> OperationResult<()>;
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The core change is here. Notes:

  • for_points_values is now batched.
  • for_each_value_map operates on &mut dyn Iterator which is not worse than IdIter aka Box<dyn Iter>.

@xzfc
xzfc force-pushed the uio-FacetIndex-callbacks branch from c90ee2d to dc381f3 Compare April 22, 2026 09:57
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR changes many field-index traversal APIs from iterator-returning functions to callback-based, fallible visitor methods that return OperationResult<()>. Iterator-producing methods (iter_*, get_point_values, etc.) were replaced with for_each_* and for_points_values variants across BoolIndex, MapIndex (immutable/mmap/mutable), FacetIndex, and related modules. Callbacks now receive mutable iterators or value/count pairs and can short-circuit via OperationResult. Call sites in segment/facet.rs and other consumers were updated to aggregate results and perform early-stop checks within the new callbacks.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • generall
  • ffuugoo
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title "Callback-based FacetIndex" clearly summarizes the main change: converting FacetIndex APIs from iterator-returning methods to callback-based methods.
Description check ✅ Passed The description is directly related to the changeset, explaining the motivation (MmapHashMap UIO migration) and the approach (callback-based interface instead of iterator-based).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

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.

♻️ Duplicate comments (2)
lib/segment/src/index/field_index/facet_index.rs (1)

80-85: ⚠️ Potential issue | 🟠 Major

Use a full scan for deferred visibility checks.

take_while assumes id_iter is sorted, which is not guaranteed for mmap-backed value-point lists. This can hide a value when a deferred ID appears before a later visible ID.

🐛 Proposed fix
             Some(deferred_internal_id) => {
                 self.for_each_value_map(hw_counter, |facet_value, id_iter| {
-                    let has_visible_point = id_iter
-                        .take_while(|&id| id < deferred_internal_id)
-                        .next()
-                        .is_some();
+                    let has_visible_point = id_iter.any(|id| id < deferred_internal_id);
 
                     if has_visible_point {
                         f(facet_value)?;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/facet_index.rs` around lines 80 - 85, The
visibility check uses id_iter.take_while(...).next().is_some(), which wrongly
assumes id_iter is sorted; change the deferred visibility logic in the closure
passed to for_each_value_map (the hw_counter / deferred_internal_id path) to
perform a full scan of id_iter (e.g., use an any/find over all elements) so
every point is considered rather than stopping at the first non-matching id;
update the check that computes has_visible_point to scan the entire id_iter for
ids < deferred_internal_id instead of using take_while.
lib/segment/src/segment/facet.rs (1)

83-102: ⚠️ Potential issue | 🟠 Major

Avoid sorted-iterator assumptions when counting filtered facet hits.

for_each_value_map may yield unsorted mmap-backed point IDs, so the debug assertion can fire and take_while can skip later visible IDs. dedup() also only removes adjacent duplicates; use a full deferred filter plus unique().

🐛 Proposed fix
                 facet_index.for_each_value_map(hw_counter, |value, iter| {
                     check_process_stopped(is_stopped)?;
 
-                    #[cfg(debug_assertions)]
-                    let iter = {
-                        let mut prev_id = None;
-                        iter.inspect(move |&id| {
-                            let previous = prev_id.get_or_insert(id);
-                            debug_assert!(*previous <= id, "Sorted iter assertion broken");
-                            *previous = id;
-                        })
-                    };
-
                     let count = iter
-                        .dedup()
-                        .take_while(|&point_id| {
+                        .filter(|&point_id| {
                             point_id < self.deferred_internal_id().unwrap_or(PointOffsetType::MAX)
                         })
+                        .unique()
                         .filter(|&point_id| context.check(point_id))
                         .count();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/facet.rs` around lines 83 - 102, The code assumes the
iterator from facet_index.for_each_value_map yields sorted IDs (uses
debug_assert on ordering and take_while + dedup), which is unsafe for
mmap-backed unsorted data; change the counting logic inside the closure used by
facet_index.for_each_value_map to (1) remove the debug_assert and the
take_while, (2) replace the adjacency-only dedup() with a full uniqueness filter
(e.g., track seen PointOffsetType in a HashSet or use an iterator unique()
implementation) and (3) apply
deferred_internal_id().unwrap_or(PointOffsetType::MAX) and
context.check(point_id) as explicit filters before counting so only
non-deferred, visible, and unique point IDs are counted (reference: the closure
passed to facet_index.for_each_value_map, variables iter, dedup(), take_while,
deferred_internal_id(), and context.check).
🧹 Nitpick comments (1)
lib/segment/src/index/field_index/map_index/mod.rs (1)

1248-1303: Use explicit FacetValueRef::from(...) conversions.

The new generic forwarding code relies on several implicit .into() calls for FacetValueRef, which makes the target conversion harder to audit.

♻️ Proposed refactor
 where
     Vec<<N as MapIndexKey>::Owned>: Blob + Send + Sync,
-    for<'a> Cow<'a, N>: Into<FacetValueRef<'a>>,
-    for<'a> &'a N: Into<FacetValueRef<'a>>,
+    for<'a> FacetValueRef<'a>: From<Cow<'a, N>>,
+    for<'a> FacetValueRef<'a>: From<&'a N>,
 {
     fn for_points_values(
         &self,
         points: impl Iterator<Item = PointOffsetType>,
         hw_counter: &HardwareCounterCell,
@@
         match self {
             MapIndex::Mutable(index) => index.for_points_values(points, |idx, slice| {
-                f(idx, &mut slice.iter().map(|v| v.borrow().into()));
+                f(idx, &mut slice.iter().map(|v| FacetValueRef::from(v.borrow())));
             }),
             MapIndex::Immutable(index) => index.for_points_values(points, |idx, slice| {
-                f(idx, &mut slice.iter().map(|v| v.borrow().into()));
+                f(idx, &mut slice.iter().map(|v| FacetValueRef::from(v.borrow())));
             }),
             MapIndex::Mmap(index) => index.for_points_values(points, hw_counter, |idx, vals| {
-                f(idx, &mut vals.map(|v| v.into()));
+                f(idx, &mut vals.map(FacetValueRef::from));
             })?,
         }
         Ok(())
     }
@@
     fn for_each_value(
         &self,
         mut f: impl FnMut(FacetValueRef<'_>) -> OperationResult<()>,
     ) -> OperationResult<()> {
-        self.for_each_value(|v| f(v.into()))
+        self.for_each_value(|v| f(FacetValueRef::from(v)))
     }
@@
     ) -> OperationResult<()> {
-        self.for_each_value_map(hw_counter, |value, iter| f(value.into(), iter))
+        self.for_each_value_map(hw_counter, |value, iter| f(FacetValueRef::from(value), iter))
     }
@@
         mut f: impl FnMut(FacetHit<FacetValueRef<'_>>) -> OperationResult<()>,
     ) -> OperationResult<()> {
         self.for_each_count_per_value(deferred_internal_id, |value, count| {
             f(FacetHit {
-                value: value.into(),
+                value: FacetValueRef::from(value),
                 count,
             })
         })

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/src/index/field_index/map_index/mod.rs` around lines 1248 - 1303,
The impl for FacetIndex on MapIndex uses implicit .into() conversions; change
them to explicit FacetValueRef::from(...) calls. Specifically, in
for_points_values replace map(|v| v.borrow().into()) with map(|v|
FacetValueRef::from(v.borrow())) and replace vals.map(|v| v.into()) with
vals.map(|v| FacetValueRef::from(v)); in for_each_value, for_each_value_map and
for_each_count_per_value replace f(v.into()) / f(value.into(), ...) /
value.into() with FacetValueRef::from(v) / FacetValueRef::from(value) /
FacetValueRef::from(value) respectively so all conversions to FacetValueRef are
explicit; keep the same closure signatures and return types.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/segment/src/index/field_index/facet_index.rs`:
- Around line 80-85: The visibility check uses
id_iter.take_while(...).next().is_some(), which wrongly assumes id_iter is
sorted; change the deferred visibility logic in the closure passed to
for_each_value_map (the hw_counter / deferred_internal_id path) to perform a
full scan of id_iter (e.g., use an any/find over all elements) so every point is
considered rather than stopping at the first non-matching id; update the check
that computes has_visible_point to scan the entire id_iter for ids <
deferred_internal_id instead of using take_while.

In `@lib/segment/src/segment/facet.rs`:
- Around line 83-102: The code assumes the iterator from
facet_index.for_each_value_map yields sorted IDs (uses debug_assert on ordering
and take_while + dedup), which is unsafe for mmap-backed unsorted data; change
the counting logic inside the closure used by facet_index.for_each_value_map to
(1) remove the debug_assert and the take_while, (2) replace the adjacency-only
dedup() with a full uniqueness filter (e.g., track seen PointOffsetType in a
HashSet or use an iterator unique() implementation) and (3) apply
deferred_internal_id().unwrap_or(PointOffsetType::MAX) and
context.check(point_id) as explicit filters before counting so only
non-deferred, visible, and unique point IDs are counted (reference: the closure
passed to facet_index.for_each_value_map, variables iter, dedup(), take_while,
deferred_internal_id(), and context.check).

---

Nitpick comments:
In `@lib/segment/src/index/field_index/map_index/mod.rs`:
- Around line 1248-1303: The impl for FacetIndex on MapIndex uses implicit
.into() conversions; change them to explicit FacetValueRef::from(...) calls.
Specifically, in for_points_values replace map(|v| v.borrow().into()) with
map(|v| FacetValueRef::from(v.borrow())) and replace vals.map(|v| v.into()) with
vals.map(|v| FacetValueRef::from(v)); in for_each_value, for_each_value_map and
for_each_count_per_value replace f(v.into()) / f(value.into(), ...) /
value.into() with FacetValueRef::from(v) / FacetValueRef::from(value) /
FacetValueRef::from(value) respectively so all conversions to FacetValueRef are
explicit; keep the same closure signatures and return types.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 554cff00-0a17-44a8-aa81-315d0175c097

📥 Commits

Reviewing files that changed from the base of the PR and between c90ee2d and dc381f3.

📒 Files selected for processing (9)
  • lib/segment/src/index/field_index/bool_index/mod.rs
  • lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs
  • lib/segment/src/index/field_index/facet_index.rs
  • lib/segment/src/index/field_index/immutable_point_to_values.rs
  • lib/segment/src/index/field_index/map_index/immutable_map_index.rs
  • lib/segment/src/index/field_index/map_index/mmap_map_index.rs
  • lib/segment/src/index/field_index/map_index/mod.rs
  • lib/segment/src/index/field_index/map_index/mutable_map_index.rs
  • lib/segment/src/segment/facet.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/field_index/immutable_point_to_values.rs

@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.

♻️ Duplicate comments (1)
lib/segment/src/segment/facet.rs (1)

88-102: ⚠️ Potential issue | 🟠 Major

Remove the sorted-iterator assumption before this ships.

This path still assumes iter is sorted: the debug assertion can fire for mmap-backed lists, .take_while() can skip later visible IDs, and .dedup() only removes adjacent duplicates. Filter deferred IDs across the full stream and use unique() instead.

🐛 Proposed fix
-                    #[cfg(debug_assertions)]
-                    let iter = {
-                        let mut prev_id = None;
-                        iter.inspect(move |&id| {
-                            let previous = prev_id.get_or_insert(id);
-                            debug_assert!(*previous <= id, "Sorted iter assertion broken");
-                            *previous = id;
-                        })
-                    };
-
                     let count = iter
-                        .dedup()
-                        .take_while(|&point_id| point_id < max_id)
+                        .filter(|&point_id| point_id < max_id)
+                        .unique()
                         .filter(|&point_id| context.check(point_id))
                         .count();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/segment/facet.rs` around lines 88 - 102, The current logic
around iter assumes a sorted iterator (uses inspect with prev_id and
debug_assert, then dedup() and take_while()), which can skip or incorrectly
handle visible IDs for mmap-backed lists; replace this by removing the
sorted-only assertions and ordering-dependent operators and instead perform a
full-stream uniqueness and filtering pass: eliminate the
prev_id/inspect/debug_assert block, stop using take_while() and dedup(), and
apply a unique() (or equivalent global-uniqueness iterator) over iter before
calling filter(|&point_id| context.check(point_id)) and count(), ensuring every
ID is considered regardless of order or adjacency.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@lib/segment/src/segment/facet.rs`:
- Around line 88-102: The current logic around iter assumes a sorted iterator
(uses inspect with prev_id and debug_assert, then dedup() and take_while()),
which can skip or incorrectly handle visible IDs for mmap-backed lists; replace
this by removing the sorted-only assertions and ordering-dependent operators and
instead perform a full-stream uniqueness and filtering pass: eliminate the
prev_id/inspect/debug_assert block, stop using take_while() and dedup(), and
apply a unique() (or equivalent global-uniqueness iterator) over iter before
calling filter(|&point_id| context.check(point_id)) and count(), ensuring every
ID is considered regardless of order or adjacency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bfdd00cd-8544-4cb3-859c-aa2e76c51aa9

📥 Commits

Reviewing files that changed from the base of the PR and between dc381f3 and 5526986.

📒 Files selected for processing (1)
  • lib/segment/src/segment/facet.rs

@xzfc
xzfc force-pushed the uio-FacetIndex-callbacks branch from 5526986 to b509cb1 Compare April 24, 2026 13:35

@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: 1

🧹 Nitpick comments (1)
lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs (1)

242-256: Nit: hw_counter accounting is a flat 8 bytes per bucket.

incr_delta(u8::BITS as usize) adds a fixed 8 "bytes" per bucket regardless of how many point IDs the callback actually consumes from the iterator. The sibling in-memory backends in this PR track per-element cost via measure_hw_with_acc* on the inner iterator (e.g. MutableBoolIndex::filter on line 457-461, and MmapMapIndex::for_each_value_map on line 395-399). If the intent is per-point-id IO accounting parity with the rest of the index, consider wrapping the returned iterator with measure_hw_with_acc_and_fraction(..., u8::BITS as usize, |i| i.payload_index_io_read_counter()) (mirroring filter) instead of a fixed pre-increment.

Non-blocking — BoolIndex is RAM-backed, so the discrepancy is small in practice.

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

In `@lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs` around
lines 242 - 256, The hw_counter accounting in for_each_value_map currently calls
hw_counter.payload_index_io_read_counter().incr_delta(u8::BITS as usize) once
per bucket, which charges a flat 8 bytes regardless of how many point IDs are
consumed; change this to per-element accounting by wrapping the iterators
returned from self.storage.falses_flags.iter_trues() and
self.storage.trues_flags.iter_trues() with the same helper used elsewhere
(measure_hw_with_acc_and_fraction) so the counter is incremented per-item (use
the same u8::BITS as the byte weight and the iterator's
payload_index_io_read_counter() accessor), and pass those wrapped iterators into
the callback f instead of the raw iterators.
🤖 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/map_index/mod.rs`:
- Around line 1227-1276: Replace the implicit .into() conversions with explicit
FacetValueRef::from(...) in this FacetIndex impl: in for_points_values (the
closures passed to MapIndex::Mutable, MapIndex::Immutable and MapIndex::Mmap),
in for_each_value, in for_each_value_map and in for_each_count_per_value replace
each v.into() and value.into() with FacetValueRef::from(v) (i.e. use
FacetValueRef::from(...) for all six conversions) so the code uses the explicit
constructor rather than implicit Into.

---

Nitpick comments:
In `@lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs`:
- Around line 242-256: The hw_counter accounting in for_each_value_map currently
calls hw_counter.payload_index_io_read_counter().incr_delta(u8::BITS as usize)
once per bucket, which charges a flat 8 bytes regardless of how many point IDs
are consumed; change this to per-element accounting by wrapping the iterators
returned from self.storage.falses_flags.iter_trues() and
self.storage.trues_flags.iter_trues() with the same helper used elsewhere
(measure_hw_with_acc_and_fraction) so the counter is incremented per-item (use
the same u8::BITS as the byte weight and the iterator's
payload_index_io_read_counter() accessor), and pass those wrapped iterators into
the callback f instead of the raw iterators.
🪄 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: 54f01fdf-b6bf-4a2d-be0a-6f2afd848fd2

📥 Commits

Reviewing files that changed from the base of the PR and between 5526986 and b509cb1.

📒 Files selected for processing (10)
  • lib/segment/src/index/field_index/bool_index/immutable_bool_index.rs
  • lib/segment/src/index/field_index/bool_index/mod.rs
  • lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs
  • lib/segment/src/index/field_index/facet_index.rs
  • lib/segment/src/index/field_index/immutable_point_to_values.rs
  • lib/segment/src/index/field_index/map_index/immutable_map_index.rs
  • lib/segment/src/index/field_index/map_index/mmap_map_index.rs
  • lib/segment/src/index/field_index/map_index/mod.rs
  • lib/segment/src/index/field_index/map_index/mutable_map_index.rs
  • lib/segment/src/segment/facet.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/segment/src/index/field_index/immutable_point_to_values.rs
  • lib/segment/src/index/field_index/facet_index.rs

@xzfc
xzfc merged commit 9bea287 into dev Apr 24, 2026
15 checks passed
@xzfc
xzfc deleted the uio-FacetIndex-callbacks branch April 24, 2026 14:06
timvisee pushed a commit that referenced this pull request May 8, 2026
* Segment::approximate_facet: don't use iter

* Callback-based FacetIndex

* take deferred internal id out of the loop

---------

Co-authored-by: Luis Cossío <[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.

2 participants