Skip to content

distributed optimization info - #8120

Merged
generall merged 7 commits into
devfrom
distributed-optimization-info
Feb 13, 2026
Merged

generall merged 7 commits into
devfrom
distributed-optimization-info

Conversation

@generall

Copy link
Copy Markdown
Member

This PR makes collection optimizations API functionality to query the whole cluster.

Task prompted to AI:

# Distributed optimization info

Currently `/collections/{name}/optimizations` API reads optimizations only from the local node.
In cluster mode with remote shards it meands that API response will depend on the node which receives the request.
It is not very convenient in cases, when API results are visualized in UI.


We need to make this API collect optimizations from all shards in the cluster, including remote ones.

## The plan:

- refactor `pub async fn optimizations` inside `lib/collection/src/collection/collection_ops.rs`:
    - currently it generates `OptimizationsResponse` based on individual shards. We need to change that, so each shard generates `OptimizationsResponse` and collection level function merges them togheter.


- On the shard level in `lib/collection/src/shards/replica_set/mod.rs`, there are
    - `pub async fn optimizers_log(&self) -> Option<Arc<ParkingMutex<TrackerLog>>>`
    - `pub async fn optimizations(&self) -> Option<LocalShardOptimizations>`

we need the following changes there:

- make it into one function that returns `OptimizationsResponse`.
- work with loced sctrucutres like `Option<Arc<ParkingMutex<TrackerLog>>>` should not be exposed in the public interface of the replica set.


- `pub async fn optimizations` should be implemented for `RemoteShard` as well, so we can get optimizations from remote shards.
  - In order to do that, we would require:
    - Create a new internal grpc API in `lib/api/src/grpc/proto/collections_internal_service.proto`, that will be used to get optimizations from remote shards.
    - the API should allow to retrieve optimizations for a specific shard.
    - Follow the example of other internal API to implement it

Followup fixes:

- OptimizationsResponse.merge method could benefit from deconstruction of the objects, to make it impossile to forget to use any fields.
- Same for `options: OptimizationsRequestOptions` in `optimizations` method
- `pub async fn optimizations(` method in the ReplicaSet doesn't return error, only `OptimizationsResponse`. But there should be a possibility of an error when talking to remote shards. Error is incorrectly ignored, it should be propagated all the way to the top level API.
- `// Collect from remote shards` loop and `local_optimizations.await` in the replica set should use try_join_all instead of iterating one-by-one
- in the `merge` of `OptimizationsResponse`, check for `Some` in optional fields discards values from `other` if the current object has `None` in that field. That might lead to loss of data.

Comment on lines +99 to +104
message GetShardOptimizationsResponse {
// JSON-serialized OptimizationsResponse
bytes optimizations_json = 1;
// Time spent to process
double time = 2;
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

About the idea to use JSON field inside gRPC to transfer.

From one point of view, it is not how we usually utilize our gRPC APIs. For example
telemetry_internal is strongly typed. Likely, the json overlay introduce some (small) overhead, compare to the native gRPC serialization.

On the other hand:

  • telemetry_internal.proto is VERY verbose, it requires thinking about reserved fields for future use.
  • Our APIs are internal, therefore we can serialize and deserialize with exactly same structure.
  • Avoid huge boilerplate of converters.
  • Potentially easier backward compatibility.

I am leaning towards the JSON field option.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

At this point, why not to call REST API instead?

This way we don't even need to query per shard. (instead, for the whole collection)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

because we don't know how the rest interface is exposed. We only do it for snapshot transfers and only because it is not possible to use grpc for file streaming. It also requires explicit url generation on the source side and usage of the public certificate

@generall
generall requested review from coszio and xzfc February 13, 2026 00:38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@lib/api/src/grpc/proto/collections_internal_service.proto`:
- Around line 93-94: The comment on the optional uint32 field completed_limit is
misleading — update its docstring to reflect that the absence/unset state (not
the value 0) indicates completed optimizations should not be included; e.g.,
replace "0 means not included" with wording such as "If not set, completed
optimizations are not included" and keep reference to the field name
completed_limit to ensure the semantics match the optional uint32 type.
🧹 Nitpick comments (3)
lib/api/src/grpc/proto/collections_internal_service.proto (1)

99-103: JSON-serialized response in bytes field — acceptable for internal API, but worth a note.

Using bytes optimizations_json avoids duplicating the complex OptimizationsResponse structure in proto, which is pragmatic for an internal-only endpoint. Just be aware this bypasses protobuf's schema evolution and type-safety guarantees. If this endpoint is ever exposed externally or the response structure evolves frequently, consider modeling it in proto directly.

lib/collection/src/shards/replica_set/mod.rs (2)

1358-1403: try_join_all makes this info endpoint fragile to single-remote failures.

If any one remote shard is unreachable (e.g., during a rolling restart), try_join_all at line 1380 will short-circuit and the entire /optimizations request will fail. For a read-only, best-effort informational endpoint, consider using futures::future::join_all and filtering/logging errors so that the response still includes data from the reachable replicas.

This also applies to the same pattern in collection_ops.rs (line ~459), which uses future::try_join_all(futures).await? across all shards.


1374-1381: Remotes read lock is held for the full duration of remote gRPC calls.

The self.remotes.read().await guard lives for the entire async block (through try_join_all), blocking any concurrent writes to the remotes list (e.g., add_remote, remove_remote) for the duration of all gRPC round-trips. This is architecturally necessary here since the futures borrow &RemoteShard from the guarded Vec, but worth keeping in mind — if remote shard counts or gRPC latencies grow, this could become a bottleneck for shard topology changes.

One alternative would be to clone or Arc-wrap individual RemoteShard entries so the lock can be released before try_join_all, but that's a larger refactor and likely not urgent.

Comment on lines +93 to +94
// Limit for completed optimizations (0 means not included)
optional uint32 completed_limit = 4;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Misleading comment on completed_limit.

The comment says "0 means not included," but since the field is optional uint32, the absence semantic is conveyed by the field being unset (i.e., None in Rust). A value of 0 would be a set value and could be misinterpreted. Consider updating the comment to reflect the optional semantics, e.g., "If not set, completed optimizations are not included."

🤖 Prompt for AI Agents
In `@lib/api/src/grpc/proto/collections_internal_service.proto` around lines 93 -
94, The comment on the optional uint32 field completed_limit is misleading —
update its docstring to reflect that the absence/unset state (not the value 0)
indicates completed optimizations should not be included; e.g., replace "0 means
not included" with wording such as "If not set, completed optimizations are not
included" and keep reference to the field name completed_limit to ensure the
semantics match the optional uint32 type.

Comment thread lib/collection/src/collection/mod.rs Resolved
@xzfc

xzfc commented Feb 13, 2026 •

Copy link
Copy Markdown
Member

It throws an error if there are dead shards. Should we instead ignore dead peers in the cluster?

$ curl 127.1:6333/collections/benchmark/optimizations  
{"status":{"error":"Service internal error: Tonic status error: status: Unavailable, message: \"Failed to connect to http://127.0.0.1:6375/, error: transport error\", details: [], metadata: MetadataMap { headers: {} }"},"time":0.435550089}

Also, would it make sense to add ?local_only=true query parameter? (or ?include_remote=true)

@qdrant qdrant deleted a comment from coderabbitai Bot Feb 13, 2026
@generall

Copy link
Copy Markdown
Member Author

Should we instead ignore dead peers in the cluster?

I think you are right, ignoring non-healthy shards is good idea.

, would it make sense to add ?local_only=true query parameter? (or ?include_remote=true)

I don't think I see a use-case for it right now, maybe later

@generall
generall requested a review from xzfc February 13, 2026 10:03
@coderabbitai

coderabbitai Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a new gRPC endpoint GetShardOptimizations (proto, client, server wiring) and an API handler to fetch per-shard optimization data. Introduces OptimizationsRequestOptions and OptimizationsResponse types with serde (de)serialization and a merge method. Reworks optimization collection: Collection optimizations now fetch shard results concurrently and merge them; ReplicaSet/RemoteShard gain new optimizations/local_optimizations methods; optimizer fields changed from &'static str to String. ProgressTree in OpenAPI had "children" removed from required. Minor derive and import adjustments across modules.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • xzfc
  • timvisee
🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'distributed optimization info' is vague and does not clearly convey the main change, using non-descriptive terminology without specifics about what is being modified. Consider using a more descriptive title such as 'Make collection optimizations API query all cluster shards' or 'Add distributed shard optimization queries'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description is clearly related to the changeset, providing detailed context about making the optimizations API gather data from all cluster shards including remote ones.
Docstring Coverage ✅ Passed Docstring coverage is 81.48% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into dev

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch distributed-optimization-info

No actionable comments were generated in the recent review. 🎉


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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@lib/collection/src/shards/replica_set/mod.rs`:
- Around line 1384-1395: The current remote_futures uses
futures::future::try_join_all which will abort the whole optimizations call if
any single remote.optimizations(remote.peer_id) fails; change remote_futures to
use futures::future::join_all over the collected futures from
remotes.iter().filter(|remote|
self.peer_is_updatable(remote.peer_id)).map(|remote|
remote.optimizations(options)) so you get Vec<Result<OptimizationsResponse, _>>;
then handle each item by logging/discarding Errs and collecting successful
OptimizationsResponse values into remote_responses (so the overall
remote_futures always returns Ok(Vec<OptimizationsResponse>)), and finally
replace the try_join that combines local_future with remote_futures accordingly
(use try_join if local_future should still propagate errors, or join and
consolidate errors) so a single unreachable peer no longer short-circuits the
whole request.
🧹 Nitpick comments (3)
lib/api/src/grpc/proto/collections_internal_service.proto (1)

99-104: JSON-in-bytes transport for an internal API is a pragmatic choice, but worth noting.

Using bytes optimizations_json avoids defining complex nested proto messages for ProgressTree and all optimization structures. This is reasonable for an internal-only API, though it bypasses protobuf's type safety and schema evolution guarantees. If this response shape stabilizes, consider migrating to proper proto messages for stronger contracts.

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

461-470: Sorting and truncation logic is sound, but note the completed_limit of Some(0) edge case.

If options.completed_limit is Some(0), this will truncate completed to an empty vec, yielding completed: Some([]) in the response. This is technically distinct from completed: None (which means "not requested"). This seems intentional, but if consumers treat Some([]) and None differently, it could cause confusion. Worth a quick sanity check that downstream consumers handle both cases.

lib/collection/src/shards/remote_shard.rs (1)

957-985: New optimizations method looks good overall — minor note on the as u32 cast.

The method cleanly follows the existing with_collections_client pattern used by other methods in this file. The JSON deserialization with proper error wrapping is appropriate.

On line 969, options.completed_limit.map(|l| l as u32) silently truncates if completed_limit is a usize larger than u32::MAX. While practically impossible for this use case, a safer cast would be more idiomatic:

Suggested safer cast
-                        completed_limit: options.completed_limit.map(|l| l as u32),
+                        completed_limit: options.completed_limit.map(|l| u32::try_from(l).unwrap_or(u32::MAX)),

Comment on lines +1384 to +1395
let remote_futures = async {
let remotes = self.remotes.read().await;
let futures: Vec<_> = remotes
.iter()
.filter(|remote| self.peer_is_updatable(remote.peer_id))
.map(|remote| remote.optimizations(options))
.collect();
futures::future::try_join_all(futures).await
};

let (mut response, remote_responses) =
futures::future::try_join(local_future, remote_futures).await?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

try_join_all propagates a single remote failure to the caller — consider graceful degradation.

If a remote peer is in an Active/Updatable state but temporarily unreachable (e.g., network partition, restart), try_join_all at line 1391 will short-circuit and fail the entire optimizations request. This matches the issue xzfc reported in the PR discussion.

Consider using futures::future::join_all instead, then logging/discarding individual Err results so that the response still includes data from reachable peers:

Sketch: graceful degradation
-            futures::future::try_join_all(futures).await
+            let results = futures::future::join_all(futures).await;
+            let mut responses = Vec::with_capacity(results.len());
+            for result in results {
+                match result {
+                    Ok(response) => responses.push(response),
+                    Err(err) => {
+                        log::warn!("Failed to fetch optimizations from remote shard: {err}");
+                    }
+                }
+            }
+            Ok(responses)

The return type of remote_futures would change to CollectionResult<Vec<OptimizationsResponse>> (always Ok) and try_join becomes a regular join or stays as-is depending on whether local_future should also be failable.

📝 Committable suggestion

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

Suggested change
let remote_futures = async {
let remotes = self.remotes.read().await;
let futures: Vec<_> = remotes
.iter()
.filter(|remote| self.peer_is_updatable(remote.peer_id))
.map(|remote| remote.optimizations(options))
.collect();
futures::future::try_join_all(futures).await
};
let (mut response, remote_responses) =
futures::future::try_join(local_future, remote_futures).await?;
let remote_futures = async {
let remotes = self.remotes.read().await;
let futures: Vec<_> = remotes
.iter()
.filter(|remote| self.peer_is_updatable(remote.peer_id))
.map(|remote| remote.optimizations(options))
.collect();
let results = futures::future::join_all(futures).await;
let mut responses = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(response) => responses.push(response),
Err(err) => {
log::warn!("Failed to fetch optimizations from remote shard: {err}");
}
}
}
Ok(responses)
};
let (mut response, remote_responses) =
futures::future::try_join(local_future, remote_futures).await?;
🤖 Prompt for AI Agents
In `@lib/collection/src/shards/replica_set/mod.rs` around lines 1384 - 1395, The
current remote_futures uses futures::future::try_join_all which will abort the
whole optimizations call if any single remote.optimizations(remote.peer_id)
fails; change remote_futures to use futures::future::join_all over the collected
futures from remotes.iter().filter(|remote|
self.peer_is_updatable(remote.peer_id)).map(|remote|
remote.optimizations(options)) so you get Vec<Result<OptimizationsResponse, _>>;
then handle each item by logging/discarding Errs and collecting successful
OptimizationsResponse values into remote_responses (so the overall
remote_futures always returns Ok(Vec<OptimizationsResponse>)), and finally
replace the try_join that combines local_future with remote_futures accordingly
(use try_join if local_future should still propagate errors, or join and
consolidate errors) so a single unreachable peer no longer short-circuits the
whole request.

@generall
generall force-pushed the distributed-optimization-info branch from 51db6d4 to 5913fa2 Compare February 13, 2026 10:48

@timvisee timvisee left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This merges distributed metrics into the existing /collections/{name}/optimizations. Doesn't it make more sense to use a dedicated endpoint for it? Maybe just /cluster/telemetry?

@coszio

coszio commented Feb 13, 2026

Copy link
Copy Markdown
Contributor

This merges distributed metrics into the existing /collections/{name}/optimizations. Doesn't it make more sense to use a dedicated endpoint for it? Maybe just /cluster/telemetry?

My thoughts as well, although in cluster/telemetry we don't want the level of detail of this API, probably just indexing status and progress for each shard

@generall

Copy link
Copy Markdown
Member Author

I would prefer not to create a universal APIs which report everything unless it is needed.
/telemtery is needed for cluster manager, so it doesn't make a dozen calls all the time

@generall
generall merged commit 171b7cf into dev Feb 13, 2026
15 checks passed
@generall
generall deleted the distributed-optimization-info branch February 13, 2026 12:58
timvisee pushed a commit that referenced this pull request Feb 16, 2026
* [AI] initial implementation

* [AI] review fixes

* [manaul] some small fix

* [AI] fix issue about serializing optional fields

* upd schema

* [manual] review fixes

* [manual] only ask updatable replicas about optimizations
@timvisee timvisee added this to the Optimization Progress milestone Feb 16, 2026
KShivendu pushed a commit that referenced this pull request Mar 30, 2026
* [AI] initial implementation

* [AI] review fixes

* [manaul] some small fix

* [AI] fix issue about serializing optional fields

* upd schema

* [manual] review fixes

* [manual] only ask updatable replicas about optimizations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants