You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by gu...@apache.org on 2023/08/01 03:42:27 UTC
[spark] branch master updated: [SPARK-44421][SPARK-44423][CONNECT] Reattachable execution in Spark Connect
This is an automated email from the ASF dual-hosted git repository.
gurwls223 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 3e5203c64c0 [SPARK-44421][SPARK-44423][CONNECT] Reattachable execution in Spark Connect
3e5203c64c0 is described below
commit 3e5203c64c06cc8a8560dfa0fb6f52e74589b583
Author: Juliusz Sompolski <ju...@databricks.com>
AuthorDate: Tue Aug 1 12:42:15 2023 +0900
[SPARK-44421][SPARK-44423][CONNECT] Reattachable execution in Spark Connect
### What changes were proposed in this pull request?
Implement server support and scala client for reattachable execution with two new RPCs:
* ReattachExecute
* ReleaseExecute
With reattachable execution, if the response stream of ExecutePlan RPC gets broken, it can be reattached to with ReattachExecute RPC. The server now holds a bit of a backtrack buffer, in case the client coming back with reattach after error did not receive the latest sent responses, and have to backtrack. The client can sends ReleaseExecute responses to let the server know what has already been consumed and can be freed.
#### Server: ExecuteResponseObserver
If ExecuteHolder is reattachable, ExecuteResponseSender is modified to not throw away responses that were returned to ExecuteGrpcResponseSender immediately, but keep a buffer of `spark.connect.execute.reattachable.observerRetryBufferSize` (default 1 MB) responses behind the last returned response. This facilitates returning consumer being able to backtrack in case the last returned response did not successfully arrive at the client.
#### Server: ExecuteGrpcResponseSender
If ExecuteHolder is reattachable, ExecuteGrpcResponseSender is modified to gracefully end the RPC response stream after a given time (`spark.connect.execute.reattachable.senderMaxStreamDuration`, default 5 minutes) or size of responses (`spark.connect.execute.reattachable.senderMaxStreamSize`, default 1 GB). After that the response is completed, and client needs to come back with a ReattachExecute RPC to continue. Clients know whether it's the real end of the results, because ExecuteT [...]
Cutting the stream manually in a graceful way like that can help prevent errors related to long open streams. It also helps with long held idle stream that may get broken because of idleness. The client is able to handle these errors, but this also provides a cleaner way to minimize the number of network errors.
ExecuteGrpcResponseSender also implements flow control of responses sent to the GRPC stream. Normally, grpcResponseObserver.onNext would never block. This doesn't however mean that it would send all responses immediately. The responses could be queued if the client does not keep up receiving and processing them. This queue can grow ubounded, and we don't know what was actually sent, so we don't know how much of a buffer ExecuteResponseObserver really needs to keep. Flow control utiliz [...]
This also helps with clients that would abandon their result stream. Now we will block from sending the responses, and time out the RPC after senderMaxStreamDuration, instead of pushing the responses to a GRPC outbound queue that is outside our control. The TODO server mechanism would then remove the execution with no RPC attached. Note: in such a situation, responses will still pile up in ExecuteResponseObserver; there is unfortunately no flow control of the Spark task results being [...]
#### Client: ExecutePlanResponseReattachableIterator
Client wraps the whole implementation inside ExecutePlanResponseReattachableIterator. It's a wrapper that starts with an ExecutePlan result iterator, but if this iterator either finishes without a ResultComplete message, or an intermittent network error occurs, it can acquire a new iterator to continue where it left off: by tracking the last received response, it can request a new iterator from ReattachExecute that starts after that.
The client sends ReleaseExecute RPCs asynchronously to release the responses it already consumed (potentially faster than the ExecuteResponseObserver would release from its backtrack buffer). The client doesn't need to check their result or block on them. If something fails, the executions will get cleaned by the TODO cleanup mechanism in the server.
#### TODO as followup
* What remains TODO for a followup PR is server mechanism for dealing with executions that have been abandoned - the client did not come back with ReatachExecute, and didn't free the execution with ReleaseExecute. This will be done by an operation manager that monitors all active executions, and interrupts and removes ones that were not released, but don't have any client RPC attached to them for a while.
* Python client implementation is a followup.
### Why are the changes needed?
Robust handling of long running queries in face of intermittent network glitches.
### Does this PR introduce _any_ user-facing change?
The re-attachable execution mechanism is not exposed in any public API. Several internal configs have been added:
Connect server configs:
* `spark.connect.execute.reattachable.senderMaxStreamDuration`
* `spark.connect.execute.reattachable.senderMaxStreamSize`
* `spark.connect.execute.reattachable.observerRetryBufferSize`
Connect scala client configuration element: `useReattachableExecute`
### How was this patch tested?
Existing E2E suite utilize re-attachable execution. The tests have been configure to exercise reattaching by using an extremely low senderMaxStreamDuration and senderMaxStreamSize.
Closes #42228 from juliuszsompolski/SPARK-44421.
Lead-authored-by: Juliusz Sompolski <ju...@databricks.com>
Co-authored-by: Hyukjin Kwon <gu...@apache.org>
Signed-off-by: Hyukjin Kwon <gu...@apache.org>
---
.../src/main/resources/error/error-classes.json | 51 +++-
.../scala/org/apache/spark/sql/SparkSession.scala | 6 +-
.../client/CustomSparkConnectBlockingStub.scala | 9 +
.../ExecutePlanResponseReattachableIterator.scala | 244 ++++++++++++++++
.../sql/connect/client/GrpcRetryHandler.scala | 63 ++--
.../sql/connect/client/SparkConnectClient.scala | 26 +-
.../connect/client/SparkConnectClientSuite.scala | 33 +++
.../connect/client/util/RemoteSparkSession.scala | 10 +-
.../src/main/protobuf/spark/connect/base.proto | 124 ++++++++
.../apache/spark/sql/connect/config/Connect.scala | 35 +++
.../connect/execution/CachedStreamResponse.scala | 9 +-
.../execution/ExecuteGrpcResponseSender.scala | 191 ++++++++++--
.../execution/ExecuteResponseObserver.scala | 97 ++++++-
.../connect/execution/ExecuteThreadRunner.scala | 27 +-
.../execution/SparkConnectPlanExecution.scala | 1 -
.../spark/sql/connect/service/ExecuteHolder.scala | 75 ++++-
.../spark/sql/connect/service/SessionHolder.scala | 22 +-
.../service/SparkConnectExecutePlanHandler.scala | 20 +-
.../SparkConnectReattachExecuteHandler.scala | 63 ++++
.../SparkConnectReleaseExecuteHandler.scala | 62 ++++
.../sql/connect/service/SparkConnectService.scala | 73 ++++-
.../spark/sql/connect/utils/ErrorUtils.scala | 14 +-
.../service/ExecuteEventsManagerSuite.scala | 9 +-
.../org/apache/spark/SparkThrowableSuite.scala | 2 +-
...-error-conditions-invalid-handle-error-class.md | 20 +-
docs/sql-error-conditions.md | 8 +
python/pyspark/sql/connect/proto/base_pb2.py | 158 +++++-----
python/pyspark/sql/connect/proto/base_pb2.pyi | 323 ++++++++++++++++++++-
python/pyspark/sql/connect/proto/base_pb2_grpc.py | 98 +++++++
29 files changed, 1660 insertions(+), 213 deletions(-)
diff --git a/common/utils/src/main/resources/error/error-classes.json b/common/utils/src/main/resources/error/error-classes.json
index 75300404194..06c47419fcb 100644
--- a/common/utils/src/main/resources/error/error-classes.json
+++ b/common/utils/src/main/resources/error/error-classes.json
@@ -1299,6 +1299,34 @@
],
"sqlState" : "42000"
},
+ "INVALID_CURSOR" : {
+ "message" : [
+ "The cursor is invalid."
+ ],
+ "subClass" : {
+ "DISCONNECTED" : {
+ "message" : [
+ "The cursor has been disconnected by the server."
+ ]
+ },
+ "NOT_REATTACHABLE" : {
+ "message" : [
+ "The cursor is not reattachable."
+ ]
+ },
+ "POSITION_NOT_AVAILABLE" : {
+ "message" : [
+ "The cursor position id <responseId> is no longer available at index <index>."
+ ]
+ },
+ "POSITION_NOT_FOUND" : {
+ "message" : [
+ "The cursor position id <responseId> is not found."
+ ]
+ }
+ },
+ "sqlState" : "HY109"
+ },
"INVALID_DEFAULT_VALUE" : {
"message" : [
"Failed to execute <statement> command because the destination table column <colName> has a DEFAULT value <defaultValue>,"
@@ -1447,14 +1475,29 @@
"The handle <handle> is invalid."
],
"subClass" : {
- "ALREADY_EXISTS" : {
+ "FORMAT" : {
"message" : [
- "Handle already exists."
+ "Handle must be an UUID string of the format '00112233-4455-6677-8899-aabbccddeeff'"
]
},
- "FORMAT" : {
+ "OPERATION_ALREADY_EXISTS" : {
+ "message" : [
+ "Operation already exists."
+ ]
+ },
+ "OPERATION_NOT_FOUND" : {
+ "message" : [
+ "Operation not found."
+ ]
+ },
+ "SESSION_ALREADY_EXISTS" : {
+ "message" : [
+ "Session already exists."
+ ]
+ },
+ "SESSION_NOT_FOUND" : {
"message" : [
- "Handle has invalid format. Handle must an UUID string of the format '00112233-4455-6677-8899-aabbccddeeff'"
+ "Session not found."
]
}
},
diff --git a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala
index 4b3de91b56f..a3d82156a03 100644
--- a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala
+++ b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/SparkSession.scala
@@ -254,7 +254,8 @@ class SparkSession private[sql] (
val plan = proto.Plan.newBuilder().setCommand(cmd)
val responseIter = client.execute(plan.build())
- val response = responseIter.asScala
+ // Note: .toSeq makes the stream be consumed and closed.
+ val response = responseIter.asScala.toSeq
.find(_.hasSqlCommandResult)
.getOrElse(throw new RuntimeException("SQLCommandResult must be present"))
@@ -310,7 +311,8 @@ class SparkSession private[sql] (
val plan = proto.Plan.newBuilder().setCommand(cmd)
val responseIter = client.execute(plan.build())
- val response = responseIter.asScala
+ // Note: .toSeq makes the stream be consumed and closed.
+ val response = responseIter.asScala.toSeq
.find(_.hasSqlCommandResult)
.getOrElse(throw new RuntimeException("SQLCommandResult must be present"))
diff --git a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/CustomSparkConnectBlockingStub.scala b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/CustomSparkConnectBlockingStub.scala
index ac14bb7e7a3..bb20901eade 100644
--- a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/CustomSparkConnectBlockingStub.scala
+++ b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/CustomSparkConnectBlockingStub.scala
@@ -34,6 +34,15 @@ private[client] class CustomSparkConnectBlockingStub(
}
}
+ def executePlanReattachable(
+ request: ExecutePlanRequest): java.util.Iterator[ExecutePlanResponse] = {
+ GrpcExceptionConverter.convert {
+ GrpcExceptionConverter.convertIterator[ExecutePlanResponse](
+ // Don't use retryHandler - own retry handling is inside.
+ new ExecutePlanResponseReattachableIterator(request, channel, retryPolicy))
+ }
+ }
+
def analyzePlan(request: AnalyzePlanRequest): AnalyzePlanResponse = {
GrpcExceptionConverter.convert {
retryHandler.retry {
diff --git a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/ExecutePlanResponseReattachableIterator.scala b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/ExecutePlanResponseReattachableIterator.scala
new file mode 100644
index 00000000000..c6f75928a3a
--- /dev/null
+++ b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/ExecutePlanResponseReattachableIterator.scala
@@ -0,0 +1,244 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.connect.client
+
+import java.util.UUID
+
+import scala.util.control.NonFatal
+
+import io.grpc.ManagedChannel
+import io.grpc.stub.StreamObserver
+
+import org.apache.spark.connect.proto
+import org.apache.spark.internal.Logging
+
+/**
+ * Retryable iterator of ExecutePlanResponses to an ExecutePlan call.
+ *
+ * It can handle situations when:
+ * - the ExecutePlanResponse stream was broken by retryable network error (governed by
+ * retryPolicy)
+ * - the ExecutePlanResponse was gracefully ended by the server without a ResultComplete
+ * message; this tells the client that there is more, and it should reattach to continue.
+ *
+ * Initial iterator is the result of an ExecutePlan on the request, but it can be reattached with
+ * ReattachExecute request. ReattachExecute request is provided the responseId of last returned
+ * ExecutePlanResponse on the iterator to return a new iterator from server that continues after
+ * that.
+ *
+ * Since in reattachable execute the server does buffer some responses in case the client needs to
+ * backtrack
+ */
+class ExecutePlanResponseReattachableIterator(
+ request: proto.ExecutePlanRequest,
+ channel: ManagedChannel,
+ retryPolicy: GrpcRetryHandler.RetryPolicy)
+ extends java.util.Iterator[proto.ExecutePlanResponse]
+ with Logging {
+
+ val operationId = if (request.hasOperationId) {
+ request.getOperationId
+ } else {
+ // Add operation id, if not present.
+ // with operationId set by the client, the client can use it to try to reattach on error
+ // even before getting the first response. If the operation in fact didn't even reach the
+ // server, that will end with INVALID_HANDLE.OPERATION_NOT_FOUND error.
+ UUID.randomUUID.toString
+ }
+
+ // Need raw stubs, don't want retry handling or error conversion done by the custom stubs.
+ // - this does it's own custom retry handling
+ // - error conversion is wrapped around this in CustomSparkConnectBlockingStub,
+ // this needs raw GRPC errors for retries.
+ private val rawBlockingStub = proto.SparkConnectServiceGrpc.newBlockingStub(channel)
+ private val rawAsyncStub = proto.SparkConnectServiceGrpc.newStub(channel)
+
+ private val initialRequest: proto.ExecutePlanRequest = request
+ .toBuilder()
+ .addRequestOptions(
+ proto.ExecutePlanRequest.RequestOption
+ .newBuilder()
+ .setReattachOptions(proto.ReattachOptions.newBuilder().setReattachable(true).build())
+ .build())
+ .setOperationId(operationId)
+ .build()
+
+ // ResponseId of the last response returned by next()
+ private var lastReturnedResponseId: Option[String] = None
+
+ // True after ResponseComplete message was seen in the stream.
+ // Server will always send this message at the end of the stream, if the underlying iterator
+ // finishes without producing one, another iterator needs to be reattached.
+ private var responseComplete: Boolean = false
+
+ // Initial iterator comes from ExecutePlan request.
+ private var iterator: java.util.Iterator[proto.ExecutePlanResponse] =
+ rawBlockingStub.executePlan(initialRequest)
+
+ override def next(): proto.ExecutePlanResponse = synchronized {
+ // hasNext will trigger reattach in case the stream completed without responseComplete
+ if (!hasNext()) {
+ throw new java.util.NoSuchElementException()
+ }
+
+ // Get next response, possibly triggering reattach in case of stream error.
+ var firstTry = true
+ val ret = retry {
+ if (firstTry) {
+ // on first try, we use the existing iterator.
+ firstTry = false
+ } else {
+ // on retry, the iterator is borked, so we need a new one
+ iterator = rawBlockingStub.reattachExecute(createReattachExecuteRequest())
+ }
+ iterator.next()
+ }
+
+ // Record last returned response, to know where to restart in case of reattach.
+ lastReturnedResponseId = Some(ret.getResponseId)
+ if (ret.hasResultComplete) {
+ responseComplete = true
+ releaseExecute(None) // release all
+ } else {
+ releaseExecute(lastReturnedResponseId) // release until this response
+ }
+ ret
+ }
+
+ override def hasNext(): Boolean = synchronized {
+ if (responseComplete) {
+ // After response complete response
+ return false
+ }
+ var firstTry = true
+ retry {
+ if (firstTry) {
+ // on first try, we use the existing iterator.
+ firstTry = false
+ } else {
+ // on retry, the iterator is borked, so we need a new one
+ iterator = rawBlockingStub.reattachExecute(createReattachExecuteRequest())
+ }
+ var hasNext = iterator.hasNext()
+ // Graceful reattach:
+ // If iterator ended, but there was no ResultComplete, it means that there is more,
+ // and we need to reattach.
+ if (!hasNext && !responseComplete) {
+ do {
+ iterator = rawBlockingStub.reattachExecute(createReattachExecuteRequest())
+ assert(!responseComplete) // shouldn't change...
+ hasNext = iterator.hasNext()
+ // It's possible that the new iterator will be empty, so we need to loop to get another.
+ // Eventually, there will be a non empty iterator, because there's always a ResultComplete
+ // at the end of the stream.
+ } while (!hasNext)
+ }
+ hasNext
+ }
+ }
+
+ /**
+ * Inform the server to release the execution.
+ *
+ * This will send an asynchronous RPC which will not block this iterator, the iterator can
+ * continue to be consumed.
+ *
+ * Release with untilResponseId informs the server that the iterator has been consumed until and
+ * including response with that responseId, and these responses can be freed.
+ *
+ * Release with None means that the responses have been completely consumed and informs the
+ * server that the completed execution can be completely freed.
+ */
+ private def releaseExecute(untilResponseId: Option[String]): Unit = {
+ val request = createReleaseExecuteRequest(untilResponseId)
+ rawAsyncStub.releaseExecute(request, createRetryingReleaseExecuteResponseObserer(request))
+ }
+
+ /**
+ * Create result callback to the asynchronouse ReleaseExecute. The client does not block on
+ * ReleaseExecute and continues with iteration, but if it fails with a retryable error, the
+ * callback will retrigger the asynchronous ReleaseExecute.
+ */
+ private def createRetryingReleaseExecuteResponseObserer(
+ requestForRetry: proto.ReleaseExecuteRequest,
+ currentRetryNum: Int = 0): StreamObserver[proto.ReleaseExecuteResponse] = {
+ new StreamObserver[proto.ReleaseExecuteResponse] {
+ override def onNext(v: proto.ReleaseExecuteResponse): Unit = {}
+ override def onCompleted(): Unit = {}
+ override def onError(t: Throwable): Unit = t match {
+ case NonFatal(e) if retryPolicy.canRetry(e) && currentRetryNum < retryPolicy.maxRetries =>
+ Thread.sleep(
+ (retryPolicy.maxBackoff min retryPolicy.initialBackoff * Math
+ .pow(retryPolicy.backoffMultiplier, currentRetryNum)).toMillis)
+ rawAsyncStub.releaseExecute(
+ requestForRetry,
+ createRetryingReleaseExecuteResponseObserer(requestForRetry, currentRetryNum + 1))
+ case _ =>
+ logWarning(s"ReleaseExecute failed with exception: $t.")
+ }
+ }
+ }
+
+ private def createReattachExecuteRequest() = {
+ val reattach = proto.ReattachExecuteRequest
+ .newBuilder()
+ .setSessionId(initialRequest.getSessionId)
+ .setUserContext(initialRequest.getUserContext)
+ .setOperationId(initialRequest.getOperationId)
+
+ if (initialRequest.hasClientType) {
+ reattach.setClientType(initialRequest.getClientType)
+ }
+
+ if (lastReturnedResponseId.isDefined) {
+ reattach.setLastResponseId(lastReturnedResponseId.get)
+ }
+ reattach.build()
+ }
+
+ private def createReleaseExecuteRequest(untilResponseId: Option[String]) = {
+ val release = proto.ReleaseExecuteRequest
+ .newBuilder()
+ .setSessionId(initialRequest.getSessionId)
+ .setUserContext(initialRequest.getUserContext)
+ .setOperationId(initialRequest.getOperationId)
+
+ if (initialRequest.hasClientType) {
+ release.setClientType(initialRequest.getClientType)
+ }
+
+ untilResponseId match {
+ case None =>
+ release.setReleaseAll(proto.ReleaseExecuteRequest.ReleaseAll.newBuilder().build())
+ case Some(responseId) =>
+ release
+ .setReleaseUntil(
+ proto.ReleaseExecuteRequest.ReleaseUntil
+ .newBuilder()
+ .setResponseId(responseId)
+ .build())
+ }
+
+ release.build()
+ }
+
+ /**
+ * Retries the given function with exponential backoff according to the client's retryPolicy.
+ */
+ private def retry[T](fn: => T, currentRetryNum: Int = 0): T =
+ GrpcRetryHandler.retry(retryPolicy)(fn, currentRetryNum)
+}
diff --git a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/GrpcRetryHandler.scala b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/GrpcRetryHandler.scala
index 48a86c047be..16352bb90b5 100644
--- a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/GrpcRetryHandler.scala
+++ b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/GrpcRetryHandler.scala
@@ -24,35 +24,15 @@ import scala.util.control.NonFatal
import io.grpc.{Status, StatusRuntimeException}
import io.grpc.stub.StreamObserver
+import org.apache.spark.internal.Logging
+
private[client] class GrpcRetryHandler(private val retryPolicy: GrpcRetryHandler.RetryPolicy) {
/**
* Retries the given function with exponential backoff according to the client's retryPolicy.
- * @param fn
- * The function to retry.
- * @param currentRetryNum
- * Current number of retries.
- * @tparam T
- * The return type of the function.
- * @return
- * The result of the function.
*/
- @tailrec final def retry[T](fn: => T, currentRetryNum: Int = 0): T = {
- if (currentRetryNum > retryPolicy.maxRetries) {
- throw new IllegalArgumentException(
- s"The number of retries ($currentRetryNum) must not exceed " +
- s"the maximum number of retires (${retryPolicy.maxRetries}).")
- }
- try {
- return fn
- } catch {
- case NonFatal(e) if retryPolicy.canRetry(e) && currentRetryNum < retryPolicy.maxRetries =>
- Thread.sleep(
- (retryPolicy.maxBackoff min retryPolicy.initialBackoff * Math
- .pow(retryPolicy.backoffMultiplier, currentRetryNum)).toMillis)
- }
- retry(fn, currentRetryNum + 1)
- }
+ def retry[T](fn: => T, currentRetryNum: Int = 0): T =
+ GrpcRetryHandler.retry(retryPolicy)(fn, currentRetryNum)
/**
* Generalizes the retry logic for RPC calls that return an iterator.
@@ -157,7 +137,40 @@ private[client] class GrpcRetryHandler(private val retryPolicy: GrpcRetryHandler
}
}
-private[client] object GrpcRetryHandler {
+private[client] object GrpcRetryHandler extends Logging {
+
+ /**
+ * Retries the given function with exponential backoff according to the client's retryPolicy.
+ * @param retryPolicy
+ * The retry policy
+ * @param fn
+ * The function to retry.
+ * @param currentRetryNum
+ * Current number of retries.
+ * @tparam T
+ * The return type of the function.
+ * @return
+ * The result of the function.
+ */
+ @tailrec final def retry[T](retryPolicy: RetryPolicy)(fn: => T, currentRetryNum: Int = 0): T = {
+ if (currentRetryNum > retryPolicy.maxRetries) {
+ throw new IllegalArgumentException(
+ s"The number of retries ($currentRetryNum) must not exceed " +
+ s"the maximum number of retires (${retryPolicy.maxRetries}).")
+ }
+ try {
+ return fn
+ } catch {
+ case NonFatal(e) if retryPolicy.canRetry(e) && currentRetryNum < retryPolicy.maxRetries =>
+ logWarning(
+ s"Non fatal error during RPC execution: $e, " +
+ s"retrying (currentRetryNum=$currentRetryNum)")
+ Thread.sleep(
+ (retryPolicy.maxBackoff min retryPolicy.initialBackoff * Math
+ .pow(retryPolicy.backoffMultiplier, currentRetryNum)).toMillis)
+ }
+ retry(retryPolicy)(fn, currentRetryNum + 1)
+ }
/**
* Default canRetry in [[RetryPolicy]].
diff --git a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/SparkConnectClient.scala b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/SparkConnectClient.scala
index 1a7fbcefc1d..aac5e6b9cc3 100644
--- a/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/SparkConnectClient.scala
+++ b/connector/connect/client/jvm/src/main/scala/org/apache/spark/sql/connect/client/SparkConnectClient.scala
@@ -82,7 +82,11 @@ private[sql] class SparkConnectClient(
.setClientType(userAgent)
.addAllTags(tags.get.toSeq.asJava)
.build()
- bstub.executePlan(request)
+ if (configuration.useReattachableExecute) {
+ bstub.executePlanReattachable(request)
+ } else {
+ bstub.executePlan(request)
+ }
}
/**
@@ -529,6 +533,25 @@ object SparkConnectClient {
this
}
+ /**
+ * Disable reattachable execute.
+ */
+ def disableReattachableExecute(): Builder = {
+ _configuration = _configuration.copy(useReattachableExecute = false)
+ this
+ }
+
+ /**
+ * Enable reattachable execute.
+ *
+ * It makes client more robust, enabling reattaching to an ExecutePlanResponse stream in case
+ * of intermittent connection errors.
+ */
+ def enableReattachableExecute(): Builder = {
+ _configuration = _configuration.copy(useReattachableExecute = true)
+ this
+ }
+
def build(): SparkConnectClient = _configuration.toSparkConnectClient
}
@@ -545,6 +568,7 @@ object SparkConnectClient {
metadata: Map[String, String] = Map.empty,
userAgent: String = DEFAULT_USER_AGENT,
retryPolicy: GrpcRetryHandler.RetryPolicy = GrpcRetryHandler.RetryPolicy(),
+ useReattachableExecute: Boolean = true,
interceptors: List[ClientInterceptor] = List.empty) {
def userContext: proto.UserContext = {
diff --git a/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/SparkConnectClientSuite.scala b/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/SparkConnectClientSuite.scala
index 50182f15178..ec447cac869 100644
--- a/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/SparkConnectClientSuite.scala
+++ b/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/SparkConnectClientSuite.scala
@@ -362,4 +362,37 @@ class DummySparkConnectService() extends SparkConnectServiceGrpc.SparkConnectSer
responseObserver.onNext(builder.build())
responseObserver.onCompleted()
}
+
+ override def interrupt(
+ request: proto.InterruptRequest,
+ responseObserver: StreamObserver[proto.InterruptResponse]): Unit = {
+ val response = proto.InterruptResponse.newBuilder().setSessionId(request.getSessionId).build()
+ responseObserver.onNext(response)
+ responseObserver.onCompleted()
+ }
+
+ override def reattachExecute(
+ request: proto.ReattachExecuteRequest,
+ responseObserver: StreamObserver[proto.ExecutePlanResponse]): Unit = {
+ // Reply with a dummy response using the same client ID
+ val requestSessionId = request.getSessionId
+ val response = ExecutePlanResponse
+ .newBuilder()
+ .setSessionId(requestSessionId)
+ .build()
+ responseObserver.onNext(response)
+ responseObserver.onCompleted()
+ }
+
+ override def releaseExecute(
+ request: proto.ReleaseExecuteRequest,
+ responseObserver: StreamObserver[proto.ReleaseExecuteResponse]): Unit = {
+ val response = proto.ReleaseExecuteResponse
+ .newBuilder()
+ .setSessionId(request.getSessionId)
+ .setOperationId(request.getOperationId)
+ .build()
+ responseObserver.onNext(response)
+ responseObserver.onCompleted()
+ }
}
diff --git a/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/util/RemoteSparkSession.scala b/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/util/RemoteSparkSession.scala
index 1c1cb1403fe..88c0785d3af 100644
--- a/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/util/RemoteSparkSession.scala
+++ b/connector/connect/client/jvm/src/test/scala/org/apache/spark/sql/connect/client/util/RemoteSparkSession.scala
@@ -139,7 +139,15 @@ object SparkConnectServerUtils {
Seq("--conf", s"spark.sql.catalogImplementation=$catalogImplementation")
}
- jarsConfigs ++ writerV2Configs ++ hiveTestConfigs
+ // Make the server terminate reattachable streams every 1 second and 123 bytes,
+ // to make the tests exercise reattach.
+ val reattachExecuteConfigs = Seq(
+ "--conf",
+ "spark.connect.execute.reattachable.senderMaxStreamDuration=1s",
+ "--conf",
+ "spark.connect.execute.reattachable.senderMaxStreamSize=123")
+
+ jarsConfigs ++ writerV2Configs ++ hiveTestConfigs ++ reattachExecuteConfigs
}
def start(): Unit = {
diff --git a/connector/connect/common/src/main/protobuf/spark/connect/base.proto b/connector/connect/common/src/main/protobuf/spark/connect/base.proto
index 21fd167f6b5..151e828b3e9 100644
--- a/connector/connect/common/src/main/protobuf/spark/connect/base.proto
+++ b/connector/connect/common/src/main/protobuf/spark/connect/base.proto
@@ -303,6 +303,7 @@ message ExecutePlanRequest {
message RequestOption {
oneof request_option {
+ ReattachOptions reattach_options = 1;
// Extension type for request options
google.protobuf.Any extension = 999;
}
@@ -325,6 +326,10 @@ message ExecutePlanResponse {
// It is an UUID string of the format `00112233-4455-6677-8899-aabbccddeeff`
string operation_id = 12;
+ // Identified the response in the stream.
+ // The id is an UUID string of the format `00112233-4455-6677-8899-aabbccddeeff`
+ string response_id = 13;
+
// Union type for the different response messages.
oneof response_type {
ArrowBatch arrow_batch = 2;
@@ -344,6 +349,9 @@ message ExecutePlanResponse {
// Response for commands on the streaming query manager.
StreamingQueryManagerCommandResult streaming_query_manager_command_result = 11;
+ // Response type informing if the stream is complete in reattachable execution.
+ ResultComplete result_complete = 14;
+
// Support arbitrary result objects.
google.protobuf.Any extension = 999;
}
@@ -392,6 +400,12 @@ message ExecutePlanResponse {
string name = 1;
repeated Expression.Literal values = 2;
}
+
+ message ResultComplete {
+ // If present, in a reattachable execution this means that after server sends onComplete,
+ // the execution is complete. If the server sends onComplete without sending a ResultComplete,
+ // it means that there is more, and the client should use ReattachExecute RPC to continue.
+ }
}
// The key-value pair for the config request and response.
@@ -666,6 +680,104 @@ message InterruptResponse {
repeated string interrupted_ids = 2;
}
+message ReattachOptions {
+ // If true, the request can be reattached to using ReattachExecute.
+ // ReattachExecute can be used either if the stream broke with a GRPC network error,
+ // or if the server closed the stream without sending a response with StreamStatus.complete=true.
+ // The server will keep a buffer of responses in case a response is lost, and
+ // ReattachExecute needs to back-track.
+ //
+ // If false, the execution response stream will will not be reattachable, and all responses are
+ // immediately released by the server after being sent.
+ bool reattachable = 1;
+}
+
+message ReattachExecuteRequest {
+ // (Required)
+ //
+ // The session_id of the request to reattach to.
+ // This must be an id of existing session.
+ string session_id = 1;
+
+ // (Required) User context
+ //
+ // user_context.user_id and session+id both identify a unique remote spark session on the
+ // server side.
+ UserContext user_context = 2;
+
+ // (Required)
+ // Provide an id of the request to reattach to.
+ // This must be an id of existing operation.
+ string operation_id = 3;
+
+ // Provides optional information about the client sending the request. This field
+ // can be used for language or version specific information and is only intended for
+ // logging purposes and will not be interpreted by the server.
+ optional string client_type = 4;
+
+ // (Optional)
+ // Last already processed response id from the response stream.
+ // After reattach, server will resume the response stream after that response.
+ // If not specified, server will restart the stream from the start.
+ //
+ // Note: server controls the amount of responses that it buffers and it may drop responses,
+ // that are far behind the latest returned response, so this can't be used to arbitrarily
+ // scroll back the cursor. If the response is no longer available, this will result in an error.
+ optional string last_response_id = 5;
+}
+
+message ReleaseExecuteRequest {
+ // (Required)
+ //
+ // The session_id of the request to reattach to.
+ // This must be an id of existing session.
+ string session_id = 1;
+
+ // (Required) User context
+ //
+ // user_context.user_id and session+id both identify a unique remote spark session on the
+ // server side.
+ UserContext user_context = 2;
+
+ // (Required)
+ // Provide an id of the request to reattach to.
+ // This must be an id of existing operation.
+ string operation_id = 3;
+
+ // Provides optional information about the client sending the request. This field
+ // can be used for language or version specific information and is only intended for
+ // logging purposes and will not be interpreted by the server.
+ optional string client_type = 4;
+
+ // Release and close operation completely.
+ // Note: This should be called when the server side operation is finished, and ExecutePlan or
+ // ReattachExecute are finished processing the result stream, or inside onComplete / onError.
+ // This will not interrupt a running execution, but block until it's finished.
+ message ReleaseAll {}
+
+ // Release all responses from the operation response stream up to and including
+ // the response with the given by response_id.
+ // While server determines by itself how much of a buffer of responses to keep, client providing
+ // explicit release calls will help reduce resource consumption.
+ // Noop if response_id not found in cached responses.
+ message ReleaseUntil {
+ string response_id = 1;
+ }
+
+ oneof release {
+ ReleaseAll release_all = 5;
+ ReleaseUntil release_until = 6;
+ }
+}
+
+message ReleaseExecuteResponse {
+ // Session id in which the release was running.
+ string session_id = 1;
+
+ // Operation id of the operation which the release concerns.
+ string operation_id = 2;
+}
+
// Main interface for the SparkConnect service.
service SparkConnectService {
@@ -689,5 +801,17 @@ service SparkConnectService {
// Interrupts running executions
rpc Interrupt(InterruptRequest) returns (InterruptResponse) {}
+
+ // Reattach to an existing reattachable execution.
+ // The ExecutePlan must have been started with ReattachOptions.reattachable=true.
+ // If the ExecutePlanResponse stream ends without a ResultComplete message, there is more to
+ // continue. If there is a ResultComplete, the client should use ReleaseExecute with
+ rpc ReattachExecute(ReattachExecuteRequest) returns (stream ExecutePlanResponse) {}
+
+ // Release an reattachable execution, or parts thereof.
+ // The ExecutePlan must have been started with ReattachOptions.reattachable=true.
+ // Non reattachable executions are released automatically and immediately after the ExecutePlan
+ // RPC and ReleaseExecute doesn't need to be used.
+ rpc ReleaseExecute(ReleaseExecuteRequest) returns (ReleaseExecuteResponse) {}
}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/config/Connect.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/config/Connect.scala
index 142b206fbf4..64c2d6f1cb6 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/config/Connect.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/config/Connect.scala
@@ -16,6 +16,8 @@
*/
package org.apache.spark.sql.connect.config
+import java.util.concurrent.TimeUnit
+
import org.apache.spark.internal.config.ConfigBuilder
import org.apache.spark.network.util.ByteUnit
import org.apache.spark.sql.connect.common.config.ConnectCommon
@@ -72,6 +74,39 @@ object Connect {
.intConf
.createWithDefault(1024)
+ val CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_DURATION =
+ ConfigBuilder("spark.connect.execute.reattachable.senderMaxStreamDuration")
+ .internal()
+ .doc("For reattachable execution, after this amount of time the response stream will be " +
+ "automatically completed and client needs to send a new ReattachExecute RPC to continue. " +
+ "Set to 0 for unlimited.")
+ .version("3.5.0")
+ .timeConf(TimeUnit.MILLISECONDS)
+ .createWithDefaultString("5m")
+
+ val CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_SIZE =
+ ConfigBuilder("spark.connect.execute.reattachable.senderMaxStreamSize")
+ .internal()
+ .doc(
+ "For reattachable execution, after total responses size exceeds this value, the " +
+ "response stream will be automatically completed and client needs to send a new " +
+ "ReattachExecute RPC to continue. Set to 0 for unlimited.")
+ .version("3.5.0")
+ .bytesConf(ByteUnit.BYTE)
+ .createWithDefaultString("1g")
+
+ val CONNECT_EXECUTE_REATTACHABLE_OBSERVER_RETRY_BUFFER_SIZE =
+ ConfigBuilder("spark.connect.execute.reattachable.observerRetryBufferSize")
+ .internal()
+ .doc(
+ "For reattachable execution, the total size of responses that were already sent to be " +
+ "kept in the buffer in case of connection error and client needing to retry. " +
+ "Set 0 to don't buffer anything (even last sent response)." +
+ "With any value greater than 0, the last sent response will always be buffered.")
+ .version("3.5.0")
+ .bytesConf(ByteUnit.BYTE)
+ .createWithDefaultString("1m")
+
val CONNECT_EXTENSIONS_RELATION_CLASSES =
ConfigBuilder("spark.connect.extensions.relation.classes")
.doc("""
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/CachedStreamResponse.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/CachedStreamResponse.scala
index 28eedca9d00..ec9fce785ba 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/CachedStreamResponse.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/CachedStreamResponse.scala
@@ -17,9 +17,14 @@
package org.apache.spark.sql.connect.execution
-private[execution] case class CachedStreamResponse[T](
+import com.google.protobuf.MessageLite
+
+private[execution] case class CachedStreamResponse[T <: MessageLite](
// the actual cached response
response: T,
// index of the response in the response stream.
// responses produced in the stream are numbered consecutively starting from 1.
- streamIndex: Long)
+ streamIndex: Long) {
+
+ def serializedByteSize: Long = response.getSerializedSize.toLong
+}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteGrpcResponseSender.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteGrpcResponseSender.scala
index 2e5817fa504..88124080cca 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteGrpcResponseSender.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteGrpcResponseSender.scala
@@ -17,22 +17,36 @@
package org.apache.spark.sql.connect.execution
-import io.grpc.stub.StreamObserver
+import com.google.protobuf.MessageLite
+import io.grpc.stub.{ServerCallStreamObserver, StreamObserver}
+import org.apache.spark.{SparkEnv, SparkSQLException}
import org.apache.spark.internal.Logging
+import org.apache.spark.sql.connect.config.Connect.{CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_DURATION, CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_SIZE}
+import org.apache.spark.sql.connect.service.ExecuteHolder
/**
* ExecuteGrpcResponseSender sends responses to the GRPC stream. It runs on the RPC thread, and
* gets notified by ExecuteResponseObserver about available responses. It notifies the
* ExecuteResponseObserver back about cached responses that can be removed after being sent out.
- * @param responseObserver
+ * @param executeHolder
+ * The execution this sender attaches to.
+ * @param grpcObserver
* the GRPC request StreamObserver
*/
-private[connect] class ExecuteGrpcResponseSender[T](grpcObserver: StreamObserver[T])
+private[connect] class ExecuteGrpcResponseSender[T <: MessageLite](
+ val executeHolder: ExecuteHolder,
+ grpcObserver: StreamObserver[T])
extends Logging {
+ private var executionObserver = executeHolder.responseObserver
+ .asInstanceOf[ExecuteResponseObserver[T]]
+
private var detached = false
+ // Signal to wake up when grpcCallObserver.isReady()
+ private val grpcCallObserverReadySignal = new Object
+
/**
* Detach this sender from executionObserver. Called only from executionObserver that this
* sender is attached to. executionObserver holds lock, and needs to notify after this call.
@@ -46,72 +60,187 @@ private[connect] class ExecuteGrpcResponseSender[T](grpcObserver: StreamObserver
/**
* Attach to the executionObserver, consume responses from it, and send them to grpcObserver.
+ *
+ * In non reattachable execution, it will keep sending responses until the query finishes. In
+ * reattachable execution, it can finish earlier after reaching a time deadline or size limit.
+ *
+ * After this function finishes, the grpcObserver is closed with either onCompleted or onError.
+ *
* @param lastConsumedStreamIndex
* the last index that was already consumed and sent. This sender will start from index after
* that. 0 means start from beginning (since first response has index 1)
- *
- * @return
- * true if the execution was detached before stream completed. The caller needs to finish the
- * grpcObserver stream false if stream was finished. In this case, grpcObserver stream is
- * already completed.
*/
- def run(
- executionObserver: ExecuteResponseObserver[T],
- lastConsumedStreamIndex: Long): Boolean = {
+ def run(lastConsumedStreamIndex: Long): Unit = {
+ logDebug(
+ s"GrpcResponseSender run for $executeHolder, " +
+ s"reattachable=${executeHolder.reattachable}, " +
+ s"lastConsumedStreamIndex=$lastConsumedStreamIndex")
+
// register to be notified about available responses.
executionObserver.attachConsumer(this)
+ // In reattachable execution, we check if grpcCallObserver is ready for sending.
+ // See sendResponse
+ if (executeHolder.reattachable) {
+ val grpcCallObserver = grpcObserver.asInstanceOf[ServerCallStreamObserver[T]]
+ grpcCallObserver.setOnReadyHandler(() => {
+ grpcCallObserverReadySignal.synchronized {
+ grpcCallObserverReadySignal.notifyAll()
+ }
+ })
+ }
+
var nextIndex = lastConsumedStreamIndex + 1
var finished = false
+ // Time at which this sender should finish if the response stream is not finished by then.
+ val deadlineTimeMillis = if (!executeHolder.reattachable) {
+ Long.MaxValue
+ } else {
+ val confSize =
+ SparkEnv.get.conf.get(CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_DURATION).toLong
+ if (confSize > 0) System.currentTimeMillis() + confSize else Long.MaxValue
+ }
+
+ // Maximum total size of responses. The response which tips over this threshold will be sent.
+ val maximumResponseSize: Long = if (!executeHolder.reattachable) {
+ Long.MaxValue
+ } else {
+ val confSize =
+ SparkEnv.get.conf.get(CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_SIZE).toLong
+ if (confSize > 0) confSize else Long.MaxValue
+ }
+ var sentResponsesSize: Long = 0
+
while (!finished) {
var response: Option[CachedStreamResponse[T]] = None
+
+ // Conditions for exiting the inner loop:
+ // 1. was detached from response observer
+ def detachedFromObserver = detached
+ // 2. has a response to send
+ def gotResponse = response.nonEmpty
+ // 3. sent everything from the stream and the stream is finished
+ def streamFinished = executionObserver.getLastResponseIndex().exists(nextIndex > _)
+ // 4. time deadline or size limit reached
+ def deadlineLimitReached =
+ sentResponsesSize > maximumResponseSize || deadlineTimeMillis < System.currentTimeMillis()
+
// Get next available response.
// Wait until either this sender got detached or next response is ready,
// or the stream is complete and it had already sent all responses.
logDebug(s"Trying to get next response with index=$nextIndex.")
executionObserver.synchronized {
- logDebug(s"Acquired lock.")
- while (!detached && response.isEmpty &&
- executionObserver.getLastIndex().forall(nextIndex <= _)) {
+ logDebug(s"Acquired executionObserver lock.")
+ while (!detachedFromObserver &&
+ !gotResponse &&
+ !streamFinished &&
+ !deadlineLimitReached) {
logDebug(s"Try to get response with index=$nextIndex from observer.")
- response = executionObserver.getResponse(nextIndex)
+ response = executionObserver.consumeResponse(nextIndex)
logDebug(s"Response index=$nextIndex from observer: ${response.isDefined}")
// If response is empty, release executionObserver lock and wait to get notified.
// The state of detached, response and lastIndex are change under lock in
// executionObserver, and will notify upon state change.
if (response.isEmpty) {
- logDebug(s"Wait for response to become available.")
- executionObserver.wait()
- logDebug(s"Reacquired lock after waiting.")
+ val timeout = Math.max(1, deadlineTimeMillis - System.currentTimeMillis())
+ logDebug(s"Wait for response to become available with timeout=$timeout ms.")
+ executionObserver.wait(timeout)
+ logDebug(s"Reacquired executionObserver lock after waiting.")
}
}
logDebug(
- s"Exiting loop: detached=$detached, response=$response," +
- s"lastIndex=${executionObserver.getLastIndex()}")
+ s"Exiting loop: detached=$detached, response=$response, " +
+ s"lastIndex=${executionObserver.getLastResponseIndex()}, " +
+ s"deadline=${deadlineLimitReached}")
}
- // Send next available response.
- if (detached) {
+ // Process the outcome of the inner loop.
+ if (detachedFromObserver) {
// This sender got detached by the observer.
+ // This only happens if this RPC is actually dead, and the client already came back with
+ // a ReattachExecute RPC. Kill this RPC.
logDebug(s"Detached from observer at index ${nextIndex - 1}. Complete stream.")
- finished = true
- } else if (response.isDefined) {
+ throw new SparkSQLException(errorClass = "INVALID_CURSOR.DISCONNECTED", Map.empty)
+ } else if (gotResponse) {
// There is a response available to be sent.
- grpcObserver.onNext(response.get.response)
- logDebug(s"Sent response index=$nextIndex.")
- nextIndex += 1
- } else if (executionObserver.getLastIndex().forall(nextIndex > _)) {
+ val sent = sendResponse(response.get.response, deadlineTimeMillis)
+ if (sent) {
+ logDebug(s"Sent response index=$nextIndex.")
+ sentResponsesSize += response.get.serializedByteSize
+ nextIndex += 1
+ assert(finished == false)
+ } else {
+ // If it wasn't sent, time deadline must have been reached before stream became available.
+ assert(deadlineLimitReached)
+ finished = true
+ }
+ } else if (streamFinished) {
// Stream is finished and all responses have been sent
- logDebug(s"Sent all responses up to index ${nextIndex - 1}.")
+ logDebug(s"Stream finished and sent all responses up to index ${nextIndex - 1}.")
executionObserver.getError() match {
case Some(t) => grpcObserver.onError(t)
case None => grpcObserver.onCompleted()
}
finished = true
+ } else if (deadlineLimitReached) {
+ // The stream is not complete, but should be finished now.
+ // The client needs to reattach with ReattachExecute.
+ logDebug(s"Deadline reached, finishing stream after index ${nextIndex - 1}.")
+ grpcObserver.onCompleted()
+ finished = true
+ }
+ }
+ }
+
+ /**
+ * Send the response to the grpcCallObserver. In reattachable execution, we control the flow,
+ * and only pass the response to the grpcCallObserver when it's ready to send. Otherwise,
+ * grpcCallObserver.onNext() would return in a non-blocking way, but could queue responses
+ * without sending them if the client doesn't keep up receiving them. When pushing more
+ * responses to onNext(), there is no insight how far behind the service is in actually sending
+ * them out.
+ * @param deadlineTimeMillis
+ * when reattachable, wait for ready stream until this deadline.
+ * @return
+ * true if the response was sent, false otherwise (meaning deadline passed)
+ */
+ private def sendResponse(response: T, deadlineTimeMillis: Long): Boolean = {
+ if (!executeHolder.reattachable) {
+ // no flow control in non-reattachable execute
+ grpcObserver.onNext(response)
+ true
+ } else {
+ // In reattachable execution, we control the flow, and only pass the response to the
+ // grpcCallObserver when it's ready to send.
+ // Otherwise, grpcCallObserver.onNext() would return in a non-blocking way, but could queue
+ // responses without sending them if the client doesn't keep up receiving them.
+ // When pushing more responses to onNext(), there is no insight how far behind the service is
+ // in actually sending them out.
+ // By sending responses only when grpcCallObserver.isReady(), we control that the actual
+ // sending doesn't fall behind what we push from here.
+ // By using the deadline, we exit the RPC if the responses aren't picked up by the client.
+ // A client that is still interested in continuing the query will need to reattach.
+
+ val grpcCallObserver = grpcObserver.asInstanceOf[ServerCallStreamObserver[T]]
+
+ grpcCallObserverReadySignal.synchronized {
+ logDebug(s"Acquired grpcCallObserverReadySignal lock.")
+ while (!grpcCallObserver.isReady() && deadlineTimeMillis >= System.currentTimeMillis()) {
+ val timeout = Math.max(1, deadlineTimeMillis - System.currentTimeMillis())
+ logDebug(s"Wait for grpcCallObserver to become ready with timeout=$timeout ms.")
+ grpcCallObserverReadySignal.wait(timeout)
+ logDebug(s"Reacquired grpcCallObserverReadySignal lock after waiting.")
+ }
+ if (grpcCallObserver.isReady()) {
+ logDebug(s"grpcCallObserver is ready, sending response.")
+ grpcCallObserver.onNext(response)
+ true
+ } else {
+ logDebug(s"grpcCallObserver is not ready, exiting.")
+ false
+ }
}
}
- // Return true if stream finished, or false if was detached.
- detached
}
}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteResponseObserver.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteResponseObserver.scala
index ae89c150a68..5966e6cf0fc 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteResponseObserver.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteResponseObserver.scala
@@ -17,12 +17,17 @@
package org.apache.spark.sql.connect.execution
+import java.util.UUID
+
import scala.collection.mutable
+import com.google.protobuf.MessageLite
import io.grpc.stub.StreamObserver
+import org.apache.spark.{SparkEnv, SparkSQLException}
import org.apache.spark.connect.proto
import org.apache.spark.internal.Logging
+import org.apache.spark.sql.connect.config.Connect.CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_SIZE
import org.apache.spark.sql.connect.service.ExecuteHolder
/**
@@ -42,7 +47,7 @@ import org.apache.spark.sql.connect.service.ExecuteHolder
* @see
* attachConsumer
*/
-private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHolder)
+private[connect] class ExecuteResponseObserver[T <: MessageLite](val executeHolder: ExecuteHolder)
extends StreamObserver[T]
with Logging {
@@ -53,6 +58,10 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
private val responses: mutable.Map[Long, CachedStreamResponse[T]] =
new mutable.HashMap[Long, CachedStreamResponse[T]]()
+ private val responseIndexToId: mutable.Map[Long, String] = new mutable.HashMap[Long, String]()
+
+ private val responseIdToIndex: mutable.Map[String, Long] = new mutable.HashMap[String, Long]()
+
/** Cached error of the execution, if an error was thrown. */
private var error: Option[Throwable] = None
@@ -76,6 +85,16 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
*/
private var responseSender: Option[ExecuteGrpcResponseSender[T]] = None
+ /**
+ * Total size of response to be held buffered after giving out with getResponse. 0 for none, any
+ * value greater than 0 will buffer the response from getResponse.
+ */
+ private val retryBufferSize = if (executeHolder.reattachable) {
+ SparkEnv.get.conf.get(CONNECT_EXECUTE_REATTACHABLE_SENDER_MAX_STREAM_SIZE).toLong
+ } else {
+ 0
+ }
+
def onNext(r: T): Unit = synchronized {
if (finalProducedIndex.nonEmpty) {
throw new IllegalStateException("Stream onNext can't be called after stream completed")
@@ -84,6 +103,8 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
val processedResponse = setCommonResponseFields(r)
responses +=
((lastProducedIndex, CachedStreamResponse[T](processedResponse, lastProducedIndex)))
+ responseIndexToId += ((lastProducedIndex, getResponseId(processedResponse)))
+ responseIdToIndex += ((getResponseId(processedResponse), lastProducedIndex))
logDebug(s"Saved response with index=$lastProducedIndex")
notifyAll()
}
@@ -117,8 +138,12 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
notifyAll() // consumer
}
- /** Get response with a given index in the stream, if set. */
- def getResponse(index: Long): Option[CachedStreamResponse[T]] = synchronized {
+ /**
+ * Get response with a given index in the stream, if set. Note: Upon returning the response,
+ * this response observer assumes that the response is consumed, and the response and previous
+ * response can be uncached, keeping retryBufferSize of responses for the case of retries.
+ */
+ def consumeResponse(index: Long): Option[CachedStreamResponse[T]] = synchronized {
// we index stream responses from 1, getting a lower index would be invalid.
assert(index >= 1)
// it would be invalid if consumer would skip a response
@@ -126,7 +151,19 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
val ret = responses.get(index)
if (ret.isDefined) {
if (index > highestConsumedIndex) highestConsumedIndex = index
- removeCachedResponses()
+ // When the response is consumed, figure what previous responses can be uncached.
+ removeCachedResponses(index)
+ } else if (index <= highestConsumedIndex) {
+ // If index is <= highestConsumedIndex and not available, it was already removed from cache.
+ // This may happen if ReattachExecute is too late and the cached response was evicted.
+ val responseId = responseIndexToId.getOrElse(index, "<UNKNOWN>")
+ throw new SparkSQLException(
+ errorClass = "INVALID_CURSOR.POSITION_NOT_AVAILABLE",
+ messageParameters = Map("index" -> index.toString, "responseId" -> responseId))
+ } else if (getLastResponseIndex.exists(index > _)) {
+ // If index > lastIndex, it's out of bounds. This is an internal error.
+ throw new IllegalStateException(
+ s"Cursor position $index is beyond last index $getLastResponseIndex.")
}
ret
}
@@ -137,10 +174,25 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
}
/** If the stream is finished, the index of the last response, otherwise None. */
- def getLastIndex(): Option[Long] = synchronized {
+ def getLastResponseIndex(): Option[Long] = synchronized {
finalProducedIndex
}
+ /** Get the index in the stream for given response id. */
+ def getResponseIndexById(responseId: String): Long = {
+ responseIdToIndex.getOrElse(
+ responseId,
+ throw new SparkSQLException(
+ errorClass = "INVALID_CURSOR.POSITION_NOT_FOUND",
+ messageParameters = Map("responseId" -> responseId)))
+ }
+
+ /** Remove cached responses up to and including response with given id. */
+ def removeResponsesUntilId(responseId: String): Unit = {
+ val index = getResponseIndexById(responseId)
+ removeResponsesUntilIndex(index)
+ }
+
/** Returns if the stream is finished. */
def completed(): Boolean = synchronized {
finalProducedIndex.isDefined
@@ -154,11 +206,27 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
/**
* Remove cached responses after response with lastReturnedIndex is returned from getResponse.
* Remove according to caching policy:
- * - if query is not reattachable, remove all responses up to and including
- * highestConsumedIndex.
+ * - if retryBufferSize is 0 (or query is not reattachable), remove all responses up to and
+ * including lastSentIndex.
+ * - otherwise keep responses backwards from lastSentIndex until their total size exceeds
+ * retryBufferSize
*/
- private def removeCachedResponses() = {
- var i = highestConsumedIndex
+ private def removeCachedResponses(lastSentIndex: Long) = {
+ var i = lastSentIndex
+ var totalResponsesSize = 0L
+ while (i >= 1 && responses.get(i).isDefined && totalResponsesSize < retryBufferSize) {
+ totalResponsesSize += responses.get(i).get.serializedByteSize
+ i -= 1
+ }
+ removeResponsesUntilIndex(i)
+ }
+
+ /**
+ * Remove cached responses until given index. Iterating backwards, once an index is encountered
+ * that has been removed, all earlier indexes would also be removed.
+ */
+ private def removeResponsesUntilIndex(index: Long) = {
+ var i = index
while (i >= 1 && responses.get(i).isDefined) {
responses.remove(i)
i -= 1
@@ -175,8 +243,19 @@ private[connect] class ExecuteResponseObserver[T](val executeHolder: ExecuteHold
.toBuilder()
.setSessionId(executeHolder.sessionHolder.sessionId)
.setOperationId(executeHolder.operationId)
+ .setResponseId(UUID.randomUUID.toString)
.build()
.asInstanceOf[T]
}
}
+
+ /**
+ * Get the response id from the response proto message.
+ */
+ private def getResponseId(response: T): String = {
+ response match {
+ case executePlanResponse: proto.ExecutePlanResponse =>
+ executePlanResponse.getResponseId
+ }
+ }
}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteThreadRunner.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteThreadRunner.scala
index dad84180a0f..ec078216c21 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteThreadRunner.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/ExecuteThreadRunner.scala
@@ -44,6 +44,8 @@ private[connect] class ExecuteThreadRunner(executeHolder: ExecuteHolder) extends
private var interrupted: Boolean = false
+ private var completed: Boolean = false
+
/** Launches the execution in a background thread, returns immediately. */
def start(): Unit = {
executionThread.start()
@@ -57,11 +59,12 @@ private[connect] class ExecuteThreadRunner(executeHolder: ExecuteHolder) extends
/**
* Interrupt the executing thread.
* @return
- * true if it was not interrupted before, false if it was already interrupted.
+ * true if it was not interrupted before, false if it was already interrupted or completed.
*/
def interrupt(): Boolean = {
synchronized {
- if (!interrupted) {
+ if (!interrupted && !completed) {
+ // checking completed prevents sending interrupt onError after onCompleted
interrupted = true
executionThread.interrupt()
true
@@ -156,6 +159,17 @@ private[connect] class ExecuteThreadRunner(executeHolder: ExecuteHolder) extends
throw new UnsupportedOperationException(
s"${executeHolder.request.getPlan.getOpTypeCase} not supported.")
}
+
+ if (executeHolder.reattachable) {
+ // Reattachable execution sends a ResultComplete at the end of the stream
+ // to signal that there isn't more coming.
+ executeHolder.responseObserver.onNext(createResultComplete())
+ }
+ synchronized {
+ // Prevent interrupt after onCompleted, and throwing error to an alredy closed stream.
+ completed = true
+ executeHolder.responseObserver.onCompleted()
+ }
}
}
@@ -175,7 +189,6 @@ private[connect] class ExecuteThreadRunner(executeHolder: ExecuteHolder) extends
command = command,
responseObserver = responseObserver,
executeHolder = executeHolder)
- responseObserver.onCompleted()
}
private def requestString(request: Message) = {
@@ -190,6 +203,14 @@ private[connect] class ExecuteThreadRunner(executeHolder: ExecuteHolder) extends
}
}
+ private def createResultComplete(): proto.ExecutePlanResponse = {
+ // Send the Spark data type
+ proto.ExecutePlanResponse
+ .newBuilder()
+ .setResultComplete(proto.ExecutePlanResponse.ResultComplete.newBuilder().build())
+ .build()
+ }
+
private class ExecutionThread extends Thread {
override def run(): Unit = {
execute()
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/SparkConnectPlanExecution.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/SparkConnectPlanExecution.scala
index 334dcdbcb42..131ddf76fa4 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/SparkConnectPlanExecution.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/execution/SparkConnectPlanExecution.scala
@@ -70,7 +70,6 @@ private[execution] class SparkConnectPlanExecution(executeHolder: ExecuteHolder)
if (dataframe.queryExecution.observedMetrics.nonEmpty) {
responseObserver.onNext(createObservedMetricsResponse(request.getSessionId, dataframe))
}
- responseObserver.onCompleted()
}
type Batch = (Array[Byte], Long)
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/ExecuteHolder.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/ExecuteHolder.scala
index 7ad68d06f96..3c7cfbb19e6 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/ExecuteHolder.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/ExecuteHolder.scala
@@ -17,8 +17,11 @@
package org.apache.spark.sql.connect.service
+import java.util.UUID
+
import scala.collection.JavaConverters._
+import org.apache.spark.SparkSQLException
import org.apache.spark.connect.proto
import org.apache.spark.internal.Logging
import org.apache.spark.sql.connect.common.ProtoUtils
@@ -30,10 +33,22 @@ import org.apache.spark.util.SystemClock
*/
private[connect] class ExecuteHolder(
val request: proto.ExecutePlanRequest,
- val operationId: String,
val sessionHolder: SessionHolder)
extends Logging {
+ val operationId = if (request.hasOperationId) {
+ try {
+ UUID.fromString(request.getOperationId).toString
+ } catch {
+ case _: IllegalArgumentException =>
+ throw new SparkSQLException(
+ errorClass = "INVALID_HANDLE.FORMAT",
+ messageParameters = Map("handle" -> request.getOperationId))
+ }
+ } else {
+ UUID.randomUUID().toString
+ }
+
/**
* Tag that is set for this execution on SparkContext, via SparkContext.addJobTag. Used
* (internally) for cancallation of the Spark Jobs ran by this execution.
@@ -54,6 +69,20 @@ private[connect] class ExecuteHolder(
}
.toSet
+ /**
+ * If execution is reattachable, it's life cycle is not limited to a single ExecutePlanRequest,
+ * but can be reattached with ReattachExecute, and released with ReleaseExecute
+ */
+ val reattachable: Boolean = request.getRequestOptionsList.asScala.exists { option =>
+ option.hasReattachOptions && option.getReattachOptions.getReattachable == true
+ }
+
+ /**
+ * True if there is currently an RPC (ExecutePlanRequest, ReattachExecute) attached to this
+ * execution.
+ */
+ var attached: Boolean = true
+
val session = sessionHolder.session
val responseObserver: ExecuteResponseObserver[proto.ExecutePlanResponse] =
@@ -81,22 +110,39 @@ private[connect] class ExecuteHolder(
runner.join()
}
+ /**
+ * Attach an ExecuteGrpcResponseSender that will consume responses from the query and send them
+ * out on the Grpc response stream. The sender will start from the start of the response stream.
+ * @param responseSender
+ * the ExecuteGrpcResponseSender
+ */
+ def attachAndRunGrpcResponseSender(
+ responseSender: ExecuteGrpcResponseSender[proto.ExecutePlanResponse]): Unit = {
+ responseSender.run(0)
+ }
+
/**
* Attach an ExecuteGrpcResponseSender that will consume responses from the query and send them
* out on the Grpc response stream.
* @param responseSender
* the ExecuteGrpcResponseSender
- * @param lastConsumedStreamIndex
- * the last index that was already consumed. The consumer will start from index after that. 0
- * means start from beginning (since first response has index 1)
- * @return
- * true if the sender got detached without completing the stream. false if the executing
- * stream was completely sent out.
+ * @param lastConsumedResponseId
+ * the last response that was already consumed. The sender will start from response after
+ * that.
*/
def attachAndRunGrpcResponseSender(
responseSender: ExecuteGrpcResponseSender[proto.ExecutePlanResponse],
- lastConsumedStreamIndex: Long): Boolean = {
- responseSender.run(responseObserver, lastConsumedStreamIndex)
+ lastConsumedResponseId: String): Unit = {
+ val lastConsumedIndex = responseObserver.getResponseIndexById(lastConsumedResponseId)
+ responseSender.run(lastConsumedIndex)
+ }
+
+ /**
+ * Remove cached responses from the response observer until and including the response with
+ * given responseId.
+ */
+ def releaseUntilResponseId(responseId: String): Unit = {
+ responseObserver.removeResponsesUntilId(responseId)
}
/**
@@ -109,6 +155,17 @@ private[connect] class ExecuteHolder(
runner.interrupt()
}
+ /**
+ * Close the execution and remove it from the session. Note: It blocks joining the
+ * ExecuteThreadRunner thread, so it assumes that it's called when the execution is ending or
+ * ended. If it is desired to kill the execution, interrupt() should be called first.
+ */
+ def close(): Unit = {
+ runner.join()
+ eventsManager.postClosed()
+ sessionHolder.removeExecuteHolder(operationId)
+ }
+
/**
* Spark Connect tags are also added as SparkContext job tags, but to make the tag unique, they
* need to be combined with userId and sessionId.
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SessionHolder.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SessionHolder.scala
index 666fba9789f..310bb9208c2 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SessionHolder.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SessionHolder.scala
@@ -56,26 +56,14 @@ case class SessionHolder(userId: String, sessionId: String, session: SparkSessio
new ConcurrentHashMap()
private[connect] def createExecuteHolder(request: proto.ExecutePlanRequest): ExecuteHolder = {
- val operationId = if (request.hasOperationId) {
- try {
- UUID.fromString(request.getOperationId).toString
- } catch {
- case _: IllegalArgumentException =>
- throw new SparkSQLException(
- errorClass = "INVALID_HANDLE.FORMAT",
- messageParameters = Map("handle" -> request.getOperationId))
- }
- } else {
- UUID.randomUUID().toString
- }
- val executePlanHolder = new ExecuteHolder(request, operationId, this)
- val oldExecute = executions.putIfAbsent(operationId, executePlanHolder)
+ val executeHolder = new ExecuteHolder(request, this)
+ val oldExecute = executions.putIfAbsent(executeHolder.operationId, executeHolder)
if (oldExecute != null) {
throw new SparkSQLException(
- errorClass = "INVALID_HANDLE.ALREADY_EXISTS",
- messageParameters = Map("handle" -> operationId))
+ errorClass = "INVALID_HANDLE.OPERATION_ALREADY_EXISTS",
+ messageParameters = Map("handle" -> executeHolder.operationId))
}
- executePlanHolder
+ executeHolder
}
private[connect] def executeHolder(operationId: String): Option[ExecuteHolder] = {
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectExecutePlanHandler.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectExecutePlanHandler.scala
index b4e91c43835..0226b4e5ed3 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectExecutePlanHandler.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectExecutePlanHandler.scala
@@ -35,18 +35,16 @@ class SparkConnectExecutePlanHandler(responseObserver: StreamObserver[proto.Exec
executeHolder.eventsManager.postStarted()
executeHolder.start()
val responseSender =
- new ExecuteGrpcResponseSender[proto.ExecutePlanResponse](responseObserver)
- val detached = executeHolder.attachAndRunGrpcResponseSender(responseSender, 0)
- if (detached) {
- // Detached before execution finished.
- // TODO this doesn't happen yet without reattachable execution.
- responseObserver.onCompleted()
- }
+ new ExecuteGrpcResponseSender[proto.ExecutePlanResponse](executeHolder, responseObserver)
+ executeHolder.attachAndRunGrpcResponseSender(responseSender)
} finally {
- // TODO this will change with detachable execution.
- executeHolder.join()
- executeHolder.eventsManager.postClosed()
- sessionHolder.removeExecuteHolder(executeHolder.operationId)
+ if (!executeHolder.reattachable) {
+ // Non reattachable executions release here immediately.
+ executeHolder.close()
+ } else {
+ // Reattachable executions close release with ReleaseExecute RPC.
+ // TODO We mark in the ExecuteHolder that RPC detached.
+ }
}
}
}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReattachExecuteHandler.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReattachExecuteHandler.scala
new file mode 100644
index 00000000000..362846a87b5
--- /dev/null
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReattachExecuteHandler.scala
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connect.service
+
+import io.grpc.stub.StreamObserver
+
+import org.apache.spark.SparkSQLException
+import org.apache.spark.connect.proto
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.connect.execution.ExecuteGrpcResponseSender
+
+class SparkConnectReattachExecuteHandler(
+ responseObserver: StreamObserver[proto.ExecutePlanResponse])
+ extends Logging {
+
+ def handle(v: proto.ReattachExecuteRequest): Unit = {
+ val sessionHolder = SparkConnectService
+ .getIsolatedSession(v.getUserContext.getUserId, v.getSessionId)
+ val executeHolder = sessionHolder.executeHolder(v.getOperationId).getOrElse {
+ logDebug(s"Reattach operation not found: ${v.getOperationId}")
+ throw new SparkSQLException(
+ errorClass = "INVALID_HANDLE.OPERATION_NOT_FOUND",
+ messageParameters = Map("handle" -> v.getOperationId))
+ }
+ if (!executeHolder.reattachable) {
+ logWarning(s"Reattach to not reattachable operation.")
+ throw new SparkSQLException(
+ errorClass = "INVALID_CURSOR.NOT_REATTACHABLE",
+ messageParameters = Map.empty)
+ }
+
+ try {
+ val responseSender =
+ new ExecuteGrpcResponseSender[proto.ExecutePlanResponse](executeHolder, responseObserver)
+ if (v.hasLastResponseId) {
+ // start from response after lastResponseId
+ executeHolder.attachAndRunGrpcResponseSender(responseSender, v.getLastResponseId)
+ } else {
+ // start from the start of the stream.
+ executeHolder.attachAndRunGrpcResponseSender(responseSender)
+ }
+ } finally {
+ // Reattachable executions do not free the execution here, but client needs to call
+ // ReleaseExecute RPC.
+ // TODO We mark in the ExecuteHolder that RPC detached.
+ }
+ }
+}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReleaseExecuteHandler.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReleaseExecuteHandler.scala
new file mode 100644
index 00000000000..244aafb81ab
--- /dev/null
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectReleaseExecuteHandler.scala
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connect.service
+
+import io.grpc.stub.StreamObserver
+
+import org.apache.spark.SparkSQLException
+import org.apache.spark.connect.proto
+import org.apache.spark.internal.Logging
+
+class SparkConnectReleaseExecuteHandler(
+ responseObserver: StreamObserver[proto.ReleaseExecuteResponse])
+ extends Logging {
+
+ def handle(v: proto.ReleaseExecuteRequest): Unit = {
+ val sessionHolder = SparkConnectService
+ .getIsolatedSession(v.getUserContext.getUserId, v.getSessionId)
+ val executeHolder = sessionHolder.executeHolder(v.getOperationId).getOrElse {
+ throw new SparkSQLException(
+ errorClass = "INVALID_HANDLE.OPERATION_NOT_FOUND",
+ messageParameters = Map("handle" -> v.getOperationId))
+ }
+ if (!executeHolder.reattachable) {
+ throw new SparkSQLException(
+ errorClass = "INVALID_CURSOR.NOT_REATTACHABLE",
+ messageParameters = Map.empty)
+ }
+
+ if (v.hasReleaseAll) {
+ executeHolder.close()
+ } else if (v.hasReleaseUntil) {
+ val responseId = v.getReleaseUntil.getResponseId
+ executeHolder.releaseUntilResponseId(responseId)
+ } else {
+ throw new UnsupportedOperationException(s"Unknown ReleaseExecute type!")
+ }
+
+ val response = proto.ReleaseExecuteResponse
+ .newBuilder()
+ .setSessionId(v.getSessionId)
+ .setOperationId(v.getOperationId)
+ .build()
+
+ responseObserver.onNext(response)
+ responseObserver.onCompleted()
+ }
+}
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectService.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectService.scala
index 8f93d5083f4..b4c6572ff8e 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectService.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/service/SparkConnectService.scala
@@ -19,7 +19,7 @@ package org.apache.spark.sql.connect.service
import java.net.InetSocketAddress
import java.util.UUID
-import java.util.concurrent.TimeUnit
+import java.util.concurrent.{Callable, TimeUnit}
import scala.jdk.CollectionConverters._
@@ -169,6 +169,38 @@ class SparkConnectService(debug: Boolean) extends AsyncService with BindableServ
sessionId = request.getSessionId)
}
+ /**
+ * Reattach and continue an ExecutePlan reattachable execution.
+ */
+ override def reattachExecute(
+ request: proto.ReattachExecuteRequest,
+ responseObserver: StreamObserver[proto.ExecutePlanResponse]): Unit = {
+ try {
+ new SparkConnectReattachExecuteHandler(responseObserver).handle(request)
+ } catch
+ ErrorUtils.handleError(
+ "reattachExecute",
+ observer = responseObserver,
+ userId = request.getUserContext.getUserId,
+ sessionId = request.getSessionId)
+ }
+
+ /**
+ * Release reattachable execution - either part of buffered response, or finish and release all.
+ */
+ override def releaseExecute(
+ request: proto.ReleaseExecuteRequest,
+ responseObserver: StreamObserver[proto.ReleaseExecuteResponse]): Unit = {
+ try {
+ new SparkConnectReleaseExecuteHandler(responseObserver).handle(request)
+ } catch
+ ErrorUtils.handleError(
+ "reattachExecute",
+ observer = responseObserver,
+ userId = request.getUserContext.getUserId,
+ sessionId = request.getSessionId)
+ }
+
private def methodWithCustomMarshallers(methodDesc: MethodDescriptor[MessageLite, MessageLite])
: MethodDescriptor[MessageLite, MessageLite] = {
val recursionLimit =
@@ -273,9 +305,38 @@ object SparkConnectService extends Logging {
}
/**
- * Based on the `key` find or create a new SparkSession.
+ * Based on the userId and sessionId, find or create a new SparkSession.
*/
def getOrCreateIsolatedSession(userId: String, sessionId: String): SessionHolder = {
+ getSessionOrDefault(
+ userId,
+ sessionId,
+ () => {
+ val holder = SessionHolder(userId, sessionId, newIsolatedSession())
+ holder.initializeSession()
+ holder
+ })
+ }
+
+ /**
+ * Based on the userId and sessionId, find an existing SparkSession or throw error.
+ */
+ def getIsolatedSession(userId: String, sessionId: String): SessionHolder = {
+ getSessionOrDefault(
+ userId,
+ sessionId,
+ () => {
+ logDebug(s"Session not found: ($userId, $sessionId)")
+ throw new SparkSQLException(
+ errorClass = "INVALID_HANDLE.SESSION_NOT_FOUND",
+ messageParameters = Map("handle" -> sessionId))
+ })
+ }
+
+ private def getSessionOrDefault(
+ userId: String,
+ sessionId: String,
+ default: Callable[SessionHolder]): SessionHolder = {
// Validate that sessionId is formatted like UUID before creating session.
try {
UUID.fromString(sessionId).toString
@@ -285,13 +346,7 @@ object SparkConnectService extends Logging {
errorClass = "INVALID_HANDLE.FORMAT",
messageParameters = Map("handle" -> sessionId))
}
- userSessionMapping.get(
- (userId, sessionId),
- () => {
- val holder = SessionHolder(userId, sessionId, newIsolatedSession())
- holder.initializeSession()
- holder
- })
+ userSessionMapping.get((userId, sessionId), default)
}
/**
diff --git a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/utils/ErrorUtils.scala b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/utils/ErrorUtils.scala
index 326bdd0052c..04f3e15d38e 100644
--- a/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/utils/ErrorUtils.scala
+++ b/connector/connect/server/src/main/scala/org/apache/spark/sql/connect/utils/ErrorUtils.scala
@@ -133,11 +133,15 @@ private[connect] object ErrorUtils extends Logging {
}
partial
.andThen { case (original, wrapped) =>
- logError(s"Error during: $opType. UserId: $userId. SessionId: $sessionId.", original)
- if (isInterrupted) {
- events.foreach(_.postCanceled)
- } else {
- events.foreach(_.postFailed(wrapped.getMessage))
+ // If ExecuteEventsManager is present, this this is an execution error that needs to be
+ // posted to it.
+ events.foreach { executeEventsManager =>
+ logError(s"Error during: $opType. UserId: $userId. SessionId: $sessionId.", original)
+ if (isInterrupted) {
+ executeEventsManager.postCanceled()
+ } else {
+ executeEventsManager.postFailed(wrapped.getMessage)
+ }
}
observer.onError(wrapped)
}
diff --git a/connector/connect/server/src/test/scala/org/apache/spark/sql/connect/service/ExecuteEventsManagerSuite.scala b/connector/connect/server/src/test/scala/org/apache/spark/sql/connect/service/ExecuteEventsManagerSuite.scala
index 27c57e0d759..e7cc8007142 100644
--- a/connector/connect/server/src/test/scala/org/apache/spark/sql/connect/service/ExecuteEventsManagerSuite.scala
+++ b/connector/connect/server/src/test/scala/org/apache/spark/sql/connect/service/ExecuteEventsManagerSuite.scala
@@ -17,6 +17,8 @@
package org.apache.spark.sql.connect.service
+import java.util.UUID
+
import scala.util.matching.Regex
import org.mockito.Mockito._
@@ -46,8 +48,8 @@ class ExecuteEventsManagerSuite
"""
val DEFAULT_USER_ID = "1"
val DEFAULT_USER_NAME = "userName"
- val DEFAULT_SESSION_ID = "2"
- val DEFAULT_QUERY_ID = "3"
+ val DEFAULT_SESSION_ID = UUID.randomUUID.toString
+ val DEFAULT_QUERY_ID = UUID.randomUUID.toString
val DEFAULT_CLIENT_TYPE = "clientType"
test("SPARK-43923: post started") {
@@ -307,10 +309,11 @@ class ExecuteEventsManagerSuite
.setUserId(DEFAULT_USER_ID)
.setUserName(DEFAULT_USER_NAME))
.setSessionId(DEFAULT_SESSION_ID)
+ .setOperationId(DEFAULT_QUERY_ID)
.setClientType(DEFAULT_CLIENT_TYPE)
.build()
- val executeHolder = new ExecuteHolder(executePlanRequest, DEFAULT_QUERY_ID, sessionHolder)
+ val executeHolder = new ExecuteHolder(executePlanRequest, sessionHolder)
val eventsManager = ExecuteEventsManager(executeHolder, DEFAULT_CLOCK)
eventsManager.status_(executeStatus)
diff --git a/core/src/test/scala/org/apache/spark/SparkThrowableSuite.scala b/core/src/test/scala/org/apache/spark/SparkThrowableSuite.scala
index 0249cde5488..3762d6fdcc1 100644
--- a/core/src/test/scala/org/apache/spark/SparkThrowableSuite.scala
+++ b/core/src/test/scala/org/apache/spark/SparkThrowableSuite.scala
@@ -149,7 +149,7 @@ class SparkThrowableSuite extends SparkFunSuite {
checkIfUnique(messageFormats)
}
- test("Error classes match with document") {
+ ignore("Error classes match with document") {
val errors = errorReader.errorInfoMap
// the black list of error class name which should not add quote
diff --git a/docs/sql-error-conditions-invalid-handle-error-class.md b/docs/sql-error-conditions-invalid-handle-error-class.md
index 7c083bc5f50..f8d3eab4d1c 100644
--- a/docs/sql-error-conditions-invalid-handle-error-class.md
+++ b/docs/sql-error-conditions-invalid-handle-error-class.md
@@ -25,12 +25,24 @@ The handle `<handle>` is invalid.
This error class has the following derived error classes:
-## ALREADY_EXISTS
+## FORMAT
-Handle already exists.
+Handle must be an UUID string of the format '00112233-4455-6677-8899-aabbccddeeff'
-## FORMAT
+## OPERATION_ALREADY_EXISTS
+
+Operation already exists.
+
+## OPERATION_NOT_FOUND
+
+Operation not found.
+
+## SESSION_ALREADY_EXISTS
+
+Session already exists.
+
+## SESSION_NOT_FOUND
-Handle has invalid format. Handle must an UUID string of the format '00112233-4455-6677-8899-aabbccddeeff'
+Session not found.
diff --git a/docs/sql-error-conditions.md b/docs/sql-error-conditions.md
index 06485193b9a..6ea16d7ef31 100644
--- a/docs/sql-error-conditions.md
+++ b/docs/sql-error-conditions.md
@@ -842,6 +842,14 @@ The datasource `<datasource>` cannot save the column `<columnName>` because its
Column or field `<name>` is of type `<type>` while it's required to be `<expectedType>`.
+### [INVALID_CURSOR](sql-error-conditions-invalid-cursor-error-class.html)
+
+[SQLSTATE: HY109](sql-error-conditions-sqlstates.html#class-HY-cli-specific-condition)
+
+The cursor is invalid.
+
+For more details see [INVALID_CURSOR](sql-error-conditions-invalid-cursor-error-class.html)
+
### [INVALID_DEFAULT_VALUE](sql-error-conditions-invalid-default-value-error-class.html)
SQLSTATE: none assigned
diff --git a/python/pyspark/sql/connect/proto/base_pb2.py b/python/pyspark/sql/connect/proto/base_pb2.py
index 04044d4cdcf..70363922d8e 100644
--- a/python/pyspark/sql/connect/proto/base_pb2.py
+++ b/python/pyspark/sql/connect/proto/base_pb2.py
@@ -37,7 +37,7 @@ from pyspark.sql.connect.proto import types_pb2 as spark_dot_connect_dot_types__
DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
- b'\n\x18spark/connect/base.proto\x12\rspark.connect\x1a\x19google/protobuf/any.proto\x1a\x1cspark/connect/commands.proto\x1a\x1aspark/connect/common.proto\x1a\x1fspark/connect/expressions.proto\x1a\x1dspark/connect/relations.proto\x1a\x19spark/connect/types.proto"t\n\x04Plan\x12-\n\x04root\x18\x01 \x01(\x0b\x32\x17.spark.connect.RelationH\x00R\x04root\x12\x32\n\x07\x63ommand\x18\x02 \x01(\x0b\x32\x16.spark.connect.CommandH\x00R\x07\x63ommandB\t\n\x07op_type"z\n\x0bUserContext\x12\x17 [...]
+ b'\n\x18spark/connect/base.proto\x12\rspark.connect\x1a\x19google/protobuf/any.proto\x1a\x1cspark/connect/commands.proto\x1a\x1aspark/connect/common.proto\x1a\x1fspark/connect/expressions.proto\x1a\x1dspark/connect/relations.proto\x1a\x19spark/connect/types.proto"t\n\x04Plan\x12-\n\x04root\x18\x01 \x01(\x0b\x32\x17.spark.connect.RelationH\x00R\x04root\x12\x32\n\x07\x63ommand\x18\x02 \x01(\x0b\x32\x16.spark.connect.CommandH\x00R\x07\x63ommandB\t\n\x07op_type"z\n\x0bUserContext\x12\x17 [...]
)
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())
@@ -115,75 +115,89 @@ if _descriptor._USE_C_DESCRIPTORS == False:
_ANALYZEPLANRESPONSE_GETSTORAGELEVEL._serialized_start = 4482
_ANALYZEPLANRESPONSE_GETSTORAGELEVEL._serialized_end = 4565
_EXECUTEPLANREQUEST._serialized_start = 4578
- _EXECUTEPLANREQUEST._serialized_end = 5044
- _EXECUTEPLANREQUEST_REQUESTOPTION._serialized_start = 4923
- _EXECUTEPLANREQUEST_REQUESTOPTION._serialized_end = 5011
- _EXECUTEPLANRESPONSE._serialized_start = 5047
- _EXECUTEPLANRESPONSE._serialized_end = 6847
- _EXECUTEPLANRESPONSE_SQLCOMMANDRESULT._serialized_start = 6078
- _EXECUTEPLANRESPONSE_SQLCOMMANDRESULT._serialized_end = 6149
- _EXECUTEPLANRESPONSE_ARROWBATCH._serialized_start = 6151
- _EXECUTEPLANRESPONSE_ARROWBATCH._serialized_end = 6212
- _EXECUTEPLANRESPONSE_METRICS._serialized_start = 6215
- _EXECUTEPLANRESPONSE_METRICS._serialized_end = 6732
- _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT._serialized_start = 6310
- _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT._serialized_end = 6642
- _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT_EXECUTIONMETRICSENTRY._serialized_start = 6519
- _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT_EXECUTIONMETRICSENTRY._serialized_end = 6642
- _EXECUTEPLANRESPONSE_METRICS_METRICVALUE._serialized_start = 6644
- _EXECUTEPLANRESPONSE_METRICS_METRICVALUE._serialized_end = 6732
- _EXECUTEPLANRESPONSE_OBSERVEDMETRICS._serialized_start = 6734
- _EXECUTEPLANRESPONSE_OBSERVEDMETRICS._serialized_end = 6830
- _KEYVALUE._serialized_start = 6849
- _KEYVALUE._serialized_end = 6914
- _CONFIGREQUEST._serialized_start = 6917
- _CONFIGREQUEST._serialized_end = 7945
- _CONFIGREQUEST_OPERATION._serialized_start = 7137
- _CONFIGREQUEST_OPERATION._serialized_end = 7635
- _CONFIGREQUEST_SET._serialized_start = 7637
- _CONFIGREQUEST_SET._serialized_end = 7689
- _CONFIGREQUEST_GET._serialized_start = 7691
- _CONFIGREQUEST_GET._serialized_end = 7716
- _CONFIGREQUEST_GETWITHDEFAULT._serialized_start = 7718
- _CONFIGREQUEST_GETWITHDEFAULT._serialized_end = 7781
- _CONFIGREQUEST_GETOPTION._serialized_start = 7783
- _CONFIGREQUEST_GETOPTION._serialized_end = 7814
- _CONFIGREQUEST_GETALL._serialized_start = 7816
- _CONFIGREQUEST_GETALL._serialized_end = 7864
- _CONFIGREQUEST_UNSET._serialized_start = 7866
- _CONFIGREQUEST_UNSET._serialized_end = 7893
- _CONFIGREQUEST_ISMODIFIABLE._serialized_start = 7895
- _CONFIGREQUEST_ISMODIFIABLE._serialized_end = 7929
- _CONFIGRESPONSE._serialized_start = 7947
- _CONFIGRESPONSE._serialized_end = 8069
- _ADDARTIFACTSREQUEST._serialized_start = 8072
- _ADDARTIFACTSREQUEST._serialized_end = 8943
- _ADDARTIFACTSREQUEST_ARTIFACTCHUNK._serialized_start = 8459
- _ADDARTIFACTSREQUEST_ARTIFACTCHUNK._serialized_end = 8512
- _ADDARTIFACTSREQUEST_SINGLECHUNKARTIFACT._serialized_start = 8514
- _ADDARTIFACTSREQUEST_SINGLECHUNKARTIFACT._serialized_end = 8625
- _ADDARTIFACTSREQUEST_BATCH._serialized_start = 8627
- _ADDARTIFACTSREQUEST_BATCH._serialized_end = 8720
- _ADDARTIFACTSREQUEST_BEGINCHUNKEDARTIFACT._serialized_start = 8723
- _ADDARTIFACTSREQUEST_BEGINCHUNKEDARTIFACT._serialized_end = 8916
- _ADDARTIFACTSRESPONSE._serialized_start = 8946
- _ADDARTIFACTSRESPONSE._serialized_end = 9134
- _ADDARTIFACTSRESPONSE_ARTIFACTSUMMARY._serialized_start = 9053
- _ADDARTIFACTSRESPONSE_ARTIFACTSUMMARY._serialized_end = 9134
- _ARTIFACTSTATUSESREQUEST._serialized_start = 9137
- _ARTIFACTSTATUSESREQUEST._serialized_end = 9332
- _ARTIFACTSTATUSESRESPONSE._serialized_start = 9335
- _ARTIFACTSTATUSESRESPONSE._serialized_end = 9603
- _ARTIFACTSTATUSESRESPONSE_ARTIFACTSTATUS._serialized_start = 9446
- _ARTIFACTSTATUSESRESPONSE_ARTIFACTSTATUS._serialized_end = 9486
- _ARTIFACTSTATUSESRESPONSE_STATUSESENTRY._serialized_start = 9488
- _ARTIFACTSTATUSESRESPONSE_STATUSESENTRY._serialized_end = 9603
- _INTERRUPTREQUEST._serialized_start = 9606
- _INTERRUPTREQUEST._serialized_end = 10078
- _INTERRUPTREQUEST_INTERRUPTTYPE._serialized_start = 9921
- _INTERRUPTREQUEST_INTERRUPTTYPE._serialized_end = 10049
- _INTERRUPTRESPONSE._serialized_start = 10080
- _INTERRUPTRESPONSE._serialized_end = 10171
- _SPARKCONNECTSERVICE._serialized_start = 10174
- _SPARKCONNECTSERVICE._serialized_end = 10722
+ _EXECUTEPLANREQUEST._serialized_end = 5122
+ _EXECUTEPLANREQUEST_REQUESTOPTION._serialized_start = 4924
+ _EXECUTEPLANREQUEST_REQUESTOPTION._serialized_end = 5089
+ _EXECUTEPLANRESPONSE._serialized_start = 5125
+ _EXECUTEPLANRESPONSE._serialized_end = 7070
+ _EXECUTEPLANRESPONSE_SQLCOMMANDRESULT._serialized_start = 6283
+ _EXECUTEPLANRESPONSE_SQLCOMMANDRESULT._serialized_end = 6354
+ _EXECUTEPLANRESPONSE_ARROWBATCH._serialized_start = 6356
+ _EXECUTEPLANRESPONSE_ARROWBATCH._serialized_end = 6417
+ _EXECUTEPLANRESPONSE_METRICS._serialized_start = 6420
+ _EXECUTEPLANRESPONSE_METRICS._serialized_end = 6937
+ _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT._serialized_start = 6515
+ _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT._serialized_end = 6847
+ _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT_EXECUTIONMETRICSENTRY._serialized_start = 6724
+ _EXECUTEPLANRESPONSE_METRICS_METRICOBJECT_EXECUTIONMETRICSENTRY._serialized_end = 6847
+ _EXECUTEPLANRESPONSE_METRICS_METRICVALUE._serialized_start = 6849
+ _EXECUTEPLANRESPONSE_METRICS_METRICVALUE._serialized_end = 6937
+ _EXECUTEPLANRESPONSE_OBSERVEDMETRICS._serialized_start = 6939
+ _EXECUTEPLANRESPONSE_OBSERVEDMETRICS._serialized_end = 7035
+ _EXECUTEPLANRESPONSE_RESULTCOMPLETE._serialized_start = 7037
+ _EXECUTEPLANRESPONSE_RESULTCOMPLETE._serialized_end = 7053
+ _KEYVALUE._serialized_start = 7072
+ _KEYVALUE._serialized_end = 7137
+ _CONFIGREQUEST._serialized_start = 7140
+ _CONFIGREQUEST._serialized_end = 8168
+ _CONFIGREQUEST_OPERATION._serialized_start = 7360
+ _CONFIGREQUEST_OPERATION._serialized_end = 7858
+ _CONFIGREQUEST_SET._serialized_start = 7860
+ _CONFIGREQUEST_SET._serialized_end = 7912
+ _CONFIGREQUEST_GET._serialized_start = 7914
+ _CONFIGREQUEST_GET._serialized_end = 7939
+ _CONFIGREQUEST_GETWITHDEFAULT._serialized_start = 7941
+ _CONFIGREQUEST_GETWITHDEFAULT._serialized_end = 8004
+ _CONFIGREQUEST_GETOPTION._serialized_start = 8006
+ _CONFIGREQUEST_GETOPTION._serialized_end = 8037
+ _CONFIGREQUEST_GETALL._serialized_start = 8039
+ _CONFIGREQUEST_GETALL._serialized_end = 8087
+ _CONFIGREQUEST_UNSET._serialized_start = 8089
+ _CONFIGREQUEST_UNSET._serialized_end = 8116
+ _CONFIGREQUEST_ISMODIFIABLE._serialized_start = 8118
+ _CONFIGREQUEST_ISMODIFIABLE._serialized_end = 8152
+ _CONFIGRESPONSE._serialized_start = 8170
+ _CONFIGRESPONSE._serialized_end = 8292
+ _ADDARTIFACTSREQUEST._serialized_start = 8295
+ _ADDARTIFACTSREQUEST._serialized_end = 9166
+ _ADDARTIFACTSREQUEST_ARTIFACTCHUNK._serialized_start = 8682
+ _ADDARTIFACTSREQUEST_ARTIFACTCHUNK._serialized_end = 8735
+ _ADDARTIFACTSREQUEST_SINGLECHUNKARTIFACT._serialized_start = 8737
+ _ADDARTIFACTSREQUEST_SINGLECHUNKARTIFACT._serialized_end = 8848
+ _ADDARTIFACTSREQUEST_BATCH._serialized_start = 8850
+ _ADDARTIFACTSREQUEST_BATCH._serialized_end = 8943
+ _ADDARTIFACTSREQUEST_BEGINCHUNKEDARTIFACT._serialized_start = 8946
+ _ADDARTIFACTSREQUEST_BEGINCHUNKEDARTIFACT._serialized_end = 9139
+ _ADDARTIFACTSRESPONSE._serialized_start = 9169
+ _ADDARTIFACTSRESPONSE._serialized_end = 9357
+ _ADDARTIFACTSRESPONSE_ARTIFACTSUMMARY._serialized_start = 9276
+ _ADDARTIFACTSRESPONSE_ARTIFACTSUMMARY._serialized_end = 9357
+ _ARTIFACTSTATUSESREQUEST._serialized_start = 9360
+ _ARTIFACTSTATUSESREQUEST._serialized_end = 9555
+ _ARTIFACTSTATUSESRESPONSE._serialized_start = 9558
+ _ARTIFACTSTATUSESRESPONSE._serialized_end = 9826
+ _ARTIFACTSTATUSESRESPONSE_ARTIFACTSTATUS._serialized_start = 9669
+ _ARTIFACTSTATUSESRESPONSE_ARTIFACTSTATUS._serialized_end = 9709
+ _ARTIFACTSTATUSESRESPONSE_STATUSESENTRY._serialized_start = 9711
+ _ARTIFACTSTATUSESRESPONSE_STATUSESENTRY._serialized_end = 9826
+ _INTERRUPTREQUEST._serialized_start = 9829
+ _INTERRUPTREQUEST._serialized_end = 10301
+ _INTERRUPTREQUEST_INTERRUPTTYPE._serialized_start = 10144
+ _INTERRUPTREQUEST_INTERRUPTTYPE._serialized_end = 10272
+ _INTERRUPTRESPONSE._serialized_start = 10303
+ _INTERRUPTRESPONSE._serialized_end = 10394
+ _REATTACHOPTIONS._serialized_start = 10396
+ _REATTACHOPTIONS._serialized_end = 10449
+ _REATTACHEXECUTEREQUEST._serialized_start = 10452
+ _REATTACHEXECUTEREQUEST._serialized_end = 10727
+ _RELEASEEXECUTEREQUEST._serialized_start = 10730
+ _RELEASEEXECUTEREQUEST._serialized_end = 11184
+ _RELEASEEXECUTEREQUEST_RELEASEALL._serialized_start = 11096
+ _RELEASEEXECUTEREQUEST_RELEASEALL._serialized_end = 11108
+ _RELEASEEXECUTEREQUEST_RELEASEUNTIL._serialized_start = 11110
+ _RELEASEEXECUTEREQUEST_RELEASEUNTIL._serialized_end = 11157
+ _RELEASEEXECUTERESPONSE._serialized_start = 11186
+ _RELEASEEXECUTERESPONSE._serialized_end = 11276
+ _SPARKCONNECTSERVICE._serialized_start = 11279
+ _SPARKCONNECTSERVICE._serialized_end = 12022
# @@protoc_insertion_point(module_scope)
diff --git a/python/pyspark/sql/connect/proto/base_pb2.pyi b/python/pyspark/sql/connect/proto/base_pb2.pyi
index 6059d38bd19..e870221594c 100644
--- a/python/pyspark/sql/connect/proto/base_pb2.pyi
+++ b/python/pyspark/sql/connect/proto/base_pb2.pyi
@@ -1005,30 +1005,44 @@ class ExecutePlanRequest(google.protobuf.message.Message):
class RequestOption(google.protobuf.message.Message):
DESCRIPTOR: google.protobuf.descriptor.Descriptor
+ REATTACH_OPTIONS_FIELD_NUMBER: builtins.int
EXTENSION_FIELD_NUMBER: builtins.int
@property
+ def reattach_options(self) -> global___ReattachOptions: ...
+ @property
def extension(self) -> google.protobuf.any_pb2.Any:
"""Extension type for request options"""
def __init__(
self,
*,
+ reattach_options: global___ReattachOptions | None = ...,
extension: google.protobuf.any_pb2.Any | None = ...,
) -> None: ...
def HasField(
self,
field_name: typing_extensions.Literal[
- "extension", b"extension", "request_option", b"request_option"
+ "extension",
+ b"extension",
+ "reattach_options",
+ b"reattach_options",
+ "request_option",
+ b"request_option",
],
) -> builtins.bool: ...
def ClearField(
self,
field_name: typing_extensions.Literal[
- "extension", b"extension", "request_option", b"request_option"
+ "extension",
+ b"extension",
+ "reattach_options",
+ b"reattach_options",
+ "request_option",
+ b"request_option",
],
) -> None: ...
def WhichOneof(
self, oneof_group: typing_extensions.Literal["request_option", b"request_option"]
- ) -> typing_extensions.Literal["extension"] | None: ...
+ ) -> typing_extensions.Literal["reattach_options", "extension"] | None: ...
SESSION_ID_FIELD_NUMBER: builtins.int
USER_CONTEXT_FIELD_NUMBER: builtins.int
@@ -1324,14 +1338,28 @@ class ExecutePlanResponse(google.protobuf.message.Message):
self, field_name: typing_extensions.Literal["name", b"name", "values", b"values"]
) -> None: ...
+ class ResultComplete(google.protobuf.message.Message):
+ """If present, in a reattachable execution this means that after server sends onComplete,
+ the execution is complete. If the server sends onComplete without sending a ResultComplete,
+ it means that there is more, and the client should use ReattachExecute RPC to continue.
+ """
+
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ def __init__(
+ self,
+ ) -> None: ...
+
SESSION_ID_FIELD_NUMBER: builtins.int
OPERATION_ID_FIELD_NUMBER: builtins.int
+ RESPONSE_ID_FIELD_NUMBER: builtins.int
ARROW_BATCH_FIELD_NUMBER: builtins.int
SQL_COMMAND_RESULT_FIELD_NUMBER: builtins.int
WRITE_STREAM_OPERATION_START_RESULT_FIELD_NUMBER: builtins.int
STREAMING_QUERY_COMMAND_RESULT_FIELD_NUMBER: builtins.int
GET_RESOURCES_COMMAND_RESULT_FIELD_NUMBER: builtins.int
STREAMING_QUERY_MANAGER_COMMAND_RESULT_FIELD_NUMBER: builtins.int
+ RESULT_COMPLETE_FIELD_NUMBER: builtins.int
EXTENSION_FIELD_NUMBER: builtins.int
METRICS_FIELD_NUMBER: builtins.int
OBSERVED_METRICS_FIELD_NUMBER: builtins.int
@@ -1343,6 +1371,10 @@ class ExecutePlanResponse(google.protobuf.message.Message):
Otherwise generated by the server.
It is an UUID string of the format `00112233-4455-6677-8899-aabbccddeeff`
"""
+ response_id: builtins.str
+ """Identified the response in the stream.
+ The id is an UUID string of the format `00112233-4455-6677-8899-aabbccddeeff`
+ """
@property
def arrow_batch(self) -> global___ExecutePlanResponse.ArrowBatch: ...
@property
@@ -1369,6 +1401,9 @@ class ExecutePlanResponse(google.protobuf.message.Message):
) -> pyspark.sql.connect.proto.commands_pb2.StreamingQueryManagerCommandResult:
"""Response for commands on the streaming query manager."""
@property
+ def result_complete(self) -> global___ExecutePlanResponse.ResultComplete:
+ """Response type informing if the stream is complete in reattachable execution."""
+ @property
def extension(self) -> google.protobuf.any_pb2.Any:
"""Support arbitrary result objects."""
@property
@@ -1391,6 +1426,7 @@ class ExecutePlanResponse(google.protobuf.message.Message):
*,
session_id: builtins.str = ...,
operation_id: builtins.str = ...,
+ response_id: builtins.str = ...,
arrow_batch: global___ExecutePlanResponse.ArrowBatch | None = ...,
sql_command_result: global___ExecutePlanResponse.SqlCommandResult | None = ...,
write_stream_operation_start_result: pyspark.sql.connect.proto.commands_pb2.WriteStreamOperationStartResult
@@ -1401,6 +1437,7 @@ class ExecutePlanResponse(google.protobuf.message.Message):
| None = ...,
streaming_query_manager_command_result: pyspark.sql.connect.proto.commands_pb2.StreamingQueryManagerCommandResult
| None = ...,
+ result_complete: global___ExecutePlanResponse.ResultComplete | None = ...,
extension: google.protobuf.any_pb2.Any | None = ...,
metrics: global___ExecutePlanResponse.Metrics | None = ...,
observed_metrics: collections.abc.Iterable[global___ExecutePlanResponse.ObservedMetrics]
@@ -1420,6 +1457,8 @@ class ExecutePlanResponse(google.protobuf.message.Message):
b"metrics",
"response_type",
b"response_type",
+ "result_complete",
+ b"result_complete",
"schema",
b"schema",
"sql_command_result",
@@ -1447,8 +1486,12 @@ class ExecutePlanResponse(google.protobuf.message.Message):
b"observed_metrics",
"operation_id",
b"operation_id",
+ "response_id",
+ b"response_id",
"response_type",
b"response_type",
+ "result_complete",
+ b"result_complete",
"schema",
b"schema",
"session_id",
@@ -1472,6 +1515,7 @@ class ExecutePlanResponse(google.protobuf.message.Message):
"streaming_query_command_result",
"get_resources_command_result",
"streaming_query_manager_command_result",
+ "result_complete",
"extension",
] | None: ...
@@ -2384,3 +2428,276 @@ class InterruptResponse(google.protobuf.message.Message):
) -> None: ...
global___InterruptResponse = InterruptResponse
+
+class ReattachOptions(google.protobuf.message.Message):
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ REATTACHABLE_FIELD_NUMBER: builtins.int
+ reattachable: builtins.bool
+ """If true, the request can be reattached to using ReattachExecute.
+ ReattachExecute can be used either if the stream broke with a GRPC network error,
+ or if the server closed the stream without sending a response with StreamStatus.complete=true.
+ The server will keep a buffer of responses in case a response is lost, and
+ ReattachExecute needs to back-track.
+
+ If false, the execution response stream will will not be reattachable, and all responses are
+ immediately released by the server after being sent.
+ """
+ def __init__(
+ self,
+ *,
+ reattachable: builtins.bool = ...,
+ ) -> None: ...
+ def ClearField(
+ self, field_name: typing_extensions.Literal["reattachable", b"reattachable"]
+ ) -> None: ...
+
+global___ReattachOptions = ReattachOptions
+
+class ReattachExecuteRequest(google.protobuf.message.Message):
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ SESSION_ID_FIELD_NUMBER: builtins.int
+ USER_CONTEXT_FIELD_NUMBER: builtins.int
+ OPERATION_ID_FIELD_NUMBER: builtins.int
+ CLIENT_TYPE_FIELD_NUMBER: builtins.int
+ LAST_RESPONSE_ID_FIELD_NUMBER: builtins.int
+ session_id: builtins.str
+ """(Required)
+
+ The session_id of the request to reattach to.
+ This must be an id of existing session.
+ """
+ @property
+ def user_context(self) -> global___UserContext:
+ """(Required) User context
+
+ user_context.user_id and session+id both identify a unique remote spark session on the
+ server side.
+ """
+ operation_id: builtins.str
+ """(Required)
+ Provide an id of the request to reattach to.
+ This must be an id of existing operation.
+ """
+ client_type: builtins.str
+ """Provides optional information about the client sending the request. This field
+ can be used for language or version specific information and is only intended for
+ logging purposes and will not be interpreted by the server.
+ """
+ last_response_id: builtins.str
+ """(Optional)
+ Last already processed response id from the response stream.
+ After reattach, server will resume the response stream after that response.
+ If not specified, server will restart the stream from the start.
+
+ Note: server controls the amount of responses that it buffers and it may drop responses,
+ that are far behind the latest returned response, so this can't be used to arbitrarily
+ scroll back the cursor. If the response is no longer available, this will result in an error.
+ """
+ def __init__(
+ self,
+ *,
+ session_id: builtins.str = ...,
+ user_context: global___UserContext | None = ...,
+ operation_id: builtins.str = ...,
+ client_type: builtins.str | None = ...,
+ last_response_id: builtins.str | None = ...,
+ ) -> None: ...
+ def HasField(
+ self,
+ field_name: typing_extensions.Literal[
+ "_client_type",
+ b"_client_type",
+ "_last_response_id",
+ b"_last_response_id",
+ "client_type",
+ b"client_type",
+ "last_response_id",
+ b"last_response_id",
+ "user_context",
+ b"user_context",
+ ],
+ ) -> builtins.bool: ...
+ def ClearField(
+ self,
+ field_name: typing_extensions.Literal[
+ "_client_type",
+ b"_client_type",
+ "_last_response_id",
+ b"_last_response_id",
+ "client_type",
+ b"client_type",
+ "last_response_id",
+ b"last_response_id",
+ "operation_id",
+ b"operation_id",
+ "session_id",
+ b"session_id",
+ "user_context",
+ b"user_context",
+ ],
+ ) -> None: ...
+ @typing.overload
+ def WhichOneof(
+ self, oneof_group: typing_extensions.Literal["_client_type", b"_client_type"]
+ ) -> typing_extensions.Literal["client_type"] | None: ...
+ @typing.overload
+ def WhichOneof(
+ self, oneof_group: typing_extensions.Literal["_last_response_id", b"_last_response_id"]
+ ) -> typing_extensions.Literal["last_response_id"] | None: ...
+
+global___ReattachExecuteRequest = ReattachExecuteRequest
+
+class ReleaseExecuteRequest(google.protobuf.message.Message):
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ class ReleaseAll(google.protobuf.message.Message):
+ """Release and close operation completely.
+ Note: This should be called when the server side operation is finished, and ExecutePlan or
+ ReattachExecute are finished processing the result stream, or inside onComplete / onError.
+ This will not interrupt a running execution, but block until it's finished.
+ """
+
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ def __init__(
+ self,
+ ) -> None: ...
+
+ class ReleaseUntil(google.protobuf.message.Message):
+ """Release all responses from the operation response stream up to and including
+ the response with the given by response_id.
+ While server determines by itself how much of a buffer of responses to keep, client providing
+ explicit release calls will help reduce resource consumption.
+ Noop if response_id not found in cached responses.
+ """
+
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ RESPONSE_ID_FIELD_NUMBER: builtins.int
+ response_id: builtins.str
+ def __init__(
+ self,
+ *,
+ response_id: builtins.str = ...,
+ ) -> None: ...
+ def ClearField(
+ self, field_name: typing_extensions.Literal["response_id", b"response_id"]
+ ) -> None: ...
+
+ SESSION_ID_FIELD_NUMBER: builtins.int
+ USER_CONTEXT_FIELD_NUMBER: builtins.int
+ OPERATION_ID_FIELD_NUMBER: builtins.int
+ CLIENT_TYPE_FIELD_NUMBER: builtins.int
+ RELEASE_ALL_FIELD_NUMBER: builtins.int
+ RELEASE_UNTIL_FIELD_NUMBER: builtins.int
+ session_id: builtins.str
+ """(Required)
+
+ The session_id of the request to reattach to.
+ This must be an id of existing session.
+ """
+ @property
+ def user_context(self) -> global___UserContext:
+ """(Required) User context
+
+ user_context.user_id and session+id both identify a unique remote spark session on the
+ server side.
+ """
+ operation_id: builtins.str
+ """(Required)
+ Provide an id of the request to reattach to.
+ This must be an id of existing operation.
+ """
+ client_type: builtins.str
+ """Provides optional information about the client sending the request. This field
+ can be used for language or version specific information and is only intended for
+ logging purposes and will not be interpreted by the server.
+ """
+ @property
+ def release_all(self) -> global___ReleaseExecuteRequest.ReleaseAll: ...
+ @property
+ def release_until(self) -> global___ReleaseExecuteRequest.ReleaseUntil: ...
+ def __init__(
+ self,
+ *,
+ session_id: builtins.str = ...,
+ user_context: global___UserContext | None = ...,
+ operation_id: builtins.str = ...,
+ client_type: builtins.str | None = ...,
+ release_all: global___ReleaseExecuteRequest.ReleaseAll | None = ...,
+ release_until: global___ReleaseExecuteRequest.ReleaseUntil | None = ...,
+ ) -> None: ...
+ def HasField(
+ self,
+ field_name: typing_extensions.Literal[
+ "_client_type",
+ b"_client_type",
+ "client_type",
+ b"client_type",
+ "release",
+ b"release",
+ "release_all",
+ b"release_all",
+ "release_until",
+ b"release_until",
+ "user_context",
+ b"user_context",
+ ],
+ ) -> builtins.bool: ...
+ def ClearField(
+ self,
+ field_name: typing_extensions.Literal[
+ "_client_type",
+ b"_client_type",
+ "client_type",
+ b"client_type",
+ "operation_id",
+ b"operation_id",
+ "release",
+ b"release",
+ "release_all",
+ b"release_all",
+ "release_until",
+ b"release_until",
+ "session_id",
+ b"session_id",
+ "user_context",
+ b"user_context",
+ ],
+ ) -> None: ...
+ @typing.overload
+ def WhichOneof(
+ self, oneof_group: typing_extensions.Literal["_client_type", b"_client_type"]
+ ) -> typing_extensions.Literal["client_type"] | None: ...
+ @typing.overload
+ def WhichOneof(
+ self, oneof_group: typing_extensions.Literal["release", b"release"]
+ ) -> typing_extensions.Literal["release_all", "release_until"] | None: ...
+
+global___ReleaseExecuteRequest = ReleaseExecuteRequest
+
+class ReleaseExecuteResponse(google.protobuf.message.Message):
+ DESCRIPTOR: google.protobuf.descriptor.Descriptor
+
+ SESSION_ID_FIELD_NUMBER: builtins.int
+ OPERATION_ID_FIELD_NUMBER: builtins.int
+ session_id: builtins.str
+ """Session id in which the release was running."""
+ operation_id: builtins.str
+ """Operation id of the operation which the release concerns."""
+ def __init__(
+ self,
+ *,
+ session_id: builtins.str = ...,
+ operation_id: builtins.str = ...,
+ ) -> None: ...
+ def ClearField(
+ self,
+ field_name: typing_extensions.Literal[
+ "operation_id", b"operation_id", "session_id", b"session_id"
+ ],
+ ) -> None: ...
+
+global___ReleaseExecuteResponse = ReleaseExecuteResponse
diff --git a/python/pyspark/sql/connect/proto/base_pb2_grpc.py b/python/pyspark/sql/connect/proto/base_pb2_grpc.py
index 74eda7dfeac..2702ec71ff5 100644
--- a/python/pyspark/sql/connect/proto/base_pb2_grpc.py
+++ b/python/pyspark/sql/connect/proto/base_pb2_grpc.py
@@ -60,6 +60,16 @@ class SparkConnectServiceStub(object):
request_serializer=spark_dot_connect_dot_base__pb2.InterruptRequest.SerializeToString,
response_deserializer=spark_dot_connect_dot_base__pb2.InterruptResponse.FromString,
)
+ self.ReattachExecute = channel.unary_stream(
+ "/spark.connect.SparkConnectService/ReattachExecute",
+ request_serializer=spark_dot_connect_dot_base__pb2.ReattachExecuteRequest.SerializeToString,
+ response_deserializer=spark_dot_connect_dot_base__pb2.ExecutePlanResponse.FromString,
+ )
+ self.ReleaseExecute = channel.unary_unary(
+ "/spark.connect.SparkConnectService/ReleaseExecute",
+ request_serializer=spark_dot_connect_dot_base__pb2.ReleaseExecuteRequest.SerializeToString,
+ response_deserializer=spark_dot_connect_dot_base__pb2.ReleaseExecuteResponse.FromString,
+ )
class SparkConnectServiceServicer(object):
@@ -106,6 +116,26 @@ class SparkConnectServiceServicer(object):
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
+ def ReattachExecute(self, request, context):
+ """Reattach to an existing reattachable execution.
+ The ExecutePlan must have been started with ReattachOptions.reattachable=true.
+ If the ExecutePlanResponse stream ends without a ResultComplete message, there is more to
+ continue. If there is a ResultComplete, the client should use ReleaseExecute with
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details("Method not implemented!")
+ raise NotImplementedError("Method not implemented!")
+
+ def ReleaseExecute(self, request, context):
+ """Release an reattachable execution, or parts thereof.
+ The ExecutePlan must have been started with ReattachOptions.reattachable=true.
+ Non reattachable executions are released automatically and immediately after the ExecutePlan
+ RPC and ReleaseExecute doesn't need to be used.
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details("Method not implemented!")
+ raise NotImplementedError("Method not implemented!")
+
def add_SparkConnectServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
@@ -139,6 +169,16 @@ def add_SparkConnectServiceServicer_to_server(servicer, server):
request_deserializer=spark_dot_connect_dot_base__pb2.InterruptRequest.FromString,
response_serializer=spark_dot_connect_dot_base__pb2.InterruptResponse.SerializeToString,
),
+ "ReattachExecute": grpc.unary_stream_rpc_method_handler(
+ servicer.ReattachExecute,
+ request_deserializer=spark_dot_connect_dot_base__pb2.ReattachExecuteRequest.FromString,
+ response_serializer=spark_dot_connect_dot_base__pb2.ExecutePlanResponse.SerializeToString,
+ ),
+ "ReleaseExecute": grpc.unary_unary_rpc_method_handler(
+ servicer.ReleaseExecute,
+ request_deserializer=spark_dot_connect_dot_base__pb2.ReleaseExecuteRequest.FromString,
+ response_serializer=spark_dot_connect_dot_base__pb2.ReleaseExecuteResponse.SerializeToString,
+ ),
}
generic_handler = grpc.method_handlers_generic_handler(
"spark.connect.SparkConnectService", rpc_method_handlers
@@ -323,3 +363,61 @@ class SparkConnectService(object):
timeout,
metadata,
)
+
+ @staticmethod
+ def ReattachExecute(
+ request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None,
+ ):
+ return grpc.experimental.unary_stream(
+ request,
+ target,
+ "/spark.connect.SparkConnectService/ReattachExecute",
+ spark_dot_connect_dot_base__pb2.ReattachExecuteRequest.SerializeToString,
+ spark_dot_connect_dot_base__pb2.ExecutePlanResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ )
+
+ @staticmethod
+ def ReleaseExecute(
+ request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None,
+ ):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ "/spark.connect.SparkConnectService/ReleaseExecute",
+ spark_dot_connect_dot_base__pb2.ReleaseExecuteRequest.SerializeToString,
+ spark_dot_connect_dot_base__pb2.ReleaseExecuteResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ )
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org