Repository navigation
OptimizationPlanner - #7752
OptimizationPlanner#7752
Conversation
2727fff to
df86a0e
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
68-75: Guardtotal_point_count() == 0before division to avoid NaN ratios.
Even if it currently short-circuits viais_big, this makes the ratio calculation more robust and avoids any accidental propagation of NaN if the logic changes later.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 total = segment.total_point_count(); + if total == 0 { + return None; + } + let littered_ratio = segment.deleted_point_count() as f64 / total as f64; + let is_big = total >= self.min_vectors_number; let is_littered = littered_ratio > self.deleted_threshold;
🧹 Nitpick comments (7)
lib/collection/src/update_handler.rs (1)
283-295: Setcurrent_optimizerbefore callingplan_optimizations()for consistency with established patterns.While the current code produces the correct boolean result (the scheduled work will still be recorded even if
current_optimizerisNone), the OptimizationPlanner documentation recommends setting the optimizer if you want it attached to the scheduled entries. Theoptimization_worker.rscode consistently follows this pattern (lines 270-276), which makes the optimizer identity available for downstream consumers who may need it.let segments = self.segments.read(); let mut planner = OptimizationPlanner::new(segments.iter_original()); let has_suboptimal_optimizers = self.optimizers.iter().any(|optimizer| { + planner.set_current_optimizer(Arc::clone(optimizer)); optimizer.plan_optimizations(&mut planner); !planner.scheduled().is_empty() });lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
118-155: Avoid per-vectorclone()for quantization target config (cheap ref-based lookup).
target_quantization_vectorclonesquantization_configfrom params (Line 120-125) just to use it by ref. Prefer holdingOption<&QuantizationConfig>(or cloning only when actually needed for rebuild), to reduce allocations in hot planning paths.
212-231: Simplify planningfilter_mapto avoidOption<Option<_>>+?(readability).
The currentthen(|| Some(...))?pattern is correct but non-idiomatic and easy to misread. Consider a straightforwardif/then_some((..)).- .filter_map(|(&segment_id, segment)| { - let read_segment = segment.read(); - self.config_mismatch(&*read_segment).then(|| { - let vector_size = read_segment - .max_available_vectors_size_in_bytes() - .unwrap_or_default(); - Some((segment_id, vector_size)) - })? - }) + .filter_map(|(&segment_id, segment)| { + let read_segment = segment.read(); + if !self.config_mismatch(&*read_segment) { + return None; + } + let vector_size = read_segment + .max_available_vectors_size_in_bytes() + .unwrap_or_default(); + Some((segment_id, vector_size)) + })lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
1004-1008: Document thatexpected_segments_number()is approximate (COW segment can add +1).
Indexing/merge logic uses this for decisions; it’s fine as a heuristic, but the doc should acknowledge it can under-estimate whenoptimize()creates an extra appendable segment.lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (2)
140-150:take_batchis fine, but consider making the “no progress” case explicit.
When the first item size is already>= max_size, this returns&[]and leavesitemsunchanged. That’s OK with the current loop condition, but a short comment (or a debug_assert in the caller) would make the invariant clearer.
281-290: Test: assertdataremains unchanged after the empty batch to lock in semantics.
Right nowtest_take_batchchecks that the returned batch is empty, but not thatdatadidn’t advance. Adding that assertion will prevent accidental behavioral changes later.lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)
156-230: Pairing logic is reasonable, but the “segment count” heuristic may be off by +1.
BecauseSegmentOptimizer::optimize()can create an extra COW segment,planner.expected_segments_number()can under-estimate the post-execution count; that can weaken the intent behind the “plan 2 segments to preserve count” branch (Line 197-200). Consider either (a) documenting that this is best-effort, or (b) teaching the planner an “extra segment might be needed” signal if that’s feasible to precompute.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs(13 hunks)lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs(14 hunks)lib/collection/src/collection_manager/optimizers/merge_optimizer.rs(6 hunks)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs(5 hunks)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs(11 hunks)lib/collection/src/shards/local_shard/snapshot_tests.rs(2 hunks)lib/collection/src/shards/local_shard/testing.rs(1 hunks)lib/collection/src/update_handler.rs(2 hunks)lib/collection/src/update_workers/optimization_worker.rs(2 hunks)lib/shard/src/segment_holder/mod.rs(6 hunks)lib/shard/src/segment_holder/tests.rs(2 hunks)lib/shard/src/update.rs(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.github/review-rules.md)
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust
In new code, don't usetransmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead
Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later (exceptions: tests and benchmarks, or when sure new variants won't affect logic)
Prefer explicit field ignoring using: _over using..in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)
Files:
lib/collection/src/shards/local_shard/testing.rslib/shard/src/segment_holder/tests.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/collection/src/update_handler.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/update.rs
🧠 Learnings (19)
📚 Learning: 2025-07-11T11:35:21.549Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/shard/src/segment_holder/tests.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/update.rs
📚 Learning: 2025-09-01T11:42:06.964Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7157
File: lib/shard/src/segment_holder/mod.rs:808-814
Timestamp: 2025-09-01T11:42:06.964Z
Learning: In Qdrant's segment holder, panicking when no segments exist during flush_all is intentional and preferred over graceful error handling, as having zero segments could permanently corrupt the WAL by acknowledging u64::MAX. The maintainers consider this condition impossible and use the panic as a fail-fast safety mechanism to prevent data corruption.
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/update.rs
📚 Learning: 2025-10-13T22:58:03.121Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7400
File: lib/segment/src/id_tracker/simple_id_tracker.rs:234-241
Timestamp: 2025-10-13T22:58:03.121Z
Learning: SimpleIdTracker in lib/segment/src/id_tracker/simple_id_tracker.rs is being deprecated and should not receive fixes related to version tracking or recovery logic, as it has a different version storage structure that is incompatible with newer trackers.
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/shard/src/segment_holder/tests.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/update.rs
📚 Learning: 2025-09-01T11:19:26.371Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-10T18:30:02.986Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/update.rs
📚 Learning: 2025-08-15T11:42:00.297Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR #7048, using checked_mul with u64 casting to prevent silent overflow.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-18T10:56:43.707Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs:340-347
Timestamp: 2025-08-18T10:56:43.707Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs, the create_offsets_file_from_iter function intentionally requires paths to have a parent directory and returns an error if path.parent() is None. This was a conscious design decision to ensure proper path validation.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-09-08T08:47:43.795Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7188
File: lib/collection/src/update_handler.rs:810-813
Timestamp: 2025-09-08T08:47:43.795Z
Learning: In the Qdrant codebase, CollectionId implements traits that allow &CollectionId to convert Into<String>, so passing &collection_name to functions requiring Into<String> works correctly without needing .clone() or .to_string().
Applied to files:
lib/collection/src/shards/local_shard/snapshot_tests.rs
📚 Learning: 2025-08-15T11:41:10.629Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-20T15:03:18.522Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7100
File: lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs:82-100
Timestamp: 2025-08-20T15:03:18.522Z
Learning: The merge_postings_iterator function in lib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rs handles deduplication internally, so there's no need to add .dedup() when using it for OR-merge operations in inverted indexes.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-08-14T11:31:21.777Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-06T09:56:59.311Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6982
File: lib/segment/src/index/hnsw_index/graph_links/view.rs:217-220
Timestamp: 2025-08-06T09:56:59.311Z
Learning: In Qdrant's GraphLinksView implementation (lib/segment/src/index/hnsw_index/graph_links/view.rs), methods like links() and links_with_vectors() intentionally use unwrap() and can panic for performance reasons, maintaining consistency across similar methods. Error handling improvements are considered secondary to feature completion and require benchmarking before implementation.
Applied to files:
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-09-16T21:39:09.353Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7232
File: lib/shard/src/segment_holder/mod.rs:1088-1094
Timestamp: 2025-09-16T21:39:09.353Z
Learning: The hnsw_format_force and hnsw_with_vectors flags in HnswGlobalConfig primarily affect existing segment conversion during load/startup, not the initial format selection for newly created empty segments. For new segments, format decisions are made by GraphLinksFormatParam::recommended() based on runtime conditions. Therefore, using HnswGlobalConfig::default() for temporary/proxy segments in SegmentHolder::build_tmp_segment is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-11T00:37:34.100Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs:46-55
Timestamp: 2025-08-11T00:37:34.100Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs`, the `ChunkedVectors` used in `QuantizedRamStorage` is intentionally designed to be non-persistent during updates. The `push_vector` method only updates the in-memory vectors without flushing to disk, and this is expected behavior rather than a bug.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-10T18:31:56.855Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/point_ops.rs:501-528
Timestamp: 2025-08-10T18:31:56.855Z
Learning: In Qdrant, batch operations validate that `ids`, `vectors`, and `payloads` (if present) have matching lengths at the REST API level in `lib/api/src/rest/validate.rs` through the `Validate` trait implementation for `Batch`. This validation happens before data is converted to internal structures like `PointInsertOperationsInternal`, so methods operating on these internal structures can safely assume the lengths match.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-10T18:20:42.252Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: src/common/update.rs:272-281
Timestamp: 2025-08-10T18:20:42.252Z
Learning: In Qdrant, conditional updates with `update_filter` always apply the condition check to a small, pre-determined set of point IDs (those being updated) and never perform a full collection scan. Therefore, strict mode validation for unindexed filtering is not necessary for conditional update operations, as the performance concerns that strict mode addresses don't apply to these targeted operations.
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-08-10T18:26:12.443Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: docs/redoc/master/openapi.json:13645-13652
Timestamp: 2025-08-10T18:26:12.443Z
Learning: In qdrant, docs/redoc/master/openapi.json is auto-generated from the REST schemas. To change field docs, edit lib/api/src/rest/schema.rs (e.g., add doc comments or #[schemars(description = ...)]). Specifically, UpdateVectors.update_filter lacked a description and should state: "If specified, only update vectors for points that match this filter; points not matching the filter are left unchanged."
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-04-20T19:08:45.034Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6403
File: lib/collection/src/collection_manager/holders/proxy_segment.rs:1178-1197
Timestamp: 2025-04-20T19:08:45.034Z
Learning: In the ProxySegment implementation, overwriting previous index changes when inserting a DeleteIfIncompatible operation is intentional. When an incompatible index is detected, the DeleteIfIncompatible operation should take precedence over any previously scheduled operations on that index.
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-10-12T22:22:11.435Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7388
File: lib/shard/src/segment_holder/flush.rs:167-191
Timestamp: 2025-10-12T22:22:11.435Z
Learning: In Qdrant's SegmentHolder flush logic, when calculating the minimum unsaved version for WAL acknowledgment, the code intentionally returns `segment_persisted_version` (not `segment_persisted_version + 1`) when there are unsaved changes. This conservative approach assumes the last persisted version might not have been fully applied and allows the system to safely retry operations when versions match, ensuring WAL consistency.
Applied to files:
lib/shard/src/update.rs
🧬 Code graph analysis (6)
lib/collection/src/shards/local_shard/testing.rs (2)
lib/shard/src/segment_holder/mod.rs (1)
segments(930-933)lib/collection/src/shards/local_shard/mod.rs (1)
segments(277-279)
lib/collection/src/update_workers/optimization_worker.rs (4)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (3)
scheduled(996-998)new(978-984)name(59-59)lib/edge/python/src/query.rs (1)
limit(86-88)lib/collection/src/shards/shard.rs (1)
optimizers_log(239-249)lib/collection/src/collection_manager/optimizers/mod.rs (1)
start(112-124)
lib/shard/src/segment_holder/mod.rs (3)
lib/shard/src/proxy_segment/segment_entry.rs (1)
point_version(38-55)lib/segment/src/segment/entry.rs (1)
point_version(51-56)lib/segment/src/entry/entry_point.rs (1)
point_version(43-43)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/shard/src/segment_holder/mod.rs (2)
iter(94-99)iter(926-929)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (4)
lib/common/common/src/flags.rs (1)
feature_flags(130-138)lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
plan_optimizations(94-133)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
plan_optimizations(154-172)
lib/shard/src/update.rs (1)
lib/segment/src/segment/snapshot.rs (1)
segment_id(104-122)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: test-consensus-compose
- GitHub Check: integration-tests
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: integration-tests-consensus
- GitHub Check: test-consistency
- GitHub Check: e2e-tests
- GitHub Check: lint
🔇 Additional comments (16)
lib/collection/src/shards/local_shard/snapshot_tests.rs (1)
30-34: Good adaptation toSegmentHolder::iter()yielding IDs by value (prevents lock-guard lifetime coupling).
This looks correct: collecting owned IDs avoids accidentally tyingbefore_ids/after_idsto theRwLockReadGuardlifetime. Optionally, consider spelling out the type (HashSet<SegmentId>) for readability if inference ever gets ambiguous.Also applies to: 60-64
lib/shard/src/update.rs (1)
354-402: SegmentId-by-value map key change is correct and consistent with new SegmentHolder::iter().
This should avoid accidental key mismatches now thatiter()yields(SegmentId, ...)by value.lib/shard/src/segment_holder/mod.rs (5)
24-26:Segmentimport is justified byiter_original()’s return type.
90-107: Newiter()signature +iter_original()look correct and nicely separate proxy vs original iteration.
Good use of an exhaustivematch(no_), and this aligns the rest of the codebase with SegmentId-by-value iteration.
372-456: SegmentId-by-value propagation in point-version grouping is correct.
Thesmallvec![segment_id]/.push(segment_id)updates keep behavior while matching the new iterator shape.
484-507: apply_segments_batched now passesSegmentIdby value consistently.
This matches the newiter()API and avoids repeated deref/copy at call sites.
925-934: Deduplication segment collection updated safely for value-based IDs.
Thesegments.iter().map(|(segment_id, ...)| (segment_id, ...))change is correct given the new iterator element type.lib/shard/src/segment_holder/tests.rs (2)
536-541: Test updated correctly for value-basedSegmentIditeration.
610-615: Second SegmentId set capture updated correctly for value-based iteration.lib/collection/src/update_handler.rs (1)
18-20: Import change is consistent with planner-based optimization checks.lib/collection/src/update_workers/optimization_worker.rs (3)
24-26: Planner import aligns with the new plan-then-execute scheduling flow.
269-277: Global planning stage is a clean refactor: single pass over optimizers withremainingtracked in planner.
This matches the intended “plan first, then execute while permits are available” design.
279-319: Thedebug_assert!(false)pattern here is correct and aligns with Qdrant's established practices.The
Nonecase would only occur ifOptimizationPlannerproduces tuples without setting the optimizer—a planner bug. In production,set_current_optimizer()is always called beforeplan_optimizations()(lines 273–274 in the loop), making this condition impossible under normal operation. Qdrant's coding guidelines preferdebug_assert!for validating impossible conditions to ensure production stability; usingexpect()instead would cause unnecessary panics in production.lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
154-172: Planner-based vacuum selection looks coherent and preserves “worst-first” ordering.
Computing the worst of point-level vs vector-level ratios, then sorting desc and scheduling single-segment batches matches the optimizer’s purpose, just generalized to “plan all”.lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
82-96: Test helper wiring is clean; good migration path fromcheck_condition().
UsingOptimizationPlanner::new(segments.iter_original())and returning only batches keeps tests focused on the selection logic.lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)
278-283:normalizehelper is good for order-insensitive group comparison.
Sorting within each planned batch makes the assertions resilient to intra-batch ordering changes while still allowing you to assert scheduling order when needed.
df86a0e to
00b4733
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (4)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
74-80: Fix misleading comment at line 80.The comment says "Skip segments with payload mismatch" but the code returns
true, which means "this segment has a mismatch and should be optimized". The comment should say something like "Select segments with payload mismatch for optimization" instead.Apply this diff to fix the comment:
- return true; // Skip segments with payload mismatch + return true; // Select segment with payload mismatch for optimization
151-152: Fix copy-paste error in comment at line 151.The comment says "Determine whether dense data in segment has mismatch" but this block is for sparse vectors. It's a copy-paste from line 83.
Apply this diff to fix the comment:
- // Determine whether dense data in segment has mismatch + // Determine whether sparse data in segment has mismatchlib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)
61-120: Add SegmentType::Special check for consistency with other optimizers.The
require_optimizationmethod doesn't check forSegmentType::Specialsegments, unlikeMergeOptimizerandConfigMismatchOptimizerwhich explicitly skip Special segments. According toSegmentType::Specialdocumentation ("Some index which you better don't touch"), these segments should not be modified.Add this check at the start of
require_optimization:fn require_optimization(&self, segment: &Segment) -> bool { + // Never optimize Special segments + if segment.segment_type() == segment::types::SegmentType::Special { + return false; + } + let segment_config = segment.config();lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
1041-1051: Empty batch protection only fires in debug builds.The
debug_assert!(false)on line 1043 won't prevent empty batches from being scheduled in release builds. As noted in the previous review, consider adding an early return to make this release-safe:pub fn plan(&mut self, segments: Vec<SegmentId>) { if segments.is_empty() { - debug_assert!(false); + debug_assert!(false, "OptimizationPlanner::plan called with empty batch"); + return; }This prevents potential downstream issues like "optimize with empty ids" or incorrect
expected_segments_number()counts.
🧹 Nitpick comments (1)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
68-75: Minor: Division occurs before the bounds check.If
total_point_count()is 0, line 70 producesNaNbefore theis_bigcheck on line 71 guards against it. While functionally safe (NaN comparisons returnfalse), consider reordering for clarity:fn littered_ratio_segment(&self, segment: &Segment) -> Option<f64> { + 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 / segment.total_point_count() as f64; - let is_big = segment.total_point_count() >= self.min_vectors_number; + segment.deleted_point_count() as f64 / total as f64; let is_littered = littered_ratio > self.deleted_threshold; - - (is_big && is_littered).then_some(littered_ratio) + is_littered.then_some(littered_ratio) }This avoids the unnecessary division and makes the early-exit explicit.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs(16 hunks)lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs(17 hunks)lib/collection/src/collection_manager/optimizers/merge_optimizer.rs(7 hunks)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs(8 hunks)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs(12 hunks)lib/collection/src/common/stoppable_task.rs(4 hunks)lib/collection/src/shards/local_shard/snapshot_tests.rs(2 hunks)lib/collection/src/shards/local_shard/testing.rs(1 hunks)lib/collection/src/tests/mod.rs(3 hunks)lib/collection/src/update_handler.rs(2 hunks)lib/collection/src/update_workers/optimization_worker.rs(5 hunks)lib/shard/src/segment_holder/mod.rs(6 hunks)lib/shard/src/segment_holder/tests.rs(2 hunks)lib/shard/src/update.rs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- lib/collection/src/shards/local_shard/testing.rs
- lib/shard/src/update.rs
- lib/shard/src/segment_holder/tests.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.github/review-rules.md)
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust
In new code, don't usetransmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead
Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later (exceptions: tests and benchmarks, or when sure new variants won't affect logic)
Prefer explicit field ignoring using: _over using..in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)
Files:
lib/collection/src/common/stoppable_task.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/update_handler.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/tests/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/shards/local_shard/snapshot_tests.rs
🧠 Learnings (27)
📓 Common learnings
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: Don't report issues related to `.unwrap()` and `panic!()` usage in Rust tests and benchmarks
Applied to files:
lib/collection/src/common/stoppable_task.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-08-11T14:48:43.405Z
Learnt from: ffuugoo
Repo: qdrant/qdrant PR: 7015
File: lib/collection/src/collection_manager/collection_updater.rs:46-71
Timestamp: 2025-08-11T14:48:43.405Z
Learning: In Tokio, `tokio::task::block_in_place` does NOT panic when called from `spawn_blocking` threads or other non-runtime contexts. When called outside a runtime, it simply executes the provided closure normally without any special behavior. This is documented behavior and makes it safe to use `block_in_place` in functions that may be called from both async and blocking contexts.
Applied to files:
lib/collection/src/common/stoppable_task.rs
📚 Learning: 2025-05-19T09:25:54.285Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6546
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:497-518
Timestamp: 2025-05-19T09:25:54.285Z
Learning: In the Qdrant project, using `.expect()` and `.unwrap()` is considered acceptable in test code since test failures should be loud and obvious, and proper error propagation adds unnecessary complexity to test code.
Applied to files:
lib/collection/src/common/stoppable_task.rs
📚 Learning: 2025-06-14T20:35:10.603Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6635
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:784-832
Timestamp: 2025-06-14T20:35:10.603Z
Learning: Functions gated with `#[cfg(feature = "testing")]` within `#[cfg(test)]` modules are safe from compilation issues since both the function and its call sites are restricted to test builds. The additional feature gate is often used for optional heavy test utilities.
Applied to files:
lib/collection/src/common/stoppable_task.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-10-13T22:58:03.121Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7400
File: lib/segment/src/id_tracker/simple_id_tracker.rs:234-241
Timestamp: 2025-10-13T22:58:03.121Z
Learning: SimpleIdTracker in lib/segment/src/id_tracker/simple_id_tracker.rs is being deprecated and should not receive fixes related to version tracking or recovery logic, as it has a different version storage structure that is incompatible with newer trackers.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/update_handler.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/shards/local_shard/snapshot_tests.rs
📚 Learning: 2025-08-15T11:42:00.297Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR #7048, using checked_mul with u64 casting to prevent silent overflow.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-15T11:41:10.629Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-10-16T13:00:46.809Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 7368
File: lib/shard/src/query/mod.rs:313-341
Timestamp: 2025-10-16T13:00:46.809Z
Learning: In the Qdrant codebase, for the `Feedback` query variant in `lib/shard/src/query/mod.rs`, validation for sparse vectors should happen down the line rather than early in the `query_enum_from_grpc_raw_query` function. The `Nearest` variant is treated as a special case where early validation with better error messages is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-10T18:26:12.443Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: docs/redoc/master/openapi.json:13645-13652
Timestamp: 2025-08-10T18:26:12.443Z
Learning: In qdrant, docs/redoc/master/openapi.json is auto-generated from the REST schemas. To change field docs, edit lib/api/src/rest/schema.rs (e.g., add doc comments or #[schemars(description = ...)]). Specifically, UpdateVectors.update_filter lacked a description and should state: "If specified, only update vectors for points that match this filter; points not matching the filter are left unchanged."
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-20T15:03:18.522Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7100
File: lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs:82-100
Timestamp: 2025-08-20T15:03:18.522Z
Learning: The merge_postings_iterator function in lib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rs handles deduplication internally, so there's no need to add .dedup() when using it for OR-merge operations in inverted indexes.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-07-11T11:35:21.549Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/shards/local_shard/snapshot_tests.rs
📚 Learning: 2025-09-01T11:42:06.964Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7157
File: lib/shard/src/segment_holder/mod.rs:808-814
Timestamp: 2025-09-01T11:42:06.964Z
Learning: In Qdrant's segment holder, panicking when no segments exist during flush_all is intentional and preferred over graceful error handling, as having zero segments could permanently corrupt the WAL by acknowledging u64::MAX. The maintainers consider this condition impossible and use the panic as a fail-fast safety mechanism to prevent data corruption.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-09-16T21:39:09.353Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7232
File: lib/shard/src/segment_holder/mod.rs:1088-1094
Timestamp: 2025-09-16T21:39:09.353Z
Learning: The hnsw_format_force and hnsw_with_vectors flags in HnswGlobalConfig primarily affect existing segment conversion during load/startup, not the initial format selection for newly created empty segments. For new segments, format decisions are made by GraphLinksFormatParam::recommended() based on runtime conditions. Therefore, using HnswGlobalConfig::default() for temporary/proxy segments in SegmentHolder::build_tmp_segment is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-09-01T11:19:26.371Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-04-29T16:48:34.967Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 6446
File: lib/gridstore/benches/flush_bench.rs:18-18
Timestamp: 2025-04-29T16:48:34.967Z
Learning: The Rust rand crate version 0.9+ has introduced a top-level `rng()` function that replaces the now-deprecated `thread_rng()` function.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: For Rust code review, checking whether code compiles is out of scope, including: missing imports for `size_of` or `align_of` (included in Rust 1.80+ prelude), methods not implemented for types, different method names across `rand` crate versions (e.g., `random_range` vs `gen_range`), and other compiler errors or warnings
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-08-10T18:30:02.986Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/shard/src/segment_holder/mod.rs
📚 Learning: 2025-08-10T18:31:56.855Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/point_ops.rs:501-528
Timestamp: 2025-08-10T18:31:56.855Z
Learning: In Qdrant, batch operations validate that `ids`, `vectors`, and `payloads` (if present) have matching lengths at the REST API level in `lib/api/src/rest/validate.rs` through the `Validate` trait implementation for `Batch`. This validation happens before data is converted to internal structures like `PointInsertOperationsInternal`, so methods operating on these internal structures can safely assume the lengths match.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-06T09:56:59.311Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6982
File: lib/segment/src/index/hnsw_index/graph_links/view.rs:217-220
Timestamp: 2025-08-06T09:56:59.311Z
Learning: In Qdrant's GraphLinksView implementation (lib/segment/src/index/hnsw_index/graph_links/view.rs), methods like links() and links_with_vectors() intentionally use unwrap() and can panic for performance reasons, maintaining consistency across similar methods. Error handling improvements are considered secondary to feature completion and require benchmarking before implementation.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-06-06T07:52:38.478Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6644
File: lib/gridstore/src/blob.rs:41-57
Timestamp: 2025-06-06T07:52:38.478Z
Learning: In the Blob trait implementations for gridstore (lib/gridstore/src/blob.rs), the maintainer prefers using assert! for input validation over Result-based error handling, as they don't expect invalid inputs in real scenarios and changing to Result would require updating the entire trait interface.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-03-29T17:43:28.174Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6274
File: lib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs:233-233
Timestamp: 2025-03-29T17:43:28.174Z
Learning: In the qdrant codebase, `debug_assert!` is preferred over runtime checks that would panic in release builds to ensure production stability, even when validating conditions like vector sorting.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-11-14T10:01:31.926Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7526
File: src/wal_pop.rs:7-8
Timestamp: 2025-11-14T10:01:31.926Z
Learning: In the Qdrant codebase, development binaries (like src/wal_pop.rs) don't require explicit bounds checking for command-line arguments. Rust's built-in out-of-bounds panic is acceptable for these development tools.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-11-18T18:20:20.021Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7520
File: lib/quantization/src/p_square.rs:41-49
Timestamp: 2025-11-18T18:20:20.021Z
Learning: In lib/quantization/src/p_square.rs, IvanPleshkov prefers using defensive double-checks (e.g., `let Ok(x) = NotNan::new(x) else { return; }`) over `.unwrap()` even when a prior check guarantees success, to avoid panic-causing code and maintain defensive programming practices.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-08-18T10:56:43.707Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs:340-347
Timestamp: 2025-08-18T10:56:43.707Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs, the create_offsets_file_from_iter function intentionally requires paths to have a parent directory and returns an error if path.parent() is None. This was a conscious design decision to ensure proper path validation.
Applied to files:
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-08-14T11:31:21.777Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-09-08T08:47:43.795Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7188
File: lib/collection/src/update_handler.rs:810-813
Timestamp: 2025-09-08T08:47:43.795Z
Learning: In the Qdrant codebase, CollectionId implements traits that allow &CollectionId to convert Into<String>, so passing &collection_name to functions requiring Into<String> works correctly without needing .clone() or .to_string().
Applied to files:
lib/collection/src/shards/local_shard/snapshot_tests.rs
🧬 Code graph analysis (4)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
lib/common/common/src/flags.rs (1)
feature_flags(130-138)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)
lib/collection/src/update_handler.rs (3)
lib/shard/src/segment_holder/mod.rs (1)
segments(930-933)lib/collection/src/shards/local_shard/mod.rs (3)
segments(277-279)new(190-275)new(1056-1061)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
new(999-1006)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (2)
plan_optimizations(83-83)new(999-1006)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (3)
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (2)
plan_optimizations(156-222)new(38-59)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (2)
plan_optimizations(83-83)new(999-1006)lib/shard/src/segment_holder/mod.rs (2)
iter(94-99)iter(926-929)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: Build Qdrant Edge Python bindings
- GitHub Check: integration-tests
- GitHub Check: e2e-tests
- GitHub Check: integration-tests-consensus
- GitHub Check: lint
- GitHub Check: test-consistency
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: test-consensus-compose
🔇 Additional comments (18)
lib/collection/src/shards/local_shard/snapshot_tests.rs (1)
30-34: LGTM! Consistent adaptation to new SegmentHolder iterator API.Both map closures correctly adapt to the new iterator semantics that yield owned
SegmentIdvalues instead of references. The test logic remains unchanged and both collections still produce the sameHashSet<SegmentId>type for comparison.Also applies to: 60-64
lib/shard/src/segment_holder/mod.rs (2)
94-107: LGTM! Iterator API changes support planner-based optimization.The signature change from
(&SegmentId, &LockedSegment)to(SegmentId, &LockedSegment)and the newiter_original()method align well with the planner-driven workflow introduced in this PR. The ownedSegmentIdsimplifies downstream usage in planning logic.
384-421: Consistent usage of owned SegmentId throughout.All call sites correctly handle the owned
SegmentIdfrom the iterator, replacing previous dereferences with direct value usage.lib/collection/src/tests/mod.rs (1)
82-82: LGTM! Callback signature updated to match new API.The change from a one-parameter to a zero-parameter closure aligns with the updated
launch_optimizationsignature in the planner-based workflow.lib/collection/src/update_handler.rs (1)
287-292: LGTM! Planner-based condition checking is cleaner.The new approach using
OptimizationPlannerandplanner.scheduled()provides a more unified way to check for pending optimizations across all optimizers.lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
93-133: LGTM! Batching logic correctly uses planner-based approach.The new implementation:
- Sorts candidates by size
- Forms batches respecting
max_segment_size_kbthreshold- Requires minimum 3 segments per batch to guarantee segment count reduction
- Correctly uses
planner.expected_segments_number()for early-exit checksThe past review comment about using
planner.expected_segments_number()instead ofcandidates.len()is addressed (line 114).lib/collection/src/update_workers/optimization_worker.rs (2)
269-277: LGTM! Planner-based scheduling simplifies optimization flow.The new approach creates an
OptimizationPlannerupfront, lets each optimizer contribute their planned batches, then iterates over the scheduled batches. This is cleaner than the previous nested-loop approach.
347-409: Inline panic handling improves error reporting.Moving panic handling from the
StoppableTaskHandleto inlinecatch_unwindallows better integration with the tracker status system and segment-level error reporting. The unified error handling path (lines 365-402) correctly updates tracker status and reports optimizer errors to the segment holder.lib/collection/src/common/stoppable_task.rs (1)
37-55: LGTM! Simplified join API removes custom panic handling.The removal of panic handling from
StoppableTaskHandlesimplifies the API. Panic handling is now the caller's responsibility (e.g., viacatch_unwindin optimization_worker.rs).lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)
156-222: LGTM! Planner-based indexing logic correctly prioritizes largest unindexed segments.The new implementation:
- Separates segments into unindexed (requiring optimization) and indexed categories
- Prioritizes largest unindexed segments first
- Attempts to pair segments to maintain segment count when above
default_segments_number- Respects
max_segment_size_kbwhen forming pairsThe logic is sound and aligns with the planner-based approach.
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (4)
1-4: LGTM on the new imports.The added imports for
BTreeMap,Arc,RwLock, andOptimizerare necessary for the newOptimizationPlannerstruct and planner-based workflow.Also applies to: 16-16, 38-38
82-109: Well-designed test helper with consistency validation.The
plan_optimizations_for_testwrapper provides valuable consistency checking by verifying that re-planning with remaining segments produces matching results. This ensures optimizer implementations are deterministic and stable.
629-629: Good placement of theon_successful_startcallback.The callback is invoked after all validation checks pass (segment availability, disk space, process stopped checks) but before the expensive segment building work begins. This allows callers to be notified that optimization has committed to proceeding.
Also applies to: 638-638, 685-686
978-1006: Clean design for theOptimizationPlannerstruct.The struct effectively separates planning from execution by tracking remaining segments, scheduled batches, and the current optimizer context. The
extrafield for phantom segments inexpected_segments_number()is a thoughtful addition for accurate segment count estimation.lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (4)
4-4: LGTM on the updated imports.The changes correctly bring in
Itertoolsfor collection operations and shift toSegment-based access with the newOptimizationPlannertype.Also applies to: 10-11, 14-15
86-118: LGTM on the refactoredlittered_vectors_index_ratio.The method now cleanly operates on
&Segmentdirectly, properly handles the zeroindexed_vector_countcase (line 107-111), and correctly usesOrderedFloatfor finding the maximum ratio.
154-172: Clean implementation ofplan_optimizations.The method correctly:
- Iterates over remaining segments from the planner
- Computes the worst ratio across segment and vector-level metrics
- Sorts by descending ratio to prioritize the most littered segments
- Plans each segment individually (appropriate for vacuum which rebuilds segments independently)
305-306: Test updates align well with the new planner-based API.The tests correctly:
- Use
plan_optimizations_for_testto get planned batches- Use
iter_original()for segment iteration- Pass the new
on_successful_startcallback (Box::new(|| ()))- Unwrap single-element results with
exactly_one()where appropriateAlso applies to: 327-327, 476-476, 487-492, 495-496, 557-558, 573-574, 584-584, 592-593
00b4733 to
09b6225
Compare
09b6225 to
c7f5732
Compare
📝 WalkthroughWalkthroughRefactors the optimization subsystem to a planner-driven model: adds OptimizationPlanner and replaces all optimizers' check_condition(...) with plan_optimizations(&mut OptimizationPlanner). Optimizers (config_mismatch, indexing, merge, vacuum) now schedule plans via the planner. SegmentHolder adds running_optimizations (ProcessCounter), iter_original(), and iter() now yields owned SegmentId. update_handler and optimization_worker build and consume OptimizationPlanner. Adds a new ProcessCounter module and adjusts tests and helpers to the planner-based API. unwrap_proxy now returns () and planner/test wrappers were added. Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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: 2
🤖 Fix all issues with AI agents
In @lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs:
- Around line 156-221: The comparisons using selected_segment_size + size <
max_segment_size_bytes can overflow; replace them with a checked addition and
compare the resulting sum safely (e.g.,
selected_segment_size.checked_add(size).map_or(false, |sum| sum <
max_segment_size_bytes)) in both places inside plan_optimizations where
selected_segment_size and size are summed, so you avoid wrapping on large values
while keeping the existing branching and planner.plan(...) logic.
In @lib/collection/src/collection_manager/optimizers/merge_optimizer.rs:
- Around line 116-165: In plan_optimizations, the batch accumulator (*size_sum
+= size) can overflow; change the accumulator used in the scan to a wider
integer type (or use saturating_add/checked_add) and perform additions &
comparisons in that wider type (cast segment size and threshold to the wider
type) so overflow cannot make *size_sum < threshold true; ensure the scan
returns None once addition would reach or exceed threshold (or on overflow) so
batches never exceed threshold, updating the scan initializer and the comparison
logic around size_sum, threshold, and the produced batch accordingly.
🧹 Nitpick comments (5)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
68-75: Avoid NaN inlittered_ratio_segmentby guardingtotal_point_count == 0(clarity).
Currentlydeleted/totalis computed even whentotal == 0. It won’t be returned due tois_big, but it’s still a surprising intermediate.Proposed tweak
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 total = segment.total_point_count(); + if total == 0 { + return None; + } + let littered_ratio = segment.deleted_point_count() as f64 / total as f64; + let is_big = total >= self.min_vectors_number; let is_littered = littered_ratio > self.deleted_threshold; (is_big && is_littered).then_some(littered_ratio) }lib/shard/src/segment_holder/mod.rs (1)
55-82: Consider makingrunning_optimizationsnon-public to protect its invariants.
As apubfield, any caller with a mutable holder can replace/reset it, breaking the “count is tied to handle lifetimes” model.Possible direction
pub struct SegmentHolder { @@ - /// The amount of currently running optimizations. - pub running_optimizations: ProcessCounter, + /// The amount of currently running optimizations. + running_optimizations: ProcessCounter, } + +impl SegmentHolder { + pub fn running_optimizations(&self) -> usize { + self.running_optimizations.count() + } + + pub fn start_optimization(&mut self) -> common::process_counter::CountedProcessHandle { + self.running_optimizations.inc() + } +}lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
17-44: Doc typo: “greedely” → “greedily”.lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (1)
206-225: Simplifyfilter_mapinplan_optimizations(same laziness, clearer).Proposed refactor
let to_optimize = planner .remaining() .iter() .filter_map(|(&segment_id, segment)| { let segment = segment.read(); - self.config_mismatch(&*segment).then(|| { - let vector_size = segment - .max_available_vectors_size_in_bytes() - .unwrap_or_default(); - Some((segment_id, vector_size)) - })? + self.config_mismatch(&*segment).then(|| { + let vector_size = segment + .max_available_vectors_size_in_bytes() + .unwrap_or_default(); + (segment_id, vector_size) + }) })lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
1028-1039: Consider adding assertion messages for debugging clarity.The debug assertions at Lines 1031 and 1035 would benefit from descriptive messages to aid debugging when optimizer implementations violate the planning contract.
💡 Suggested improvement
pub fn plan(&mut self, segments: Vec<SegmentId>) { if segments.is_empty() { - debug_assert!(false); + debug_assert!(false, "attempted to plan empty segment batch"); } for segment_id in &segments { let removed = self.remaining.remove(segment_id).is_some(); - debug_assert!(removed); + debug_assert!(removed, "attempted to plan segment {segment_id} that is not in remaining set (already planned or invalid ID)"); } self.scheduled.push((self.optimizer.clone(), segments)); }
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/collection/src/shards/local_shard/testing.rslib/collection/src/update_handler.rslib/collection/src/update_workers/optimization_worker.rslib/common/common/src/lib.rslib/common/common/src/process_counter.rslib/shard/src/segment_holder/mod.rslib/shard/src/segment_holder/tests.rslib/shard/src/update.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.github/review-rules.md)
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust
In new code, don't usetransmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead
Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later (exceptions: tests and benchmarks, or when sure new variants won't affect logic)
Prefer explicit field ignoring using: _over using..in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)
Files:
lib/common/common/src/lib.rslib/shard/src/update.rslib/common/common/src/process_counter.rslib/shard/src/segment_holder/tests.rslib/collection/src/update_handler.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/shards/local_shard/testing.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/update_workers/optimization_worker.rs
🧠 Learnings (33)
📚 Learning: 2025-08-10T18:30:02.986Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Applied to files:
lib/shard/src/update.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-10T18:26:12.443Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: docs/redoc/master/openapi.json:13645-13652
Timestamp: 2025-08-10T18:26:12.443Z
Learning: In qdrant, docs/redoc/master/openapi.json is auto-generated from the REST schemas. To change field docs, edit lib/api/src/rest/schema.rs (e.g., add doc comments or #[schemars(description = ...)]). Specifically, UpdateVectors.update_filter lacked a description and should state: "If specified, only update vectors for points that match this filter; points not matching the filter are left unchanged."
Applied to files:
lib/shard/src/update.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-10-13T22:58:03.121Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7400
File: lib/segment/src/id_tracker/simple_id_tracker.rs:234-241
Timestamp: 2025-10-13T22:58:03.121Z
Learning: SimpleIdTracker in lib/segment/src/id_tracker/simple_id_tracker.rs is being deprecated and should not receive fixes related to version tracking or recovery logic, as it has a different version storage structure that is incompatible with newer trackers.
Applied to files:
lib/shard/src/update.rslib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/shards/local_shard/testing.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-07-11T11:35:21.549Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Applied to files:
lib/shard/src/update.rslib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/shards/local_shard/testing.rslib/collection/src/shards/local_shard/snapshot_tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-09-16T19:14:17.614Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7183
File: lib/api/src/grpc/qdrant.rs:4263-4273
Timestamp: 2025-09-16T19:14:17.614Z
Learning: In qdrant, lib/api/src/grpc/qdrant.rs is auto-generated by prost-build; do not edit it directly. Make changes in lib/api/src/grpc/proto/points.proto (e.g., add [deprecated=true], doc comments, or encoding options), then regenerate the Rust code.
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-08-11T00:37:34.100Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs:46-55
Timestamp: 2025-08-11T00:37:34.100Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs`, the `ChunkedVectors` used in `QuantizedRamStorage` is intentionally designed to be non-persistent during updates. The `push_vector` method only updates the in-memory vectors without flushing to disk, and this is expected behavior rather than a bug.
Applied to files:
lib/shard/src/update.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-20T15:03:18.522Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7100
File: lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs:82-100
Timestamp: 2025-08-20T15:03:18.522Z
Learning: The merge_postings_iterator function in lib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rs handles deduplication internally, so there's no need to add .dedup() when using it for OR-merge operations in inverted indexes.
Applied to files:
lib/shard/src/update.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-05-08T10:34:42.223Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6444
File: lib/segment/src/index/field_index/map_index/immutable_map_index.rs:373-375
Timestamp: 2025-05-08T10:34:42.223Z
Learning: In the Qdrant codebase, storage backends may have different error handling approaches. Specifically, the mmap variant of `remove_point` method does not return errors, while the RocksDB variant does propagate errors using the `?` operator. These differences are intentional by design.
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-08-10T18:20:42.252Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: src/common/update.rs:272-281
Timestamp: 2025-08-10T18:20:42.252Z
Learning: In Qdrant, conditional updates with `update_filter` always apply the condition check to a small, pre-determined set of point IDs (those being updated) and never perform a full collection scan. Therefore, strict mode validation for unindexed filtering is not necessary for conditional update operations, as the performance concerns that strict mode addresses don't apply to these targeted operations.
Applied to files:
lib/shard/src/update.rs
📚 Learning: 2025-04-20T19:08:45.034Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6403
File: lib/collection/src/collection_manager/holders/proxy_segment.rs:1178-1197
Timestamp: 2025-04-20T19:08:45.034Z
Learning: In the ProxySegment implementation, overwriting previous index changes when inserting a DeleteIfIncompatible operation is intentional. When an incompatible index is detected, the DeleteIfIncompatible operation should take precedence over any previously scheduled operations on that index.
Applied to files:
lib/shard/src/update.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-09-01T11:19:26.371Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-18T10:56:43.707Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs:340-347
Timestamp: 2025-08-18T10:56:43.707Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs, the create_offsets_file_from_iter function intentionally requires paths to have a parent directory and returns an error if path.parent() is None. This was a conscious design decision to ensure proper path validation.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-09-01T11:42:06.964Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7157
File: lib/shard/src/segment_holder/mod.rs:808-814
Timestamp: 2025-09-01T11:42:06.964Z
Learning: In Qdrant's segment holder, panicking when no segments exist during flush_all is intentional and preferred over graceful error handling, as having zero segments could permanently corrupt the WAL by acknowledging u64::MAX. The maintainers consider this condition impossible and use the panic as a fail-fast safety mechanism to prevent data corruption.
Applied to files:
lib/shard/src/segment_holder/tests.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/shards/local_shard/testing.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-15T11:42:00.297Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR #7048, using checked_mul with u64 casting to prevent silent overflow.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-10-16T13:00:46.809Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 7368
File: lib/shard/src/query/mod.rs:313-341
Timestamp: 2025-10-16T13:00:46.809Z
Learning: In the Qdrant codebase, for the `Feedback` query variant in `lib/shard/src/query/mod.rs`, validation for sparse vectors should happen down the line rather than early in the `query_enum_from_grpc_raw_query` function. The `Nearest` variant is treated as a special case where early validation with better error messages is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-15T11:41:10.629Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-09-16T21:39:09.353Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7232
File: lib/shard/src/segment_holder/mod.rs:1088-1094
Timestamp: 2025-09-16T21:39:09.353Z
Learning: The hnsw_format_force and hnsw_with_vectors flags in HnswGlobalConfig primarily affect existing segment conversion during load/startup, not the initial format selection for newly created empty segments. For new segments, format decisions are made by GraphLinksFormatParam::recommended() based on runtime conditions. Therefore, using HnswGlobalConfig::default() for temporary/proxy segments in SegmentHolder::build_tmp_segment is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-05-19T09:25:54.285Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6546
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:497-518
Timestamp: 2025-05-19T09:25:54.285Z
Learning: In the Qdrant project, using `.expect()` and `.unwrap()` is considered acceptable in test code since test failures should be loud and obvious, and proper error propagation adds unnecessary complexity to test code.
Applied to files:
lib/collection/src/shards/local_shard/testing.rs
📚 Learning: 2025-10-13T09:34:22.740Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7388
File: lib/shard/src/segment_holder/flush.rs:73-76
Timestamp: 2025-10-13T09:34:22.740Z
Learning: In Qdrant's SegmentHolder flush logic, when `sync=false` and a background flush is already running, returning early is acceptable because: (1) flushes normally only start if there are changes, (2) the lowest version number is acknowledged in the WAL when changes exist, and (3) missed operations will replay on restart. However, an edge case exists when the `force` flag is used: if the first forced flush has no changes but a follow-up non-force flush with changes is ignored, the system might acknowledge a version that is too recent.
Applied to files:
lib/collection/src/shards/local_shard/testing.rs
📚 Learning: 2025-08-14T11:31:21.777Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-10-12T22:22:11.435Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7388
File: lib/shard/src/segment_holder/flush.rs:167-191
Timestamp: 2025-10-12T22:22:11.435Z
Learning: In Qdrant's SegmentHolder flush logic, when calculating the minimum unsaved version for WAL acknowledgment, the code intentionally returns `segment_persisted_version` (not `segment_persisted_version + 1`) when there are unsaved changes. This conservative approach assumes the last persisted version might not have been fully applied and allows the system to safely retry operations when versions match, ensuring WAL consistency.
Applied to files:
lib/collection/src/shards/local_shard/testing.rs
📚 Learning: 2025-11-18T18:20:20.021Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7520
File: lib/quantization/src/p_square.rs:41-49
Timestamp: 2025-11-18T18:20:20.021Z
Learning: In lib/quantization/src/p_square.rs, IvanPleshkov prefers using defensive double-checks (e.g., `let Ok(x) = NotNan::new(x) else { return; }`) over `.unwrap()` even when a prior check guarantees success, to avoid panic-causing code and maintain defensive programming practices.
Applied to files:
lib/collection/src/shards/local_shard/testing.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: Don't report issues related to `.unwrap()` and `panic!()` usage in Rust tests and benchmarks
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-14T10:01:31.926Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7526
File: src/wal_pop.rs:7-8
Timestamp: 2025-11-14T10:01:31.926Z
Learning: In the Qdrant codebase, development binaries (like src/wal_pop.rs) don't require explicit bounds checking for command-line arguments. Rust's built-in out-of-bounds panic is acceptable for these development tools.
Applied to files:
lib/collection/src/shards/local_shard/testing.rslib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-09-08T08:47:43.795Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7188
File: lib/collection/src/update_handler.rs:810-813
Timestamp: 2025-09-08T08:47:43.795Z
Learning: In the Qdrant codebase, CollectionId implements traits that allow &CollectionId to convert Into<String>, so passing &collection_name to functions requiring Into<String> works correctly without needing .clone() or .to_string().
Applied to files:
lib/collection/src/shards/local_shard/snapshot_tests.rs
📚 Learning: 2025-03-20T13:19:35.328Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6209
File: lib/collection/src/shards/shard_holder/shard_mapping.rs:119-122
Timestamp: 2025-03-20T13:19:35.328Z
Learning: The `to_map()` method in `ShardKeyMappingWrapper` is a temporary solution that will be replaced in a future version (likely in version 1.15 based on the TODO comment). Performance benchmarking for this method is not necessary as it's not used frequently and will be replaced with an implementation that doesn't require cloning.
Applied to files:
lib/collection/src/shards/local_shard/snapshot_tests.rs
📚 Learning: 2025-08-06T09:56:59.311Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6982
File: lib/segment/src/index/hnsw_index/graph_links/view.rs:217-220
Timestamp: 2025-08-06T09:56:59.311Z
Learning: In Qdrant's GraphLinksView implementation (lib/segment/src/index/hnsw_index/graph_links/view.rs), methods like links() and links_with_vectors() intentionally use unwrap() and can panic for performance reasons, maintaining consistency across similar methods. Error handling improvements are considered secondary to feature completion and require benchmarking before implementation.
Applied to files:
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-08-10T18:31:56.855Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/point_ops.rs:501-528
Timestamp: 2025-08-10T18:31:56.855Z
Learning: In Qdrant, batch operations validate that `ids`, `vectors`, and `payloads` (if present) have matching lengths at the REST API level in `lib/api/src/rest/validate.rs` through the `Validate` trait implementation for `Batch`. This validation happens before data is converted to internal structures like `PointInsertOperationsInternal`, so methods operating on these internal structures can safely assume the lengths match.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-06-14T20:35:10.603Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6635
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:784-832
Timestamp: 2025-06-14T20:35:10.603Z
Learning: Functions gated with `#[cfg(feature = "testing")]` within `#[cfg(test)]` modules are safe from compilation issues since both the function and its call sites are restricted to test builds. The additional feature gate is often used for optional heavy test utilities.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-04-29T16:48:34.967Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 6446
File: lib/gridstore/benches/flush_bench.rs:18-18
Timestamp: 2025-04-29T16:48:34.967Z
Learning: The Rust rand crate version 0.9+ has introduced a top-level `rng()` function that replaces the now-deprecated `thread_rng()` function.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: For Rust code review, checking whether code compiles is out of scope, including: missing imports for `size_of` or `align_of` (included in Rust 1.80+ prelude), methods not implemented for types, different method names across `rand` crate versions (e.g., `random_range` vs `gen_range`), and other compiler errors or warnings
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-06-06T07:52:38.478Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6644
File: lib/gridstore/src/blob.rs:41-57
Timestamp: 2025-06-06T07:52:38.478Z
Learning: In the Blob trait implementations for gridstore (lib/gridstore/src/blob.rs), the maintainer prefers using assert! for input validation over Result-based error handling, as they don't expect invalid inputs in real scenarios and changing to Result would require updating the entire trait interface.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
📚 Learning: 2025-03-29T17:43:28.174Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6274
File: lib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs:233-233
Timestamp: 2025-03-29T17:43:28.174Z
Learning: In the qdrant codebase, `debug_assert!` is preferred over runtime checks that would panic in release builds to ensure production stability, even when validating conditions like vector sorting.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rs
🧬 Code graph analysis (7)
lib/shard/src/update.rs (1)
lib/segment/src/segment/snapshot.rs (1)
segment_id(104-122)
lib/collection/src/update_handler.rs (1)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
new(983-993)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (3)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
plan_optimizations(116-166)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
plan_optimizations(154-171)
lib/collection/src/shards/local_shard/testing.rs (2)
lib/shard/src/segment_holder/mod.rs (1)
segments(934-937)lib/collection/src/shards/local_shard/mod.rs (1)
segments(278-280)
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/shard/src/segment_holder/mod.rs (2)
iter(98-103)iter(930-933)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (5)
lib/segment/src/common/operation_error.rs (1)
check_process_stopped(284-289)lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (2)
plan_optimizations(116-166)new(59-80)lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
plan_optimizations(206-225)new(35-54)lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (2)
plan_optimizations(156-222)new(38-59)lib/collection/src/update_handler.rs (1)
new(129-172)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (2)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (2)
plan_optimizations(83-83)new(983-993)lib/collection/src/collection_manager/fixtures.rs (1)
get_merge_optimizer(225-250)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: integration-tests-consensus
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: test-consistency
- GitHub Check: test-consensus-compose
- GitHub Check: e2e-tests
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: integration-tests
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: lint
- GitHub Check: Test Python bindings
🔇 Additional comments (27)
lib/collection/src/shards/local_shard/snapshot_tests.rs (1)
33-33: LGTM! Correct adaptation to the newiter()signature.The removal of the dereference operator correctly adapts to
SegmentHolder::iter()now returning ownedSegmentIdvalues instead of references. The test logic remains functionally equivalent.Also applies to: 63-63
lib/common/common/src/lib.rs (1)
23-23: LGTM!The new
process_countermodule is properly added to the public API and maintains alphabetical ordering.lib/shard/src/segment_holder/tests.rs (2)
536-540: LGTM!The change from
*idtoidcorrectly adapts to the new iterator signature that returns ownedSegmentIdvalues instead of references.
610-614: LGTM!Consistent with the earlier change, this correctly uses the owned
SegmentIdvalue directly.lib/shard/src/update.rs (1)
364-378: LGTM!The change from
*segment_idtosegment_idcorrectly adapts to the new iterator signature that returns ownedSegmentIdvalues.lib/collection/src/shards/local_shard/testing.rs (1)
6-11: LGTM!The simplified iteration over
iter_original()removes the need for pattern matching on segment variants, making the test helper more straightforward. This aligns with the planner-based refactor.lib/collection/src/update_handler.rs (2)
18-20: LGTM!The import correctly adds
OptimizationPlanneralongsideSegmentOptimizerto support the new planner-based optimization flow.
298-306: The short-circuiting withany()is intentional and correct for this context.The
check_optimizer_conditions()method is only used for shard status reporting (to determine Yellow/Grey vs Green status), not for building an actual optimization plan. For this status-checking purpose, usingany()is appropriate—you only need to determine whether any optimizers have pending work.The actual global optimization plan is built separately in the optimization workflow (
optimization_worker.rs), which uses an explicit loop to let all optimizers contribute:for optimizer in optimizers.iter() { planner.set_optimizer(Arc::clone(optimizer)); optimizer.plan_optimizations(&mut planner); }No changes are needed.
Likely an incorrect or invalid review comment.
lib/common/common/src/process_counter.rs (2)
17-39: ProcessCounter API looks solid; the&mut selfonincis a good guardrail.
No issues with the refcount-based counting givenCountedProcessHandleis non-cloneable and its field is private.
45-69: Tests cover the important failure mode (panic-path drop) well.lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
154-171: Planning/sorting approach looks consistent and deterministic.
304-306: Test updates match the new planner +iter_original()access pattern.Also applies to: 326-327, 486-492, 494-496, 553-558, 572-574, 591-593
lib/shard/src/segment_holder/mod.rs (2)
98-111:iter()/iter_original()changes look good and keep deterministic ordering.
388-426: Downstream adjustments for ownedSegmentIdlook correct.Also applies to: 501-502, 930-933
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (1)
173-381: The expanded test table is a nice way to pin down batching edge cases.lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (2)
61-120:require_optimizationrefactor reads clean and keeps threshold math saturating.
269-274: Test updates align with planner output being multi-batch and withiter_original().Also applies to: 329-337, 440-454, 458-472, 495-507, 517-523, 531-533, 646-648, 763-769, 872-902, 961-978
lib/collection/src/update_workers/optimization_worker.rs (2)
282-414: Planner → scheduled → spawn flow looks coherent; permit wakeup hook is a nice touch.
Only concern is making sure non-success outcomes (cancel/error/panic) still reliably lead to another scheduling attempt (either via permit release callback or other signals).
269-280:running_optimizationscounter is correctly incremented and held for the full optimization lifetime.The counter is properly managed:
CountedProcessHandleis created insegment_optimizer.rs:736at the start ofoptimize(), held throughout the operation including the slow propagation phase, and explicitly dropped (drop(counter_handler)) after the optimized segment is swapped in. Error and panic paths also properly release the handle via early return or closure unwinding, ensuring the counter accurately reflects active optimizations whencount()is read byOptimizationPlannerinoptimization_worker.rs:272.lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
74-170:config_mismatchconsolidation looks good; explicit sparse index-type matching is clear.
Minor nit: the comment at Line 151 says “dense” but is describing sparse.
251-252: Test updates matchiter_original()and planner-based selection.Also applies to: 356-357, 368-370, 387-389, 519-521, 539-541, 558-560, 696-698, 719-721, 738-740
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (6)
82-119: LGTM: Planner-based API and test verification logic.The refactoring from
check_conditiontoplan_optimizationsaligns with the PR objectives. The test wrapper includes incremental verification to ensure planning consistency, with a documented special case for the merge optimizer's requirements.
384-401: LGTM: Simplified interface.The signature change from returning
Vec<SegmentId>to()simplifies the API, and the implementation correctly ignores the return value fromswap_new.
697-739: LGTM: Proper counter lifecycle management.The counter is correctly incremented when proxies are inserted and decremented (via
drop) after the optimized segment is swapped in. The RAII pattern ensures the counter is decremented even on error paths.
757-758: LGTM: Consistent with signature change.The call to
unwrap_proxycorrectly ignores the return value, matching the updated signature.
765-765: LGTM: Counter decrement at correct scope.Dropping
counter_handlerimmediately after the optimized segment is swapped in ensures the running optimization count is accurately maintained.
962-1027: LGTM: Well-designed planner abstraction.The
OptimizationPlannerprovides a clean interface for coordinating segment optimization scheduling. The use ofBTreeMapforremainingensures deterministic iteration order, and theexpected_segments_number()calculation correctly accounts for running optimizations and planned batches.
|
@IvanPleshkov are you happy with changes? |
IvanPleshkov
left a comment
There was a problem hiding this comment.
All found questions were resolved, just leave a list of nits which are not a blocker to merge. The changed logic of how we perform indexing/merge optimizers was approved by @generall. Approve
c7f5732 to
be92cbf
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In
@lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs:
- Around line 74-81: The inline comment in has_config_mismatch is inaccurate:
remove or replace "Skip segments with payload mismatch" with a comment that
states the opposite, e.g., that returning true marks the segment as having a
config mismatch and therefore selected for optimization; refer to
has_config_mismatch, segment.config().payload_storage_type.is_on_disk(), and
self.collection_params.on_disk_payload so reviewers can locate and update the
comment to correctly describe that a payload storage mismatch causes the segment
to be selected (return true) for optimization.
- Around line 151-169: The comment above the sparse vector mismatch check is
incorrect: it says "Determine whether dense data in segment has mismatch" but
the code inspects segment_config.sparse_vector_data and computes
sparse_has_mismatch; update the comment to refer to sparse data/mismatch (e.g.,
"Determine whether sparse data in segment has mismatch") and ensure any
surrounding documentation mentions sparse vectors when referencing
sparse_has_mismatch, check_if_sparse_vectors_index_on_disk, and the
SparseIndexType match arms (MutableRam, ImmutableRam, Mmap).
🧹 Nitpick comments (1)
lib/collection/src/update_workers/optimization_worker.rs (1)
282-286: Consider usinglog::error!alongsidedebug_assert!for production visibility.The
debug_assert!(false)will be stripped in release builds, so if an optimizer is unexpectedlyNone, the issue will be silently skipped. Based on learnings from this codebase,debug_assert!is preferred for production stability, but consider adding alog::error!for observability.💡 Suggested improvement
for (optimizer, segments_to_merge) in scheduled { let Some(optimizer) = optimizer else { + log::error!("Scheduled optimization has no optimizer attached, skipping"); debug_assert!(false); continue; };
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/update_handler.rslib/collection/src/update_workers/optimization_worker.rslib/common/common/src/lib.rslib/common/common/src/process_counter.rslib/shard/src/segment_holder/mod.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.github/review-rules.md)
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust
In new code, don't usetransmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead
Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later (exceptions: tests and benchmarks, or when sure new variants won't affect logic)
Prefer explicit field ignoring using: _over using..in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)
Files:
lib/collection/src/update_handler.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/common/common/src/process_counter.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/common/common/src/lib.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
🧠 Learnings (29)
📚 Learning: 2025-08-15T11:42:00.297Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR #7048, using checked_mul with u64 casting to prevent silent overflow.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-10-16T13:00:46.809Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 7368
File: lib/shard/src/query/mod.rs:313-341
Timestamp: 2025-10-16T13:00:46.809Z
Learning: In the Qdrant codebase, for the `Feedback` query variant in `lib/shard/src/query/mod.rs`, validation for sparse vectors should happen down the line rather than early in the `query_enum_from_grpc_raw_query` function. The `Nearest` variant is treated as a special case where early validation with better error messages is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-10T18:26:12.443Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: docs/redoc/master/openapi.json:13645-13652
Timestamp: 2025-08-10T18:26:12.443Z
Learning: In qdrant, docs/redoc/master/openapi.json is auto-generated from the REST schemas. To change field docs, edit lib/api/src/rest/schema.rs (e.g., add doc comments or #[schemars(description = ...)]). Specifically, UpdateVectors.update_filter lacked a description and should state: "If specified, only update vectors for points that match this filter; points not matching the filter are left unchanged."
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-20T15:03:18.522Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7100
File: lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs:82-100
Timestamp: 2025-08-20T15:03:18.522Z
Learning: The merge_postings_iterator function in lib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rs handles deduplication internally, so there's no need to add .dedup() when using it for OR-merge operations in inverted indexes.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-07-11T11:35:21.549Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-10-13T22:58:03.121Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7400
File: lib/segment/src/id_tracker/simple_id_tracker.rs:234-241
Timestamp: 2025-10-13T22:58:03.121Z
Learning: SimpleIdTracker in lib/segment/src/id_tracker/simple_id_tracker.rs is being deprecated and should not receive fixes related to version tracking or recovery logic, as it has a different version storage structure that is incompatible with newer trackers.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-08-15T11:41:10.629Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-09-01T11:42:06.964Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7157
File: lib/shard/src/segment_holder/mod.rs:808-814
Timestamp: 2025-09-01T11:42:06.964Z
Learning: In Qdrant's segment holder, panicking when no segments exist during flush_all is intentional and preferred over graceful error handling, as having zero segments could permanently corrupt the WAL by acknowledging u64::MAX. The maintainers consider this condition impossible and use the panic as a fail-fast safety mechanism to prevent data corruption.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-09-16T21:39:09.353Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7232
File: lib/shard/src/segment_holder/mod.rs:1088-1094
Timestamp: 2025-09-16T21:39:09.353Z
Learning: The hnsw_format_force and hnsw_with_vectors flags in HnswGlobalConfig primarily affect existing segment conversion during load/startup, not the initial format selection for newly created empty segments. For new segments, format decisions are made by GraphLinksFormatParam::recommended() based on runtime conditions. Therefore, using HnswGlobalConfig::default() for temporary/proxy segments in SegmentHolder::build_tmp_segment is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-09-01T11:19:26.371Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-08-11T00:37:34.100Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs:46-55
Timestamp: 2025-08-11T00:37:34.100Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs`, the `ChunkedVectors` used in `QuantizedRamStorage` is intentionally designed to be non-persistent during updates. The `push_vector` method only updates the in-memory vectors without flushing to disk, and this is expected behavior rather than a bug.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-06T09:56:59.311Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6982
File: lib/segment/src/index/hnsw_index/graph_links/view.rs:217-220
Timestamp: 2025-08-06T09:56:59.311Z
Learning: In Qdrant's GraphLinksView implementation (lib/segment/src/index/hnsw_index/graph_links/view.rs), methods like links() and links_with_vectors() intentionally use unwrap() and can panic for performance reasons, maintaining consistency across similar methods. Error handling improvements are considered secondary to feature completion and require benchmarking before implementation.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-06-06T07:52:38.478Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6644
File: lib/gridstore/src/blob.rs:41-57
Timestamp: 2025-06-06T07:52:38.478Z
Learning: In the Blob trait implementations for gridstore (lib/gridstore/src/blob.rs), the maintainer prefers using assert! for input validation over Result-based error handling, as they don't expect invalid inputs in real scenarios and changing to Result would require updating the entire trait interface.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-03-29T17:43:28.174Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6274
File: lib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs:233-233
Timestamp: 2025-03-29T17:43:28.174Z
Learning: In the qdrant codebase, `debug_assert!` is preferred over runtime checks that would panic in release builds to ensure production stability, even when validating conditions like vector sorting.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-11-14T10:01:31.926Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7526
File: src/wal_pop.rs:7-8
Timestamp: 2025-11-14T10:01:31.926Z
Learning: In the Qdrant codebase, development binaries (like src/wal_pop.rs) don't require explicit bounds checking for command-line arguments. Rust's built-in out-of-bounds panic is acceptable for these development tools.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-11-18T18:20:20.021Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7520
File: lib/quantization/src/p_square.rs:41-49
Timestamp: 2025-11-18T18:20:20.021Z
Learning: In lib/quantization/src/p_square.rs, IvanPleshkov prefers using defensive double-checks (e.g., `let Ok(x) = NotNan::new(x) else { return; }`) over `.unwrap()` even when a prior check guarantees success, to avoid panic-causing code and maintain defensive programming practices.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-18T10:56:43.707Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs:340-347
Timestamp: 2025-08-18T10:56:43.707Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs, the create_offsets_file_from_iter function intentionally requires paths to have a parent directory and returns an error if path.parent() is None. This was a conscious design decision to ensure proper path validation.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs
📚 Learning: 2025-08-22T13:49:39.261Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7118
File: lib/segment/src/index/hnsw_index/graph_links/serializer.rs:50-54
Timestamp: 2025-08-22T13:49:39.261Z
Learning: In Qdrant's graph serialization code (lib/segment/src/index/hnsw_index/graph_links/serializer.rs), the team prefers to keep the code simple rather than adding defensive input validation for edge cases that don't occur in practice, relying on unit tests to catch any unexpected issues early.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-10T18:30:02.986Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-14T11:31:21.777Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-05-19T09:25:54.285Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6546
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:497-518
Timestamp: 2025-05-19T09:25:54.285Z
Learning: In the Qdrant project, using `.expect()` and `.unwrap()` is considered acceptable in test code since test failures should be loud and obvious, and proper error propagation adds unnecessary complexity to test code.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-05-08T16:39:07.893Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6501
File: lib/segment/src/index/hnsw_index/links_container.rs:158-158
Timestamp: 2025-05-08T16:39:07.893Z
Learning: In the Qdrant codebase, allocation failures are generally not handled (allowed to panic) except in very few specific cases. Most `unwrap()` calls on allocation operations are intentional.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-06-14T20:35:10.603Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6635
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:784-832
Timestamp: 2025-06-14T20:35:10.603Z
Learning: Functions gated with `#[cfg(feature = "testing")]` within `#[cfg(test)]` modules are safe from compilation issues since both the function and its call sites are restricted to test builds. The additional feature gate is often used for optional heavy test utilities.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-04-29T16:48:34.967Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 6446
File: lib/gridstore/benches/flush_bench.rs:18-18
Timestamp: 2025-04-29T16:48:34.967Z
Learning: The Rust rand crate version 0.9+ has introduced a top-level `rng()` function that replaces the now-deprecated `thread_rng()` function.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: Don't report issues related to `.unwrap()` and `panic!()` usage in Rust tests and benchmarks
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: For Rust code review, checking whether code compiles is out of scope, including: missing imports for `size_of` or `align_of` (included in Rust 1.80+ prelude), methods not implemented for types, different method names across `rand` crate versions (e.g., `random_range` vs `gen_range`), and other compiler errors or warnings
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-04-20T19:08:45.034Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6403
File: lib/collection/src/collection_manager/holders/proxy_segment.rs:1178-1197
Timestamp: 2025-04-20T19:08:45.034Z
Learning: In the ProxySegment implementation, overwriting previous index changes when inserting a DeleteIfIncompatible operation is intentional. When an incompatible index is detected, the DeleteIfIncompatible operation should take precedence over any previously scheduled operations on that index.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-11T07:57:01.399Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:81-84
Timestamp: 2025-08-11T07:57:01.399Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the BitsStoreType parameter difference between single-vector and multi-vector Binary quantization is intentional: single-vector storage uses `EncodedVectorsBin<u128, ...>` to enable 128-bit SIMD/popcount optimizations for longer vectors, while multi-vector storage uses `EncodedVectorsBin<u8, ...>` because multivectors are typically shorter and benefit from byte-granular storage.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-10T18:31:56.855Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/point_ops.rs:501-528
Timestamp: 2025-08-10T18:31:56.855Z
Learning: In Qdrant, batch operations validate that `ids`, `vectors`, and `payloads` (if present) have matching lengths at the REST API level in `lib/api/src/rest/validate.rs` through the `Validate` trait implementation for `Batch`. This validation happens before data is converted to internal structures like `PointInsertOperationsInternal`, so methods operating on these internal structures can safely assume the lengths match.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
🧬 Code graph analysis (7)
lib/collection/src/update_handler.rs (1)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
new(983-993)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
lib/common/common/src/flags.rs (1)
feature_flags(130-138)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)
lib/collection/src/update_workers/optimization_worker.rs (3)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (3)
scheduled(1005-1007)new(983-993)name(59-59)lib/collection/src/shards/shard.rs (1)
optimizers_log(239-249)lib/collection/src/collection_manager/optimizers/mod.rs (1)
start(112-124)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (3)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (2)
plan_optimizations(116-166)new(59-80)lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (2)
plan_optimizations(156-222)new(38-59)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
plan_optimizations(154-171)new(40-63)
lib/shard/src/segment_holder/mod.rs (2)
lib/segment/src/segment/entry.rs (1)
point_version(51-56)lib/shard/src/proxy_segment/segment_entry.rs (1)
point_version(38-55)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (4)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (2)
plan_optimizations(83-83)new(983-993)lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
plan_optimizations(206-225)new(35-54)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
plan_optimizations(154-171)new(40-63)lib/collection/src/collection_manager/fixtures.rs (1)
get_merge_optimizer(225-250)
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (2)
lib/segment/src/index/field_index/field_index_base.rs (1)
is_on_disk(413-427)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: Test Python bindings
- GitHub Check: lint
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: e2e-tests
- GitHub Check: integration-tests-consensus
- GitHub Check: test-consensus-compose
- GitHub Check: test-consistency
- GitHub Check: integration-tests
- GitHub Check: test-shard-snapshot-api-s3-minio
🔇 Additional comments (29)
lib/common/common/src/process_counter.rs (2)
1-39: LGTM! Clever use of Arc strong_count for reference-counted process tracking.The design elegantly leverages
Arc's reference counting to provide automatic decrement-on-drop semantics. Thesaturating_sub(1)correctly excludes the base reference, and the deliberate&mut selfoninc()prevents accidental calls from read guards.
41-69: Good test coverage including panic-path verification.The test properly validates that handles are dropped even during panics via
catch_unwind, ensuring the counter remains accurate in all scenarios.lib/common/common/src/lib.rs (1)
23-23: LGTM!Module export correctly placed in alphabetical order.
lib/shard/src/segment_holder/mod.rs (3)
79-81: LGTM! ProcessCounter field for tracking running optimizations.This enables the planner to make capacity-aware scheduling decisions based on currently running optimizations.
98-111: LGTM! Good use of explicit match arms.The
iter_original()method correctly uses explicit pattern matching forLockedSegment::OriginalandLockedSegment::Proxyvariants rather than a catch-all_, ensuring compile-time safety if new variants are added. As per coding guidelines, this is the preferred approach.
388-428: LGTM! Mechanical updates for owned SegmentId.The changes in
find_points_to_update_and_deletecorrectly adapt to using ownedSegmentIdvalues from the updatediter()signature.lib/collection/src/update_handler.rs (1)
294-309: Verify: Planner accumulates schedules across all optimizers in this check.The
any()iterator will short-circuit on the first optimizer that schedules work, but sinceplan_optimizationsmutates the shared planner, thescheduled()check includes all previously scheduled batches. This appears intentional for checking if any optimizer has pending work, but worth confirming this is the desired behavior versus checking each optimizer independently.lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (4)
154-171: LGTM! Clean planner-based vacuum optimization.The implementation correctly:
- Iterates remaining segments from the planner
- Calculates littered ratios (point-level and vector-index-level)
- Sorts by worst ratio descending to prioritize most fragmented segments
- Plans each segment individually, which is appropriate for vacuum optimization
The use of
sorted_by_key(|(_, ratio)| OrderedFloat(-ratio))for descending order is idiomatic.
68-118: LGTM! Cleaner API with direct Segment references.The helper methods now accept
&Segmentdirectly instead of locked segments, simplifying the interface. The caller (plan_optimizations) handles the read lock, and the ratio calculation logic remains unchanged.
304-306: LGTM! Test correctly adapted to planner-based API.The test now uses
plan_optimizations_for_testandexactly_one()to extract the single expected optimization batch.
486-491: LGTM! Correct use of iter_original() for finding segments.Using
iter_original()is appropriate here since the test needs direct access to non-proxy segments.lib/collection/src/update_workers/optimization_worker.rs (3)
269-280: Planner initialization and population looks correct.The planner is created with the current running optimization count and original segments, then each optimizer contributes its planned optimizations. This two-phase approach (plan then execute) aligns with the PR's goal of decoupling planning from execution.
318-321: Early break with callback invocation for budget exhaustion is appropriate.When no IO permit is available and there are no running handles, invoking the callback ensures the worker will be awakened to retry later. This prevents optimization stalls.
349-412: Optimization task spawning logic is well-structured.The panic handling with
catch_unwind, status tracking viaTracker, and proper error propagation toreport_optimizer_errorare all correctly implemented. The callback pattern ensures subsequent optimizations can be triggered.lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
84-149: Dense vector mismatch detection logic is comprehensive.The logic correctly checks for HNSW config mismatches, on_disk storage mismatches, and quantization config mismatches including the appendable quantization feature flag handling. The explicit
Indexes::Plain {}andIndexes::Hnsw(effective_hnsw)match arms follow the coding guideline for explicit exhaustive matches.
206-225: Plan optimizations implementation is clean and follows the pattern.Segments are filtered by mismatch, sorted by largest vector size first (using
Reverse), and each is planned individually. This aligns with the config mismatch optimizer's purpose of handling segments one at a time.lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (3)
17-44: Excellent documentation of the merge batching strategy.The ASCII art and examples clearly explain the algorithm's goals: guarantee segment count reduction by either merging 3+ segments in one batch or having at least two batches. This documentation will help future maintainers understand the rationale.
116-165: Merge planning algorithm is well-implemented.The greedy batching approach sorts candidates by size, accumulates batches under the threshold, and correctly handles the first_batch deferral to guarantee segment count reduction. The algorithm matches the documentation.
307-344: Comprehensive test table provides excellent coverage.The test cases cover various combinations of
default_segments_numberandmax_segment_size_kb, validating batch formation and size calculations. The human-readable format (10+11+12+13 =46) makes test failures easy to diagnose.lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (4)
61-120: Well-structured optimization requirement check.The
is_optimization_requiredmethod cleanly separates the indexing decision logic. It correctly checks both dense and sparse vectors against thresholds, respecting expliciton_diskconfiguration over automatic threshold-based decisions.
156-177: Segment classification into indexed/unindexed queues is correct.Segments are correctly categorized: unindexed if they require optimization, indexed if they have any vector indexed or on disk. Note that a segment can appear in both queues (unindexed for one vector, indexed for another), which the algorithm handles via the
remaining()containment check.
182-221: Segment pairing logic correctly maintains segment count.The algorithm pairs the largest unindexed segment with the smallest unindexed/indexed segment when under the size threshold, helping maintain the target segment count. The staleness checks via
planner.remaining().contains_key()prevent planning segments that were already scheduled in previous iterations.
200-207: Consider:unindexed.pop_front()should be inside the if-block guard.The code correctly pops from
unindexedonly after confirming the segment is still inremaining. This is a subtle but important detail for correctness.lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (6)
82-83: Trait method signature change is well-designed.The new
plan_optimizations(&self, planner: &mut OptimizationPlanner)signature enables the planner-driven workflow where all optimizers contribute to a shared plan before execution begins.
85-119: Test wrapper provides valuable consistency verification.The
plan_optimizations_for_testwrapper verifies that incremental planning (re-planning after each batch is removed) produces the same tail results. The special case for MergeOptimizer's[A B] [C D]pattern is correctly documented. This helps catch algorithmic regressions.
384-401: unwrap_proxy signature change is appropriate.The method no longer returns segment IDs since callers already have the proxy IDs. The simplification is clean.
734-738: Counter handler lifecycle ensures accurate running optimization tracking.The counter is incremented immediately after proxy insertion and decremented (via
drop(counter_handler)) after the optimized segment is swapped in at line 765. This accurately tracks the period when proxies are active.
962-1037: OptimizationPlanner implementation is clean and correct.The struct correctly tracks:
remaining: segments available for schedulingscheduled: planned optimizations with attached optimizerrunning: count of in-flight optimizations for segment count estimationThe
plan()method correctly removes segments fromremainingand thedebug_assert!calls validate invariants without impacting release builds. Per coding guidelines,debug_assert!is preferred for production stability.
1028-1036: The plan method correctly maintains invariants.Each segment ID is removed from
remainingbefore being added toscheduled. The debug assertions validate that segments aren't planned twice and that batches are non-empty.
It's `segment_id`/`_segment_id`, not `idx`/`sid`/`x.0`/`_`.
be92cbf to
9ae95d0
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
lib/collection/src/update_workers/optimization_worker.rs (1)
282-286: Silent skip in release mode for None optimizer.The
debug_assert!(false)will only trigger in debug builds. In release, aNoneoptimizer silently skips the batch. Consider logging a warning for visibility in production, or usedebug_assert!with a message.♻️ Suggested improvement
for (optimizer, segments_to_merge) in scheduled { let Some(optimizer) = optimizer else { - debug_assert!(false); + debug_assert!(false, "scheduled optimization missing optimizer reference"); + log::warn!("Skipping scheduled optimization batch: missing optimizer reference"); continue; };
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/update_handler.rslib/collection/src/update_workers/optimization_worker.rslib/common/common/src/lib.rslib/common/common/src/process_counter.rslib/shard/src/segment_holder/mod.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit inference engine (.github/review-rules.md)
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust
In new code, don't usetransmute_from_u8,transmute_to_u8,transmute_from_u8_to_slice,transmute_from_u8_to_mut_slice,transmute_to_u8_slice- usebytemuckorzerocopycrates instead
Prefer explicit exhaustive matches over catch-all_arm in Rust match expressions, so we don't miss handling new enum variants when they are added later (exceptions: tests and benchmarks, or when sure new variants won't affect logic)
Prefer explicit field ignoring using: _over using..in Rust struct destructuring (exceptions: tests and benchmarks, or when sure new fields won't affect logic)
Files:
lib/collection/src/update_handler.rslib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/shard/src/segment_holder/mod.rslib/common/common/src/process_counter.rslib/common/common/src/lib.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
🧠 Learnings (30)
📓 Common learnings
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
📚 Learning: 2025-08-20T15:03:18.522Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7100
File: lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs:82-100
Timestamp: 2025-08-20T15:03:18.522Z
Learning: The merge_postings_iterator function in lib/segment/src/index/field_index/full_text_index/inverted_index/postings_iterator.rs handles deduplication internally, so there's no need to add .dedup() when using it for OR-merge operations in inverted indexes.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-07-11T11:35:21.549Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6854
File: lib/segment/src/index/query_estimator.rs:320-327
Timestamp: 2025-07-11T11:35:21.549Z
Learning: In test code for Qdrant's query estimator (lib/segment/src/index/query_estimator.rs), simplified ID resolution logic using `id.to_string().parse().unwrap()` is acceptable for testing purposes and doesn't need to match production code's `id_tracker.internal_id()` approach. Test code can use mock implementations that serve the testing goals.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-15T11:42:00.297Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs:86-90
Timestamp: 2025-08-15T11:42:00.297Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_mmap_storage.rs, overflow protection for encoded_storage_size computation (quantized_vector_size * vectors_count) is implemented in PR #7048, using checked_mul with u64 casting to prevent silent overflow.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-09-01T11:19:26.371Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7193
File: lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs:17-30
Timestamp: 2025-09-01T11:19:26.371Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_chunked_mmap_storage.rs, the ChunkedMmapVectors underlying implementation does not validate against zero-sized vectors, so adding such validation in QuantizedChunkedMmapStorage::new is unnecessary and would be redundant.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-06-14T20:35:10.603Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6635
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:784-832
Timestamp: 2025-06-14T20:35:10.603Z
Learning: Functions gated with `#[cfg(feature = "testing")]` within `#[cfg(test)]` modules are safe from compilation issues since both the function and its call sites are restricted to test builds. The additional feature gate is often used for optional heavy test utilities.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-04-29T16:48:34.967Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 6446
File: lib/gridstore/benches/flush_bench.rs:18-18
Timestamp: 2025-04-29T16:48:34.967Z
Learning: The Rust rand crate version 0.9+ has introduced a top-level `rng()` function that replaces the now-deprecated `thread_rng()` function.
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: Don't report issues related to `.unwrap()` and `panic!()` usage in Rust tests and benchmarks
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs
📚 Learning: 2025-11-25T11:56:33.176Z
Learnt from: CR
Repo: qdrant/qdrant PR: 0
File: .github/review-rules.md:0-0
Timestamp: 2025-11-25T11:56:33.176Z
Learning: For Rust code review, checking whether code compiles is out of scope, including: missing imports for `size_of` or `align_of` (included in Rust 1.80+ prelude), methods not implemented for types, different method names across `rand` crate versions (e.g., `random_range` vs `gen_range`), and other compiler errors or warnings
Applied to files:
lib/collection/src/collection_manager/optimizers/merge_optimizer.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-10-13T22:58:03.121Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7400
File: lib/segment/src/id_tracker/simple_id_tracker.rs:234-241
Timestamp: 2025-10-13T22:58:03.121Z
Learning: SimpleIdTracker in lib/segment/src/id_tracker/simple_id_tracker.rs is being deprecated and should not receive fixes related to version tracking or recovery logic, as it has a different version storage structure that is incompatible with newer trackers.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-15T11:41:10.629Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:857-857
Timestamp: 2025-08-15T11:41:10.629Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the multivector offset storage has two different patterns: for RAM storage, offsets are collected into Vec<MultivectorOffset> and used directly; for MMAP storage, offsets are consumed to create a file via create_offsets_file_from_iter, then the file is loaded back as MultivectorOffsetsStorageMmap. The direct consumption of offsets iterator in the MMAP case is intentional.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-09-01T11:42:06.964Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7157
File: lib/shard/src/segment_holder/mod.rs:808-814
Timestamp: 2025-09-01T11:42:06.964Z
Learning: In Qdrant's segment holder, panicking when no segments exist during flush_all is intentional and preferred over graceful error handling, as having zero segments could permanently corrupt the WAL by acknowledging u64::MAX. The maintainers consider this condition impossible and use the panic as a fail-fast safety mechanism to prevent data corruption.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-10T18:30:02.986Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/verification/update.rs:158-174
Timestamp: 2025-08-10T18:30:02.986Z
Learning: In Qdrant's strict mode verification code (lib/collection/src/operations/verification/update.rs), exhaustive pattern matching without `..` is intentionally used for structs like PointsBatch and PointsList. This design pattern ensures compilation fails when new fields are added, forcing developers to explicitly consider how new fields should be handled in the indexed_filter_write method. This provides visibility and compile-time safety for struct evolution.
Applied to files:
lib/shard/src/segment_holder/mod.rslib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-04-20T19:08:45.034Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6403
File: lib/collection/src/collection_manager/holders/proxy_segment.rs:1178-1197
Timestamp: 2025-04-20T19:08:45.034Z
Learning: In the ProxySegment implementation, overwriting previous index changes when inserting a DeleteIfIncompatible operation is intentional. When an incompatible index is detected, the DeleteIfIncompatible operation should take precedence over any previously scheduled operations on that index.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-14T11:31:21.777Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7048
File: lib/quantization/src/encoded_storage.rs:61-79
Timestamp: 2025-08-14T11:31:21.777Z
Learning: In test storage implementations (like TestEncodedStorage in lib/quantization/src/encoded_storage.rs), IvanPleshkov prefers to keep the code simple rather than adding complex overflow protection, since test storage is not used in production and can be allowed to panic on edge cases.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-11-18T18:20:20.021Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7520
File: lib/quantization/src/p_square.rs:41-49
Timestamp: 2025-11-18T18:20:20.021Z
Learning: In lib/quantization/src/p_square.rs, IvanPleshkov prefers using defensive double-checks (e.g., `let Ok(x) = NotNan::new(x) else { return; }`) over `.unwrap()` even when a prior check guarantees success, to avoid panic-causing code and maintain defensive programming practices.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-11T00:37:34.100Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs:46-55
Timestamp: 2025-08-11T00:37:34.100Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_ram_storage.rs`, the `ChunkedVectors` used in `QuantizedRamStorage` is intentionally designed to be non-persistent during updates. The `push_vector` method only updates the in-memory vectors without flushing to disk, and this is expected behavior rather than a bug.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-11T07:57:01.399Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 6986
File: lib/segment/src/vector_storage/quantized/quantized_vectors.rs:81-84
Timestamp: 2025-08-11T07:57:01.399Z
Learning: In `lib/segment/src/vector_storage/quantized/quantized_vectors.rs`, the BitsStoreType parameter difference between single-vector and multi-vector Binary quantization is intentional: single-vector storage uses `EncodedVectorsBin<u128, ...>` to enable 128-bit SIMD/popcount optimizations for longer vectors, while multi-vector storage uses `EncodedVectorsBin<u8, ...>` because multivectors are typically shorter and benefit from byte-granular storage.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rslib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-10T18:31:56.855Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: lib/collection/src/operations/point_ops.rs:501-528
Timestamp: 2025-08-10T18:31:56.855Z
Learning: In Qdrant, batch operations validate that `ids`, `vectors`, and `payloads` (if present) have matching lengths at the REST API level in `lib/api/src/rest/validate.rs` through the `Validate` trait implementation for `Batch`. This validation happens before data is converted to internal structures like `PointInsertOperationsInternal`, so methods operating on these internal structures can safely assume the lengths match.
Applied to files:
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs
📚 Learning: 2025-08-18T10:56:43.707Z
Learnt from: IvanPleshkov
Repo: qdrant/qdrant PR: 7043
File: lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs:340-347
Timestamp: 2025-08-18T10:56:43.707Z
Learning: In lib/segment/src/vector_storage/quantized/quantized_multivector_storage.rs, the create_offsets_file_from_iter function intentionally requires paths to have a parent directory and returns an error if path.parent() is None. This was a conscious design decision to ensure proper path validation.
Applied to files:
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-08-06T09:56:59.311Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6982
File: lib/segment/src/index/hnsw_index/graph_links/view.rs:217-220
Timestamp: 2025-08-06T09:56:59.311Z
Learning: In Qdrant's GraphLinksView implementation (lib/segment/src/index/hnsw_index/graph_links/view.rs), methods like links() and links_with_vectors() intentionally use unwrap() and can panic for performance reasons, maintaining consistency across similar methods. Error handling improvements are considered secondary to feature completion and require benchmarking before implementation.
Applied to files:
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rslib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-06-06T07:52:38.478Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6644
File: lib/gridstore/src/blob.rs:41-57
Timestamp: 2025-06-06T07:52:38.478Z
Learning: In the Blob trait implementations for gridstore (lib/gridstore/src/blob.rs), the maintainer prefers using assert! for input validation over Result-based error handling, as they don't expect invalid inputs in real scenarios and changing to Result would require updating the entire trait interface.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-03-29T17:43:28.174Z
Learnt from: generall
Repo: qdrant/qdrant PR: 6274
File: lib/segment/src/vector_storage/sparse/mmap_sparse_vector_storage.rs:233-233
Timestamp: 2025-03-29T17:43:28.174Z
Learning: In the qdrant codebase, `debug_assert!` is preferred over runtime checks that would panic in release builds to ensure production stability, even when validating conditions like vector sorting.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-11-14T10:01:31.926Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 7526
File: src/wal_pop.rs:7-8
Timestamp: 2025-11-14T10:01:31.926Z
Learning: In the Qdrant codebase, development binaries (like src/wal_pop.rs) don't require explicit bounds checking for command-line arguments. Rust's built-in out-of-bounds panic is acceptable for these development tools.
Applied to files:
lib/collection/src/update_workers/optimization_worker.rslib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-10-16T13:00:46.809Z
Learnt from: coszio
Repo: qdrant/qdrant PR: 7368
File: lib/shard/src/query/mod.rs:313-341
Timestamp: 2025-10-16T13:00:46.809Z
Learning: In the Qdrant codebase, for the `Feedback` query variant in `lib/shard/src/query/mod.rs`, validation for sparse vectors should happen down the line rather than early in the `query_enum_from_grpc_raw_query` function. The `Nearest` variant is treated as a special case where early validation with better error messages is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-10T18:26:12.443Z
Learnt from: generall
Repo: qdrant/qdrant PR: 7006
File: docs/redoc/master/openapi.json:13645-13652
Timestamp: 2025-08-10T18:26:12.443Z
Learning: In qdrant, docs/redoc/master/openapi.json is auto-generated from the REST schemas. To change field docs, edit lib/api/src/rest/schema.rs (e.g., add doc comments or #[schemars(description = ...)]). Specifically, UpdateVectors.update_filter lacked a description and should state: "If specified, only update vectors for points that match this filter; points not matching the filter are left unchanged."
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-09-16T21:39:09.353Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7232
File: lib/shard/src/segment_holder/mod.rs:1088-1094
Timestamp: 2025-09-16T21:39:09.353Z
Learning: The hnsw_format_force and hnsw_with_vectors flags in HnswGlobalConfig primarily affect existing segment conversion during load/startup, not the initial format selection for newly created empty segments. For new segments, format decisions are made by GraphLinksFormatParam::recommended() based on runtime conditions. Therefore, using HnswGlobalConfig::default() for temporary/proxy segments in SegmentHolder::build_tmp_segment is acceptable.
Applied to files:
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs
📚 Learning: 2025-08-22T13:49:39.261Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 7118
File: lib/segment/src/index/hnsw_index/graph_links/serializer.rs:50-54
Timestamp: 2025-08-22T13:49:39.261Z
Learning: In Qdrant's graph serialization code (lib/segment/src/index/hnsw_index/graph_links/serializer.rs), the team prefers to keep the code simple rather than adding defensive input validation for edge cases that don't occur in practice, relying on unit tests to catch any unexpected issues early.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-05-19T09:25:54.285Z
Learnt from: timvisee
Repo: qdrant/qdrant PR: 6546
File: lib/segment/src/index/field_index/full_text_index/text_index.rs:497-518
Timestamp: 2025-05-19T09:25:54.285Z
Learning: In the Qdrant project, using `.expect()` and `.unwrap()` is considered acceptable in test code since test failures should be loud and obvious, and proper error propagation adds unnecessary complexity to test code.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
📚 Learning: 2025-05-08T16:39:07.893Z
Learnt from: xzfc
Repo: qdrant/qdrant PR: 6501
File: lib/segment/src/index/hnsw_index/links_container.rs:158-158
Timestamp: 2025-05-08T16:39:07.893Z
Learning: In the Qdrant codebase, allocation failures are generally not handled (allowed to panic) except in very few specific cases. Most `unwrap()` calls on allocation operations are intentional.
Applied to files:
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs
🧬 Code graph analysis (5)
lib/collection/src/update_handler.rs (1)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
new(983-993)
lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (3)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (1)
plan_optimizations(156-222)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
plan_optimizations(154-171)
lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (3)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (2)
plan_optimizations(83-83)new(983-993)lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (2)
plan_optimizations(207-226)new(35-54)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (2)
plan_optimizations(154-171)new(40-63)
lib/collection/src/update_workers/optimization_worker.rs (7)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (3)
scheduled(1005-1007)new(983-993)name(59-59)lib/collection/src/shards/local_shard/mod.rs (4)
segments(278-280)new(191-276)new(1099-1104)optimizers_log(964-966)lib/collection/src/update_handler.rs (1)
new(129-172)lib/segment/src/index/hnsw_index/mod.rs (1)
num_rayon_threads(74-81)lib/collection/src/shards/replica_set/mod.rs (1)
optimizers_log(1309-1312)lib/collection/src/shards/shard.rs (1)
optimizers_log(239-249)lib/collection/src/collection_manager/optimizers/mod.rs (2)
start(112-124)handle(127-129)
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (3)
lib/common/common/src/flags.rs (1)
feature_flags(130-138)lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
plan_optimizations(83-83)lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (1)
plan_optimizations(154-171)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: e2e-tests
- GitHub Check: integration-tests-consensus
- GitHub Check: lint
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: test-consensus-compose
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: test-consistency
- GitHub Check: integration-tests
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: Test Python bindings
🔇 Additional comments (40)
lib/common/common/src/lib.rs (1)
23-23: LGTM!The new
process_countermodule is properly added in alphabetical order.lib/common/common/src/process_counter.rs (2)
1-39: LGTM! Clean reference-counting implementation.The design using
Arcstrong count for automatic decrement on drop is elegant. Good defensive choices:
- No
Cloneon either type to prevent counting errors#[must_use]onCountedProcessHandleto catch accidental immediate drops&mut selfoninc()to prevent calling fromRwLockReadGuard
41-69: Good test coverage including panic unwinding.The test properly verifies that
CountedProcessHandledecrements the counter even when dropped during a panic, which is critical for correctness in error scenarios.lib/shard/src/segment_holder/mod.rs (5)
19-19: LGTM!Import added for the new
ProcessCountertype used in therunning_optimizationsfield.
79-81: LGTM!The
running_optimizationscounter is appropriately added as a public field, consistent with other public fields inSegmentHolder. TheProcessCountertype ensures proper tracking with automatic decrement on drop.
98-103: LGTM!Returning owned
SegmentId(which isusize, aCopytype) simplifies caller code by eliminating the need to dereference.
105-111: LGTM!The
iter_original()method cleanly provides access to non-proxy segments for the optimization planner. Good use of explicit pattern matching onLockedSegmentvariants rather than a catch-all, per coding guidelines.
400-426: LGTM!Internal usages correctly updated to use the owned
SegmentIdreturned byiter().lib/collection/src/update_handler.rs (2)
18-20: LGTM!Import updated to include
OptimizationPlannerfor the new planner-based flow.
298-306: LGTM! Clean transition to planner-based optimization checking.The implementation correctly:
- Initializes the planner with running optimization count and original segments
- Lets each optimizer populate the planner via
plan_optimizations- Determines suboptimality by checking if any optimizations were scheduled
This aligns well with the PR's goal of decoupling planning from execution.
lib/collection/src/collection_manager/optimizers/vacuum_optimizer.rs (7)
4-4: LGTM!
Itertoolsimport added forsorted_by_key()andcollect_vec()used inplan_optimizations.
68-75: LGTM!Parameter type changed to concrete
&Segmentto align with the planner-based flow that works directly withSegmentreferences.
86-118: LGTM!Method updated to work with
&Segmentdirectly, enabling direct access tosegment.config()andsegment.vector_datafor the littered ratio calculations.
154-171: LGTM! Clean implementation of the planner-based flow.The vacuum optimizer correctly:
- Evaluates all remaining segments for littered ratios
- Sorts by descending ratio (worst segments first)
- Plans each qualifying segment individually (vacuum rebuilds one segment at a time)
The use of
sorted_by_key(|(_, ratio)| OrderedFloat(-ratio))ensures the worst (highest littered ratio) segments are prioritized.
304-305: LGTM!Test updated to use
plan_optimizations_for_testhelper, which aligns with the new planner-based API.
486-491: LGTM!Test correctly uses
iter_original()to find the segment with points, which is appropriate since we need directSegmentaccess to checktotal_point_count().
556-557: LGTM!Test assertions updated to use
iter_original()for directSegmentaccess.lib/collection/src/update_workers/optimization_worker.rs (4)
269-280: LGTM! Clean planner initialization and population.The planner is correctly initialized with the current running optimization count and original segments. Each optimizer is properly set before calling
plan_optimizations, ensuring the scheduled batches are tagged with the correct optimizer reference.
288-298: LGTM! Proper limit enforcement and failure handling.The limit check correctly bounds optimization jobs, and the failure flag prevents cascading optimization attempts on error.
310-322: LGTM! Resource budget handling is robust.The permit acquisition correctly breaks the loop when budget is exhausted, and the callback mechanism ensures the optimization worker retries later when no optimizations are in progress.
349-412: LGTM! Comprehensive task spawning with robust error handling.The stoppable task correctly handles all outcomes: success, cancellation, errors, and panics. The tracker status is properly updated in all cases, and errors are propagated to the segment holder.
lib/collection/src/collection_manager/optimizers/config_mismatch_optimizer.rs (5)
74-81: LGTM! Payload storage mismatch detection.Correctly identifies payload storage type mismatches between collection config and segment config.
130-148: Complex quantization mismatch logic - verify edge cases.The logic for determining quantization rebuild is intricate, especially the
unindexed_changedcheck involving theappendable_quantizationfeature flag. The condition combines multiple boolean states which may be hard to reason about.Consider adding a comment explaining when this branch triggers:
// Rebuild if quantization enabled state changed AND // (segment is indexed OR appendable quantization is involved)
151-171: LGTM! Sparse vector mismatch detection is clear.The match expression correctly handles all
SparseIndexTypevariants with explicit rebuild conditions for on-disk configuration changes.
207-226: LGTM! Clean planner integration with priority ordering.Segments are correctly filtered, sorted by size (largest first), and planned individually. The implementation aligns with the expected planner-based workflow.
356-370: LGTM! Test updates correctly use the new planner API.Tests properly use
plan_optimizations_for_testandexactly_one()for assertions on single-batch results.lib/collection/src/collection_manager/optimizers/merge_optimizer.rs (4)
17-44: LGTM! Excellent documentation with clear examples.The ASCII diagram effectively illustrates the batching strategy and the segment count reduction guarantee. The examples clarify the "at least 3 segments OR at least 2 batches" rule.
307-344: LGTM! Comprehensive test table with excellent coverage.The test table covers various combinations of
default_segment_numberandmax_segment_size, including edge cases where no merging should occur. The expected output format clearly shows batch composition and sums.
346-380: LGTM! Well-structured table-driven test.The test uses seeded randomization for reproducibility and validates batch compositions against expected strings. This effectively tests the batching algorithm across many scenarios.
135-165: Last_candidate calculation and batching logic are correct.The calculation
(planner.expected_segments_number() + 2).saturating_sub(self.default_segments_number)creates an initial search window that expands by 1 each iteration (line 153), allowing the optimizer to progressively consider more candidates. This strategy balances merge planning with computational efficiency.The first-batch hold mechanism (lines 154-160) correctly guarantees segment reduction by requiring at least two batches before committing any merges. The comprehensive TEST_TABLE validates this logic across 27 different configurations with varying
default_segments_number(1–12) andmax_segment_size_kb(5–233), confirming expected merge plans for each case.lib/collection/src/collection_manager/optimizers/indexing_optimizer.rs (4)
61-120: LGTM! Well-structured optimization requirement check.The
is_optimization_requiredmethod cleanly separates dense and sparse vector checks, with clear threshold comparisons for indexing and mmap requirements.
156-221: LGTM! Clever pairing strategy for segment count preservation.The implementation smartly pairs the largest unindexed segment with either the smallest unindexed or smallest indexed segment when size constraints allow, maintaining the expected segment count. The VecDeque usage enables efficient front/back access.
269-274: LGTM! Clean test helper for order-independent comparison.The
normalizefunction ensures tests don't fail due to arbitrary ordering within batches.
440-471: LGTM! Test assertions updated for planner-based API.Tests correctly use
normalize()for multi-batch comparisons and verify expected segment groupings.lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (6)
82-84: LGTM! Clean trait method signature for planner-based optimization.The new
plan_optimizationsmethod signature properly accepts a mutable reference to the planner, allowing implementations to schedule batches.
85-119: Excellent consistency verification in test helper.The
plan_optimizations_for_testwrapper validates that incremental planning produces consistent results. The special case for the merge optimizer correctly handles the documented "2-segment batch requires a second batch" rule.
384-401: LGTM! Simplified unwrap_proxy signature.Changing the return type to
()removes unused return values and simplifies the API.
734-738: LGTM! Proper RAII counter management.The
counter_handlercorrectly brackets the optimization period: incremented when proxies are inserted, decremented (via drop) after the optimized segment replaces them. This enables accurateexpected_segments_number()calculations.
962-1037: LGTM! Well-designed OptimizationPlanner with clear semantics.The planner cleanly separates segment selection from optimization execution. Key design choices:
BTreeMapfor deterministic iteration orderdebug_assertguards validate invariants without runtime cost in releaseexpected_segments_number()enables optimizers to reason about final segment count
1028-1036: LGTM! Clean plan() implementation with proper invariant checks.The
debug_assertguards ensure segments are non-empty and exist inremainingbefore removal, catching logic errors during development.
* refactor(SegmentHolder::iter): use SegmentId, not &SegmentId * refactor(SegmentHolder): Add SegmentHolder::iter_original * refactor: inline *Optimizer::worst_segment() into SegmentOptimizer::check_condition * refactor(ConfigMismatchOptimizer): extract config_mismatch function * Fix comments * refactor: consistent variable naming It's `segment_id`/`_segment_id`, not `idx`/`sid`/`x.0`/`_`. * refactor(IndexingOptimizer): extract large chunks of logic * refactor(SegmentOptimizer): simplify unwrap_proxy/handle_cancellation * SegmentHolder: add running_optimizations counter * OptimizationPlanner * MergeOptimizer: allow merging two segments, update doc
This PR refactors optimizers to let them write the full optimization plan before performing any optimization. In subsequent PR this plan will be used to estimate amount of points to be indexed.
Before this PR:
SegmentOptimizer::check_condition()returns a single batch of segments to optimize. (aka the worst batch)UpdateWorkers::launch_optimization()callscheck_conditionin two nested loops and schedules optimization immediately.In this PR:
SegmentOptimizer::check_condition()is replaced withSegmentOptimizer::plan_optimizations(). It returns all possible batches of segments to optimize, not just the first one.UpdateWorkers::launch_optimization()works in two stages: first make plan, then launch optimizations.In pseudo-code, before this PR:
In this PR:
Commits
First 7 commits are preparation refactoring: minor fixes, renames and code moves. No changes in logic.
This is the main part.
This tweaks
MergeOptimizerto be more efficient.The goal of
MergeOptimizeris not changed: it should guerantee that optimizing will decrease overall segment count.Old approach: merge at least three segments into one.
New approach: merge at least three segments OR merge at least two batches (merge 4 segments into 2 segments).
This would help us predict more than one step ahead; and also should trigger parallel optimizations earlier.