Async methods preserve the SDK's result, failure cause and cancellation behavior.
+ * Spans finish on SDK completion, before the returned future exposes the outcome.
+ * The calling context is used as the parent and the operation span is current when
+ * invoking the SDK. No scope is held open while waiting. As with the SDK itself,
+ * applications must propagate context when scheduling their own future listeners.
The existing blocking methods remain available and delegate to the async methods.
+ * Operations performed via {@link #unwrap()} are not traced by this wrapper.
*/
public class TracedQdrantClient {
-
private final QdrantClient client;
private final FITracer tracer;
- /**
- * Creates a new traced Qdrant client with the given client and tracer.
- *
- * @param client the QdrantClient to wrap
- * @param tracer the FITracer for instrumentation
- */
public TracedQdrantClient(QdrantClient client, FITracer tracer) {
this.client = client;
this.tracer = tracer;
}
- /**
- * Creates a new traced Qdrant client using the global TraceAI tracer.
- *
- * @param client the QdrantClient to wrap
- */
public TracedQdrantClient(QdrantClient client) {
this(client, TraceAI.getTracer());
}
- /**
- * Searches for similar vectors with tracing.
- * Builds a SearchPoints request from the given parameters.
- *
- * @param collectionName the collection to search
- * @param queryVector the query vector
- * @param limit maximum number of results
- * @return list of scored points
- * @throws ExecutionException if search fails
- * @throws InterruptedException if interrupted
- */
public List search(String collectionName, List queryVector, int limit)
throws ExecutionException, InterruptedException {
- // Build SearchPoints request from simple params
- SearchPoints searchRequest = SearchPoints.newBuilder()
- .setCollectionName(collectionName)
- .addAllVector(queryVector)
- .setLimit(limit)
- .build();
-
- return search(searchRequest);
- }
-
- /**
- * Searches with filter and additional options with tracing.
- *
- * @param searchRequest the search request
- * @return list of scored points
- * @throws ExecutionException if search fails
- * @throws InterruptedException if interrupted
- */
- public List search(SearchPoints searchRequest)
+ return searchAsync(collectionName, queryVector, limit).get();
+ }
+
+ public List search(SearchPoints request)
throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant Search", FISpanKind.RETRIEVER);
+ return searchAsync(request).get();
+ }
- try (Scope scope = span.makeCurrent()) {
- // Set attributes
- span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
- span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, searchRequest.getCollectionName());
- span.setAttribute(SemanticConventions.RETRIEVER_TOP_K, searchRequest.getLimit());
+ public ListenableFuture> searchAsync(
+ String collectionName, List queryVector, int limit) {
+ return searchAsync(SearchPoints.newBuilder().setCollectionName(collectionName)
+ .addAllVector(queryVector).setLimit(limit).build());
+ }
- // Capture vector dimensions from the repeated vector field
- int vectorCount = searchRequest.getVectorCount();
- if (vectorCount > 0) {
- span.setAttribute(SemanticConventions.EMBEDDING_DIMENSIONS, (long) vectorCount);
- }
+ public ListenableFuture> searchAsync(SearchPoints request) {
+ return searchAsync(request, null);
+ }
- if (searchRequest.hasFilter()) {
+ public ListenableFuture> searchAsync(SearchPoints request, Duration timeout) {
+ return traceAsync("Search", FISpanKind.RETRIEVER, request.getCollectionName(), span -> {
+ span.setAttribute(SemanticConventions.RETRIEVER_TOP_K, request.getLimit());
+ if (request.getVectorCount() > 0) {
+ span.setAttribute(SemanticConventions.EMBEDDING_DIMENSIONS, (long) request.getVectorCount());
+ }
+ if (request.hasFilter()) {
span.setAttribute("qdrant.has_filter", true);
}
+ }, () -> client.searchAsync(request, timeout), this::recordScoredPoints);
+ }
- // Execute search
- List results = client.searchAsync(searchRequest).get();
+ /** Universal query, including hybrid and multi-stage requests. */
+ public List query(QueryPoints request) throws ExecutionException, InterruptedException {
+ return queryAsync(request).get();
+ }
+
+ public ListenableFuture> queryAsync(QueryPoints request) {
+ return queryAsync(request, null);
+ }
- // Capture results
- span.setAttribute(SemanticConventions.DB_VECTOR_RESULTS_COUNT, (long) results.size());
- if (!results.isEmpty()) {
- span.setAttribute("qdrant.top_score", results.get(0).getScore());
+ /** Passes the request and optional SDK timeout through unchanged. */
+ public ListenableFuture> queryAsync(QueryPoints request, Duration timeout) {
+ return traceAsync("Query", FISpanKind.RETRIEVER, request.getCollectionName(), span -> {
+ if (request.hasLimit()) {
+ span.setAttribute(SemanticConventions.RETRIEVER_TOP_K, request.getLimit());
}
+ if (request.hasFilter()) {
+ span.setAttribute("qdrant.has_filter", true);
+ }
+ span.setAttribute("qdrant.prefetch_count", (long) request.getPrefetchCount());
+ }, () -> client.queryAsync(request, timeout), this::recordScoredPoints);
+ }
+
+ public List queryBatch(String collectionName, List queries)
+ throws ExecutionException, InterruptedException {
+ return queryBatchAsync(collectionName, queries).get();
+ }
- span.setStatus(StatusCode.OK);
- return results;
+ public ListenableFuture> queryBatchAsync(
+ String collectionName, List queries) {
+ return queryBatchAsync(collectionName, queries, null, null);
+ }
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
- }
+ public ListenableFuture> queryBatchAsync(
+ String collectionName, List queries, ReadConsistency readConsistency) {
+ return queryBatchAsync(collectionName, queries, readConsistency, null);
+ }
+
+ public ListenableFuture> queryBatchAsync(
+ String collectionName, List queries,
+ ReadConsistency readConsistency, Duration timeout) {
+ return traceAsync("Query Batch", FISpanKind.RETRIEVER, collectionName,
+ span -> span.setAttribute("qdrant.query_count", (long) queries.size()),
+ () -> client.queryBatchAsync(collectionName, queries, readConsistency, timeout),
+ (span, results) -> {
+ span.setAttribute("qdrant.batch_count", (long) results.size());
+ span.setAttribute(SemanticConventions.DB_VECTOR_RESULTS_COUNT,
+ results.stream().mapToLong(BatchResult::getResultCount).sum());
+ });
+ }
+
+ public List queryGroups(QueryPointGroups request)
+ throws ExecutionException, InterruptedException {
+ return queryGroupsAsync(request).get();
+ }
+
+ public ListenableFuture> queryGroupsAsync(QueryPointGroups request) {
+ return queryGroupsAsync(request, null);
+ }
+
+ public ListenableFuture> queryGroupsAsync(QueryPointGroups request, Duration timeout) {
+ return traceAsync("Query Groups", FISpanKind.RETRIEVER, request.getCollectionName(), span -> {
+ if (request.hasLimit()) {
+ span.setAttribute(SemanticConventions.RETRIEVER_TOP_K, request.getLimit());
+ }
+ if (request.hasFilter()) {
+ span.setAttribute("qdrant.has_filter", true);
+ }
+ }, () -> client.queryGroupsAsync(request, timeout), (span, groups) -> {
+ span.setAttribute("qdrant.groups_count", (long) groups.size());
+ span.setAttribute(SemanticConventions.DB_VECTOR_RESULTS_COUNT,
+ groups.stream().mapToLong(PointGroup::getHitsCount).sum());
+ });
}
- /**
- * Upserts points with tracing.
- *
- * @param collectionName the collection name
- * @param points the points to upsert
- * @return the update result
- * @throws ExecutionException if upsert fails
- * @throws InterruptedException if interrupted
- */
public UpdateResult upsert(String collectionName, List points)
throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant Upsert", FISpanKind.VECTOR_DB);
+ return upsertAsync(collectionName, points).get();
+ }
- try (Scope scope = span.makeCurrent()) {
- // Set attributes
- span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
- span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, collectionName);
+ public ListenableFuture upsertAsync(String collectionName, List points) {
+ return traceAsync("Upsert", FISpanKind.VECTOR_DB, collectionName, span -> {
span.setAttribute(SemanticConventions.DB_VECTOR_UPSERT_COUNT, (long) points.size());
-
- // Try to capture vector dimensions from the first point
if (!points.isEmpty() && points.get(0).hasVectors()) {
Vectors vectors = points.get(0).getVectors();
if (vectors.hasVector()) {
span.setAttribute(SemanticConventions.EMBEDDING_DIMENSIONS,
- (long) vectors.getVector().getDataCount());
+ (long) vectors.getVector().getDataCount());
}
}
-
- // Execute upsert
- UpdateResult result = client.upsertAsync(collectionName, points).get();
-
- // Capture result
- span.setAttribute("qdrant.status", result.getStatus().name());
-
- span.setStatus(StatusCode.OK);
- return result;
-
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
- }
+ }, () -> client.upsertAsync(collectionName, points), this::recordUpdate);
}
- /**
- * Deletes points by filter with tracing.
- * In Qdrant Java client v1.16.x, deleteAsync takes a Filter, not a list of PointIds.
- *
- * @param collectionName the collection name
- * @param filter the filter to match points for deletion
- * @return the update result
- * @throws ExecutionException if delete fails
- * @throws InterruptedException if interrupted
- */
public UpdateResult delete(String collectionName, Filter filter)
throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant Delete", FISpanKind.VECTOR_DB);
-
- try (Scope scope = span.makeCurrent()) {
- // Set attributes
- span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
- span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, collectionName);
- span.setAttribute("qdrant.has_filter", true);
-
- // Execute delete
- UpdateResult result = client.deleteAsync(collectionName, filter).get();
-
- span.setAttribute("qdrant.status", result.getStatus().name());
- span.setStatus(StatusCode.OK);
- return result;
+ return deleteAsync(collectionName, filter).get();
+ }
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
- }
+ public ListenableFuture deleteAsync(String collectionName, Filter filter) {
+ return traceAsync("Delete", FISpanKind.VECTOR_DB, collectionName,
+ span -> span.setAttribute("qdrant.has_filter", true),
+ () -> client.deleteAsync(collectionName, filter), this::recordUpdate);
}
- /**
- * Gets points by IDs with tracing.
- *
- * @param collectionName the collection name
- * @param pointIds the point IDs to retrieve
- * @param withPayload whether to include payload
- * @param withVectors whether to include vectors
- * @return list of retrieved points
- * @throws ExecutionException if retrieval fails
- * @throws InterruptedException if interrupted
- */
public List get(String collectionName, List pointIds,
- boolean withPayload, boolean withVectors)
+ boolean withPayload, boolean withVectors)
throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant Get", FISpanKind.VECTOR_DB);
+ return getAsync(collectionName, pointIds, withPayload, withVectors).get();
+ }
- try (Scope scope = span.makeCurrent()) {
- // Set attributes
- span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
- span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, collectionName);
- span.setAttribute("qdrant.requested_count", (long) pointIds.size());
-
- // Execute get
- List results = client.retrieveAsync(
- collectionName,
- pointIds,
- withPayload,
- withVectors,
- null // readConsistency
- ).get();
-
- span.setAttribute("qdrant.retrieved_count", (long) results.size());
- span.setStatus(StatusCode.OK);
- return results;
-
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
- }
+ public ListenableFuture> getAsync(String collectionName, List pointIds,
+ boolean withPayload, boolean withVectors) {
+ return traceAsync("Get", FISpanKind.VECTOR_DB, collectionName,
+ span -> span.setAttribute("qdrant.requested_count", (long) pointIds.size()),
+ () -> client.retrieveAsync(collectionName, pointIds, withPayload, withVectors, null),
+ (span, results) -> span.setAttribute("qdrant.retrieved_count", (long) results.size()));
}
- /**
- * Creates a collection with tracing.
- *
- * @param collectionName the collection name
- * @param vectorSize the vector dimensions
- * @param distance the distance metric
- * @throws ExecutionException if creation fails
- * @throws InterruptedException if interrupted
- */
public void createCollection(String collectionName, int vectorSize, Distance distance)
throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant Create Collection", FISpanKind.VECTOR_DB);
+ createCollectionAsync(collectionName, vectorSize, distance).get();
+ }
- try (Scope scope = span.makeCurrent()) {
- // Set attributes
- span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
- span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, collectionName);
+ public ListenableFuture createCollectionAsync(
+ String collectionName, int vectorSize, Distance distance) {
+ return traceAsync("Create Collection", FISpanKind.VECTOR_DB, collectionName, span -> {
span.setAttribute("qdrant.vector_size", (long) vectorSize);
span.setAttribute("qdrant.distance", distance.name());
+ }, () -> client.createCollectionAsync(collectionName,
+ VectorParams.newBuilder().setSize(vectorSize).setDistance(distance).build()),
+ (span, result) -> { });
+ }
+
+ public List listCollections() throws ExecutionException, InterruptedException {
+ return listCollectionsAsync().get();
+ }
- // Execute create
- client.createCollectionAsync(
- collectionName,
- VectorParams.newBuilder()
- .setSize(vectorSize)
- .setDistance(distance)
- .build()
- ).get();
-
- span.setStatus(StatusCode.OK);
-
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
+ public ListenableFuture> listCollectionsAsync() {
+ return traceAsync("List Collections", FISpanKind.VECTOR_DB, null, span -> { },
+ client::listCollectionsAsync,
+ (span, results) -> span.setAttribute("qdrant.collections_count", (long) results.size()));
+ }
+
+ private void recordScoredPoints(Span span, List results) {
+ span.setAttribute(SemanticConventions.DB_VECTOR_RESULTS_COUNT, (long) results.size());
+ if (!results.isEmpty()) {
+ span.setAttribute("qdrant.top_score", results.get(0).getScore());
}
}
- /**
- * Lists collections with tracing.
- *
- * @return list of collection names
- * @throws ExecutionException if listing fails
- * @throws InterruptedException if interrupted
- */
- public List listCollections() throws ExecutionException, InterruptedException {
- Span span = tracer.startSpan("Qdrant List Collections", FISpanKind.VECTOR_DB);
+ private void recordUpdate(Span span, UpdateResult result) {
+ span.setAttribute("qdrant.status", result.getStatus().name());
+ }
- try (Scope scope = span.makeCurrent()) {
+ private ListenableFuture traceAsync(String operation, FISpanKind kind, String collection,
+ Consumer attributes, Supplier> call, BiConsumer resultAttributes) {
+ Span span = tracer.startSpan("Qdrant " + operation, kind);
+ Context context = Context.current().with(span);
+ ListenableFuture future;
+ try (Scope scope = context.makeCurrent()) {
span.setAttribute(SemanticConventions.DB_SYSTEM, "qdrant");
+ if (collection != null) {
+ span.setAttribute(SemanticConventions.DB_VECTOR_COLLECTION_NAME, collection);
+ }
+ attributes.accept(span);
+ future = call.get();
+ } catch (RuntimeException | Error failure) {
+ try {
+ tracer.setError(span, failure);
+ } finally {
+ span.end();
+ }
+ throw failure;
+ }
+ // Publish the outcome only after ending the span. Returning the SDK future
+ // directly lets get() race its completion callback and an immediate tracer shutdown.
+ SettableFuture completion = SettableFuture.create();
+ Futures.addCallback(future, new FutureCallback() {
+ @Override
+ public void onSuccess(T result) {
+ finish(span, context, () -> {
+ resultAttributes.accept(span, result);
+ span.setStatus(StatusCode.OK);
+ });
+ completion.set(result);
+ }
- List collections = client.listCollectionsAsync().get();
-
- span.setAttribute("qdrant.collections_count", (long) collections.size());
- span.setStatus(StatusCode.OK);
- return collections;
+ @Override
+ public void onFailure(Throwable failure) {
+ finish(span, context, () -> tracer.setError(span, failure));
+ if (future.isCancelled()) {
+ completion.cancel(false);
+ } else {
+ completion.setException(failure);
+ }
+ }
+ }, MoreExecutors.directExecutor());
+ return new ForwardingListenableFuture.SimpleForwardingListenableFuture(completion) {
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ // Preserve whether the SDK accepts cancellation, including the interrupt
+ // flag. Its completion callback transfers cancellation after ending the span.
+ return future.cancel(mayInterruptIfRunning);
+ }
+ };
+ }
- } catch (Exception e) {
- tracer.setError(span, e);
- throw e;
- } finally {
- span.end();
+ private void finish(Span span, Context context, Runnable attributes) {
+ try {
+ try (Scope scope = context.makeCurrent()) {
+ attributes.run();
+ } finally {
+ span.end();
+ }
+ } catch (RuntimeException ignored) {
+ // Optional telemetry must not change or prevent delivery of the SDK outcome.
}
}
- /**
- * Gets the underlying QdrantClient.
- *
- * @return the wrapped QdrantClient
- */
+ /** Returns the original client; operations on it bypass this wrapper. */
public QdrantClient unwrap() {
return client;
}
diff --git a/java/traceai-java-qdrant/src/test/java/ai/traceai/qdrant/TracedQdrantClientTest.java b/java/traceai-java-qdrant/src/test/java/ai/traceai/qdrant/TracedQdrantClientTest.java
new file mode 100644
index 000000000..6eb73a701
--- /dev/null
+++ b/java/traceai-java-qdrant/src/test/java/ai/traceai/qdrant/TracedQdrantClientTest.java
@@ -0,0 +1,350 @@
+package ai.traceai.qdrant;
+
+import ai.traceai.FITracer;
+import ai.traceai.SemanticConventions;
+import ai.traceai.TraceConfig;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import io.opentelemetry.api.common.AttributeKey;
+import io.opentelemetry.api.trace.Span;
+import io.opentelemetry.api.trace.StatusCode;
+import io.opentelemetry.context.Scope;
+import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
+import io.opentelemetry.sdk.trace.SdkTracerProvider;
+import io.opentelemetry.sdk.trace.data.SpanData;
+import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
+import io.qdrant.client.QdrantClient;
+import io.qdrant.client.grpc.Collections.CollectionOperationResponse;
+import io.qdrant.client.grpc.Collections.Distance;
+import io.qdrant.client.grpc.Collections.VectorParams;
+import io.qdrant.client.grpc.Common.Filter;
+import io.qdrant.client.grpc.Common.PointId;
+import io.qdrant.client.grpc.Points.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+class TracedQdrantClientTest {
+ private InMemorySpanExporter exporter;
+ private SdkTracerProvider provider;
+ private FITracer tracer;
+ private QdrantClient client;
+ private TracedQdrantClient traced;
+
+ private static final QueryPoints QUERY = QueryPoints.newBuilder().setCollectionName("documents")
+ .setLimit(3).addPrefetch(PrefetchQuery.newBuilder().setLimit(20)).build();
+ private static final SearchPoints SEARCH = SearchPoints.newBuilder().setCollectionName("documents")
+ .setLimit(3).addAllVector(List.of(0.1f, 0.2f)).setFilter(Filter.getDefaultInstance()).build();
+ private static final QueryPointGroups GROUPS = QueryPointGroups.newBuilder()
+ .setCollectionName("documents").setGroupBy("category").setGroupSize(2).setLimit(3).build();
+ private static final ScoredPoint POINT = ScoredPoint.newBuilder().setScore(0.9f).build();
+ private static final UpdateResult UPDATE = UpdateResult.newBuilder().setStatus(UpdateStatus.Completed).build();
+ private static final List IDS = List.of(PointId.newBuilder().setNum(42).build());
+
+ enum Operation { SEARCH, QUERY, BATCH, GROUPS, UPSERT, DELETE, GET, CREATE, LIST }
+
+ @BeforeEach
+ void setUp() {
+ exporter = InMemorySpanExporter.create();
+ provider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build();
+ tracer = new FITracer(provider.get("qdrant-test"), config());
+ client = mock(QdrantClient.class);
+ traced = new TracedQdrantClient(client, tracer);
+ }
+
+ static TraceConfig config() {
+ return TraceConfig.builder().apiKey("synthetic").secretKey("synthetic")
+ .baseUrl("http://localhost").projectName("qdrant-test").hideErrorDetails(true).build();
+ }
+
+ @AfterEach
+ void tearDown() {
+ provider.close();
+ }
+
+ @Test
+ void exposesNonBlockingUniversalQuery() throws Exception {
+ assertThat(TracedQdrantClient.class.getMethod("queryAsync", QueryPoints.class)
+ .getReturnType()).isEqualTo(ListenableFuture.class);
+ }
+
+ @ParameterizedTest
+ @EnumSource(Operation.class)
+ void asyncOperationsRemainOpenUntilCompletionAndPreserveResult(Operation operation) throws Exception {
+ SettableFuture