Repository navigation
[UIO] Dynamic mmap flags - #8760
Conversation
| /// 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> { |
There was a problem hiding this comment.
This function was moved from tests, but it is used in DynamicMmapFlags::set, which is now marked as deprecated for non-test code
There was a problem hiding this comment.
if it is only for tests, we have #[cfg(any(test, feature = "testing"))]. We can avoid deprecation for non-public api
| 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"); |
There was a problem hiding this comment.
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.
📝 WalkthroughWalkthroughThis PR promotes Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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: 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_batchrequires monotonic indices, andAHashMapiteration order is unspecified, so thesorted_by_keyis 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
📒 Files selected for processing (11)
lib/common/common/src/stored_bitslice.rslib/segment/benches/dynamic_mmap_flags.rslib/segment/src/common/flags/bitvec_flags.rslib/segment/src/common/flags/buffered_dynamic_flags.rslib/segment/src/common/flags/dynamic_mmap_flags.rslib/segment/src/common/flags/roaring_flags.rslib/segment/src/index/field_index/bool_index/mutable_bool_index.rslib/segment/src/index/field_index/null_index/mutable_null_index.rslib/segment/src/vector_storage/dense/appendable_dense_vector_storage.rslib/segment/src/vector_storage/multi_dense/appendable_mmap_multi_dense_vector_storage.rslib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs
| /// 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()) | ||
| } | ||
| }) | ||
| } |
There was a problem hiding this comment.
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.
| /// 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>( |
There was a problem hiding this comment.
Why generic and not simply conver PointOffsetType into u64?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
lib/segment/src/common/flags/dynamic_mmap_flags.rs (1)
251-263:⚠️ Potential issue | 🟡 MinorClamp
iter_truestoself.len().
read_all()spans the full allocated capacity, so this can yield indices beyond the logical flag length.count_flagsandget_bitslicealready clamp tostatus.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
📒 Files selected for processing (4)
lib/common/common/src/stored_bitslice.rslib/segment/benches/dynamic_mmap_flags.rslib/segment/src/common/flags/buffered_dynamic_flags.rslib/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
| 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)?) |
There was a problem hiding this comment.
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.
Refactors the
DynamicMmapFlagsto useStoredBitSliceinstead of plain mmap.This PR only covers the
flagsfield, we'll refactorstatus(MmapType) later.Additionally, it leverages
set_ascending_bits_batchduring flushing.