Skip to content

refactor: read-only numeric index - #9038

Merged
generall merged 16 commits into
devfrom
read-only-numeric-index
May 14, 2026
Merged

generall merged 16 commits into
devfrom
read-only-numeric-index

Conversation

@generall

@generall generall commented May 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Refactors lib/segment's numeric_index along the same lines as the earlier map_index rework, and builds out a full read-only numeric index path (ReadOnlyNumericIndex / ReadOnlyNumericIndexInner) wired into ReadOnlyFieldIndex.

The work was done as a sequence of small, reviewable steps — each instruction below maps roughly to one or two commits.

Instructions, in order

  1. Refactor numeric_index as was done for map_index. As step 1, move MutableNumericIndex, ImmutableNumericIndex, and MmapNumericIndex into their own dedicated modules, each split into mod.rs, lifecycle.rs, and read_ops.rs as in map_index.
  2. Remove the redundant single-variant Storage enum in immutable_numeric_index and use MmapNumericIndex<T> directly.
  3. Do the same for mutable_numeric_index — drop its single-variant Storage enum.
  4. Similar to MapIndexRead, introduce a NumericIndexRead trait and move the common read functions into it across the mutable, immutable, and mmap numeric index variants.
  5. Similar to ReadOnlyAppendableMapIndex, implement ReadOnlyAppendableNumericIndex as the counterpart to MutableNumericIndex, reusing the existing in_memory_index part.
  6. Update MmapNumericIndex to expose the UniversalRead trait parameter with a default of MmapFile instead of a hard-coded type, and rename it to UniversalNumericIndex. Keep the enum variant names (still Mmap), which use MmapFile as the configured UniversalRead type.
  7. Split numeric_index/storage/mod.rs into read_ops and lifecycle.
  8. Implement NumericIndexRead for NumericIndexInner, so the read ops are part of the trait rather than loose functions.
  9. Similar to ReadOnlyMapIndex, implement ReadOnlyNumericIndexInner with two variants — one for ReadOnlyAppendableNumericIndex and one for the immutable stored format (UniversalNumericIndex) — placed under the storage/read_only module.
  10. Rename numeric_index/read_ops.rs to numeric_index_read.rs, then split numeric_index/mod.rs into read_ops and lifecycle.
  11. Keep NumericIndex in mod.rs; move the inherent impl NumericIndex block to lifecycle.rs and the PayloadFieldIndexRead impl to read_ops.rs.
  12. Move the Encodable trait out of lifecycle.rs into its own encodable.rs.
  13. Implement ReadOnlyNumericIndex.
  14. ReadOnlyNumericIndex should implement PayloadFieldIndexRead.
  15. Put the PayloadFieldIndexRead impl into numeric_index/read_only/read_ops.rs.
  16. The query helpers in query.rs and the per-NumericIndexInner impls in storage/trait_impls.rs were duplicated (along with some other functions). Make them use a single source of truth for the logic instead of duplicating.
  17. Propagate hw_counter properly through values_range_size instead of fabricating a disposable counter.
  18. Integrate the read-only numeric index into ReadOnlyFieldIndex.
  19. Generalize numeric_index/read_only/value_retriever.rs (promote to a trait) so the same function isn't repeated for every numeric variant.

Result

  • Each numeric-index storage variant lives in its own module split into mod.rs / lifecycle.rs / read_ops.rs.
  • NumericIndexRead is the shared read interface, implemented by every variant, the dispatch enum NumericIndexInner, and the read-only types.
  • query.rs holds the generic query logic (cardinality, filter, payload blocks, condition checker, range streaming) once, over NumericIndexRead; both the writable and read-only paths plug into it.
  • Read-only path: ReadOnlyAppendableNumericIndex, ReadOnlyNumericIndexInner, ReadOnlyNumericIndex, and ReadOnlyNumericFieldIndex, all wired into ReadOnlyFieldIndex with PayloadFieldIndexRead + FieldIndexRead.
  • UniversalNumericIndex is generic over UniversalRead with an MmapFile default.

Test plan

  • cargo check -p segment --all-targets
  • cargo clippy -p segment --all-targets -- -D warnings
  • cargo test -p segment --lib numeric_index (26 passed)

🤖 Generated with Claude Code

@generall generall changed the title refactor: split numeric index variants into dedicated modules refactor: read-only numeric index May 14, 2026
generall and others added 15 commits May 14, 2026 17:31
Move MutableNumericIndex, ImmutableNumericIndex, and MmapNumericIndex
into their own directories, each split into mod.rs (struct definitions),
lifecycle.rs (open/build/wipe/mutations), and read_ops.rs (accessors),
mirroring the map_index layout.

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

Replace `Storage<T>` wrappers around the only backing store with the
store types directly: `Gridstore<Vec<T>>` for `MutableNumericIndex` and
`Box<MmapNumericIndex<T>>` for `ImmutableNumericIndex`. Collapses the
trivial single-arm matches into direct method calls.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Mirror `MapIndexRead` from the map_index refactor: define a
`NumericIndexRead<T>` trait in `numeric_index/read_ops.rs` and implement
it on each of the three storage variants
(`MutableNumericIndex`, `ImmutableNumericIndex`, `MmapNumericIndex`).

Trait signatures are unified across variants — in-memory variants accept
and ignore the `hw_counter` argument that the mmap-backed variant uses
for IO tracking, and `total_unique_values_count`, `values_range`, and
`orderable_values_range` return `OperationResult` everywhere so the
dispatcher in `NumericIndexInner` can call them generically.

Variant-specific helpers that don't fit the shared shape stay as
inherent methods: `MutableNumericIndex::map()`,
`ImmutableNumericIndex::values_range_size()`, and
`MmapNumericIndex::{values_range_size, is_on_disk}`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Counterpart to `MutableNumericIndex`, mirroring `ReadOnlyAppendableMapIndex`
from the map_index refactor. It reuses the shared `InMemoryNumericIndex`
in-memory state but is backed by a `GridstoreReader` over generic
`UniversalRead` instead of a writable `Gridstore`, and implements
`NumericIndexRead` by forwarding to the in-memory index — no mutation
surface.

Loading / lifecycle (constructor, files, populate, clear_cache) will
follow in a separate change; the storage field is held only to pin the
on-disk layout for now.

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

Mirror `UniversalMapIndex`: the type is now generic over `S: UniversalRead`
with a `MmapFile` default, so the index can be served from any
`UniversalRead` backend (io_uring, disk-cache wrappers, …) rather than
the hard-coded `MmapFile`.

The `NumericIndexRead` impl and read-side helpers are generic over `S`;
`build` / `open` and the other lifecycle methods stay `MmapFile`-only
since they construct mmap-backed storage from a path. The
`NumericIndexInner::Mmap` enum variant keeps its name and uses the
default `S = MmapFile`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`storage/mod.rs` now holds only the `NumericIndexInner` enum and module
wiring. The variant-dispatch impls are split into sibling modules
matching the layout of the individual storage variants:

- `lifecycle.rs`: construction, persistence, file listing, cache
  control, and `remove_point`.
- `read_ops.rs`: read-path forwarding — value lookups, telemetry, RAM
  accounting, `is_on_disk`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The enum-level read dispatch was a set of inherent methods scattered
across storage/read_ops.rs and storage/statistics.rs with signatures
that drifted from the variant trait (`values_count` returned `usize`,
`max_values_per_point` vs `get_max_values_per_point`, a hand-rolled
`get_telemetry_data`). Make `NumericIndexInner` implement
`NumericIndexRead` directly so it shares one interface with the three
storage variants.

- All 12 trait methods are forwarded via match dispatch in
  storage/read_ops.rs; `values_range` / `orderable_values_range` box
  the per-variant iterators.
- `get_histogram`, `get_points_count`, `total_unique_values_count` move
  out of statistics.rs into the trait impl; `values_is_empty` and
  `get_telemetry_data` now come from the trait defaults.
- `point_ids_by_value` and `is_on_disk` stay as enum-only inherent
  helpers (not part of the shared trait).
- Callers updated: `NumericIndex::values_count` unwraps the now
  `Option`-returning trait method; `filter` boxes `point_ids_by_value`;
  `field_index.rs` and `numeric_field_index.rs` import the trait.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Read-only counterpart to `NumericIndexInner`, mirroring `ReadOnlyMapIndex`
from the map_index refactor. Lives under
`numeric_index/storage/read_only` and selects across the two read-only
storage backends:

- `Appendable(ReadOnlyAppendableNumericIndex<T, S>)` — loaded into RAM
  from the appendable Gridstore format.
- `Immutable(UniversalNumericIndex<T, S>)` — served directly from the
  immutable stored format.

Implements `NumericIndexRead` by forwarding each method to the active
variant; `values_is_empty` / `get_telemetry_data` come from the trait
defaults.

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

Two changes:

- Rename `numeric_index/read_ops.rs` (the `NumericIndexRead` trait
  definition) to `numeric_index_read.rs`, freeing the `read_ops` name.
- Split the leftover content of `numeric_index/mod.rs` into sibling
  modules, matching the per-variant layout:
  - `lifecycle.rs`: the `Encodable` key-format trait + impls and the
    `HISTOGRAM_*` construction constants.
  - `read_ops.rs`: the `StreamRange` trait and the `Range` →
    index-key-bounds conversion.

`mod.rs` now only wires modules and re-exports. `Encodable` and
`StreamRange` keep their public paths via re-export; `tests.rs` gains
explicit imports for the symbols it previously picked up through the
`mod.rs` glob.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`index.rs` only held the `NumericIndex` wrapper and its two impl blocks;
spread them to match the per-module layout used elsewhere:

- `NumericIndex` struct + `NumericIndexIntoInnerValue` trait → `mod.rs`
  (type definitions live with the module wiring).
- The inherent `impl NumericIndex` (open / build / cache control /
  storage introspection) → `lifecycle.rs`, alongside the `HISTOGRAM_*`
  seed constants.
- The `PayloadFieldIndexRead` impl → `read_ops.rs`.

Also move the `Encodable` key-format trait out of `lifecycle.rs` into
its own `encodable.rs`. `mod.rs` keeps re-exporting `Encodable` so its
public path is unchanged.

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

Read-only counterpart to `NumericIndex`, wrapping `ReadOnlyNumericIndexInner`
plus the payload value type parameter `P`. Implements both `NumericIndexRead`
and `PayloadFieldIndexRead` by forwarding to the inner storage-variant enum.

To support `PayloadFieldIndexRead` without duplicating the query logic, the
cardinality/filter/payload-block/condition-checker code is extracted into a
new `query` module of generic free functions over `NumericIndexRead<T>`.
`ReadOnlyNumericIndexInner` implements `PayloadFieldIndexRead` by plugging
into those helpers; `ReadOnlyNumericIndex` delegates to its inner.

The writable `NumericIndexInner` path is left untouched — its existing
variant-specialized `estimate_points` heuristic stays in `storage`.

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

The generic `query` helpers and the per-`NumericIndexInner` impls in
`storage/{trait_impls,statistics}.rs` had duplicated cardinality /
filter / payload-block / condition-checker logic. Collapse them onto
the shared `query` helpers:

- `storage/trait_impls.rs`: `PayloadFieldIndexRead for NumericIndexInner`
  now forwards each method to `query::*` instead of carrying its own copy.
- `storage/statistics.rs`: deleted — `range_cardinality` and
  `estimate_points` were duplicates of the `query` versions.
- `estimate_points` needs a range size; add `values_range_size` to the
  `NumericIndexRead` trait with a default that counts `values_range`,
  overridden by the `Immutable` / `Mmap` variants with their `O(log n)`
  boundary search. The `MutableNumericIndex::map()` accessor (its only
  caller was the old `estimate_points`) is removed.
- `values_range_size` takes `hw_counter` and threads it into
  `values_range` rather than fabricating a disposable counter.

`tests.rs` calls `query::range_cardinality` directly now that the
inherent method is gone.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Wire the four numeric variants (`IntIndex`, `DatetimeIndex`,
`FloatIndex`, `UuidIndex`) into `ReadOnlyFieldIndex`, mirroring
`FieldIndex`:

- `PayloadFieldIndexRead` / `FieldIndexRead` dispatch covers the new
  variants — telemetry, value counts, value retrievers, `as_numeric`.
- `ReadOnlyNumericFieldIndex` is the read-only counterpart of
  `NumericFieldIndex` (Int/Float order-by erasure over
  `ReadOnlyNumericIndexInner`); `as_numeric` returns it for the
  Int/Datetime/Float variants (UUIDs aren't numerically order-by-able,
  matching `FieldIndex`).
- `ReadOnlyNumericIndex` gains per-`(T, P)` `value_retriever` methods
  (in `read_only/value_retriever.rs`) and an `inner()` accessor.

`StreamRange` is now backed by a shared generic `query::stream_range`
helper over `NumericIndexRead`, implemented for both `NumericIndexInner`
and `ReadOnlyNumericIndexInner` — replacing the bespoke `EitherVariant`
dispatch in `storage/trait_impls.rs`.

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

The four per-`(T, P)` `value_retriever` methods were identical except
for the per-value `T -> Value` conversion. Extract that conversion into
a `NumericValueToJson` trait (one tiny impl per `(T, P)`) and keep a
single generic `value_retriever` that builds the retriever closure once.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@generall
generall force-pushed the read-only-numeric-index branch from 7c563ef to 9a91661 Compare May 14, 2026 15:38
@generall
generall marked this pull request as ready for review May 14, 2026 15:43
@generall
generall requested a review from dancixx May 14, 2026 15:43
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ece234e3-b605-4469-be9b-4be4c23f9391

📥 Commits

Reviewing files that changed from the base of the PR and between 9a91661 and 04cfaab.

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

📝 Walkthrough

Walkthrough

The PR refactors numeric field indexing: replaces MmapNumericIndex with a generic UniversalNumericIndex, splits numeric-index code into submodules (builders, encodable, lifecycle, mmap/mutable/immutable, read_ops, storage, query), adds the Encodable, NumericIndexRead, and StreamRange traits, implements read/write/mmap/gridstore-backed numeric index variants (including read-only wrappers), and expands ReadOnlyFieldIndex to include typed numeric and UUID variants. Multiple modules and tests are updated to use the new APIs and storage abstractions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • qdrant/qdrant#8978: Adds PayloadFieldIndexRead::condition_checker which this PR implements and wires into numeric/read-only index paths.
  • qdrant/qdrant#8966: Introduces the read/write trait split (PayloadFieldIndex → read/write traits) that this PR adapts numeric index implementations to.
  • qdrant/qdrant#9030: Nearby changes to ReadOnlyFieldIndex dispatch; both PRs modify the same read-only enum and match-arm wiring.

Suggested labels

release:1.18.0

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.59% 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 clearly summarizes the main change: refactoring the numeric index module to support read-only access, which is the core objective of the PR.
Description check ✅ Passed The description comprehensively explains the refactoring work, provides detailed step-by-step instructions, and documents the resulting architecture with clear objectives and test plan.
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 read-only-numeric-index

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

🧹 Nitpick comments (2)
lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/mod.rs (1)

38-44: 💤 Low value

Consider encapsulating InMemoryNumericIndex fields.

All fields of InMemoryNumericIndex are declared pub, which allows direct access from anywhere in the crate. While MutableNumericIndex uses pub(super) for controlled visibility, InMemoryNumericIndex exposes its internals more broadly. Consider whether pub(super) or accessor methods would provide better encapsulation.

🤖 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/field_index/numeric_index/mutable_numeric_index/mod.rs`
around lines 38 - 44, The InMemoryNumericIndex struct currently exposes all
internals as pub; narrow visibility to prevent uncontrolled access by changing
fields (map, histogram, points_count, max_values_per_point, point_to_values)
from pub to pub(super) or private and provide explicit accessor/mutator methods
on InMemoryNumericIndex (e.g., get_points_count(), get_map(), iter_points(),
push_point()/update_point()) as needed; update any call sites that currently
access fields directly (look for usages of InMemoryNumericIndex::map,
::histogram, ::points_count, ::max_values_per_point, ::point_to_values) and
replace them with the new accessors so MutableNumericIndex and other modules
retain only the intended controlled access.
lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/read_ops.rs (1)

97-97: ⚡ Quick win

Avoid .. in Point destructuring here.

Use explicit ignored fields (field_name: _) instead of .. so new Point fields can’t be silently skipped in this logic path.

As per coding guidelines: "Prefer explicit field ignoring using : _ over using .. in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)".

🤖 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/field_index/numeric_index/mmap_numeric_index/read_ops.rs`
at line 97, The closure currently destructures Point using `..` (map(|Point {
val, idx, .. }| (val, idx))) which can silently ignore newly added fields;
replace the `..` with explicit ignored fields for every other field on the Point
struct (e.g., `other_field: _, another_field: _`) so only `val` and `idx` are
taken and any new Point fields will require explicit handling; locate the
destructuring of `Point` in the map closure and expand it to list each remaining
field as `field_name: _`.
🤖 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/src/index/field_index/numeric_index/immutable_numeric_index/lifecycle.rs`:
- Around line 86-103: The loop in remove_point currently calls
self.storage.remove_point(idx) for every value, causing redundant updates to the
in-memory deletion bitvec; move the single call to
self.storage.remove_point(idx) outside the for value in removed_values loop so
it is invoked once per point. Specifically, inside pub(in super::super) fn
remove_point(&mut self, idx: PointOffsetType) handle removal of entries via
Self::remove_from_map(&mut self.map, &mut self.histogram, &key) for each value,
update removed_count and points_count as before, but call
self.storage.remove_point(idx) once after the loop (and only if removed_count >
0) and before calling self.point_to_values.remove_point(idx).

In
`@lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/read_ops.rs`:
- Around line 31-42: The code currently swallows mmap read errors by calling
.check_values_any(...).unwrap_or(false); instead propagate the OperationResult
instead of coercing failures to false: modify the caller path of
NumericIndexRead::check_values_any (and similar call sites using
point_to_values.check_values_any) to return OperationResult<bool> (or map the
inner result) and use ? (or map_err) so read errors bubble up; ensure the
deleted bit logic (storage.deleted.get_bit and make_conditioned_counter) still
short-circuits correctly but returns an Ok(false) when absent rather than hiding
underlying I/O errors—apply the same change to the other occurrences noted (the
blocks at the other check_values_any usages).

---

Nitpick comments:
In
`@lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/read_ops.rs`:
- Line 97: The closure currently destructures Point using `..` (map(|Point {
val, idx, .. }| (val, idx))) which can silently ignore newly added fields;
replace the `..` with explicit ignored fields for every other field on the Point
struct (e.g., `other_field: _, another_field: _`) so only `val` and `idx` are
taken and any new Point fields will require explicit handling; locate the
destructuring of `Point` in the map closure and expand it to list each remaining
field as `field_name: _`.

In
`@lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/mod.rs`:
- Around line 38-44: The InMemoryNumericIndex struct currently exposes all
internals as pub; narrow visibility to prevent uncontrolled access by changing
fields (map, histogram, points_count, max_values_per_point, point_to_values)
from pub to pub(super) or private and provide explicit accessor/mutator methods
on InMemoryNumericIndex (e.g., get_points_count(), get_map(), iter_points(),
push_point()/update_point()) as needed; update any call sites that currently
access fields directly (look for usages of InMemoryNumericIndex::map,
::histogram, ::points_count, ::max_values_per_point, ::point_to_values) and
replace them with the new accessors so MutableNumericIndex and other modules
retain only the intended controlled access.
🪄 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: 71682756-6d73-431f-b549-74f8ce796aa5

📥 Commits

Reviewing files that changed from the base of the PR and between 823a06e and 9a91661.

📒 Files selected for processing (39)
  • lib/segment/benches/numeric_index_check_values.rs
  • lib/segment/src/index/field_index/field_index_base/field_index.rs
  • lib/segment/src/index/field_index/field_index_base/read_only/mod.rs
  • lib/segment/src/index/field_index/field_index_base/read_only/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/builders.rs
  • lib/segment/src/index/field_index/numeric_index/encodable.rs
  • lib/segment/src/index/field_index/numeric_index/immutable_numeric_index/lifecycle.rs
  • lib/segment/src/index/field_index/numeric_index/immutable_numeric_index/mod.rs
  • lib/segment/src/index/field_index/numeric_index/immutable_numeric_index/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/lifecycle.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/lifecycle.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/mod.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/mod.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/lifecycle.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/mod.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_only/mod.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_only/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/numeric_field_index.rs
  • lib/segment/src/index/field_index/numeric_index/numeric_index_read.rs
  • lib/segment/src/index/field_index/numeric_index/query.rs
  • lib/segment/src/index/field_index/numeric_index/read_only/mod.rs
  • lib/segment/src/index/field_index/numeric_index/read_only/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/read_only/value_retriever.rs
  • lib/segment/src/index/field_index/numeric_index/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/storage/lifecycle.rs
  • lib/segment/src/index/field_index/numeric_index/storage/mod.rs
  • lib/segment/src/index/field_index/numeric_index/storage/read_only/mod.rs
  • lib/segment/src/index/field_index/numeric_index/storage/read_only/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/storage/read_only/trait_impls.rs
  • lib/segment/src/index/field_index/numeric_index/storage/read_ops.rs
  • lib/segment/src/index/field_index/numeric_index/storage/statistics.rs
  • lib/segment/src/index/field_index/numeric_index/storage/trait_impls.rs
  • lib/segment/src/index/field_index/numeric_index/tests.rs
  • lib/segment/src/index/field_index/numeric_index/value_indexer.rs
  • lib/segment/src/index/field_index/stored_point_to_values.rs
💤 Files with no reviewable changes (3)
  • lib/segment/src/index/field_index/numeric_index/storage/statistics.rs
  • lib/segment/src/index/field_index/numeric_index/mutable_numeric_index.rs
  • lib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rs

Comment on lines +86 to +103
pub(in super::super) fn remove_point(&mut self, idx: PointOffsetType) {
if let Some(removed_values) = self.point_to_values.get_values(idx) {
let mut removed_count = 0;
for value in removed_values {
let key = Point::new(*value, idx);
Self::remove_from_map(&mut self.map, &mut self.histogram, &key);

// Update persisted storage
self.storage.remove_point(idx);

removed_count += 1;
}
if removed_count > 0 {
self.points_count = self.points_count.saturating_sub(1);
}
}
self.point_to_values.remove_point(idx);
}

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

Move storage.remove_point(idx) outside the value iteration loop.

Line 94 calls self.storage.remove_point(idx) once per value, but point deletion should occur once per point. Since storage.remove_point updates an in-memory bitvec (per the PR description: "Runtime deletions live in the in-memory Storage::deleted bitvec"), calling it multiple times for the same idx is redundant and wastes cycles.

♻️ Proposed fix
 pub(in super::super) fn remove_point(&mut self, idx: PointOffsetType) {
     if let Some(removed_values) = self.point_to_values.get_values(idx) {
         let mut removed_count = 0;
         for value in removed_values {
             let key = Point::new(*value, idx);
             Self::remove_from_map(&mut self.map, &mut self.histogram, &key);
-
-            // Update persisted storage
-            self.storage.remove_point(idx);
-
             removed_count += 1;
         }
+        // Update persisted storage once per point
+        self.storage.remove_point(idx);
         if removed_count > 0 {
             self.points_count = self.points_count.saturating_sub(1);
         }
     }
     self.point_to_values.remove_point(idx);
 }
🤖 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/field_index/numeric_index/immutable_numeric_index/lifecycle.rs`
around lines 86 - 103, The loop in remove_point currently calls
self.storage.remove_point(idx) for every value, causing redundant updates to the
in-memory deletion bitvec; move the single call to
self.storage.remove_point(idx) outside the for value in removed_values loop so
it is invoked once per point. Specifically, inside pub(in super::super) fn
remove_point(&mut self, idx: PointOffsetType) handle removal of entries via
Self::remove_from_map(&mut self.map, &mut self.histogram, &key) for each value,
update removed_count and points_count as before, but call
self.storage.remove_point(idx) once after the loop (and only if removed_count >
0) and before calling self.point_to_values.remove_point(idx).

Comment on lines +31 to +42
// FIXME: don't silently ignore error — propagate it once
// [`NumericIndexRead::check_values_any`] returns `OperationResult`.
let hw_counter = self.make_conditioned_counter(hw_counter);

if self.storage.deleted.get_bit(idx as usize) == Some(false) {
self.storage
.point_to_values
.check_values_any(idx, |v| check_fn(v), &hw_counter)
.unwrap_or(false)
} else {
false
}

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 silently coerce mmap read errors into “no match/no value.”

Returning false/None on read failures can hide real storage issues and produce false-negative query behavior. Please propagate an OperationResult on this path (or add an explicit error-reporting channel) so failures are observable.

Also applies to: 45-53, 60-63

🤖 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/field_index/numeric_index/mmap_numeric_index/read_ops.rs`
around lines 31 - 42, The code currently swallows mmap read errors by calling
.check_values_any(...).unwrap_or(false); instead propagate the OperationResult
instead of coercing failures to false: modify the caller path of
NumericIndexRead::check_values_any (and similar call sites using
point_to_values.check_values_any) to return OperationResult<bool> (or map the
inner result) and use ? (or map_err) so read errors bubble up; ensure the
deleted bit logic (storage.deleted.get_bit and make_conditioned_counter) still
short-circuits correctly but returns an Ok(false) when absent rather than hiding
underlying I/O errors—apply the same change to the other occurrences noted (the
blocks at the other check_values_any usages).

The two enums were structurally identical — same `StreamRange`,
`get_ordering_values`, and `NumericFieldIndexRead` bodies — differing
only in the backing storage type. Collapse them onto one generic
`NumericFieldIndexView<'a, I, F>` with a single set of impls (over
`I: NumericIndexRead<i64> + StreamRange<i64>` and the `f64` counterpart).

`NumericFieldIndex` and `ReadOnlyNumericFieldIndex` are now type aliases
of the generic view, so every existing call site is unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@generall
generall merged commit 5436eb3 into dev May 14, 2026
15 checks passed
@generall
generall deleted the read-only-numeric-index branch May 14, 2026 17:06
generall added a commit that referenced this pull request May 22, 2026
* refactor: split numeric index variants into dedicated modules

Move MutableNumericIndex, ImmutableNumericIndex, and MmapNumericIndex
into their own directories, each split into mod.rs (struct definitions),
lifecycle.rs (open/build/wipe/mutations), and read_ops.rs (accessors),
mirroring the map_index layout.

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

* refactor: drop single-variant Storage enums in mutable/immutable numeric index

Replace `Storage<T>` wrappers around the only backing store with the
store types directly: `Gridstore<Vec<T>>` for `MutableNumericIndex` and
`Box<MmapNumericIndex<T>>` for `ImmutableNumericIndex`. Collapses the
trivial single-arm matches into direct method calls.

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

* refactor: introduce NumericIndexRead trait

Mirror `MapIndexRead` from the map_index refactor: define a
`NumericIndexRead<T>` trait in `numeric_index/read_ops.rs` and implement
it on each of the three storage variants
(`MutableNumericIndex`, `ImmutableNumericIndex`, `MmapNumericIndex`).

Trait signatures are unified across variants — in-memory variants accept
and ignore the `hw_counter` argument that the mmap-backed variant uses
for IO tracking, and `total_unique_values_count`, `values_range`, and
`orderable_values_range` return `OperationResult` everywhere so the
dispatcher in `NumericIndexInner` can call them generically.

Variant-specific helpers that don't fit the shared shape stay as
inherent methods: `MutableNumericIndex::map()`,
`ImmutableNumericIndex::values_range_size()`, and
`MmapNumericIndex::{values_range_size, is_on_disk}`.

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

* refactor: add ReadOnlyAppendableNumericIndex

Counterpart to `MutableNumericIndex`, mirroring `ReadOnlyAppendableMapIndex`
from the map_index refactor. It reuses the shared `InMemoryNumericIndex`
in-memory state but is backed by a `GridstoreReader` over generic
`UniversalRead` instead of a writable `Gridstore`, and implements
`NumericIndexRead` by forwarding to the in-memory index — no mutation
surface.

Loading / lifecycle (constructor, files, populate, clear_cache) will
follow in a separate change; the storage field is held only to pin the
on-disk layout for now.

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

* refactor: rename MmapNumericIndex to UniversalNumericIndex, expose UniversalRead param

Mirror `UniversalMapIndex`: the type is now generic over `S: UniversalRead`
with a `MmapFile` default, so the index can be served from any
`UniversalRead` backend (io_uring, disk-cache wrappers, …) rather than
the hard-coded `MmapFile`.

The `NumericIndexRead` impl and read-side helpers are generic over `S`;
`build` / `open` and the other lifecycle methods stay `MmapFile`-only
since they construct mmap-backed storage from a path. The
`NumericIndexInner::Mmap` enum variant keeps its name and uses the
default `S = MmapFile`.

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

* refactor: split numeric_index/storage/mod.rs into lifecycle and read_ops

`storage/mod.rs` now holds only the `NumericIndexInner` enum and module
wiring. The variant-dispatch impls are split into sibling modules
matching the layout of the individual storage variants:

- `lifecycle.rs`: construction, persistence, file listing, cache
  control, and `remove_point`.
- `read_ops.rs`: read-path forwarding — value lookups, telemetry, RAM
  accounting, `is_on_disk`.

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

* refactor: implement NumericIndexRead for NumericIndexInner

The enum-level read dispatch was a set of inherent methods scattered
across storage/read_ops.rs and storage/statistics.rs with signatures
that drifted from the variant trait (`values_count` returned `usize`,
`max_values_per_point` vs `get_max_values_per_point`, a hand-rolled
`get_telemetry_data`). Make `NumericIndexInner` implement
`NumericIndexRead` directly so it shares one interface with the three
storage variants.

- All 12 trait methods are forwarded via match dispatch in
  storage/read_ops.rs; `values_range` / `orderable_values_range` box
  the per-variant iterators.
- `get_histogram`, `get_points_count`, `total_unique_values_count` move
  out of statistics.rs into the trait impl; `values_is_empty` and
  `get_telemetry_data` now come from the trait defaults.
- `point_ids_by_value` and `is_on_disk` stay as enum-only inherent
  helpers (not part of the shared trait).
- Callers updated: `NumericIndex::values_count` unwraps the now
  `Option`-returning trait method; `filter` boxes `point_ids_by_value`;
  `field_index.rs` and `numeric_field_index.rs` import the trait.

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

* refactor: add ReadOnlyNumericIndexInner

Read-only counterpart to `NumericIndexInner`, mirroring `ReadOnlyMapIndex`
from the map_index refactor. Lives under
`numeric_index/storage/read_only` and selects across the two read-only
storage backends:

- `Appendable(ReadOnlyAppendableNumericIndex<T, S>)` — loaded into RAM
  from the appendable Gridstore format.
- `Immutable(UniversalNumericIndex<T, S>)` — served directly from the
  immutable stored format.

Implements `NumericIndexRead` by forwarding each method to the active
variant; `values_is_empty` / `get_telemetry_data` come from the trait
defaults.

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

* refactor: rename numeric_index read_ops to numeric_index_read, split mod.rs

Two changes:

- Rename `numeric_index/read_ops.rs` (the `NumericIndexRead` trait
  definition) to `numeric_index_read.rs`, freeing the `read_ops` name.
- Split the leftover content of `numeric_index/mod.rs` into sibling
  modules, matching the per-variant layout:
  - `lifecycle.rs`: the `Encodable` key-format trait + impls and the
    `HISTOGRAM_*` construction constants.
  - `read_ops.rs`: the `StreamRange` trait and the `Range` →
    index-key-bounds conversion.

`mod.rs` now only wires modules and re-exports. `Encodable` and
`StreamRange` keep their public paths via re-export; `tests.rs` gains
explicit imports for the symbols it previously picked up through the
`mod.rs` glob.

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

* refactor: dissolve numeric_index/index.rs into mod, lifecycle, read_ops

`index.rs` only held the `NumericIndex` wrapper and its two impl blocks;
spread them to match the per-module layout used elsewhere:

- `NumericIndex` struct + `NumericIndexIntoInnerValue` trait → `mod.rs`
  (type definitions live with the module wiring).
- The inherent `impl NumericIndex` (open / build / cache control /
  storage introspection) → `lifecycle.rs`, alongside the `HISTOGRAM_*`
  seed constants.
- The `PayloadFieldIndexRead` impl → `read_ops.rs`.

Also move the `Encodable` key-format trait out of `lifecycle.rs` into
its own `encodable.rs`. `mod.rs` keeps re-exporting `Encodable` so its
public path is unchanged.

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

* feat: add ReadOnlyNumericIndex with NumericIndexRead + PayloadFieldIndexRead

Read-only counterpart to `NumericIndex`, wrapping `ReadOnlyNumericIndexInner`
plus the payload value type parameter `P`. Implements both `NumericIndexRead`
and `PayloadFieldIndexRead` by forwarding to the inner storage-variant enum.

To support `PayloadFieldIndexRead` without duplicating the query logic, the
cardinality/filter/payload-block/condition-checker code is extracted into a
new `query` module of generic free functions over `NumericIndexRead<T>`.
`ReadOnlyNumericIndexInner` implements `PayloadFieldIndexRead` by plugging
into those helpers; `ReadOnlyNumericIndex` delegates to its inner.

The writable `NumericIndexInner` path is left untouched — its existing
variant-specialized `estimate_points` heuristic stays in `storage`.

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

* refactor: make query.rs the single source of truth for numeric index queries

The generic `query` helpers and the per-`NumericIndexInner` impls in
`storage/{trait_impls,statistics}.rs` had duplicated cardinality /
filter / payload-block / condition-checker logic. Collapse them onto
the shared `query` helpers:

- `storage/trait_impls.rs`: `PayloadFieldIndexRead for NumericIndexInner`
  now forwards each method to `query::*` instead of carrying its own copy.
- `storage/statistics.rs`: deleted — `range_cardinality` and
  `estimate_points` were duplicates of the `query` versions.
- `estimate_points` needs a range size; add `values_range_size` to the
  `NumericIndexRead` trait with a default that counts `values_range`,
  overridden by the `Immutable` / `Mmap` variants with their `O(log n)`
  boundary search. The `MutableNumericIndex::map()` accessor (its only
  caller was the old `estimate_points`) is removed.
- `values_range_size` takes `hw_counter` and threads it into
  `values_range` rather than fabricating a disposable counter.

`tests.rs` calls `query::range_cardinality` directly now that the
inherent method is gone.

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

* feat: integrate read-only numeric index into ReadOnlyFieldIndex

Wire the four numeric variants (`IntIndex`, `DatetimeIndex`,
`FloatIndex`, `UuidIndex`) into `ReadOnlyFieldIndex`, mirroring
`FieldIndex`:

- `PayloadFieldIndexRead` / `FieldIndexRead` dispatch covers the new
  variants — telemetry, value counts, value retrievers, `as_numeric`.
- `ReadOnlyNumericFieldIndex` is the read-only counterpart of
  `NumericFieldIndex` (Int/Float order-by erasure over
  `ReadOnlyNumericIndexInner`); `as_numeric` returns it for the
  Int/Datetime/Float variants (UUIDs aren't numerically order-by-able,
  matching `FieldIndex`).
- `ReadOnlyNumericIndex` gains per-`(T, P)` `value_retriever` methods
  (in `read_only/value_retriever.rs`) and an `inner()` accessor.

`StreamRange` is now backed by a shared generic `query::stream_range`
helper over `NumericIndexRead`, implemented for both `NumericIndexInner`
and `ReadOnlyNumericIndexInner` — replacing the bespoke `EitherVariant`
dispatch in `storage/trait_impls.rs`.

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

* refactor: collapse ReadOnlyNumericIndex value retrievers onto one generic method

The four per-`(T, P)` `value_retriever` methods were identical except
for the per-value `T -> Value` conversion. Extract that conversion into
a `NumericValueToJson` trait (one tiny impl per `(T, P)`) and keep a
single generic `value_retriever` that builds the retriever closure once.

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

* fmt

* refactor: dedup NumericFieldIndex / ReadOnlyNumericFieldIndex

The two enums were structurally identical — same `StreamRange`,
`get_ordering_values`, and `NumericFieldIndexRead` bodies — differing
only in the backing storage type. Collapse them onto one generic
`NumericFieldIndexView<'a, I, F>` with a single set of impls (over
`I: NumericIndexRead<i64> + StreamRange<i64>` and the `f64` counterpart).

`NumericFieldIndex` and `ReadOnlyNumericFieldIndex` are now type aliases
of the generic view, so every existing call site is unchanged.

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.

2 participants