Repository navigation
distributed optimization info - #8120
Conversation
| message GetShardOptimizationsResponse { | ||
| // JSON-serialized OptimizationsResponse | ||
| bytes optimizations_json = 1; | ||
| // Time spent to process | ||
| double time = 2; | ||
| } |
There was a problem hiding this comment.
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.protois 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.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 inbytesfield — acceptable for internal API, but worth a note.Using
bytes optimizations_jsonavoids duplicating the complexOptimizationsResponsestructure 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_allmakes this info endpoint fragile to single-remote failures.If any one remote shard is unreachable (e.g., during a rolling restart),
try_join_allat line 1380 will short-circuit and the entire/optimizationsrequest will fail. For a read-only, best-effort informational endpoint, consider usingfutures::future::join_alland 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 usesfuture::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().awaitguard lives for the entireasyncblock (throughtry_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&RemoteShardfrom the guardedVec, 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
cloneorArc-wrap individualRemoteShardentries so the lock can be released beforetry_join_all, but that's a larger refactor and likely not urgent.
| // Limit for completed optimizations (0 means not included) | ||
| optional uint32 completed_limit = 4; |
There was a problem hiding this comment.
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.
|
It throws an error if there are dead shards. Should we instead ignore dead peers in the cluster? Also, would it make sense to add |
I think you are right, ignoring non-healthy shards is good idea.
I don't think I see a use-case for it right now, maybe later |
📝 WalkthroughWalkthroughAdds 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
🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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_jsonavoids defining complex nested proto messages forProgressTreeand 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 thecompleted_limitofSome(0)edge case.If
options.completed_limitisSome(0), this will truncatecompletedto an empty vec, yieldingcompleted: Some([])in the response. This is technically distinct fromcompleted: None(which means "not requested"). This seems intentional, but if consumers treatSome([])andNonedifferently, 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: Newoptimizationsmethod looks good overall — minor note on theas u32cast.The method cleanly follows the existing
with_collections_clientpattern 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 ifcompleted_limitis ausizelarger thanu32::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)),
| 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?; |
There was a problem hiding this comment.
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.
| 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.
51db6d4 to
5913fa2
Compare
timvisee
left a comment
There was a problem hiding this comment.
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 |
|
I would prefer not to create a universal APIs which report everything unless it is needed. |
* [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
* [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
This PR makes collection optimizations API functionality to query the whole cluster.
Task prompted to AI:
Followup fixes: