Skip to content

Split mmap_hashmap into multiple files - #8933

Merged
xzfc merged 1 commit into
devfrom
uio-persisted-hashmap
May 7, 2026
Merged

xzfc merged 1 commit into
devfrom
uio-persisted-hashmap

Conversation

@xzfc

@xzfc xzfc commented May 6, 2026

Copy link
Copy Markdown
Member

Preparation work for #8405.

Old layout:

lib/common/common/src/mmap_hashmap.rs

lib/common/common/benches/mmap_hashmap.rs

New layout:

lib/common/common/src/persisted_hashmap/mod.rs
lib/common/common/src/persisted_hashmap/fixtures.rs
lib/common/common/src/persisted_hashmap/mmap.rs
lib/common/common/src/persisted_hashmap/serialize.rs
lib/common/common/src/persisted_hashmap/structures.rs
lib/common/common/src/persisted_hashmap/tests.rs
lib/common/common/src/persisted_hashmap/uio.rs (not in this PR - will be in #8405)

lib/common/common/benches/persisted_hashmap.rs

The method MmapHashMap::create is extracted into serialize_hashmap.

No changes beyond splitting, module renaming and serialize_hashmap.

@xzfc
xzfc requested review from generall and timvisee May 6, 2026 21:03
@coderabbitai

coderabbitai Bot commented May 6, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request refactors the mmap-backed hash map implementation by reorganizing it into a new persisted_hashmap module. The old mmap_hashmap.rs module is removed entirely and replaced with a structured module containing separate concerns: memory-mapped access logic (mmap.rs), serialization logic (serialize.rs), on-disk data structures (structures.rs), test fixtures (fixtures.rs), and tests (tests.rs). The serialization pathway changes from an in-place MmapHashMap::create method to a free function serialize_hashmap that writes the hashmap to disk. All imports across the segment indexing codebase are updated to reference the new module paths.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

release:1.18.0

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.95% 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 accurately describes the main structural change: the mmap_hashmap module is split from a single file into multiple organized files under a persisted_hashmap directory.
Description check ✅ Passed The description clearly explains the restructuring work, showing the old and new file layouts, mentioning the method extraction, and noting this is preparation for issue #8405 with minimal behavioral changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

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

🤖 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/common/common/src/persisted_hashmap/mod.rs`:
- Around line 5-6: The bench imports the fenced fixtures module but that module
is gated with #[cfg(any(test, feature = "testing"))]
(persisted_hashmap::fixtures) so the mmap_hashmap bench fails when the crate is
used as a dependency; fix by either (A) enabling the bench to require the
testing feature: add required-features = ["testing"] to the mmap_hashmap bench
entry in Cargo.toml so the feature is activated when running that bench, or (B)
expose the fixtures unconditionally by removing or relaxing the cfg on the
fixtures mod declaration (persisted_hashmap::fixtures) so it is always compiled
for benches; pick one option and apply consistently across the crate.

In `@lib/common/common/src/persisted_hashmap/serialize.rs`:
- Around line 51-55: The loop that assigns buckets uses a narrowing cast of
values.len() to the stored values_len (u32) which can wrap if a bucket has >
u32::MAX entries; change this to perform a checked conversion (e.g.
u32::try_from(values.len())/try_into()) and return/fail fast with a clear error
if the conversion fails, then reuse the resulting u32 value in both the current
pass and the earlier sizing pass (replace the raw as cast in the loop and the
corresponding conversion at lines ~95-100) so the written values_len matches the
actual payload length and prevents silent truncation; update references to
entry_bytes::<K,V>(k, v.len()) to consume the checked value where appropriate.
🪄 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: ffce9a1c-f8e0-4895-afd9-b39023d71cdb

📥 Commits

Reviewing files that changed from the base of the PR and between 8ab30ee and 09e8e1e.

📒 Files selected for processing (13)
  • lib/common/common/benches/mmap_hashmap.rs
  • lib/common/common/src/lib.rs
  • lib/common/common/src/mmap_hashmap.rs
  • lib/common/common/src/persisted_hashmap/fixtures.rs
  • lib/common/common/src/persisted_hashmap/mmap.rs
  • lib/common/common/src/persisted_hashmap/mod.rs
  • lib/common/common/src/persisted_hashmap/serialize.rs
  • lib/common/common/src/persisted_hashmap/structures.rs
  • lib/common/common/src/persisted_hashmap/tests.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs
  • lib/segment/src/index/field_index/map_index/immutable_map_index.rs
  • lib/segment/src/index/field_index/map_index/mmap_map_index.rs
  • lib/segment/src/index/field_index/map_index/mod.rs
💤 Files with no reviewable changes (1)
  • lib/common/common/src/mmap_hashmap.rs

Comment on lines +5 to +6
#[cfg(any(test, feature = "testing"))]
pub mod fixtures;

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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "[persisted_hashmap fixtures gate]"
rg -n -C2 'cfg\(any\(test, feature = "testing"\)\)|pub mod fixtures' lib/common/common/src/persisted_hashmap/mod.rs

echo
echo "[bench imports]"
rg -n -C2 'persisted_hashmap::fixtures' lib/common/common/benches

echo
echo "[bench feature wiring in Cargo manifests]"
fd '^Cargo\.toml$' . -x rg -n -C2 '\[\[bench\]\]|required-features|^testing\s*=|name\s*=\s*"mmap_hashmap"' {}

Repository: qdrant/qdrant

Length of output: 4998


Add required-features = ["testing"] to the mmap_hashmap bench or expose fixtures unconditionally.

The fixtures module is gated behind #[cfg(any(test, feature = "testing"))] at lib/common/common/src/persisted_hashmap/mod.rs lines 5-6, but the mmap_hashmap bench at lib/common/common/benches/mmap_hashmap.rs line 1 imports from common::persisted_hashmap::fixtures. When the library is compiled as a dependency for bench targets, cfg(test) is not active. The bench must either declare required-features = ["testing"] in its Cargo.toml entry or the fixtures module must be available outside the test gate.

🤖 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/common/common/src/persisted_hashmap/mod.rs` around lines 5 - 6, The bench
imports the fenced fixtures module but that module is gated with #[cfg(any(test,
feature = "testing"))] (persisted_hashmap::fixtures) so the mmap_hashmap bench
fails when the crate is used as a dependency; fix by either (A) enabling the
bench to require the testing feature: add required-features = ["testing"] to the
mmap_hashmap bench entry in Cargo.toml so the feature is activated when running
that bench, or (B) expose the fixtures unconditionally by removing or relaxing
the cfg on the fixtures mod declaration (persisted_hashmap::fixtures) so it is
always compiled for benches; pick one option and apply consistently across the
crate.

Comment on lines +51 to +55
for (k, v) in map.clone() {
last_bucket = last_bucket.next_multiple_of(K::ALIGN);
buckets[phf.get(k).expect("Key not found in phf") as usize] = last_bucket as BucketOffset;
last_bucket += entry_bytes::<K, V>(k, v.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 | ⚡ Quick win

Reject buckets whose value count exceeds ValuesLen.

The format encodes values_len as u32, but Line 100 narrows values.len() with as. Once a bucket grows past u32::MAX, the file still writes the full payload while the stored count wraps, so reads from that bucket become truncated/corrupt. Fail fast with a checked conversion and reuse it in both passes.

💡 Proposed fix
     let mut buckets = vec![0 as BucketOffset; keys_count];
     let mut last_bucket = 0usize;
     for (k, v) in map.clone() {
+        let values_len = ValuesLen::try_from(v.len()).map_err(|_| {
+            io::Error::new(io::ErrorKind::InvalidInput, "too many values for one key")
+        })?;
         last_bucket = last_bucket.next_multiple_of(K::ALIGN);
         buckets[phf.get(k).expect("Key not found in phf") as usize] = last_bucket as BucketOffset;
-        last_bucket += entry_bytes::<K, V>(k, v.len());
+        last_bucket += entry_bytes::<K, V>(k, values_len as usize);
     }
@@
     for (key, values) in map {
         let next_pos = pos.next_multiple_of(K::ALIGN);
         if next_pos > pos {
             bufw.write_zeros(next_pos - pos)?;
             pos = next_pos;
         }
 
-        let entry_size = entry_bytes::<K, V>(key, values.len());
+        let values_len = ValuesLen::try_from(values.len()).map_err(|_| {
+            io::Error::new(io::ErrorKind::InvalidInput, "too many values for one key")
+        })?;
+        let entry_size = entry_bytes::<K, V>(key, values_len as usize);
         pos += entry_size;
 
         key.write(&mut bufw)?;
         bufw.write_zeros(key_padding_bytes::<K, V>(key))?;
-        bufw.write_all((values.len() as ValuesLen).as_bytes())?;
+        bufw.write_all(values_len.as_bytes())?;
         bufw.write_zeros(values_len_padding_bytes::<V>())?;
         for i in values {
             bufw.write_all(i.as_bytes())?;
         }
     }

Also applies to: 95-100

🤖 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/common/common/src/persisted_hashmap/serialize.rs` around lines 51 - 55,
The loop that assigns buckets uses a narrowing cast of values.len() to the
stored values_len (u32) which can wrap if a bucket has > u32::MAX entries;
change this to perform a checked conversion (e.g.
u32::try_from(values.len())/try_into()) and return/fail fast with a clear error
if the conversion fails, then reuse the resulting u32 value in both the current
pass and the earlier sizing pass (replace the raw as cast in the loop and the
corresponding conversion at lines ~95-100) so the written values_len matches the
actual payload length and prevents silent truncation; update references to
entry_bytes::<K,V>(k, v.len()) to consume the checked value where appropriate.

@xzfc
xzfc merged commit d8e4932 into dev May 7, 2026
15 checks passed
@xzfc
xzfc deleted the uio-persisted-hashmap branch May 7, 2026 14:35
@coderabbitai coderabbitai Bot mentioned this pull request May 8, 2026
timvisee pushed a commit that referenced this pull request May 8, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jul 29, 2026
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