Skip to content

[UIO] Dynamic mmap flags - #8760

Merged
coszio merged 3 commits into
devfrom
dynamic-mmap-flags
Apr 22, 2026
Merged

coszio merged 3 commits into
devfrom
dynamic-mmap-flags

Conversation

@coszio

@coszio coszio commented Apr 21, 2026

Copy link
Copy Markdown
Contributor

Refactors the DynamicMmapFlags to use StoredBitSlice instead of plain mmap.

This PR only covers the flags field, we'll refactor status (MmapType) later.

Additionally, it leverages set_ascending_bits_batch during flushing.

/// Read-modify-write a single bit. Returns the previous value.
///
/// Only writes to the backend if the element actually changed.
pub fn replace_bit(&mut self, bit_index: u64, value: bool) -> Result<bool> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This function was moved from tests, but it is used in DynamicMmapFlags::set, which is now marked as deprecated for non-test code

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.

if it is only for tests, we have #[cfg(any(test, feature = "testing"))]. We can avoid deprecation for non-public api

Comment on lines -167 to +161
let current_capacity = mmap_max_current_size(self.status.len);
let current_capacity = usize::try_from(self.flags.bit_len()).expect("bit_len fits usize");

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Minor fix: Although I don't expect this bug to have been exercised, this now reads the actual length of the file, instead of relying on idealized capacity.

@coszio
coszio requested review from generall and timvisee April 21, 2026 20:19
@coszio coszio modified the milestone: Universal IO Apr 21, 2026
@coszio coszio mentioned this pull request Apr 21, 2026
34 of 36 tasks
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR promotes StoredBitSlice::replace_bit from a test-only impl into the main public impl, and updates tests to call the public API. It changes multiple flag-related modules to use fallible APIs (returning OperationResult) and migrates DynamicMmapFlags from an MmapBitSlice backing to StoredBitSlice<MmapFile>. Several methods gain or change signatures (e.g., get, count_flags, set, set_ascending_bits, get_bitslice, iter_trues) to propagate errors, and downstream call sites are updated to ? or .unwrap() accordingly. Benchmark and buffered-flusher code now use batch set_ascending_bits and handle fallible returns.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title '[UIO] Dynamic mmap flags' is concise and directly related to the main changeset, which refactors DynamicMmapFlags to use StoredBitSlice instead of plain mmap.
Description check ✅ Passed The description accurately describes the core changes: refactoring DynamicMmapFlags to use StoredBitSlice for the flags field and leveraging set_ascending_bits_batch during flushing.
Docstring Coverage ✅ Passed Docstring coverage is 81.82% 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 dynamic-mmap-flags

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/common/flags/buffered_dynamic_flags.rs (1)

97-102: LGTM — sorting is required, not just opportunistic.

set_ascending_bits_batch requires monotonic indices, and AHashMap iteration order is unspecified, so the sorted_by_key is load-bearing here. A brief comment calling that out would help future readers (otherwise someone might "optimize" the sort away).

💬 Optional clarifying comment
+            // `set_ascending_bits_batch` assumes monotonically increasing indices;
+            // AHashMap iteration order is unspecified, so sort is required for correctness.
             flags_guard.set_ascending_bits(
                 updates
                     .iter()
                     .map(|(index, value)| (*index, *value))
                     .sorted_by_key(|(index, _value)| *index),
             )?;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/common/flags/buffered_dynamic_flags.rs` around lines 97 -
102, Add a brief inline comment above the flags_guard.set_ascending_bits call
explaining that set_ascending_bits (and set_ascending_bits_batch) require
strictly monotonic/ascending indices, that iteration over the AHashMap in
updates is not deterministic, and therefore the explicit sorted_by_key is
necessary to guarantee ascending order and must not be removed by future
optimizations; mention the function name set_ascending_bits and the source of
updates so readers know why the sort is load-bearing.
🤖 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/common/flags/dynamic_mmap_flags.rs`:
- Around line 264-278: iter_trues currently uses self.flags.read_all() and
iter_ones() over the full underlying capacity, which can yield indices >=
self.len(); change iter_trues to clamp/slice the borrowed Cow::Borrowed bitslice
and the owned Vec/Iterator to self.len() (same behavior as get_bitslice and
count_flags) so only indices < self.len() are returned — adjust the Borrowed
path (bitslice.iter_ones()) to iterate over bitslice[..self.len()] and for the
Owned path materialize only up to self.len() (or filter indices >= self.len())
so functions like set_ascending_bits/set_len residual bits won’t surface
out-of-range indices.

---

Nitpick comments:
In `@lib/segment/src/common/flags/buffered_dynamic_flags.rs`:
- Around line 97-102: Add a brief inline comment above the
flags_guard.set_ascending_bits call explaining that set_ascending_bits (and
set_ascending_bits_batch) require strictly monotonic/ascending indices, that
iteration over the AHashMap in updates is not deterministic, and therefore the
explicit sorted_by_key is necessary to guarantee ascending order and must not be
removed by future optimizations; mention the function name set_ascending_bits
and the source of updates so readers know why the sort is load-bearing.
🪄 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: d004178e-50d3-4648-bb1d-07f26cbec9ff

📥 Commits

Reviewing files that changed from the base of the PR and between 6e7f997 and 241595f.

📒 Files selected for processing (11)
  • lib/common/common/src/stored_bitslice.rs
  • lib/segment/benches/dynamic_mmap_flags.rs
  • lib/segment/src/common/flags/bitvec_flags.rs
  • lib/segment/src/common/flags/buffered_dynamic_flags.rs
  • lib/segment/src/common/flags/dynamic_mmap_flags.rs
  • lib/segment/src/common/flags/roaring_flags.rs
  • lib/segment/src/index/field_index/bool_index/mutable_bool_index.rs
  • lib/segment/src/index/field_index/null_index/mutable_null_index.rs
  • lib/segment/src/vector_storage/dense/appendable_dense_vector_storage.rs
  • lib/segment/src/vector_storage/multi_dense/appendable_mmap_multi_dense_vector_storage.rs
  • lib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs

Comment on lines 264 to 278
/// Iterate over all "true" flags
pub fn iter_trues(&self) -> impl Iterator<Item = PointOffsetType> + '_ {
self.flags.iter_ones().map(|x| x as PointOffsetType)
pub fn iter_trues(&self) -> OperationResult<impl Iterator<Item = PointOffsetType> + '_> {
Ok(match self.flags.read_all()? {
Cow::Borrowed(bitslice) => {
Either::Left(bitslice.iter_ones().map(|x| x as PointOffsetType))
}
Cow::Owned(bitvec) => {
// Owned path: backend doesn't support zero-copy; materialize into Vec
// so we don't return a reference to a local
let indices: Vec<PointOffsetType> =
bitvec.iter_ones().map(|x| x as PointOffsetType).collect();
Either::Right(indices.into_iter())
}
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

iter_trues doesn't clamp to status.len like get_bitslice/count_flags do.

read_all() returns the entire underlying capacity (rounded up to the next power-of-two via file_size_for), so iter_ones() here can surface bits at indices >= self.status.len if any were ever set (e.g., via set_ascending_bits before a corresponding set_len, or residual state). The sibling accessors both slice to self.len() — worth aligning this one too.

♻️ Suggested alignment
 pub fn iter_trues(&self) -> OperationResult<impl Iterator<Item = PointOffsetType> + '_> {
+    let len = self.len();
     Ok(match self.flags.read_all()? {
         Cow::Borrowed(bitslice) => {
-            Either::Left(bitslice.iter_ones().map(|x| x as PointOffsetType))
+            Either::Left(bitslice[..len].iter_ones().map(|x| x as PointOffsetType))
         }
         Cow::Owned(bitvec) => {
-            // Owned path: backend doesn't support zero-copy; materialize into Vec
-            // so we don't return a reference to a local
-            let indices: Vec<PointOffsetType> =
-                bitvec.iter_ones().map(|x| x as PointOffsetType).collect();
+            let indices: Vec<PointOffsetType> = bitvec[..len]
+                .iter_ones()
+                .map(|x| x as PointOffsetType)
+                .collect();
             Either::Right(indices.into_iter())
         }
     })
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Iterate over all "true" flags
pub fn iter_trues(&self) -> impl Iterator<Item = PointOffsetType> + '_ {
self.flags.iter_ones().map(|x| x as PointOffsetType)
pub fn iter_trues(&self) -> OperationResult<impl Iterator<Item = PointOffsetType> + '_> {
Ok(match self.flags.read_all()? {
Cow::Borrowed(bitslice) => {
Either::Left(bitslice.iter_ones().map(|x| x as PointOffsetType))
}
Cow::Owned(bitvec) => {
// Owned path: backend doesn't support zero-copy; materialize into Vec
// so we don't return a reference to a local
let indices: Vec<PointOffsetType> =
bitvec.iter_ones().map(|x| x as PointOffsetType).collect();
Either::Right(indices.into_iter())
}
})
}
/// Iterate over all "true" flags
pub fn iter_trues(&self) -> OperationResult<impl Iterator<Item = PointOffsetType> + '_> {
let len = self.len();
Ok(match self.flags.read_all()? {
Cow::Borrowed(bitslice) => {
Either::Left(bitslice[..len].iter_ones().map(|x| x as PointOffsetType))
}
Cow::Owned(bitvec) => {
let indices: Vec<PointOffsetType> = bitvec[..len]
.iter_ones()
.map(|x| x as PointOffsetType)
.collect();
Either::Right(indices.into_iter())
}
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/common/flags/dynamic_mmap_flags.rs` around lines 264 - 278,
iter_trues currently uses self.flags.read_all() and iter_ones() over the full
underlying capacity, which can yield indices >= self.len(); change iter_trues to
clamp/slice the borrowed Cow::Borrowed bitslice and the owned Vec/Iterator to
self.len() (same behavior as get_bitslice and count_flags) so only indices <
self.len() are returned — adjust the Borrowed path (bitslice.iter_ones()) to
iterate over bitslice[..self.len()] and for the Owned path materialize only up
to self.len() (or filter indices >= self.len()) so functions like
set_ascending_bits/set_len residual bits won’t surface out-of-range indices.

///
/// Assumes the indices for the `updates` iterator increase monotonically
pub fn set_ascending_bits_batch(
pub fn set_ascending_bits_batch<TKey>(

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.

Why generic and not simply conver PointOffsetType into u64?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Makes it more ergonomic at callsites, follows a pattern that was in DynamicMmapFlags already.

This way we don't need to call .map() just to convert from usize or u32

@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

♻️ Duplicate comments (1)
lib/segment/src/common/flags/dynamic_mmap_flags.rs (1)

251-263: ⚠️ Potential issue | 🟡 Minor

Clamp iter_trues to self.len().

read_all() spans the full allocated capacity, so this can yield indices beyond the logical flag length. count_flags and get_bitslice already clamp to status.len; this should match them.

Suggested fix
 pub fn iter_trues(&self) -> OperationResult<impl Iterator<Item = PointOffsetType> + '_> {
+    let len = self.len();
     Ok(match self.flags.read_all()? {
         Cow::Borrowed(bitslice) => {
-            Either::Left(bitslice.iter_ones().map(|x| x as PointOffsetType))
+            Either::Left(bitslice[..len].iter_ones().map(|x| x as PointOffsetType))
         }
         Cow::Owned(bitvec) => {
             // Owned path: backend doesn't support zero-copy; materialize into Vec
             // so we don't return a reference to a local
-            let indices: Vec<PointOffsetType> =
-                bitvec.iter_ones().map(|x| x as PointOffsetType).collect();
+            let indices: Vec<PointOffsetType> = bitvec[..len]
+                .iter_ones()
+                .map(|x| x as PointOffsetType)
+                .collect();
             Either::Right(indices.into_iter())
         }
     })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/common/flags/dynamic_mmap_flags.rs` around lines 251 - 263,
iter_trues currently uses flags.read_all() which yields indices across full
capacity and can return values >= self.len(); update iter_trues to clamp results
to self.len(): after calling self.flags.read_all() (both Cow::Borrowed(bitslice)
and Cow::Owned(bitvec) paths) limit the produced iterator to indices <
self.len() (e.g. by taking only the first self.len() items or filtering by x <
self.len()), and ensure the Owned path's materialized Vec is also truncated to
self.len() before returning the iterator so behavior matches count_flags and
get_bitslice.
🤖 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/common/flags/dynamic_mmap_flags.rs`:
- Around line 210-214: The batch writer set_ascending_bits currently writes
directly into the mmap backing (via flags.set_ascending_bits_batch) and can set
bits at indices >= self.status.len, violating set_len's invariant that new
elements start false; fix by filtering/clamping the incoming updates iterator to
only include entries with bit_idx < self.status.len before calling
flags.set_ascending_bits_batch (or return an error if any index is out-of-range)
so writes are bounded by the logical length; update the implementation in
set_ascending_bits to apply this filter using self.status.len and keep the call
to flags.set_ascending_bits_batch with the filtered iterator.

---

Duplicate comments:
In `@lib/segment/src/common/flags/dynamic_mmap_flags.rs`:
- Around line 251-263: iter_trues currently uses flags.read_all() which yields
indices across full capacity and can return values >= self.len(); update
iter_trues to clamp results to self.len(): after calling self.flags.read_all()
(both Cow::Borrowed(bitslice) and Cow::Owned(bitvec) paths) limit the produced
iterator to indices < self.len() (e.g. by taking only the first self.len() items
or filtering by x < self.len()), and ensure the Owned path's materialized Vec is
also truncated to self.len() before returning the iterator so behavior matches
count_flags and get_bitslice.
🪄 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: da5e9d94-12ac-4931-abda-7e65b2f75209

📥 Commits

Reviewing files that changed from the base of the PR and between 241595f and 9698198.

📒 Files selected for processing (4)
  • lib/common/common/src/stored_bitslice.rs
  • lib/segment/benches/dynamic_mmap_flags.rs
  • lib/segment/src/common/flags/buffered_dynamic_flags.rs
  • lib/segment/src/common/flags/dynamic_mmap_flags.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/segment/src/common/flags/buffered_dynamic_flags.rs
  • lib/segment/benches/dynamic_mmap_flags.rs

Comment on lines +210 to +214
pub fn set_ascending_bits(
&mut self,
key: TKey,
value: bool,
hw_counter_ref: HwMetricRefCounter,
) -> OperationResult<bool>
where
TKey: num_traits::cast::AsPrimitive<usize>,
{
// Measure write of single bool.
hw_counter_ref.incr_delta(size_of::<bool>());

let key: usize = key.as_();
if key >= self.status.len {
if value {
let new_len = key + 1;
hw_counter_ref.incr_delta(new_len - self.status.len);
self.set_len(new_len)?;
} else {
// Default value is false, so we don't need to resize
return Ok(false);
}
}

Ok(self.flags.replace(key, value))
updates: impl IntoIterator<Item = (u64, bool)>,
) -> OperationResult<()> {
Ok(self.flags.set_ascending_bits_batch(updates)?)

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 batch writes by the logical flag length.

set_ascending_bits currently writes directly to backing capacity, so an update with bit_idx >= self.status.len but still within the mmap capacity can persist a “future” flag. That violates set_len’s “new elements will be false” contract when the length later grows.

Suggested fix
 pub fn set_ascending_bits(
     &mut self,
     updates: impl IntoIterator<Item = (u64, bool)>,
 ) -> OperationResult<()> {
-    Ok(self.flags.set_ascending_bits_batch(updates)?)
+    let len = self.status.len as u64;
+    Ok(self
+        .flags
+        .set_ascending_bits_batch(updates.into_iter().take_while(move |(idx, _)| *idx < len))?)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/common/flags/dynamic_mmap_flags.rs` around lines 210 - 214,
The batch writer set_ascending_bits currently writes directly into the mmap
backing (via flags.set_ascending_bits_batch) and can set bits at indices >=
self.status.len, violating set_len's invariant that new elements start false;
fix by filtering/clamping the incoming updates iterator to only include entries
with bit_idx < self.status.len before calling flags.set_ascending_bits_batch (or
return an error if any index is out-of-range) so writes are bounded by the
logical length; update the implementation in set_ascending_bits to apply this
filter using self.status.len and keep the call to flags.set_ascending_bits_batch
with the filtered iterator.

@coszio
coszio merged commit 96c3bfa into dev Apr 22, 2026
15 checks passed
@coszio
coszio deleted the dynamic-mmap-flags branch April 22, 2026 02:57
timvisee pushed a commit that referenced this pull request May 8, 2026
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
9 tasks
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