Skip to content

Fix immutable map index zero count - #8890

Merged
agourlay merged 2 commits into
devfrom
fix-immutable-map-index-zero-count
May 4, 2026
Merged

agourlay merged 2 commits into
devfrom
fix-immutable-map-index-zero-count

Conversation

@agourlay

@agourlay agourlay commented May 4, 2026

Copy link
Copy Markdown
Member

This PR fixes ImmutableMapIndex::open_mmap so that it no longer inserts zero-count value_to_points entries for values whose live points are all deleted at open time.

The constructor now matches the runtime invariant maintained by remove_idx_from_value_list (entries with count == 0 don't exist), preventing a debug_assert! panic on the post-build sort loop after a delete-flush-reload cycle.

A new payload_index_files_are_immutable_after_build covering all 8 PayloadSchemaType variants (every immutable index variant) as been introduced.

It snapshots every byte under payload_index/ after build, then asserts byte equality + per-field query correctness through delete_point, flush, drop+reload, and another deletes+flush.

Repro (without the fix)

Build an immutable map index with a value held by a single point, delete that point, flush, drop, reload → panic at immutable_map_index.rs:119 reading value not found in value_to_points.

Triggered when MmapMapIndex::open ORs the id-tracker's runtime deletion bitvec into its own at open time and the constructor naively inserts an entry whose live count is now zero.

Test plan

  • cargo test -p segment --lib — 645 passed, 0 failed
  • New test goes red on the unfixed code, green with the fix
  • cargo clippy -p segment --tests --no-deps clean
  • Sibling immutable index loaders (numeric/geo/bool/null/text) audited — none have an analogous bug

agourlay and others added 2 commits May 4, 2026 17:10
… load

When MmapMapIndex::open ORs the id-tracker's runtime deletion bitvec
into the on-disk one at open time, ImmutableMapIndex::open_mmap could
insert a zero-count entry into value_to_points for any value whose live
points were all deleted, then immediately trip its own post-build sort
assert. Skip such values, mirroring the runtime invariant maintained by
remove_idx_from_value_list which already removes entries when their
count drops to zero.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Builds an immutable segment with all 8 PayloadSchemaType variants
indexed, snapshots every byte under payload_index/, then asserts
byte-for-byte equality plus per-field query correctness after
delete_point, flush, drop+reload, and a second deletes+flush on the
reloaded segment. Each query exercises a different read path of an
immutable index variant: map exact-match (keyword/uuid/integer),
numeric range (float), datetime range, geo bounding box, full-text
token match, bool match. Reproduces the regression fixed in the
previous commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@agourlay agourlay added this to the Immutable payload index milestone May 4, 2026
@agourlay
agourlay marked this pull request as ready for review May 4, 2026 16:23
@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request modifies ImmutableMapIndex::open_mmap to skip creating value_to_points entries when a value's filtered live point set is empty. The change includes documentation of the invariant that value_to_points only contains segments with non-zero counts. A new regression test module is added to verify that payload index files remain immutable across various operations—including point deletions, flushes, and segment reloads—for non-appendable segments, with byte-for-byte file comparisons and query result validations performed after each operation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Immutable storage for mmap map index #8828: Both PRs modify the mmap-backed map index loading logic to handle filtered live points differently, with one switching deletion checks to BitVec and the other skipping empty value-to-points entries during initialization.

Suggested labels

release:1.18.0

Suggested reviewers

  • timvisee
  • coszio
  • ffuugoo
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: fixing an issue with immutable map index zero count entries.
Description check ✅ Passed The description is directly related to the changeset, detailing the fix, test coverage, and validation approach for the immutable map index zero count issue.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-immutable-map-index-zero-count

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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/segment/src/segment/tests/test_immutable_payload_index_files.rs (1)

773-774: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use checked conversions for PointOffsetType here.

n_vectors as PointOffsetType and i as u32 - 1 assume these values always fit in the offset type, but that bound is not enforced. A future test expansion could wrap silently.

Suggested fix
-    let deferred_internal_id = (n_deferred > 0).then_some(n_vectors as PointOffsetType);
+    let deferred_internal_id = if n_deferred > 0 {
+        Some(u32::try_from(n_vectors).expect("n_vectors fits in PointOffsetType"))
+    } else {
+        None
+    };
-            .with_view(|v| v.payload_by_offset(i as u32 - 1, &hw_counter))
+            .with_view(|v| {
+                v.payload_by_offset(
+                    u32::try_from(i - 1).expect("internal id fits in PointOffsetType"),
+                    &hw_counter,
+                )
+            })

Based on learnings, in code that computes offsets or casts counts to PointOffsetType (u32), avoid unsafe or unchecked casts from usize to PointOffsetType.

Also applies to: 923-941

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

In `@lib/segment/src/segment/tests/test_immutable_payload_index_files.rs` around
lines 773 - 774, Replace unchecked casts like `n_vectors as PointOffsetType` and
`i as u32 - 1` with checked conversions using TryFrom/TryInto for
PointOffsetType (or use usize::try_into()) and handle the Result (propagate or
panic with a clear message). Locate the occurrences around the test function
that uses the `n_vectors` variable and the loop index `i` (and the similar casts
between lines ~923-941) and change them to use
`PointOffsetType::try_from(n_vectors)` / `n_vectors.try_into()` and
`PointOffsetType::try_from(i - 1)` (or `usize::try_into()`), unwrapping or
returning an error with a descriptive message if the conversion fails so the
test fails loudly instead of silently wrapping.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@lib/segment/src/segment/tests/test_immutable_payload_index_files.rs`:
- Around line 773-774: Replace unchecked casts like `n_vectors as
PointOffsetType` and `i as u32 - 1` with checked conversions using
TryFrom/TryInto for PointOffsetType (or use usize::try_into()) and handle the
Result (propagate or panic with a clear message). Locate the occurrences around
the test function that uses the `n_vectors` variable and the loop index `i` (and
the similar casts between lines ~923-941) and change them to use
`PointOffsetType::try_from(n_vectors)` / `n_vectors.try_into()` and
`PointOffsetType::try_from(i - 1)` (or `usize::try_into()`), unwrapping or
returning an error with a descriptive message if the conversion fails so the
test fails loudly instead of silently wrapping.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9d4d9327-29df-419f-abe9-d9712b2ad425

📥 Commits

Reviewing files that changed from the base of the PR and between fd4e25d and 53486c5.

📒 Files selected for processing (3)
  • lib/segment/src/index/field_index/map_index/immutable_map_index.rs
  • lib/segment/src/segment/tests/mod.rs
  • lib/segment/src/segment/tests/test_immutable_payload_index_files.rs

@agourlay
agourlay merged commit 0d4e7c4 into dev May 4, 2026
15 checks passed
@agourlay
agourlay deleted the fix-immutable-map-index-zero-count branch May 4, 2026 17:45
@coderabbitai coderabbitai Bot mentioned this pull request May 5, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
* fix(segment): immutable map index skips values with no live points on load

When MmapMapIndex::open ORs the id-tracker's runtime deletion bitvec
into the on-disk one at open time, ImmutableMapIndex::open_mmap could
insert a zero-count entry into value_to_points for any value whose live
points were all deleted, then immediately trip its own post-build sort
assert. Skip such values, mirroring the runtime invariant maintained by
remove_idx_from_value_list which already removes entries when their
count drops to zero.

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

* test(segment): file-system immutability test for payload indices

Builds an immutable segment with all 8 PayloadSchemaType variants
indexed, snapshots every byte under payload_index/, then asserts
byte-for-byte equality plus per-field query correctness after
delete_point, flush, drop+reload, and a second deletes+flush on the
reloaded segment. Each query exercises a different read path of an
immutable index variant: map exact-match (keyword/uuid/integer),
numeric range (float), datetime range, geo bounding box, full-text
token match, bool match. Reproduces the regression fixed in the
previous commit.

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