Skip to content

Expose planned optimizations in API - #7784

Merged
xzfc merged 2 commits into
devfrom
report-pending-optimizers-api
Jan 15, 2026
Merged

xzfc merged 2 commits into
devfrom
report-pending-optimizers-api

Conversation

@xzfc

@xzfc xzfc commented Dec 15, 2025 •

Copy link
Copy Markdown
Member

Depends on #7752.

This PR exposes numerical stats about pending optimizations through HTTP API.

// GET /collections/{collection_name}/optimizations
{
  "ongoing": [/*…*/],
  "completed": [/*…*/],
  // ↓ new
  "pending": {
    "optimizations": 48,
    "segments": 49,
    "points": 597284
  }
}

Detailed representation (not in this PR)

Where these numbers come from? A debug representation could help answer this.

"pending": {
  "optimizations": 5,
  "segments": 8,
  "points": 58956,
  "debug": [
    "merge: [id=55 points=1400] [id=47 points=3576] [id=45 points=4460]",
    "merge: [id=50 points=5556] [id=54 points=6464]",
    "indexing: [id=53 points=12500]",
    "indexing: [id=52 points=12500]",
    "indexing: [id=49 points=12500]"
  ]
}

I'm not sure that such detailed info could be useful outside of testing/debugging OptimizationPlanner, so I'd keep it in a separate commit.

@xzfc
xzfc force-pushed the report-pending-optimizers-api branch from ea80c7e to 30a8423 Compare January 5, 2026 09:28
@xzfc
xzfc force-pushed the report-pending-optimizers branch 2 times, most recently from 09b6225 to c7f5732 Compare January 9, 2026 14:48
@xzfc
xzfc force-pushed the report-pending-optimizers-api branch 2 times, most recently from 4870de6 to 0d0acc7 Compare January 9, 2026 18:23
@xzfc
xzfc marked this pull request as ready for review January 9, 2026 18:27
@xzfc
xzfc force-pushed the report-pending-optimizers branch from c7f5732 to be92cbf Compare January 13, 2026 10:46
@xzfc
xzfc force-pushed the report-pending-optimizers-api branch from 0d0acc7 to fdc8162 Compare January 13, 2026 11:29
@xzfc
xzfc force-pushed the report-pending-optimizers branch from be92cbf to 9ae95d0 Compare January 13, 2026 11:29
Base automatically changed from report-pending-optimizers to dev January 13, 2026 12:09
@xzfc
xzfc force-pushed the report-pending-optimizers-api branch from fdc8162 to f608e87 Compare January 13, 2026 12:41
@coderabbitai

coderabbitai Bot commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new public PendingOptimizations struct (optimizations, segments, points) in operations types; adds a pending field (PendingOptimizations) to OptimizationsResponse and to TrackerLog; aggregation of per-shard pending counts in the collection optimizations endpoint by merging TrackerLog.pending entries; and populates TrackerLog.pending in the optimization worker when scheduling optimizations (summing scheduled optimizations, segment ids, and points).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • timvisee
  • generall
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Expose planned optimizations in API' directly reflects the main objective of the PR, which is adding a new 'pending' field to the optimizations API endpoint to expose planned optimization statistics.
Description check ✅ Passed The description clearly explains the purpose of the PR, provides a concrete example of the new API response format with the pending optimizations object, and discusses related considerations about detailed representations.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 514fb94 and 2799875.

📒 Files selected for processing (4)
  • docs/redoc/master/openapi.json
  • lib/collection/src/collection/collection_ops.rs
  • lib/collection/src/operations/types.rs
  • lib/collection/src/update_workers/optimization_worker.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/redoc/master/openapi.json
  • lib/collection/src/collection/collection_ops.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/review-rules.md)

**/*.rs: Prefer explicit SomeType::from(x) over implicit x.into() in Rust
In new code, don't use transmute_from_u8, transmute_to_u8, transmute_from_u8_to_slice, transmute_from_u8_to_mut_slice, transmute_to_u8_slice - use bytemuck or zerocopy crates 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_workers/optimization_worker.rs
  • lib/collection/src/operations/types.rs
🧠 Learnings (3)
📚 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/update_workers/optimization_worker.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/update_workers/optimization_worker.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/update_workers/optimization_worker.rs
🧬 Code graph analysis (2)
lib/collection/src/update_workers/optimization_worker.rs (2)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
  • scheduled (1005-1007)
lib/collection/src/shards/shard.rs (1)
  • optimizers_log (239-249)
lib/collection/src/operations/types.rs (1)
lib/collection/src/collection/collection_ops.rs (1)
  • optimizations (429-467)
⏰ 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: rust-tests (windows-latest)
  • GitHub Check: lint
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: integration-tests
  • GitHub Check: test-consistency
  • GitHub Check: e2e-tests
  • GitHub Check: test-consensus-compose
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: integration-tests-consensus
🔇 Additional comments (5)
lib/collection/src/operations/types.rs (3)

307-309: LGTM! Clean integration of pending optimizations into the API response.

The new pending field is properly added to OptimizationsResponse, providing visibility into scheduled but not-yet-started optimizations. This complements the existing ongoing and completed fields well.


311-322: Well-structured API type with clear documentation.

The PendingOptimizations struct appropriately captures the key metrics users need for estimating optimization workload. The derive macros are appropriate for a response-only type (no Deserialize needed).


324-335: Good use of explicit field destructuring in the merge method.

The pattern correctly follows the coding guideline to prefer explicit field handling over .., ensuring that adding new fields to PendingOptimizations will cause a compile error here, prompting developers to update the merge logic accordingly.

lib/collection/src/update_workers/optimization_worker.rs (2)

13-16: Imports correctly added for the new functionality.

SegmentEntry provides the available_point_count() method, and LockedSegment enables pattern matching to distinguish original segments from proxies.


271-300: Well-implemented pending optimization tracking.

The implementation correctly:

  1. Computes metrics within the segments read lock scope
  2. Only counts Original segments (appropriate since Proxy segments shouldn't contribute to pending stats)
  3. Updates optimizers_log.pending after releasing the segments lock

The if let pattern for LockedSegment::Original is intentional filtering rather than an incomplete match, which is appropriate here.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

324-335: Consider destructuring other for compile-time safety when new fields are added.

The self destructure is exhaustive (good), but other is accessed via field notation. If new fields are added to PendingOptimizations, the compiler will flag the self destructure but won't flag missing field merges from other. Based on learnings, this codebase values exhaustive matching for struct evolution safety.

♻️ Suggested refactor
 impl PendingOptimizations {
     pub fn merge(&mut self, other: &PendingOptimizations) {
         let PendingOptimizations {
-            optimizations,
-            segments,
-            points,
-        } = self;
-        *optimizations += other.optimizations;
-        *segments += other.segments;
-        *points += other.points;
+            optimizations: other_optimizations,
+            segments: other_segments,
+            points: other_points,
+        } = other;
+        self.optimizations += other_optimizations;
+        self.segments += other_segments;
+        self.points += other_points;
     }
 }
docs/redoc/master/openapi.json (1)

16483-16511: Clarify that these are approximate counts (and may change between calls).

The schema says “Estimation of pending optimizations” (Line 16484). Consider explicitly stating (in the source schema docs) that these values are best-effort/approximate and can fluctuate as optimizers reschedule or segment states change, so clients don’t treat them as strict counters. Based on learnings.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4ca865 and f608e87.

📒 Files selected for processing (5)
  • docs/redoc/master/openapi.json
  • lib/collection/src/collection/collection_ops.rs
  • lib/collection/src/collection_manager/optimizers/mod.rs
  • lib/collection/src/operations/types.rs
  • lib/collection/src/update_workers/optimization_worker.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/review-rules.md)

**/*.rs: Prefer explicit SomeType::from(x) over implicit x.into() in Rust
In new code, don't use transmute_from_u8, transmute_to_u8, transmute_from_u8_to_slice, transmute_from_u8_to_mut_slice, transmute_to_u8_slice - use bytemuck or zerocopy crates 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/operations/types.rs
  • lib/collection/src/collection/collection_ops.rs
  • lib/collection/src/update_workers/optimization_worker.rs
  • lib/collection/src/collection_manager/optimizers/mod.rs
🧠 Learnings (6)
📚 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/operations/types.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:

  • docs/redoc/master/openapi.json
📚 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/update_workers/optimization_worker.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/update_workers/optimization_worker.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/mod.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/mod.rs
🧬 Code graph analysis (2)
lib/collection/src/operations/types.rs (1)
lib/collection/src/collection/collection_ops.rs (1)
  • optimizations (429-465)
lib/collection/src/update_workers/optimization_worker.rs (2)
lib/collection/src/collection_manager/optimizers/segment_optimizer.rs (1)
  • scheduled (1005-1007)
lib/collection/src/shards/shard.rs (1)
  • optimizers_log (239-249)
⏰ 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
  • GitHub Check: integration-tests-consensus
  • GitHub Check: e2e-tests
  • GitHub Check: test-consistency
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: Test Python bindings
  • GitHub Check: lint
🔇 Additional comments (7)
lib/collection/src/operations/types.rs (2)

307-309: LGTM!

The pending field addition to OptimizationsResponse is well-documented and correctly typed.


311-322: LGTM!

The PendingOptimizations struct is well-designed with appropriate derives for an API response type (Serialize, JsonSchema, Default, Clone, Debug). The field documentation clearly explains the semantics of each count.

docs/redoc/master/openapi.json (1)

16406-16428: Remove the required marking concern—pending is always populated.

The pending field is non-optional in OptimizationsResponse and has no conditional serialization logic. The server initializes it with PendingOptimizations::default() and always includes it in responses, making the required marking in OpenAPI correct and consistent with the implementation.

However, since openapi.json is auto-generated from source structs via schemars, any future schema refinements (e.g., clarifying that values are estimates) should be made in lib/collection/src/operations/types.rs and lib/api/src/rest/schema.rs rather than by editing the JSON directly.

lib/collection/src/collection_manager/optimizers/mod.rs (1)

12-12: LGTM!

The import and new pending field are correctly added to TrackerLog. The struct already derives Default, so PendingOptimizations will be properly initialized. This cleanly integrates with the broader pending-tracking mechanism.

Also applies to: 27-30

lib/collection/src/collection/collection_ops.rs (1)

435-465: LGTM!

The pending optimization aggregation is well-structured:

  • Lock is acquired and explicitly dropped before extending result vectors
  • merge() correctly accumulates pending counts across all shards
  • The response now includes the aggregated pending field
lib/collection/src/update_workers/optimization_worker.rs (2)

15-15: LGTM!

The imports for LockedSegment and PendingOptimizations are correctly added to support the new pending tracking logic.

Also applies to: 32-32


270-299: LGTM!

The pending optimization calculation logic is well-structured:

  • Lock ordering is safe: segments.read() is released before acquiring optimizers_log.lock()
  • The if let Some(LockedSegment::Original(segment)) pattern correctly filters to only count original segments, which aligns with how optimizations work (the planner uses iter_original())
  • The calculated pending values represent all planned work from the planner, providing useful API insight into optimization backlog

continue;
};
let IndexingProgressViews { ongoing, completed } = log.lock().progress_views();
let log = log.lock();

@IvanPleshkov IvanPleshkov Jan 15, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: I find the scope for log.lock() easier to read than manual drop

let scheduled;
let mut pending_segments = 0;
let mut pending_points = 0;
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit. WDYT about returning scheduled from the scope?

let scheduled = {
    ...
}

Comment thread lib/collection/src/operations/types.rs Resolved
@xzfc
xzfc force-pushed the report-pending-optimizers-api branch from 514fb94 to 2799875 Compare January 15, 2026 20:41
@xzfc
xzfc merged commit 76944fb into dev Jan 15, 2026
15 checks passed
@xzfc
xzfc deleted the report-pending-optimizers-api branch January 15, 2026 21:31
@generall generall added this to the Optimization Progress milestone Feb 9, 2026
generall pushed a commit that referenced this pull request Feb 9, 2026
* Expose pending optimizations in API

* Address review comments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants