Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
- Added `equals()` and `hashCode()` implementations to `FieldValue` ([#1998](https://github.com/opensearch-project/opensearch-java/pull/1998))
- Add document lifecycle guide and runnable sample ([#2017](https://github.com/opensearch-project/opensearch-java/pull/2017))
- Add transparent gRPC transport with HybridTransport (bulk over gRPC, REST fallback), translation layer, TLS, basic auth, AWS SigV4, and JWT support ([#2062](https://github.com/opensearch-project/opensearch-java/pull/2062))
- Add gRPC ML streaming support for the ML Commons `PredictModelStream` and `ExecuteAgentStream` APIs, exposed as `GrpcTransport.predictModelStream()` and `GrpcTransport.executeAgentStream()` ([#2070](https://github.com/opensearch-project/opensearch-java/pull/2070))

### Fixed

Expand Down
11 changes: 9 additions & 2 deletions java-client-grpc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ java {
val opensearchVersion = "3.5.0-SNAPSHOT"
val grpcVersion = "1.68.0"
val protobufVersion = "3.25.5"
val opensearchProtobufVersion = "1.2.0"
val opensearchProtobufVersion = "1.6.0"

dependencies {
// Depend on java-client core
Expand All @@ -53,18 +53,26 @@ dependencies {

// Test dependencies
testImplementation("io.grpc", "grpc-testing", grpcVersion)
testImplementation("io.grpc", "grpc-inprocess", grpcVersion)
testImplementation("junit", "junit", "4.13.2")
testImplementation("org.opensearch.client", "opensearch-rest-client", opensearchVersion)
testImplementation("software.amazon.awssdk", "sdk-core", "[2.21,3.0)")
testImplementation("software.amazon.awssdk", "auth", "[2.21,3.0)")
testImplementation("software.amazon.awssdk", "http-auth-aws", "[2.21,3.0)")
}

val runtimeJavaVersion = (System.getProperty("runtime.java")?.toInt())?.let(JavaVersion::toVersion) ?: JavaVersion.current()

tasks.test {
systemProperty("tests.security.manager", "false")
}

val unitTest = tasks.register<Test>("unitTest") {
// Without these the task is NO-SOURCE and silently runs nothing; skipped on Java 8, where java-client's Jackson 3 cannot compile.
if (runtimeJavaVersion >= JavaVersion.VERSION_11) {
testClassesDirs = sourceSets.test.get().output.classesDirs
classpath = sourceSets.test.get().runtimeClasspath
}
filter {
excludeTestsMatching("org.opensearch.client.opensearch.integTest.*")
}
Expand All @@ -86,7 +94,6 @@ val integrationTest = tasks.register<Test>("integrationTest") {
}

// Integration tests require Java 21+ and live in src/test/java11
val runtimeJavaVersion = (System.getProperty("runtime.java")?.toInt())?.let(JavaVersion::toVersion) ?: JavaVersion.current()
if (runtimeJavaVersion >= JavaVersion.VERSION_21) {
val java21: SourceSet = sourceSets.create("java21") {
java {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
import io.grpc.ManagedChannel;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.opensearch.client.json.JsonpMapper;
import org.opensearch.client.opensearch.core.BulkRequest;
Expand All @@ -21,10 +24,17 @@
import org.opensearch.client.transport.OpenSearchTransport;
import org.opensearch.client.transport.TransportException;
import org.opensearch.client.transport.TransportOptions;
import org.opensearch.client.transport.grpc.ml.MlExecuteAgentStreamRequest;
import org.opensearch.client.transport.grpc.ml.MlPredictStreamRequest;
import org.opensearch.client.transport.grpc.ml.MlStreamChunk;
import org.opensearch.client.transport.grpc.translation.BulkRequestConverter;
import org.opensearch.client.transport.grpc.translation.BulkResponseConverter;
import org.opensearch.client.transport.grpc.translation.GrpcStatusConverter;
import org.opensearch.client.transport.grpc.translation.MlStreamRequestConverter;
import org.opensearch.client.transport.grpc.translation.MlStreamResponseConverter;
import org.opensearch.protobufs.PredictResponse;
import org.opensearch.protobufs.services.DocumentServiceGrpc;
import org.opensearch.protobufs.services.MLServiceGrpc;

/**
* Pure gRPC transport for OpenSearch. Implements {@link OpenSearchTransport} and routes
Expand All @@ -42,6 +52,10 @@
* OpenSearchClient client = new OpenSearchClient(transport);
* client.bulk(bulkRequest); // goes over gRPC
* }</pre>
* <p>
* In addition to the {@link OpenSearchTransport} contract, this transport exposes the
* ML server-streaming APIs directly via {@link #predictModelStream} and
* {@link #executeAgentStream}.
*/
public class GrpcTransport implements OpenSearchTransport {

Expand All @@ -67,6 +81,7 @@ public static boolean isEndpointSupported(Endpoint<?, ?, ?> endpoint) {

private final ManagedChannel channel;
private final DocumentServiceGrpc.DocumentServiceBlockingStub documentStub;
private final MLServiceGrpc.MLServiceBlockingStub mlStub;
private final JsonpMapper jsonpMapper;
private final GrpcTransportOptions grpcOptions;
private final TransportOptions transportOptions;
Expand All @@ -81,6 +96,7 @@ public static boolean isEndpointSupported(Endpoint<?, ?, ?> endpoint) {
) {
this.channel = channel;
this.documentStub = channel != null ? DocumentServiceGrpc.newBlockingStub(channel) : null;
this.mlStub = channel != null ? MLServiceGrpc.newBlockingStub(channel) : null;
this.jsonpMapper = jsonpMapper;
this.grpcOptions = grpcOptions;
this.transportOptions = transportOptions;
Expand Down Expand Up @@ -238,6 +254,81 @@ private BulkResponse performBulk(BulkRequest request) throws TransportException
}
}

// ─── ML Streaming APIs ───────────────────────────────────────────────────────

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@nathaliellenaa thank you for the pull request.

A few things here:

  • GrpcTransport is a low level generic transport implementation (see please OpenSearchTransport what the expected primitives should be exposed)
  • XxxTransport classes are not supposed to be used in isolation, they are passed to OpenSearchClient which provides targeted methods (bulk, mget, ...) or/and clients (OpenSearchClusterClient, OpenSearchIndexClient, ...), in fact we already have one for ML as well - OpenSearchMlClient

The transport itself should not expose anything specific to particular API (like ml fe). The elephant in the room here is that OpenSearchTransport does not support streaming (but underlying clients do https://github.com/opensearch-project/OpenSearch/blob/main/client/rest/src/main/java/org/opensearch/client/RestClient.java#L324), so we have to close this gap first (let me pick up shortly). Once we have the streaming implementation, we could looking into bringing it to OpenSearchMlClient.

Hope it makes sense, thanks

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @reta, it makes sense that GrpcTransport shouldn't be exposing ML-specific methods. I went that route because of the gap you identified: Transport#performRequest returns a single ResponseT, so there was no way to express a server-streaming RPC returning a sequence of chunks through the existing primitives.
Happy to wait for the streaming implementation and then rebase this on top of it.


/**
* Invokes the ML streaming predict API ({@code MLService/PredictModelStream}) and
* returns an iterator over the response chunks as the server produces them.
*
* @param request the streaming predict request
* @return an iterator over the streamed chunks
*/
public Iterator<MlStreamChunk> predictModelStream(MlPredictStreamRequest request) {
org.opensearch.protobufs.MlPredictModelStreamRequest protoRequest = MlStreamRequestConverter.toProto(request);
return stream(() -> requireMlStub().predictModelStream(protoRequest));
}

/**
* Invokes the ML streaming agent execute API ({@code MLService/ExecuteAgentStream})
* and returns an iterator over the response chunks as the server produces them.
*
* @param request the streaming agent execute request
* @return an iterator over the streamed chunks
*/
public Iterator<MlStreamChunk> executeAgentStream(MlExecuteAgentStreamRequest request) {
org.opensearch.protobufs.MlExecuteAgentStreamRequest protoRequest = MlStreamRequestConverter.toProto(request);
return stream(() -> requireMlStub().executeAgentStream(protoRequest));
}

private MLServiceGrpc.MLServiceBlockingStub requireMlStub() {
if (mlStub == null) {
throw new IllegalStateException("gRPC channel is not available; ML streaming requires a connected transport");
}
return mlStub;
}

private Iterator<MlStreamChunk> stream(Supplier<Iterator<PredictResponse>> rpc) {
return new Iterator<MlStreamChunk>() {
private Iterator<PredictResponse> delegate;

@Override
public boolean hasNext() {
try {
return delegate().hasNext();
} catch (StatusRuntimeException e) {
throw convert(e);
}
}

@Override
public MlStreamChunk next() {
try {
return MlStreamResponseConverter.fromProto(delegate().next());
} catch (StatusRuntimeException e) {
throw convert(e);
}
}

private Iterator<PredictResponse> delegate() {
if (delegate == null) {
delegate = rpc.get();
}
return delegate;
}
};
}

private static RuntimeException convert(StatusRuntimeException e) {
try {
GrpcStatusConverter.throwConverted(e);
} catch (TransportException converted) {
return new UncheckedIOException(converted);
} catch (RuntimeException converted) {
return converted;
}
return new UncheckedIOException(new TransportException("gRPC error: " + e.getMessage(), e));
}

// ─── Builder ─────────────────────────────────────────────────────────────────

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.client.transport.grpc.ml;

import javax.annotation.Nullable;

/**
* Request for the ML streaming agent execute API ({@code MLService/ExecuteAgentStream}).
*/
public final class MlExecuteAgentStreamRequest {

private final String agentId;
private final MlParameters parameters;

private MlExecuteAgentStreamRequest(Builder builder) {
if (builder.agentId == null || builder.agentId.isEmpty()) {
throw new IllegalArgumentException("agentId is required");
}
this.agentId = builder.agentId;
this.parameters = builder.parameters;
}

/**
* The ID of the agent to execute. Never null.
*/
public String agentId() {
return agentId;
}

/**
* The request parameters, or null if unset.
*/
@Nullable
public MlParameters parameters() {
return parameters;
}

public static Builder builder() {
return new Builder();
}

public static final class Builder {
private String agentId;
private MlParameters parameters;

public Builder agentId(String agentId) {
this.agentId = agentId;
return this;
}

public Builder parameters(MlParameters parameters) {
this.parameters = parameters;
return this;
}

/**
* Configures the parameters using a builder function.
*/
public Builder parameters(java.util.function.Function<MlParameters.Builder, MlParameters.Builder> fn) {
return parameters(fn.apply(MlParameters.builder()).build());
}

public MlExecuteAgentStreamRequest build() {
return new MlExecuteAgentStreamRequest(this);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.client.transport.grpc.ml;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* One inference result of a streamed ML response, holding the outputs the model
* produced for this chunk.
*/
public final class MlInferenceResult {

private final List<MlOutput> output;

private MlInferenceResult(Builder builder) {
this.output = Collections.unmodifiableList(new ArrayList<>(builder.output));
}

/**
* The outputs of this inference result. Never null; empty when the server sent none.
*/
public List<MlOutput> output() {
return output;
}

public static Builder builder() {
return new Builder();
}

public static final class Builder {
private final List<MlOutput> output = new ArrayList<>();

public Builder addOutput(MlOutput out) {
this.output.add(out);
return this;
}

public MlInferenceResult build() {
return new MlInferenceResult(this);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.client.transport.grpc.ml;

import javax.annotation.Nullable;

/**
* A single chat message in an ML streaming request.
*/
public final class MlMessage {

private final String role;
private final String content;

private MlMessage(Builder builder) {
this.role = builder.role;
this.content = builder.content;
}

/**
* Creates a message with the given role and content.
*
* @param role the message role (e.g., {@code "user"}, {@code "assistant"}, {@code "system"})
* @param content the message content
*/
public static MlMessage of(String role, String content) {
return builder().role(role).content(content).build();
}

/**
* The message role, or null if unset.
*/
@Nullable
public String role() {
return role;
}

/**
* The message content, or null if unset.
*/
@Nullable
public String content() {
return content;
}

public static Builder builder() {
return new Builder();
}

public static final class Builder {
private String role;
private String content;

public Builder role(String role) {
this.role = role;
return this;
}

public Builder content(String content) {
this.content = content;
return this;
}

public MlMessage build() {
return new MlMessage(this);
}
}
}
Loading
Loading