Repository navigation
refactor: read-only numeric index - #9038
Conversation
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]>
7c563ef to
9a91661
Compare
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe 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 Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
lib/segment/src/index/field_index/numeric_index/mutable_numeric_index/mod.rs (1)
38-44: 💤 Low valueConsider encapsulating InMemoryNumericIndex fields.
All fields of
InMemoryNumericIndexare declaredpub, which allows direct access from anywhere in the crate. WhileMutableNumericIndexusespub(super)for controlled visibility,InMemoryNumericIndexexposes its internals more broadly. Consider whetherpub(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 winAvoid
..inPointdestructuring here.Use explicit ignored fields (
field_name: _) instead of..so newPointfields 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
📒 Files selected for processing (39)
lib/segment/benches/numeric_index_check_values.rslib/segment/src/index/field_index/field_index_base/field_index.rslib/segment/src/index/field_index/field_index_base/read_only/mod.rslib/segment/src/index/field_index/field_index_base/read_only/read_ops.rslib/segment/src/index/field_index/numeric_index/builders.rslib/segment/src/index/field_index/numeric_index/encodable.rslib/segment/src/index/field_index/numeric_index/immutable_numeric_index/lifecycle.rslib/segment/src/index/field_index/numeric_index/immutable_numeric_index/mod.rslib/segment/src/index/field_index/numeric_index/immutable_numeric_index/read_ops.rslib/segment/src/index/field_index/numeric_index/lifecycle.rslib/segment/src/index/field_index/numeric_index/mmap_numeric_index.rslib/segment/src/index/field_index/numeric_index/mmap_numeric_index/lifecycle.rslib/segment/src/index/field_index/numeric_index/mmap_numeric_index/mod.rslib/segment/src/index/field_index/numeric_index/mmap_numeric_index/read_ops.rslib/segment/src/index/field_index/numeric_index/mod.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index/lifecycle.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index/mod.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_only/mod.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_only/read_ops.rslib/segment/src/index/field_index/numeric_index/mutable_numeric_index/read_ops.rslib/segment/src/index/field_index/numeric_index/numeric_field_index.rslib/segment/src/index/field_index/numeric_index/numeric_index_read.rslib/segment/src/index/field_index/numeric_index/query.rslib/segment/src/index/field_index/numeric_index/read_only/mod.rslib/segment/src/index/field_index/numeric_index/read_only/read_ops.rslib/segment/src/index/field_index/numeric_index/read_only/value_retriever.rslib/segment/src/index/field_index/numeric_index/read_ops.rslib/segment/src/index/field_index/numeric_index/storage/lifecycle.rslib/segment/src/index/field_index/numeric_index/storage/mod.rslib/segment/src/index/field_index/numeric_index/storage/read_only/mod.rslib/segment/src/index/field_index/numeric_index/storage/read_only/read_ops.rslib/segment/src/index/field_index/numeric_index/storage/read_only/trait_impls.rslib/segment/src/index/field_index/numeric_index/storage/read_ops.rslib/segment/src/index/field_index/numeric_index/storage/statistics.rslib/segment/src/index/field_index/numeric_index/storage/trait_impls.rslib/segment/src/index/field_index/numeric_index/tests.rslib/segment/src/index/field_index/numeric_index/value_indexer.rslib/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
| 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); | ||
| } |
There was a problem hiding this comment.
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).
| // 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 | ||
| } |
There was a problem hiding this comment.
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]>
* 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]>
Summary
Refactors
lib/segment'snumeric_indexalong the same lines as the earliermap_indexrework, and builds out a full read-only numeric index path (ReadOnlyNumericIndex/ReadOnlyNumericIndexInner) wired intoReadOnlyFieldIndex.The work was done as a sequence of small, reviewable steps — each instruction below maps roughly to one or two commits.
Instructions, in order
numeric_indexas was done formap_index. As step 1, moveMutableNumericIndex,ImmutableNumericIndex, andMmapNumericIndexinto their own dedicated modules, each split intomod.rs,lifecycle.rs, andread_ops.rsas inmap_index.Storageenum inimmutable_numeric_indexand useMmapNumericIndex<T>directly.mutable_numeric_index— drop its single-variantStorageenum.MapIndexRead, introduce aNumericIndexReadtrait and move the common read functions into it across the mutable, immutable, and mmap numeric index variants.ReadOnlyAppendableMapIndex, implementReadOnlyAppendableNumericIndexas the counterpart toMutableNumericIndex, reusing the existingin_memory_indexpart.MmapNumericIndexto expose theUniversalReadtrait parameter with a default ofMmapFileinstead of a hard-coded type, and rename it toUniversalNumericIndex. Keep the enum variant names (stillMmap), which useMmapFileas the configuredUniversalReadtype.numeric_index/storage/mod.rsintoread_opsandlifecycle.NumericIndexReadforNumericIndexInner, so the read ops are part of the trait rather than loose functions.ReadOnlyMapIndex, implementReadOnlyNumericIndexInnerwith two variants — one forReadOnlyAppendableNumericIndexand one for the immutable stored format (UniversalNumericIndex) — placed under thestorage/read_onlymodule.numeric_index/read_ops.rstonumeric_index_read.rs, then splitnumeric_index/mod.rsintoread_opsandlifecycle.NumericIndexinmod.rs; move the inherentimpl NumericIndexblock tolifecycle.rsand thePayloadFieldIndexReadimpl toread_ops.rs.Encodabletrait out oflifecycle.rsinto its ownencodable.rs.ReadOnlyNumericIndex.ReadOnlyNumericIndexshould implementPayloadFieldIndexRead.PayloadFieldIndexReadimpl intonumeric_index/read_only/read_ops.rs.query.rsand the per-NumericIndexInnerimpls instorage/trait_impls.rswere duplicated (along with some other functions). Make them use a single source of truth for the logic instead of duplicating.hw_counterproperly throughvalues_range_sizeinstead of fabricating a disposable counter.ReadOnlyFieldIndex.numeric_index/read_only/value_retriever.rs(promote to a trait) so the same function isn't repeated for every numeric variant.Result
mod.rs/lifecycle.rs/read_ops.rs.NumericIndexReadis the shared read interface, implemented by every variant, the dispatch enumNumericIndexInner, and the read-only types.query.rsholds the generic query logic (cardinality, filter, payload blocks, condition checker, range streaming) once, overNumericIndexRead; both the writable and read-only paths plug into it.ReadOnlyAppendableNumericIndex,ReadOnlyNumericIndexInner,ReadOnlyNumericIndex, andReadOnlyNumericFieldIndex, all wired intoReadOnlyFieldIndexwithPayloadFieldIndexRead+FieldIndexRead.UniversalNumericIndexis generic overUniversalReadwith anMmapFiledefault.Test plan
cargo check -p segment --all-targetscargo clippy -p segment --all-targets -- -D warningscargo test -p segment --lib numeric_index(26 passed)🤖 Generated with Claude Code