Skip to content

refactor/opt - #8065

Merged
dancixx merged 26 commits into
devfrom
refactor/opt
Feb 19, 2026
Merged

dancixx merged 26 commits into
devfrom
refactor/opt

Conversation

@dancixx

@dancixx dancixx commented Feb 5, 2026 •

Copy link
Copy Markdown
Contributor

The goal is to separate the optimization process so it’s independent of the collection crate, allowing it to be used on Edge. The requirement is to keep the orchestration part in the collection crate, while moving the execution into the shard crate. @xzfc

All Submissions:

  • Contributions should target the dev branch. Did you create your branch from dev?
  • Have you followed the guidelines in our Contributing document?
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?

New Feature Submissions:

  1. Does your submission pass tests?
  2. Have you formatted your code locally using cargo +nightly fmt --all command prior to submission?
  3. Have you checked your code using cargo clippy --workspace --all-features command?

Changes to Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Comment thread config/config.yaml Resolved
@dancixx
dancixx marked this pull request as ready for review February 10, 2026 17:16

@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: 5

🤖 Fix all issues with AI agents
In `@lib/shard/src/optimize.rs`:
- Around line 325-329: The code is calling
optimized_segment.delete_point(...).unwrap(), which will panic on error; replace
the unwraps with the try operator (e.g., optimized_segment.delete_point(...)?),
propagate the error by updating the enclosing function signatures (e.g., the
function containing the loop handling deleted_points_snapshot and
finish_optimization) to return Result<..., ErrorType>, and adjust callers to
handle the propagated error. Apply this change for the loop over
deleted_points_snapshot where delete_point is called and the corresponding calls
in finish_optimization (both occurrences of optimized_segment.delete_point),
ensuring the error type aligns with the crate's error handling (convert or map
the error if necessary).
- Around line 746-752: On the failure path where finish_optimization returns
Err, we need to also remove the temporary COW segment before unwrapping proxies;
modify the Err(err) branch handling finish_optimization to first remove the temp
COW segment from segment_holder (the same cleanup done on the earlier error
path), then call unwrap_proxy(&segment_holder, &proxy_ids) and return Err(err).
Reference finish_optimization, unwrap_proxy, segment_holder, and proxy_ids to
locate where to add the temp-segment removal/cleanup call.
- Around line 724-732: The error paths after add_new_locked() leave the COW
segment in the holder; update both failure branches (the build_result Err branch
where optimize_segment_propagate_changes fails and the finish_optimization
failure branch) to remove the temporary COW segment before returning: if
cow_segment_id_opt.is_some(), call remove_segment_if_not_needed(cow_segment_id)
(or the appropriate removal helper) prior to calling
unwrap_proxy(&segment_holder, &proxy_ids)? and returning Err; keep using
cow_segment_id_opt to locate the segment and ensure removal happens regardless
of which error path is taken.

In `@lib/shard/src/tracker.rs`:
- Around line 156-178: TrackerTelemetry derives Deserialize but its field name
is &'static str which cannot be deserialized from typical serde inputs; either
remove Deserialize from the TrackerTelemetry derive list if the struct is only
serialized for telemetry or change the field signature pub name: &'static str to
an owned String and keep Deserialize; update any code that constructs
TrackerTelemetry (factory/constructor places referencing TrackerTelemetry::name
or building instances) to use String::from(...) if you switch to String, or
remove deserialization uses/tests if you drop Deserialize.
- Around line 33-56: The doc comment for the truncate method incorrectly
references the constant name KEEP_TRACKERS; update the comment to use the actual
constant name KEEP_LAST_TRACKERS so the docs match the code, and ensure any
surrounding wording remains accurate in the fn truncate() docblock (the function
and constant names to locate are truncate and KEEP_LAST_TRACKERS).
🧹 Nitpick comments (6)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)

39-42: Imports placed between struct definition and impl block.

These use statements are placed mid-file between the VacuumOptimizer struct (line 37) and its impl block (line 44). The idiomatic Rust convention is to group all imports at the top of the file. This same pattern appears in config_mismatch_optimizer.rs, indexing_optimizer.rs, and merge_optimizer.rs.

Move imports to the top of the file
 use segment::common::operation_time_statistics::OperationDurationsAggregator;
+use segment::common::operation_error::{OperationError, OperationResult};
 use segment::entry::entry_point::NonAppendableSegmentEntry;
 use segment::index::VectorIndex;
 use segment::segment::Segment;
+use segment::segment_constructor::segment_builder::SegmentBuilder;
 use segment::types::{HnswConfig, HnswGlobalConfig, QuantizationConfig};
 use segment::vector_storage::VectorStorage;
+use shard::locked_segment::LockedSegment;
+use shard::optimize::OptimizationStrategy;
 use shard::operations::optimization::OptimizerThresholds;

And remove lines 39–42.


127-140: Identical OptimizationStrategy implementations across all four optimizers.

The create_segment_builder and create_temp_segment implementations are copy-pasted verbatim across VacuumOptimizer, ConfigMismatchOptimizer, IndexingOptimizer, and MergeOptimizer. Since every SegmentOptimizer already provides optimized_segment_builder and temp_segment, consider providing a blanket impl or a default method to reduce the boilerplate:

impl<T: SegmentOptimizer> OptimizationStrategy for T {
    fn create_segment_builder(&self, input_segments: &[LockedSegment]) -> OperationResult<SegmentBuilder> {
        self.optimized_segment_builder(input_segments)
            .map_err(|e| OperationError::service_error(e.to_string()))
    }
    fn create_temp_segment(&self) -> OperationResult<LockedSegment> {
        self.temp_segment(false)
            .map_err(|e| OperationError::service_error(e.to_string()))
    }
}

This would eliminate four identical impl blocks and ensure consistency automatically. The current SegmentOptimizer: OptimizationStrategy + Sync supertrait bound already couples them.

lib/shard/src/optimize.rs (2)

74-95: unwrap_proxy silently skips missing segments.

At line 80, if segments_lock.get(proxy_id) returns None, the loop silently continues. In an error-recovery context this is likely fine (the segment may have already been cleaned up), but a log::warn! for the missing case would help with debugging, similar to the warning on line 85 for the already-unwrapped case.


557-581: Catch-all _ arm in match expression.

The (Option, Option) match uses _ as a catch-all for the three remaining cases ((None, Some), (Some, None), (None, None)). Per coding guidelines, explicit exhaustive matches are preferred so new variants aren't silently caught. However, since Option is a stdlib type that won't gain new variants, this is acceptable here.

As per coding guidelines: "Prefer explicit exhaustive matches over catch-all _ arm in Rust match expressions."

lib/shard/src/tracker.rs (2)

126-129: Use explicit TrackerHandle::from(...) instead of .into().

As per coding guidelines, prefer explicit SomeType::from(x) over implicit x.into() in Rust.

Proposed fix
     pub fn handle(&self) -> TrackerHandle {
-        self.state.clone().into()
+        TrackerHandle::from(self.state.clone())
     }

145-153: Use explicit OptimizationSegmentInfo::from(s) instead of s.into().

As per coding guidelines, prefer explicit SomeType::from(x) over implicit x.into() in Rust.

Proposed fix
     pub fn to_optimization(&self) -> Optimization {
         Optimization {
             optimizer: self.name,
             uuid: self.uuid,
-            segments: self.segments.iter().map(|s| s.into()).collect(),
+            segments: self.segments.iter().map(OptimizationSegmentInfo::from).collect(),
             status: self.state.lock().status.clone(),
             progress: self.progress_view.snapshot("Segment Optimizing"),
         }
     }

Comment thread lib/shard/src/optimize.rs
Comment on lines +325 to +329
for (point_id, versions) in deleted_points_snapshot {
optimized_segment
.delete_point(versions.operation_version, point_id, hw_counter)
.unwrap();
}

This comment was marked as off-topic.

Comment thread lib/shard/src/optimize.rs
Comment on lines +724 to +732
let (optimized_segment, already_remove_points) = match build_result {
Ok(result) => result,
Err(err) => {
// Properly cancel optimization on all error kinds
// Unwrap proxies and add temp segment to holder
unwrap_proxy(&segment_holder, &proxy_ids)?;
return Err(err);
}
};

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

🧩 Analysis chain

🏁 Script executed:

wc -l lib/shard/src/optimize.rs

Repository: qdrant/qdrant

Length of output: 86


🏁 Script executed:

# Read the relevant sections around the cited line numbers
cat -n lib/shard/src/optimize.rs | sed -n '695,740p'

Repository: qdrant/qdrant

Length of output: 1916


🏁 Script executed:

# Also check the success path mentioned at 472-476
cat -n lib/shard/src/optimize.rs | sed -n '460,490p'

Repository: qdrant/qdrant

Length of output: 1375


🏁 Script executed:

# Search for cow_segment patterns in the file
rg -n "cow_segment" lib/shard/src/optimize.rs -B2 -A2

Repository: qdrant/qdrant

Length of output: 2890


🏁 Script executed:

# Find the unwrap_proxy function definition
rg -n "fn unwrap_proxy" lib/shard/src/optimize.rs -A15

Repository: qdrant/qdrant

Length of output: 914


🏁 Script executed:

# Get the function signature where this code is located
cat -n lib/shard/src/optimize.rs | sed -n '550,630p'

Repository: qdrant/qdrant

Length of output: 3517


🏁 Script executed:

# Check for any error handling around cow_segment in related functions
rg -n "remove_segment_if_not_needed" lib/shard/src/optimize.rs -B3 -A3

Repository: qdrant/qdrant

Length of output: 387


🏁 Script executed:

# Check what counter_handler does and its Drop impl
rg -n "running_optimizations" lib/shard/src/optimize.rs -B2 -A2

Repository: qdrant/qdrant

Length of output: 368


🏁 Script executed:

# Check the finish_optimization function to understand the full flow
rg -n "fn finish_optimization" lib/shard/src/optimize.rs -A80 | head -100

Repository: qdrant/qdrant

Length of output: 3947


🏁 Script executed:

# Look for Drop implementations that might clean up segments
rg -n "impl Drop" lib/shard/src/optimize.rs -A10

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check the running_optimizations counter and its Drop implementation
rg -n "running_optimizations" lib/shard/src/ -A5 -B5 --type rust | head -80

Repository: qdrant/qdrant

Length of output: 1781


🏁 Script executed:

# Look at the segment_holder_write scope - when does it get dropped?
cat -n lib/shard/src/optimize.rs | sed -n '668,750p'

Repository: qdrant/qdrant

Length of output: 4265


🏁 Script executed:

# Check if there's any cleanup in the segment holder write guard drop
fd "segment_holder" lib/shard/src -type f -name "*.rs" | head -5

Repository: qdrant/qdrant

Length of output: 227


🏁 Script executed:

# Check ProcessCounter and its inc() method
rg -n "struct ProcessCounter\|impl ProcessCounter" lib/shard/src/ -A10 --type rust

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Look at what happens after the error return - does counter_handler get dropped?
cat -n lib/shard/src/optimize.rs | sed -n '720,760p'

Repository: qdrant/qdrant

Length of output: 1482


🏁 Script executed:

# Check if there are any tests that cover error paths
rg -n "optimize_segment_propagate_changes.*Err\|test.*optimize.*error" lib/shard/src/optimize.rs --type rust

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Look for other error paths after cow_segment_id_opt is set
rg -n "cow_segment_id_opt" lib/shard/src/optimize.rs -B2 -A2

Repository: qdrant/qdrant

Length of output: 1298


🏁 Script executed:

# Find ProcessCounter definition and its inc() method
fd "mod.rs" lib/shard/src/segment_holder/ | xargs grep -n "ProcessCounter" -A20 | head -60

Repository: qdrant/qdrant

Length of output: 1726


🏁 Script executed:

# Check if ProcessCounter::inc() returns something that cleans up on drop
rg -n "pub fn inc\|ProcessCounter" lib/shard/src/segment_holder/mod.rs -A3 | head -40

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Find ProcessCounter in the common module
fd "process_counter.rs" lib/ | xargs cat | head -100

Repository: qdrant/qdrant

Length of output: 2199


🏁 Script executed:

# Alternative: search for ProcessCounter definition across the codebase
rg -n "pub struct ProcessCounter\|impl.*ProcessCounter" lib/ --type rust -A10

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Let's trace the exact flow - what happens to cow_segment_id_opt in error case
cat -n lib/shard/src/optimize.rs | sed -n '724,758p'

Repository: qdrant/qdrant

Length of output: 1389


🏁 Script executed:

# Check what remove_segment_if_not_needed does
rg -n "fn remove_segment_if_not_needed" lib/shard/src/ -A15 --type rust

Repository: qdrant/qdrant

Length of output: 1409


🏁 Script executed:

# Check if there's any auto-cleanup for orphaned segments
rg -n "orphan\|leak\|cleanup" lib/shard/src/optimize.rs --type rust

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Verify the scope - cow_segment_id_opt is just a SegmentId (usize), not a guard
rg -n "type SegmentId\|SegmentId =" lib/shard/src/ --type rust | head -5

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check if the segment holder has any auto-cleanup for segments
rg -n "drop\|Drop\|cleanup" lib/shard/src/segment_holder/mod.rs -B2 -A2 | head -80

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check the comment in finish_optimization about temp segments
cat -n lib/shard/src/optimize.rs | sed -n '396,410p'

Repository: qdrant/qdrant

Length of output: 763


🏁 Script executed:

# Get full context of what remove_segment_if_not_needed does
rg -n "fn remove_segment_if_not_needed" lib/shard/src/segment_holder/mod.rs -A25

Repository: qdrant/qdrant

Length of output: 1271


🏁 Script executed:

# Check if segments are auto-cleaned by their drop implementation
rg -n "impl Drop for LockedSegment\|impl Drop for Segment" lib/ --type rust -A10

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Verify the lifecycle - is cow_segment_id_opt stored as just an ID or as a reference?
cat -n lib/shard/src/optimize.rs | sed -n '700,710p'

Repository: qdrant/qdrant

Length of output: 669


🏁 Script executed:

# Check what happens at the two error return points - does the holder get dropped?
cat -n lib/shard/src/optimize.rs | sed -n '586,610p'

Repository: qdrant/qdrant

Length of output: 1209


🏁 Script executed:

# Let me check if segments added to holder have automatic cleanup
rg -n "add_new_locked\|add_existing" lib/shard/src/segment_holder/mod.rs -A10 | head -60

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Check if there's lifecycle management for temporary segments elsewhere
rg -n "temp.*segment\|temporary.*segment" lib/shard/src/optimize.rs -i -B2 -A2

Repository: qdrant/qdrant

Length of output: 39


🏁 Script executed:

# Verify the complete error path - what scopes are active at return time
cat -n lib/shard/src/optimize.rs | sed -n '668,731p'

Repository: qdrant/qdrant

Length of output: 3509


🏁 Script executed:

# Get complete picture of the add_new_locked and what it returns
rg -n "fn add_new_locked" lib/shard/src/segment_holder/mod.rs -A15

Repository: qdrant/qdrant

Length of output: 699


🏁 Script executed:

# See the context around line 741 to understand the flow better
cat -n lib/shard/src/optimize.rs | sed -n '740,760p'

Repository: qdrant/qdrant

Length of output: 685


🏁 Script executed:

# Double-check: does counter_handler get dropped before the error return?
cat -n lib/shard/src/optimize.rs | sed -n '724,758p'

Repository: qdrant/qdrant

Length of output: 1389


🏁 Script executed:

# Check the learning about panicking in segment holder - is there related error handling?
cat -n lib/shard/src/segment_holder/mod.rs | sed -n '800,820p'

Repository: qdrant/qdrant

Length of output: 966


🏁 Script executed:

# Understand what happens when counter_handler goes out of scope
# Is it automatically cleaned up or only on explicit drop?
cat -n lib/shard/src/optimize.rs | sed -n '754,759p'

Repository: qdrant/qdrant

Length of output: 202


🏁 Script executed:

# Check if there are any other error returns between counter creation and explicit drop
cat -n lib/shard/src/optimize.rs | sed -n '705,760p'

Repository: qdrant/qdrant

Length of output: 2052


Error path doesn't clean up the COW segment.

When optimize_segment_propagate_changes fails (line 726) or finish_optimization fails (line 746), the code calls unwrap_proxy() to undo proxy segments but does not remove the cow_segment_id_opt from the segment holder. The COW segment was added at line 701 via add_new_locked() and will remain as an orphan appendable segment in the holder.

The success path in finish_optimization() (lines 472–476) explicitly calls remove_segment_if_not_needed(cow_segment_id), but both error paths lack this cleanup.

🤖 Prompt for AI Agents
In `@lib/shard/src/optimize.rs` around lines 724 - 732, The error paths after
add_new_locked() leave the COW segment in the holder; update both failure
branches (the build_result Err branch where optimize_segment_propagate_changes
fails and the finish_optimization failure branch) to remove the temporary COW
segment before returning: if cow_segment_id_opt.is_some(), call
remove_segment_if_not_needed(cow_segment_id) (or the appropriate removal helper)
prior to calling unwrap_proxy(&segment_holder, &proxy_ids)? and returning Err;
keep using cow_segment_id_opt to locate the segment and ensure removal happens
regardless of which error path is taken.

Comment thread lib/shard/src/optimize.rs
Comment on lines +746 to +752
Err(err) => {
// Properly cancel optimization on all error kinds
// Unwrap proxies and add temp segment to holder
unwrap_proxy(&segment_holder, &proxy_ids)?;
return Err(err);
}
};

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

Same COW segment cleanup missing on finish_optimization failure path.

If finish_optimization fails, unwrap_proxy restores the original segments, but the extra COW segment (if created) is not removed. This mirrors the issue noted in the first error path above.

🤖 Prompt for AI Agents
In `@lib/shard/src/optimize.rs` around lines 746 - 752, On the failure path where
finish_optimization returns Err, we need to also remove the temporary COW
segment before unwrapping proxies; modify the Err(err) branch handling
finish_optimization to first remove the temp COW segment from segment_holder
(the same cleanup done on the earlier error path), then call
unwrap_proxy(&segment_holder, &proxy_ids) and return Err(err). Reference
finish_optimization, unwrap_proxy, segment_holder, and proxy_ids to locate where
to add the temp-segment removal/cleanup call.

Comment thread lib/shard/src/tracker.rs
Comment on lines +33 to +56
/// Truncate and forget old trackers for successful/cancelled optimizations
///
/// Will never remove older trackers with failed or still ongoing optimizations.
///
/// Always keeps the last `KEEP_TRACKERS` trackers.
fn truncate(&mut self) {
let truncate_range = self.descriptions.len().saturating_sub(KEEP_LAST_TRACKERS);

// Find items to truncate, start removing from the back
let truncate = self
.descriptions
.iter()
.enumerate()
.take(truncate_range)
.filter(|(_, tracker)| match tracker.state.lock().status {
TrackerStatus::Optimizing | TrackerStatus::Error(_) => false,
TrackerStatus::Done | TrackerStatus::Cancelled(_) => true,
})
.map(|(index, _)| index)
.collect::<Vec<_>>();
truncate.into_iter().rev().for_each(|index| {
self.descriptions.remove(index);
});
}

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

Doc comment references wrong constant name.

Line 37 says "Always keeps the last KEEP_TRACKERS trackers" but the constant is named KEEP_LAST_TRACKERS.

Proposed fix
-    /// Always keeps the last `KEEP_TRACKERS` trackers.
+    /// Always keeps the last `KEEP_LAST_TRACKERS` trackers.
📝 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
/// Truncate and forget old trackers for successful/cancelled optimizations
///
/// Will never remove older trackers with failed or still ongoing optimizations.
///
/// Always keeps the last `KEEP_TRACKERS` trackers.
fn truncate(&mut self) {
let truncate_range = self.descriptions.len().saturating_sub(KEEP_LAST_TRACKERS);
// Find items to truncate, start removing from the back
let truncate = self
.descriptions
.iter()
.enumerate()
.take(truncate_range)
.filter(|(_, tracker)| match tracker.state.lock().status {
TrackerStatus::Optimizing | TrackerStatus::Error(_) => false,
TrackerStatus::Done | TrackerStatus::Cancelled(_) => true,
})
.map(|(index, _)| index)
.collect::<Vec<_>>();
truncate.into_iter().rev().for_each(|index| {
self.descriptions.remove(index);
});
}
/// Truncate and forget old trackers for successful/cancelled optimizations
///
/// Will never remove older trackers with failed or still ongoing optimizations.
///
/// Always keeps the last `KEEP_LAST_TRACKERS` trackers.
fn truncate(&mut self) {
let truncate_range = self.descriptions.len().saturating_sub(KEEP_LAST_TRACKERS);
// Find items to truncate, start removing from the back
let truncate = self
.descriptions
.iter()
.enumerate()
.take(truncate_range)
.filter(|(_, tracker)| match tracker.state.lock().status {
TrackerStatus::Optimizing | TrackerStatus::Error(_) => false,
TrackerStatus::Done | TrackerStatus::Cancelled(_) => true,
})
.map(|(index, _)| index)
.collect::<Vec<_>>();
truncate.into_iter().rev().for_each(|index| {
self.descriptions.remove(index);
});
}
🤖 Prompt for AI Agents
In `@lib/shard/src/tracker.rs` around lines 33 - 56, The doc comment for the
truncate method incorrectly references the constant name KEEP_TRACKERS; update
the comment to use the actual constant name KEEP_LAST_TRACKERS so the docs match
the code, and ensure any surrounding wording remains accurate in the fn
truncate() docblock (the function and constant names to locate are truncate and
KEEP_LAST_TRACKERS).

Comment thread lib/shard/src/tracker.rs Resolved
@xzfc
xzfc self-requested a review February 11, 2026 13:51
@qdrant qdrant deleted a comment from coderabbitai Bot Feb 12, 2026
@xzfc

xzfc commented Feb 12, 2026

Copy link
Copy Markdown
Member

Could you please explain "what for" and "why this way" in the PR description?

I suppose it's to make some of the moved items to be available in edge, but I'd appreciate more details.

@dancixx

dancixx commented Feb 12, 2026

Copy link
Copy Markdown
Contributor Author

@xzfc, the pr description is updated. If you need more details, please ping me.

@xzfc

xzfc commented Feb 13, 2026

Copy link
Copy Markdown
Member

@dancixx I'm trying to understand full picture and future steps.

  1. I suppose the plan is to make it like the following. Am I correct?

    • The collection (aka non-edge qdrant) will decide:

      • (§A) which segments to optimize based on config_mismach/indexing/merge/vacuum logic,
      • and which SegmentConfig to use based on CollectionConfig (or other non-edge configuration).
    • The edge will decide:

      • (§A) which segments to optimize based on its own logic (so, nothing in common with config_mismach/indexing/merge/vacuum),
      • and which SegmentConfig to use also based on its own logic.
  2. (the same question about (§A) but from the other perspective)
    I see that OptimizationStrategy is now in the shard.
    But all four OptimizationStrategy implementations are still in the collection crate.
    Do we want to move these four impls to the shard? Or we want to add a new edge-specific OptimizationStrategy implementation instead?

@dancixx
dancixx marked this pull request as draft February 13, 2026 07:14
@dancixx

dancixx commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@xzfc That’s a good point. I’ve moved the PR back to draft. I’m on PTO this week, but I’ll clarify everything once I’m back.

@dancixx
dancixx marked this pull request as ready for review February 19, 2026 13:05
@coderabbitai

coderabbitai Bot commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR moves optimizer implementations and optimization-related types from the collection crate into a new shard optimizer subsystem and re-exports them from collection. It adds a segment-level configuration model (SegmentOptimizerConfig and per-vector optimizer configs), introduces an optimization execution framework (lib/shard/src/optimize.rs) and a tracker subsystem (lib/shard/src/tracker.rs), and centralizes optimization operation types under shard::operations::optimization. Call sites and tests are adapted to use the new segment-level config and new shard paths; several collection methods changed to return unwrapped segment/vector configs. Workspace dependency fs4 was added.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested reviewers

  • xzfc
  • timvisee
  • coszio
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'refactor/opt' is vague and uses non-descriptive terms that do not convey meaningful information about the changeset. Use a more descriptive title that clearly explains the main change, such as 'Move optimization execution from collection to shard crate' or 'Refactor optimization logic for Edge independence'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly relates to the changeset by explaining the separation of optimization logic and relocation from collection to shard crate, aligning with the file changes observed.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/opt

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

🧹 Nitpick comments (9)
lib/shard/src/lib.rs (1)

8-9: Nit: consider whether both optimize and optimizers modules are clearly distinguishable.

The naming is close — optimize (orchestration/execution) vs optimizers (optimizer implementations). This is fine if well-documented, but worth ensuring the module-level doc comments clarify the boundary. Low priority.

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

In `@lib/shard/src/lib.rs` around lines 8 - 9, The module names optimize and
optimizers are easily confused; add concise module-level documentation
clarifying their distinct responsibilities — e.g., document that the optimize
module (optimize) contains orchestration/execution logic and public APIs for
running optimization flows, while the optimizers module (optimizers) contains
individual optimizer implementations and strategy code — by adding doc comments
above the pub mod optimize; and pub mod optimizers; declarations to make the
boundary explicit to readers and maintainers.
lib/shard/src/optimizers/indexing_optimizer.rs (1)

152-216: Stale entries at the front of unindexed/indexed deques are never drained.

When unindexed.front() or indexed.front() returns a segment that was already claimed by a prior planning round (fails contains_key), the code falls through without popping that stale entry. It stays at the front and will be re-checked on every subsequent loop iteration, each time failing. This is not a bug — the loop terminates correctly — but it degrades from O(n) to O(n²) in the worst case if many front entries are stale.

This is a minor inefficiency and likely acceptable for typical segment counts, but worth noting.

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

In `@lib/shard/src/optimizers/indexing_optimizer.rs` around lines 152 - 216, In
plan_optimizations, unindexed.front()/indexed.front() can return stale entries
that fail planner.remaining().contains_key(...) and are never removed, causing
repeated failed checks and O(n²) behavior; fix by draining stale front entries
before attempting to pair: for both unindexed and indexed, loop popping from
front while front().map(|(id,_)| !planner.remaining().contains_key(id)) ==
Some(true) (and for indexed also ensure id != selected_segment_id when checking
that constraint) so that only live segments are considered for the subsequent
size checks and planner.plan calls.
lib/shard/src/optimizers/vacuum_optimizer.rs (1)

64-71: Division by zero when total_point_count() is 0 produces NaN.

If total_point_count() returns 0, line 66 divides 0.0/0.0 yielding NaN. The function is effectively safe because is_big will be false when min_vectors_number > 0, and NaN comparisons are false. However, this is fragile — an explicit early return would be clearer and more defensive.

Suggested guard
     fn littered_ratio_segment(&self, segment: &Segment) -> Option<f64> {
+        if segment.total_point_count() == 0 {
+            return None;
+        }
         let littered_ratio =
             segment.deleted_point_count() as f64 / segment.total_point_count() as f64;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/shard/src/optimizers/vacuum_optimizer.rs` around lines 64 - 71, In
littered_ratio_segment, guard against division-by-zero by checking
segment.total_point_count() == 0 (or <= 0) and returning None early before
computing littered_ratio; update the function (which uses
segment.deleted_point_count(), segment.total_point_count(),
self.min_vectors_number and self.deleted_threshold) to perform this explicit
check so you never compute deleted/total when total is zero and then proceed
with the existing is_big/is_littered logic.
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)

47-90: Duplicate test helpers across optimizer test modules.

new_indexing_optimizer and new_config_mismatch_optimizer are duplicated in vacuum_optimizer.rs tests (per the relevant code snippet at lines 43-64). Consider extracting these into a shared test utility (e.g., in fixtures.rs) to reduce maintenance burden across optimizer test modules.

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

In `@lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs`
around lines 47 - 90, Extract the duplicated test helper functions
new_indexing_optimizer and new_config_mismatch_optimizer into a shared test
utilities module (e.g., fixtures.rs) and update optimizer test modules
(including vacuum_optimizer.rs) to import and call the shared helpers; move any
shared dependencies (build_segment_optimizer_config usage, types like
OptimizerThresholds, CollectionParams, HnswConfig, HnswGlobalConfig,
QuantizationConfig) into the fixture module or re-export them for tests so the
helpers can construct and return IndexingOptimizer and ConfigMismatchOptimizer
exactly as before, then remove the duplicate functions from individual test
files and replace their calls with the shared fixtures.
lib/collection/src/optimizers_builder.rs (1)

175-224: name.into() → prefer explicit conversion.

Line 185 uses name.into() which could be replaced with the explicit form for clarity. As per coding guidelines, "Prefer explicit SomeType::from(x) over implicit x.into() in Rust."

Suggested change
-                name.into(),
+                VectorNameBuf::from(name),

This requires adding VectorNameBuf to the imports (from segment::types).

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

In `@lib/collection/src/optimizers_builder.rs` around lines 175 - 224, In
build_segment_optimizer_config, replace the implicit conversion name.into() used
when building the dense_vector map with an explicit VectorNameBuf::from(name) to
follow the guideline preferring explicit From conversions; update imports to
include VectorNameBuf (from segment::types) and ensure
DenseVectorOptimizerConfig construction remains unchanged except for the
explicit conversion.
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)

53-95: Inconsistent config construction vs. other test modules.

test_segment_config builds SegmentOptimizerConfig by constructing an actual segment and extracting its config fields, while other test modules (e.g., indexing_optimizer.rs, fixtures.rs) use build_segment_optimizer_config. This means merge optimizer tests bypass the production builder path. Consider aligning with build_segment_optimizer_config for consistency, so that any future changes to the builder are reflected in these tests as well.

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

In `@lib/collection/src/collection_manager/optimizers/merge_optimizer.rs` around
lines 53 - 95, The test helper test_segment_config bypasses the production
builder by constructing a SegmentOptimizerConfig from a real segment; update it
to call the shared builder used elsewhere (build_segment_optimizer_config) so
tests use the same construction path as indexing_optimizer.rs and
fixtures.rs—replace the manual segment creation and HashMap assembly in
test_segment_config with a call to build_segment_optimizer_config (passing the
temp dir path, dim and Distance::Dot) and return that result, and ensure
get_merge_optimizer continues to pass the returned SegmentOptimizerConfig into
MergeOptimizer::new unchanged.
lib/shard/src/optimizers/segment_optimizer.rs (1)

253-257: Catch-all _ in (false, _) match arm is acceptable here since config_on_disk is bool.

Per coding guidelines, explicit exhaustive matches are preferred. However, since bool cannot gain new variants, the catch-all is safe. If you'd prefer to be fully explicit for consistency:

Optional: explicit arms
                 let index_type = match (is_big, config_on_disk) {
                     (true, true) => SparseIndexType::Mmap,
                     (true, false) => SparseIndexType::ImmutableRam,
-                    (false, _) => SparseIndexType::MutableRam,
+                    (false, true) | (false, false) => SparseIndexType::MutableRam,
                 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/shard/src/optimizers/segment_optimizer.rs` around lines 253 - 257, The
match on (is_big, config_on_disk) uses a catch-all arm (false, _) — change it to
explicit boolean arms for clarity by replacing that arm with two explicit arms
(false, true) => SparseIndexType::MutableRam and (false, false) =>
SparseIndexType::MutableRam; keep the existing (true, true) =>
SparseIndexType::Mmap and (true, false) => SparseIndexType::ImmutableRam so the
match on index_type (and symbols is_big, config_on_disk, and SparseIndexType
variants) is fully explicit.
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (1)

34-84: Test helpers duplicate SegmentOptimizerConfig construction logic.

segment_optimizer_config replicates part of the storage-type-from-on_disk logic that likely also exists in build_segment_optimizer_config. If the production builder's semantics change (e.g., new storage types or defaults), these test helpers won't track. Consider calling build_segment_optimizer_config (as the vacuum optimizer tests do) to keep a single source of truth, or add a comment noting why the divergence is intentional.

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

In
`@lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs`
around lines 34 - 84, The test helper duplicates storage-type logic in
segment_optimizer_config/dense_map_from_segment; replace this duplication by
delegating to the production builder build_segment_optimizer_config (passing the
SegmentConfig and dense_overrides) so tests use the single source of truth, or
if delegation is not possible add a clear comment in segment_optimizer_config
explaining why it intentionally diverges from build_segment_optimizer_config;
update references to SegmentOptimizerConfig, SegmentConfig,
DenseVectorOptimizerConfig, and DenseVectorOptimizerConfig::on_disk accordingly
to ensure behavior matches the production builder.
lib/shard/src/optimizers/merge_optimizer.rs (1)

14-14: Consider importing segment::common::BYTES_IN_KB instead of defining a local constant.

A BYTES_IN_KB constant already exists in the segment crate as segment::common::BYTES_IN_KB and is already used in other parts of the codebase (e.g., lib/collection/src/update_workers/optimization_worker.rs:460). Both the indexing optimizer and segment optimizer in the shard crate also define their own local BYTES_IN_KB. Importing the shared constant from segment::common would reduce duplication across these files.

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

In `@lib/shard/src/optimizers/merge_optimizer.rs` at line 14, Replace the locally
defined BYTES_IN_KB in merge_optimizer.rs with the shared constant from the
segment crate: remove the local const BYTES_IN_KB and add an import for
segment::common::BYTES_IN_KB, then update any references (e.g., uses inside
functions in merge_optimizer.rs such as those in MergeOptimizer or related
helper functions) to use the imported constant; this eliminates duplication and
keeps the file consistent with other modules that use
segment::common::BYTES_IN_KB.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@config/config.yaml`:
- Around line 382-384: Comment out the active inference configuration block
(keys: inference, address, token) so it follows the project's convention for
optional/sensitive settings; ensure the `inference` section is disabled (so
token is not deserialized as an active credential) to avoid passing a
placeholder to InferenceService::init_global() during startup, and add a short
"Uncomment to enable" note similar to the other optional sections.

In `@lib/shard/src/optimizers/segment_optimizer.rs`:
- Around line 212-226: The comment on the Some(false) branch of the match on
config_on_disk is misleading because although on_disk=false is respected, the
code can still set config.storage_type = VectorStorageType::InRamMmap when
common::flags::feature_flags().single_file_mmap_vector_storage is true; update
the inline comment next to the Some(false) branch (near the match on
config_on_disk) to accurately state that on_disk=false wins but InRamMmap may be
selected when the single_file_mmap_vector_storage feature flag is enabled
(reference VectorStorageType::InRamMmap and single_file_mmap_vector_storage).

In `@lib/shard/src/optimizers/vacuum_optimizer.rs`:
- Around line 78-79: Fix the typo in the doc comment that reads "indexed
vector.s" by changing it to "indexed vectors" in the vacuum optimizer's
documentation (the comment starting "This finds the maximum deletion ratio for a
named vector. The ratio is based on the number of deleted vectors versus the
number of indexed vector.s"); update that doc string so it reads "indexed
vectors".

In `@lib/shard/src/tracker.rs`:
- Around line 127-129: Replace implicit .into() conversions with explicit
Type::from(...) calls: in Tracker::handle() change the conversion of
self.state.clone() to TrackerHandle::from(self.state.clone()) (reference:
handle() and TrackerHandle), and when mapping segments replace s.into() with
OptimizationSegmentInfo::from(s) in the iterator over self.segments (reference:
segments and OptimizationSegmentInfo).

---

Duplicate comments:
In `@lib/shard/src/optimize.rs`:
- Around line 325-328: The calls to optimized_segment.delete_point(...) are
using .unwrap(), which will panic on I/O/segment errors; replace those .unwrap()
calls with ? so errors are propagated (e.g., change
optimized_segment.delete_point(...).unwrap() to
optimized_segment.delete_point(...)?), update the enclosing function(s) to
return Result<..., E> as needed and propagate errors through the call chain, and
apply this change to both occurrences of delete_point (the loop handling
deleted_points_snapshot and the second occurrence at the other location).
- Around line 724-731: The error branches in the build_result match (when
Err(err) and the other error branch around lines 746–750) call
unwrap_proxy(&segment_holder, &proxy_ids)? but do not remove the temporary COW
segment that the success path removes; update both error paths to call the same
cleanup that the success path uses (e.g., invoke remove_segment_if_not_needed or
remove the segment referenced by cow_segment_id_opt on segment_holder) before
returning Err(err) so the temporary COW appendable segment is not orphaned;
ensure you reuse the same helper logic used on the success path to avoid
duplicating removal logic.

In `@lib/shard/src/tracker.rs`:
- Around line 33-38: Update the truncate() doc comment to reference the correct
constant name KEEP_LAST_TRACKERS (not KEEP_TRACKERS); locate the truncate method
in tracker.rs and change the comment text to mention KEEP_LAST_TRACKERS so it
matches the actual constant used by the implementation.
- Around line 156-177: The TrackerTelemetry struct currently derives Deserialize
but has pub name: &'static str which cannot be deserialized; either remove
Deserialize from the derive list on TrackerTelemetry if it is only ever
serialized, or change the field signature to pub name: String and update all
constructors/creators (places that build TrackerTelemetry, e.g., any
new/constructors or places that set TrackerTelemetry::name) to pass an owned
String, and update the derive to keep Deserialize if deserialization is
required; search for usages of TrackerTelemetry and adjust creation sites
accordingly.

---

Nitpick comments:
In
`@lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs`:
- Around line 34-84: The test helper duplicates storage-type logic in
segment_optimizer_config/dense_map_from_segment; replace this duplication by
delegating to the production builder build_segment_optimizer_config (passing the
SegmentConfig and dense_overrides) so tests use the single source of truth, or
if delegation is not possible add a clear comment in segment_optimizer_config
explaining why it intentionally diverges from build_segment_optimizer_config;
update references to SegmentOptimizerConfig, SegmentConfig,
DenseVectorOptimizerConfig, and DenseVectorOptimizerConfig::on_disk accordingly
to ensure behavior matches the production builder.

In `@lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs`:
- Around line 47-90: Extract the duplicated test helper functions
new_indexing_optimizer and new_config_mismatch_optimizer into a shared test
utilities module (e.g., fixtures.rs) and update optimizer test modules
(including vacuum_optimizer.rs) to import and call the shared helpers; move any
shared dependencies (build_segment_optimizer_config usage, types like
OptimizerThresholds, CollectionParams, HnswConfig, HnswGlobalConfig,
QuantizationConfig) into the fixture module or re-export them for tests so the
helpers can construct and return IndexingOptimizer and ConfigMismatchOptimizer
exactly as before, then remove the duplicate functions from individual test
files and replace their calls with the shared fixtures.

In `@lib/collection/src/collection_manager/optimizers/merge_optimizer.rs`:
- Around line 53-95: The test helper test_segment_config bypasses the production
builder by constructing a SegmentOptimizerConfig from a real segment; update it
to call the shared builder used elsewhere (build_segment_optimizer_config) so
tests use the same construction path as indexing_optimizer.rs and
fixtures.rs—replace the manual segment creation and HashMap assembly in
test_segment_config with a call to build_segment_optimizer_config (passing the
temp dir path, dim and Distance::Dot) and return that result, and ensure
get_merge_optimizer continues to pass the returned SegmentOptimizerConfig into
MergeOptimizer::new unchanged.

In `@lib/collection/src/optimizers_builder.rs`:
- Around line 175-224: In build_segment_optimizer_config, replace the implicit
conversion name.into() used when building the dense_vector map with an explicit
VectorNameBuf::from(name) to follow the guideline preferring explicit From
conversions; update imports to include VectorNameBuf (from segment::types) and
ensure DenseVectorOptimizerConfig construction remains unchanged except for the
explicit conversion.

In `@lib/shard/src/lib.rs`:
- Around line 8-9: The module names optimize and optimizers are easily confused;
add concise module-level documentation clarifying their distinct
responsibilities — e.g., document that the optimize module (optimize) contains
orchestration/execution logic and public APIs for running optimization flows,
while the optimizers module (optimizers) contains individual optimizer
implementations and strategy code — by adding doc comments above the pub mod
optimize; and pub mod optimizers; declarations to make the boundary explicit to
readers and maintainers.

In `@lib/shard/src/optimizers/indexing_optimizer.rs`:
- Around line 152-216: In plan_optimizations, unindexed.front()/indexed.front()
can return stale entries that fail planner.remaining().contains_key(...) and are
never removed, causing repeated failed checks and O(n²) behavior; fix by
draining stale front entries before attempting to pair: for both unindexed and
indexed, loop popping from front while front().map(|(id,_)|
!planner.remaining().contains_key(id)) == Some(true) (and for indexed also
ensure id != selected_segment_id when checking that constraint) so that only
live segments are considered for the subsequent size checks and planner.plan
calls.

In `@lib/shard/src/optimizers/merge_optimizer.rs`:
- Line 14: Replace the locally defined BYTES_IN_KB in merge_optimizer.rs with
the shared constant from the segment crate: remove the local const BYTES_IN_KB
and add an import for segment::common::BYTES_IN_KB, then update any references
(e.g., uses inside functions in merge_optimizer.rs such as those in
MergeOptimizer or related helper functions) to use the imported constant; this
eliminates duplication and keeps the file consistent with other modules that use
segment::common::BYTES_IN_KB.

In `@lib/shard/src/optimizers/segment_optimizer.rs`:
- Around line 253-257: The match on (is_big, config_on_disk) uses a catch-all
arm (false, _) — change it to explicit boolean arms for clarity by replacing
that arm with two explicit arms (false, true) => SparseIndexType::MutableRam and
(false, false) => SparseIndexType::MutableRam; keep the existing (true, true) =>
SparseIndexType::Mmap and (true, false) => SparseIndexType::ImmutableRam so the
match on index_type (and symbols is_big, config_on_disk, and SparseIndexType
variants) is fully explicit.

In `@lib/shard/src/optimizers/vacuum_optimizer.rs`:
- Around line 64-71: In littered_ratio_segment, guard against division-by-zero
by checking segment.total_point_count() == 0 (or <= 0) and returning None early
before computing littered_ratio; update the function (which uses
segment.deleted_point_count(), segment.total_point_count(),
self.min_vectors_number and self.deleted_threshold) to perform this explicit
check so you never compute deleted/total when total is zero and then proceed
with the existing is_big/is_littered logic.

Comment thread lib/shard/src/tracker.rs
Comment on lines +127 to +129
pub fn handle(&self) -> TrackerHandle {
self.state.clone().into()
}

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

🧩 Analysis chain

🏁 Script executed:

cat -n lib/shard/src/tracker.rs | sed -n '120,160p'

Repository: qdrant/qdrant

Length of output: 1683


🏁 Script executed:

# Check the Tracker struct definition to understand self.state and self.segments types
rg -B5 "pub struct Tracker" lib/shard/src/tracker.rs | head -30

Repository: qdrant/qdrant

Length of output: 723


🏁 Script executed:

# Check TrackerHandle and related types
rg -n "type TrackerHandle|struct TrackerHandle" lib/shard/src/tracker.rs

Repository: qdrant/qdrant

Length of output: 87


🏁 Script executed:

# Search for OptimizationSegmentInfo to verify it's the right type
rg -n "OptimizationSegmentInfo" lib/shard/src/tracker.rs

Repository: qdrant/qdrant

Length of output: 260


🏁 Script executed:

# Get the full Tracker struct definition
rg -A20 "pub struct Tracker {" lib/shard/src/tracker.rs | head -25

Repository: qdrant/qdrant

Length of output: 160


🏁 Script executed:

# Check if there's a From implementation for TrackerHandle
rg -B2 -A5 "impl.*From.*for TrackerHandle" lib/shard/src/tracker.rs

Repository: qdrant/qdrant

Length of output: 210


🏁 Script executed:

# Get Tracker struct definition more carefully
sed -n '70,100p' lib/shard/src/tracker.rs

Repository: qdrant/qdrant

Length of output: 875


🏁 Script executed:

# Check the From implementation context and line numbers
rg -n "impl From.*for TrackerHandle" lib/shard/src/tracker.rs

Repository: qdrant/qdrant

Length of output: 116


Use explicit Type::from(...) instead of .into() for conversions.

This follows the repo's Rust guideline and keeps the target type explicit.

  • Line 128: self.state.clone().into() → TrackerHandle::from(self.state.clone())
  • Line 149: self.segments.iter().map(|s| s.into()).collect() → self.segments.iter().map(OptimizationSegmentInfo::from).collect()

Both conversions have explicit From implementations available and should use the explicit form.

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

In `@lib/shard/src/tracker.rs` around lines 127 - 129, Replace implicit .into()
conversions with explicit Type::from(...) calls: in Tracker::handle() change the
conversion of self.state.clone() to TrackerHandle::from(self.state.clone())
(reference: handle() and TrackerHandle), and when mapping segments replace
s.into() with OptimizationSegmentInfo::from(s) in the iterator over
self.segments (reference: segments and OptimizationSegmentInfo).

@qdrant qdrant deleted a comment from coderabbitai Bot Feb 19, 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.

🧹 Nitpick comments (2)
lib/collection/src/optimizers_builder.rs (1)

175-224: New build_segment_optimizer_config bridges collection-level config to shard-level optimizer config — looks correct.

The function correctly:

  • Builds per-vector dense configs with merged HNSW settings via update_opt
  • Resolves quantization config with per-vector → collection-level fallback (without the supports_appendable filter, which is appropriate for optimizer target config vs. base appendable segment config)
  • Derives base vector/sparse data from CollectionParams
  • Collects sparse vector on-disk preferences

One guideline nit: Line 185 uses name.into() for the VectorNameBuf conversion.

As per coding guidelines: "Prefer explicit SomeType::from(x) over implicit x.into() in Rust".

Optional: explicit From conversion
         .map(|(name, params)| {
             (
-                name.into(),
+                VectorNameBuf::from(name),
                 DenseVectorOptimizerConfig {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/collection/src/optimizers_builder.rs` around lines 175 - 224, In
build_segment_optimizer_config, replace the implicit conversion name.into() used
when constructing the dense_vector map with an explicit From::from call for the
vector name type (e.g., VectorNameBuf::from(name)) to follow the guideline
preferring SomeType::from(x) over x.into(); update the dense_vector mapping
expression accordingly so it constructs the tuple key with the explicit
VectorNameBuf::from(name).
lib/collection/src/config.rs (1)

546-572: Pre-existing name.into() on Line 550.

Line 550 uses name.into() to convert into VectorNameBuf. Per the coding guidelines, new code should prefer explicit VectorNameBuf::from(name). Since this line isn't newly introduced (only the Ok(...) wrapping was removed), this is a pre-existing nit — flagging only for awareness if you're touching this area anyway.

As per coding guidelines: "Prefer explicit SomeType::from(x) over implicit x.into() in Rust".

Proposed fix
             .map(|(name, params)| {
                 (
-                    name.into(),
+                    VectorNameBuf::from(name),
                     VectorDataConfig {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/collection/src/config.rs` around lines 546 - 572, Replace the implicit
conversion name.into() used when building the map key with the explicit
constructor VectorNameBuf::from(name) to follow the coding guideline preferring
SomeType::from over into; update the closure inside
self.vectors.params_iter().map(...) where the tuple key is created so the first
element uses VectorNameBuf::from(name) while leaving the rest of the
VectorDataConfig construction (fields like size, distance, index,
quantization_config, storage_type, multivector_config, datatype) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/collection/src/config.rs`:
- Around line 546-572: Replace the implicit conversion name.into() used when
building the map key with the explicit constructor VectorNameBuf::from(name) to
follow the coding guideline preferring SomeType::from over into; update the
closure inside self.vectors.params_iter().map(...) where the tuple key is
created so the first element uses VectorNameBuf::from(name) while leaving the
rest of the VectorDataConfig construction (fields like size, distance, index,
quantization_config, storage_type, multivector_config, datatype) unchanged.

In `@lib/collection/src/optimizers_builder.rs`:
- Around line 175-224: In build_segment_optimizer_config, replace the implicit
conversion name.into() used when constructing the dense_vector map with an
explicit From::from call for the vector name type (e.g.,
VectorNameBuf::from(name)) to follow the guideline preferring SomeType::from(x)
over x.into(); update the dense_vector mapping expression accordingly so it
constructs the tuple key with the explicit VectorNameBuf::from(name).

@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 (2)
lib/shard/src/optimizers/vacuum_optimizer.rs (2)

64-70: Suggest guarding total_point_count() == 0 before the division.

The ratio is computed unconditionally on line 66 before is_big is checked. When total_point_count() == 0 and min_vectors_number == 0, the result is NaN (0.0 / 0.0), which happens to produce None only because NaN > deleted_threshold is always false. Reordering the guard makes the invariant explicit and avoids the speculative FP division.

🛡️ Proposed defensive fix
 fn littered_ratio_segment(&self, segment: &Segment) -> Option<f64> {
-    let littered_ratio =
-        segment.deleted_point_count() as f64 / segment.total_point_count() as f64;
-    let is_big = segment.total_point_count() >= self.min_vectors_number;
-    let is_littered = littered_ratio > self.deleted_threshold;
-
-    (is_big && is_littered).then_some(littered_ratio)
+    let total = segment.total_point_count();
+    let is_big = total >= self.min_vectors_number;
+    if !is_big {
+        return None;
+    }
+    let littered_ratio = segment.deleted_point_count() as f64 / total as f64;
+    let is_littered = littered_ratio > self.deleted_threshold;
+    is_littered.then_some(littered_ratio)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/shard/src/optimizers/vacuum_optimizer.rs` around lines 64 - 70, In
littered_ratio_segment, avoid computing segment.deleted_point_count() as f64 /
segment.total_point_count() as f64 before ensuring total_point_count() > 0:
first check that segment.total_point_count() is nonzero and that
segment.total_point_count() >= self.min_vectors_number (min_vectors_number) and
only then compute littered_ratio and compare it to self.deleted_threshold; this
prevents a 0/0 NaN when total_point_count() == 0 and keeps the
is_big/is_littered logic explicit.

158-158: Use Reverse for descending sort instead of negating the ratio.

OrderedFloat(-ratio) achieves descending order by sign-flipping, but the rest of the crate (e.g., config_mismatch_optimizer.rs) uses Reverse(...) for this pattern. Reverse is also type-safe and doesn't rely on negation semantics of f64.

♻️ Proposed refactor for consistency
-        .sorted_by_key(|(_, ratio)| OrderedFloat(-ratio))
+        .sorted_by_key(|(_, ratio)| Reverse(OrderedFloat(*ratio)))

Add use std::cmp::Reverse; to the imports.

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

In `@lib/shard/src/optimizers/vacuum_optimizer.rs` at line 158, Replace the
descending sort that negates the float with std::cmp::Reverse to match crate
conventions: add use std::cmp::Reverse; to the imports and change the
.sorted_by_key closure that currently uses OrderedFloat(-ratio) to wrap
OrderedFloat(ratio) in Reverse (e.g., Reverse(OrderedFloat(ratio))). This keeps
type-safety for f64 ordering and is consistent with
config_mismatch_optimizer.rs.
🤖 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/shard/src/optimizers/vacuum_optimizer.rs`:
- Line 81: The doc comment "Returns `None` if littered ratio did not reach
vacuum thresholds for no named vectors." is a confusing double-negative; update
the comment above the related function in
lib/shard/src/optimizers/vacuum_optimizer.rs to a clear phrasing such as:
"Returns None when none of the named vectors have a littered (deletion) ratio
that meets the vacuum threshold." Ensure the new wording replaces the original
sentence in the function's doc comment so it clearly states the condition under
which None is returned.

---

Nitpick comments:
In `@lib/shard/src/optimizers/vacuum_optimizer.rs`:
- Around line 64-70: In littered_ratio_segment, avoid computing
segment.deleted_point_count() as f64 / segment.total_point_count() as f64 before
ensuring total_point_count() > 0: first check that segment.total_point_count()
is nonzero and that segment.total_point_count() >= self.min_vectors_number
(min_vectors_number) and only then compute littered_ratio and compare it to
self.deleted_threshold; this prevents a 0/0 NaN when total_point_count() == 0
and keeps the is_big/is_littered logic explicit.
- Line 158: Replace the descending sort that negates the float with
std::cmp::Reverse to match crate conventions: add use std::cmp::Reverse; to the
imports and change the .sorted_by_key closure that currently uses
OrderedFloat(-ratio) to wrap OrderedFloat(ratio) in Reverse (e.g.,
Reverse(OrderedFloat(ratio))). This keeps type-safety for f64 ordering and is
consistent with config_mismatch_optimizer.rs.

/// This finds the maximum deletion ratio for a named vector. The ratio is based on the number
/// of deleted vectors versus the number of indexed vectors.
///
/// Returns `None` if littered ratio did not reach vacuum thresholds for no named vectors.

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

Doc comment is ambiguous due to double-negative phrasing.

"Returns None if littered ratio did not reach vacuum thresholds for no named vectors." reads as a confusing double negative. The intended meaning is that None is returned when no named vector's deletion ratio meets the threshold.

📝 Suggested rewording
-    /// Returns `None` if littered ratio did not reach vacuum thresholds for no named vectors.
+    /// Returns `None` if the littered ratio did not reach the vacuum threshold for any named vector.
📝 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
/// Returns `None` if littered ratio did not reach vacuum thresholds for no named vectors.
/// Returns `None` if the littered ratio did not reach the vacuum threshold for any named vector.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/shard/src/optimizers/vacuum_optimizer.rs` at line 81, The doc comment
"Returns `None` if littered ratio did not reach vacuum thresholds for no named
vectors." is a confusing double-negative; update the comment above the related
function in lib/shard/src/optimizers/vacuum_optimizer.rs to a clear phrasing
such as: "Returns None when none of the named vectors have a littered (deletion)
ratio that meets the vacuum threshold." Ensure the new wording replaces the
original sentence in the function's doc comment so it clearly states the
condition under which None is returned.

@dancixx
dancixx merged commit a52a6d9 into dev Feb 19, 2026
15 checks passed
@dancixx
dancixx deleted the refactor/opt branch February 19, 2026 22:16
This was referenced Feb 27, 2026
generall pushed a commit that referenced this pull request Mar 26, 2026
* refactor: opt system

* feat: move tracker seperately

* feat: migrate opt logic to shards

* feat: add OptStrategy trait

* fix: missing drop

* fix: linter error

* fix: clippy errors

* fix: linter error

* fix: missing fns

* fix: linter

* fix: missing import

* fix: missing import

* fix: schema_gen imports

* chore: remove comment

* feat: add missing comments

* feat: restore optimize_segment_propagate_changes fn

* chore: move fs4 to workspace deps

* fix: compiler error

* chore: add import fixes

* feat: move optimzers to shard

* fix: clippy errors

* chore: restore tests and adjust them

* fix: linter issues

* fix: linter issue

* fix: remove CollectionResult where call is infallible

* fix: comment
KShivendu pushed a commit that referenced this pull request Mar 30, 2026
* refactor: opt system

* feat: move tracker seperately

* feat: migrate opt logic to shards

* feat: add OptStrategy trait

* fix: missing drop

* fix: linter error

* fix: clippy errors

* fix: linter error

* fix: missing fns

* fix: linter

* fix: missing import

* fix: missing import

* fix: schema_gen imports

* chore: remove comment

* feat: add missing comments

* feat: restore optimize_segment_propagate_changes fn

* chore: move fs4 to workspace deps

* fix: compiler error

* chore: add import fixes

* feat: move optimzers to shard

* fix: clippy errors

* chore: restore tests and adjust them

* fix: linter issues

* fix: linter issue

* fix: remove CollectionResult where call is infallible

* fix: comment
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