Skip to content

Migrate geo_index to UIO - #8507

Merged
xzfc merged 9 commits into
devfrom
uio-geo_index
Apr 14, 2026
Merged

xzfc merged 9 commits into
devfrom
uio-geo_index

Conversation

@xzfc

@xzfc xzfc commented Mar 26, 2026 •

Copy link
Copy Markdown
Member

No description provided.

@xzfc
xzfc force-pushed the uio-geo_index branch 2 times, most recently from 913b9e7 to 652eb2c Compare March 26, 2026 05:05
@xzfc
xzfc changed the base branch from dev to uio-typed-storage March 26, 2026 05:06
@xzfc
xzfc force-pushed the uio-typed-storage branch 3 times, most recently from 3759376 to 5f4d1b6 Compare March 26, 2026 13:15
Base automatically changed from uio-typed-storage to dev March 26, 2026 14:10
@xzfc
xzfc force-pushed the uio-geo_index branch 2 times, most recently from 9062718 to 07b7b5e Compare March 26, 2026 15:25
@xzfc
xzfc marked this pull request as ready for review March 26, 2026 15:25
@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This pull request introduces fallible binary-search utilities in a new module, extends the ReadRange API for chunked iteration over data, and refactors the geo-index implementation to use storage-aware fallible operations instead of direct slice access. The binary search module exports binary_search_by for custom predicates returning Result<Ordering, E> and partition_point for boolean predicates, both operating over integer index ranges. The ReadRange gains a one() constructor and iter_autochunks() method for splitting ranges into fixed-size chunks. The geo-index refactoring generalizes MmapGeoMapIndex over a storage backend trait, changes hash lookups and region iteration to be fallible and storage-read based, and updates the public GeoMapIndex API to propagate errors eagerly rather than lazily.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • Separate GeoHash/GeoHashRaw #8618 — Refactors geo-hash storage design by introducing GeoHashRaw with bytemuck derives and changing mmap-backed geo index code to normalize and read stored hashes via storage-aware operations.

Suggested reviewers

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

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The pull request has no description provided, making it impossible to assess whether it relates to the changeset. Add a description explaining the motivation, scope, and impact of the geo_index UIO migration for reviewers.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Title check ✅ Passed The title clearly identifies the main change: migrating geo_index to use UIO (Universal Input/Output), which is the primary architectural refactor across multiple files.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch uio-geo_index

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

🧹 Nitpick comments (1)
lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs (1)

422-425: Use PointKeyValue sizing for points_map reads.

Line 423 computes the byte offset with size_of::<Counts>() even though this closure reads PointKeyValues from points_map. That only works because the two structs currently happen to have the same layout; if either format changes, prefix lookups will start reading the wrong records.

♻️ Suggested fix
         let read_one = |idx| -> OperationResult<PointKeyValue> {
-            let range = ReadRange::one((idx * size_of::<Counts>()) as u64);
+            let range = ReadRange::one((idx * size_of::<PointKeyValue>()) as u64);
             let value = self.storage.points_map.read::<Random>(range)?;
             Ok(value[0])
         };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs` around lines
422 - 425, The closure read_one currently computes byte offsets using
size_of::<Counts>() while reading PointKeyValue records from points_map; change
the offset calculation to use size_of::<PointKeyValue>() (and any other reads
from points_map that use Counts) so the ReadRange::one((idx *
size_of::<PointKeyValue>()) as u64) matches the actual record size, ensuring
future layout changes don't break prefix lookups; locate the read_one closure
and any other usages that call points_map.read and replace Counts sizing with
PointKeyValue.
🤖 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/common/common/src/universal_io/read.rs`:
- Around line 68-99: The helpers read_batch_autochunks and for_each drop the
operation_index passed into read_batch which hides ordering context; change
their callback signatures to accept the same operation index as read_batch
(e.g., make read_batch_autochunks take mut callback: impl FnMut(u64, T) and
forward the operation_index from the inner closure to each item, calling
callback(operation_index + per_item_offset, item)), and update for_each likewise
to forward the operation_index instead of reconstructing indices separately so
the ordering handle is preserved and consistent with read_batch.

---

Nitpick comments:
In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs`:
- Around line 422-425: The closure read_one currently computes byte offsets
using size_of::<Counts>() while reading PointKeyValue records from points_map;
change the offset calculation to use size_of::<PointKeyValue>() (and any other
reads from points_map that use Counts) so the ReadRange::one((idx *
size_of::<PointKeyValue>()) as u64) matches the actual record size, ensuring
future layout changes don't break prefix lookups; locate the read_one closure
and any other usages that call points_map.read and replace Counts sizing with
PointKeyValue.
🪄 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: 51186a20-3554-4c10-be29-97217d2106e7

📥 Commits

Reviewing files that changed from the base of the PR and between fa8b441 and 07b7b5e.

📒 Files selected for processing (11)
  • lib/common/common/src/binary_search.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/read.rs
  • lib/common/common/src/universal_io/wrappers/read_only.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/segment/src/common/stored_bitslice.rs
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs

@xzfc
xzfc requested review from coszio, ffuugoo and generall March 27, 2026 10:04
@xzfc xzfc mentioned this pull request Mar 30, 2026
@xzfc
xzfc force-pushed the uio-geo_index branch 2 times, most recently from 6d3d741 to c512a98 Compare April 2, 2026 15:40

@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

🤖 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/geo_index/mmap_geo_index.rs`:
- Around line 422-425: The closure read_one currently computes the byte offset
using size_of::<Counts>() when reading from self.storage.points_map which only
works by accident; change the offset calculation to use the actual record stride
size_of::<PointKeyValue>() (i.e. use size_of::<PointKeyValue>() when building
the ReadRange in read_one) so prefix scans read the correct records even if
Counts or PointKeyValue layouts change; update any other readers/probers that
compute offsets from Counts to use PointKeyValue stride as well (refer to
read_one, PointKeyValue, Counts, self.storage.points_map, and ReadRange::one).
🪄 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: e8f60aae-7329-426c-94ef-e7aa6d72be71

📥 Commits

Reviewing files that changed from the base of the PR and between 07b7b5e and 6d3d741.

📒 Files selected for processing (11)
  • lib/common/common/src/binary_search.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/read.rs
  • lib/common/common/src/universal_io/wrappers/read_only.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/segment/src/common/stored_bitslice.rs
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
✅ Files skipped from review due to trivial changes (3)
  • lib/common/common/src/lib.rs
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/common/stored_bitslice.rs
🚧 Files skipped from review as they are similar to previous changes (6)
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/common/common/src/universal_io/wrappers/read_only.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/common/common/src/universal_io/read.rs
  • lib/common/common/src/binary_search.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.

Actionable comments posted: 3

🤖 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/common/common/src/universal_io/mod.rs`:
- Around line 73-89: iter_autochunks can overflow when mapping (0..) to start =
i * chunk_len before take_while; compute a safe upper bound on i instead of
multiplying unbounded values. Replace the (0..).map(...).take_while(...) pattern
with a finite range computed from length and chunk_len (e.g. max_chunks =
(length + chunk_len - 1) / chunk_len) and iterate 0..max_chunks, then map each i
to a ReadRange using start = i * chunk_len; keep the rest of the logic and
returned chunk_len unchanged.

In `@lib/segment/src/index/field_index/geo_hash.rs`:
- Around line 34-46: GeoHash is unsafe to derive bytemuck::Pod because its low
4-bit length field can be 13..=15 and break methods like GeoHash::len(),
shift_value(), starts_with(), truncate(), and Index; remove the Pod/Zeroable
derives from GeoHash and instead either (A) change mmap structs Counts and
PointKeyValue in mmap_geo_index.rs to store the raw u64 backing value and only
convert to GeoHash via a validated constructor (e.g., GeoHash::from_u64_checked)
when accessed, or (B) add explicit validation checks (validate length <
GEOHASH_MAX_LENGTH) on any GeoHash deserialized from storage before calling
shift_value(), len(), starts_with(), truncate(), or Index methods; implement the
validated conversion function and update all mmap read sites to use it so
invalid bit patterns cannot be used unchecked.

In `@lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs`:
- Around line 68-77: The code builds ReadRange lengths by computing
(item.ids_end - item.ids_start) in u32 which can underflow for corrupted on-disk
values; before creating the ReadRange for
index.storage.points_map_ids.read_batch validate that for each item from
points_map_old item.ids_end >= item.ids_start, otherwise return a storage error
(or propagate an Err) rather than performing the subtraction; after the check
perform the subtraction and cast the result to u64 and use
u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64 for byte_offset
so the ReadRange lengths are always correct and safe (refer to points_map_old,
points_map, ReadRange, item.ids_start, item.ids_end, PointOffsetType, and
index.storage.points_map_ids.read_batch).
🪄 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: 76a3c7c0-6176-494b-883b-2b5b1bfcaf24

📥 Commits

Reviewing files that changed from the base of the PR and between 6d3d741 and c512a98.

📒 Files selected for processing (8)
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/universal_io/read.rs
  • lib/common/common/src/universal_io/wrappers/read_only.rs
  • lib/common/common/src/universal_io/wrappers/typed.rs
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/common/common/src/universal_io/wrappers/typed.rs

Comment on lines +73 to +89
fn iter_autochunks<T>(self) -> (impl Iterator<Item = ReadRange>, u64) {
// TODO: align chunks. Perhaps this method and `blocks_for_range_in_file`
// can be unified.
const MAX_CHUNK_BYTES: u64 = 16 * 1024;
let chunk_len = (MAX_CHUNK_BYTES / size_of::<T>() as u64).max(1);
let Self {
byte_offset,
length,
} = self;
let iter = (0..)
.map(move |i| i * chunk_len)
.take_while(move |&start| start < length)
.map(move |start| ReadRange {
byte_offset: byte_offset + start * size_of::<T>() as u64,
length: std::cmp::min(chunk_len, length - start),
});
(iter, chunk_len)

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

Bound the chunk loop before multiplying.

(0..).map(|i| i * chunk_len).take_while(|start| start < length) can wrap u64 before take_while ever sees a terminating value. With a near-u64::MAX range and chunk_len > 1, this becomes an endless/repeating iterator instead of a finite chunk stream.

🛠️ Proposed fix
-        let iter = (0..)
-            .map(move |i| i * chunk_len)
-            .take_while(move |&start| start < length)
-            .map(move |start| ReadRange {
-                byte_offset: byte_offset + start * size_of::<T>() as u64,
-                length: std::cmp::min(chunk_len, length - start),
-            });
+        let iter = (0..length.div_ceil(chunk_len)).map(move |i| {
+            let start = i * chunk_len;
+            ReadRange {
+                byte_offset: byte_offset + start * size_of::<T>() as u64,
+                length: std::cmp::min(chunk_len, length - start),
+            }
+        });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/common/common/src/universal_io/mod.rs` around lines 73 - 89,
iter_autochunks can overflow when mapping (0..) to start = i * chunk_len before
take_while; compute a safe upper bound on i instead of multiplying unbounded
values. Replace the (0..).map(...).take_while(...) pattern with a finite range
computed from length and chunk_len (e.g. max_chunks = (length + chunk_len - 1) /
chunk_len) and iterate 0..max_chunks, then map each i to a ReadRange using start
= i * chunk_len; keep the rest of the logic and returned chunk_len unchanged.

Comment on lines +68 to +77
let points_map_old = index.storage.points_map.read_whole()?;
let mut points_map = points_map_old
.iter()
.copied()
.map(|item| {
let super::mmap_geo_index::PointKeyValue {
hash,
ids_start,
ids_end,
} = item;
(
hash,
index.storage.points_map_ids[ids_start as usize..ids_end as usize]
.iter()
.copied()
// Filter deleted points
.filter(|id| !index.storage.deleted.get(*id as usize).unwrap_or_default())
.collect(),
)
})
.collect();
.map(|item| (item.hash, AHashSet::default()))
.collect::<Vec<_>>();
index.storage.points_map_ids.read_batch::<Random>(
points_map_old.iter().map(|item| ReadRange {
byte_offset: u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64,
length: u64::from(item.ids_end - item.ids_start),
}),

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

Validate ids_end >= ids_start before subtracting.

These offsets come from disk. item.ids_end - item.ids_start is done in u32, so a malformed or partially written entry wraps to a huge length before the u64 cast and drives a bogus batched read instead of returning a storage error.

🛠️ Proposed fix
-        index.storage.points_map_ids.read_batch::<Random>(
-            points_map_old.iter().map(|item| ReadRange {
-                byte_offset: u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64,
-                length: u64::from(item.ids_end - item.ids_start),
-            }),
+        let id_ranges = points_map_old
+            .iter()
+            .map(|item| {
+                let len = item.ids_end.checked_sub(item.ids_start).ok_or_else(|| {
+                    OperationError::service_error("Corrupted geo index: ids_end < ids_start")
+                })?;
+                Ok(ReadRange {
+                    byte_offset: u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64,
+                    length: u64::from(len),
+                })
+            })
+            .collect::<OperationResult<Vec<_>>>()?;
+        index.storage.points_map_ids.read_batch::<Random>(
+            id_ranges,
             |i, ids| {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs` around
lines 68 - 77, The code builds ReadRange lengths by computing (item.ids_end -
item.ids_start) in u32 which can underflow for corrupted on-disk values; before
creating the ReadRange for index.storage.points_map_ids.read_batch validate that
for each item from points_map_old item.ids_end >= item.ids_start, otherwise
return a storage error (or propagate an Err) rather than performing the
subtraction; after the check perform the subtraction and cast the result to u64
and use u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64 for
byte_offset so the ReadRange lengths are always correct and safe (refer to
points_map_old, points_map, ReadRange, item.ids_start, item.ids_end,
PointOffsetType, and index.storage.points_map_ids.read_batch).

@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/index/field_index/geo_hash.rs (1)

34-50: ⚠️ Potential issue | 🔴 Critical

The Pod derive still turns malformed length bits into panics.

This is the same invariant break from the earlier review: a raw GeoHash with length nibble 13..=15 can still reach Index::index, starts_with, truncate, or common_hash_prefix and trip shift_value() assertions. Please keep the mmap representation as raw u64, or validate the length before constructing GeoHash.

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

In `@lib/segment/src/index/field_index/geo_hash.rs` around lines 34 - 50, The
GeoHash type deriving bytemuck::Pod allows malformed length nibble values
(13..=15) to be interpreted unsafely and can trigger assertions in shift_value()
when raw data reaches Index::index, starts_with, truncate, or
common_hash_prefix; fix by stopping use of a bytemuck-mapped GeoHash for
mmap-backed storage and instead store/read a raw u64 from disk or, if you must
construct a GeoHash from raw bits, validate the length nibble before
constructing the GeoHash (reject or sanitize lengths outside 0..=12) so
shift_value() never receives invalid state. Ensure changes target the GeoHash
definition and all code paths that construct GeoHash from raw bytes (mmap
reader, any from_bits/from_u64 helpers) and update callers Index::index,
starts_with, truncate, common_hash_prefix to handle the validated/raw-u64
representation.
🤖 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/geo_hash.rs`:
- Around line 34-50: The GeoHash type deriving bytemuck::Pod allows malformed
length nibble values (13..=15) to be interpreted unsafely and can trigger
assertions in shift_value() when raw data reaches Index::index, starts_with,
truncate, or common_hash_prefix; fix by stopping use of a bytemuck-mapped
GeoHash for mmap-backed storage and instead store/read a raw u64 from disk or,
if you must construct a GeoHash from raw bits, validate the length nibble before
constructing the GeoHash (reject or sanitize lengths outside 0..=12) so
shift_value() never receives invalid state. Ensure changes target the GeoHash
definition and all code paths that construct GeoHash from raw bytes (mmap
reader, any from_bits/from_u64 helpers) and update callers Index::index,
starts_with, truncate, common_hash_prefix to handle the validated/raw-u64
representation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f316a599-1e08-49fd-9dd6-e3c23d4dc69c

📥 Commits

Reviewing files that changed from the base of the PR and between c512a98 and 10cb566.

📒 Files selected for processing (4)
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
✅ Files skipped from review due to trivial changes (1)
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs

@xzfc xzfc mentioned this pull request Apr 7, 2026
@xzfc xzfc changed the title Migrate geo_index to UIO [WIP] Migrate geo_index to UIO Apr 7, 2026

@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/geo_index/mmap_geo_index.rs (1)

503-507: ⚠️ Potential issue | 🟠 Major

Don't mask corrupt ids_start/ids_end spans.

These offsets come from disk. saturating_sub turns ids_end < ids_start into an empty read, so a malformed PointKeyValue silently drops postings instead of surfacing storage corruption in the live mmap query path.

🛠️ Proposed fix
-                    let start = u64::from(item.ids_start);
-                    let end = u64::from(item.ids_end);
+                    let len = item.ids_end.checked_sub(item.ids_start).ok_or_else(|| {
+                        OperationError::service_error("Corrupted geo index: ids_end < ids_start")
+                    })?;
                     ranges.push(ReadRange {
-                        byte_offset: start * size_of::<PointOffsetType>() as u64,
-                        length: end.saturating_sub(start),
+                        byte_offset: u64::from(item.ids_start)
+                            * size_of::<PointOffsetType>() as u64,
+                        length: u64::from(len),
                     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs` around lines
503 - 507, The code silently masks corrupt on-disk offsets by using
saturating_sub when building ReadRange from PointKeyValue (ids_start/ids_end);
change the logic in the ReadRange construction (where start =
u64::from(item.ids_start) and end = u64::from(item.ids_end)) to explicitly check
if end < start and surface an error (or propagate a corruption Result) instead
of producing an empty length — e.g., validate ids_start/ids_end before creating
ReadRange, return Err/early-fail with a clear corruption message referencing the
offending PointKeyValue, and only compute length as end - start when the check
passes.
lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs (1)

73-79: ⚠️ Potential issue | 🟠 Major

Validate on-disk ID spans before batching reads.

ids_end.saturating_sub(ids_start) still hides malformed mmap entries here. On a corrupted or partially written index, the RAM snapshot loads with silently missing postings instead of failing the open.

🛠️ Proposed fix
-        index.storage.points_map_ids.read_batch::<Random, _>(
-            points_map_old
-                .iter()
-                .map(|item| ReadRange {
-                    byte_offset: u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64,
-                    length: u64::from(item.ids_end.saturating_sub(item.ids_start)),
-                })
-                .enumerate(),
+        let id_ranges = points_map_old
+            .iter()
+            .map(|item| {
+                let len = item.ids_end.checked_sub(item.ids_start).ok_or_else(|| {
+                    OperationError::service_error("Corrupted geo index: ids_end < ids_start")
+                })?;
+                Ok(ReadRange {
+                    byte_offset: u64::from(item.ids_start) * size_of::<PointOffsetType>() as u64,
+                    length: u64::from(len),
+                })
+            })
+            .collect::<OperationResult<Vec<_>>>()?;
+        index.storage.points_map_ids.read_batch::<Random, _>(
+            id_ranges.into_iter().enumerate(),
             |i, ids| {
🤖 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/geo_index/mmap_geo_index.rs`:
- Around line 503-507: The code silently masks corrupt on-disk offsets by using
saturating_sub when building ReadRange from PointKeyValue (ids_start/ids_end);
change the logic in the ReadRange construction (where start =
u64::from(item.ids_start) and end = u64::from(item.ids_end)) to explicitly check
if end < start and surface an error (or propagate a corruption Result) instead
of producing an empty length — e.g., validate ids_start/ids_end before creating
ReadRange, return Err/early-fail with a clear corruption message referencing the
offending PointKeyValue, and only compute length as end - start when the check
passes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6664aaf5-8968-4e11-a829-260735ca551e

📥 Commits

Reviewing files that changed from the base of the PR and between 10cb566 and b04f837.

📒 Files selected for processing (8)
  • lib/common/common/src/binary_search.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/universal_io/mod.rs
  • lib/segment/src/common/stored_bitslice.rs
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mod.rs
✅ Files skipped from review due to trivial changes (2)
  • lib/common/common/src/lib.rs
  • lib/segment/src/common/stored_bitslice.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/common/common/src/universal_io/mod.rs
  • lib/common/common/src/binary_search.rs

@coszio coszio mentioned this pull request Apr 8, 2026
34 of 36 tasks
@xzfc
xzfc force-pushed the uio-geo_index branch 3 times, most recently from 8586ceb to 03bd5df Compare April 10, 2026 15:58
@timvisee timvisee added this to the Universal IO milestone Apr 10, 2026
Comment on lines +45 to +46

fn read_iter_autochunks(

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.

It was not clear by just the name that the input ranges can contain many elements.

Suggested change
fn read_iter_autochunks(
/// Iterates over the provided ranges, reading a few elements at a time,
/// but returning in a per-element basis.
///
/// The provided ranges can span many elements, they will be auto-chunked
/// by this function to ensure each read is not too big. The argument is an
/// iterator just so that it is possible to read from non-contiguous regions in
/// the same output iterator.
fn read_iter_autobatched(

Comment on lines +50 to +52
Mmap(Box<MmapGeoMapIndex>),
Mmap(Box<MmapGeoMapIndex<MmapFile>>),

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.

We can rename the structure to StoredGeoMapIndex since it is now generic

Comment on lines +471 to +472
// The problem is that UniversalRead iterator gives us chunks in an
// arbitrary order, and we don't know where `end` is.

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.

UniversalRead iterator gives us chunks in an arbitrary order

The only case when this happens is when using io-uring, right? I think I have an alternative way of fixing this. Will make a PR about it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@coszio please don't spend too much time on it, unless you have really good idea.

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.

This is the suggestion: #8667

Co-authored-by: Luis Cossío <[email protected]>
@xzfc
xzfc merged commit aa3af83 into dev Apr 14, 2026
15 checks passed
@xzfc
xzfc deleted the uio-geo_index branch April 14, 2026 08:38
timvisee pushed a commit that referenced this pull request May 8, 2026
* Add common::iterator_ext::fallible helpers

* refactor: counts_of_hash

* Add ReadRange::one

* UniversalRead::read_iter: return Result

* Add binary_search module

* Migrate geo_index to UIO

* minor review fixes

* Review fixups

Co-authored-by: Luis Cossío <[email protected]>

---------

Co-authored-by: generall <[email protected]>
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.

4 participants