You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "HyukjinKwon (via GitHub)" <gi...@apache.org> on 2023/07/31 08:01:53 UTC

[GitHub] [spark] HyukjinKwon opened a new pull request, #42235: [SPARK-44599][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

HyukjinKwon opened a new pull request, #42235:
URL: https://github.com/apache/spark/pull/42235

   ### What changes were proposed in this pull request?
   
   This PR proposes to implement the Python client side for https://github.com/apache/spark/pull/42228.
   
   ### Why are the changes needed?
   
   TBD
   
   ### Does this PR introduce _any_ user-facing change?
   
   TBD
   
   ### How was this patch tested?
   
   TBD


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281316234


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,225 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.HasField("result_complete"):
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    # on first try, we use the existing iterator.
+                    if not attempt.is_first_try():
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not self._result_complete and not has_next:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._result_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                            if first_loop:
+                                # 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.
+                                first_loop = False
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        """
+        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.
+        """
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        request = self._create_release_execute_request(until_response_id)
+
+        def target() -> None:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    self._stub.ReleaseExecute(request)
+
+        threading.Thread(target=target).start()

Review Comment:
   I can't find the symmetry way of doing `StreamObserver` in Python (see `ExecutePlanResponseReattachableIterator.createRetryingReleaseExecuteResponseObserer`). I know this isn't super nice but it would at least work.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1280772939


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,226 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.reattach_options.reattachable = True  # type: ignore[attr-defined]
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+
+        # will trigger reattach in case the stream completed without response_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.response_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if first_try:
+                        # on first try, we use the existing iterator.
+                        first_try = False
+                    else:
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not has_next and not self._result_complete:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._result_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                            if first_loop:
+                                # 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.
+                                first_loop = False
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        """
+        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.
+        """
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        request = self._create_release_execute_request(until_response_id)
+
+        def target():
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    self._stub.ReleaseExecute(request)
+
+        threading.Thread(target=target).start()
+
+    def _create_reattach_execute_request(self) -> pb2.ReattachExecuteRequest:
+        release = pb2.ReattachExecuteRequest(
+            session_id=self._initial_request.session_id,
+            user_context=self._initial_request.user_context,
+            operation_id=self._initial_request.operation_id,
+        )
+
+        if self._initial_request.client_type:
+            release.client_type = self._initial_request.client_type
+
+        return release
+
+    def _create_release_execute_request(
+        self, until_response_id: Optional[str]
+    ) -> pb2.ReattachExecuteRequest:
+        release = pb2.ReattachExecuteRequest(
+            session_id=self._initial_request.session_id,
+            user_context=self._initial_request.user_context,
+            operation_id=self._initial_request.operation_id,
+        )
+
+        if self._initial_request.client_type:
+            release.client_type = self._initial_request.client_type
+
+        if not until_response_id:
+            release.release_all.CopyFrom(pb2.ReleaseExecuteRequest.ReleaseAll())
+        else:
+            release.release_util.response_id = until_response_id  # type: ignore[attr-defined]
+
+        return release
+
+    def throw(self, type: Any = None, value: Any = None, traceback: Any = None) -> Any:
+        super().throw(type, value, traceback)
+
+    def close(self) -> None:
+        return super().close()

Review Comment:
   on close, it should do release_all if it wasn't done.
   in scala the Iterator unfortunately doesn't have a close, but if python has it, it should do it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281310308


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:

Review Comment:
   Actually I just used a different method to make this clear.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281137263


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   I raised https://github.com/apache/spark/pull/42274 to be defensive about it in scala.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281120432


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   At least in scala, calling the `executePlan` never throws error, even if the service is absolutely not available and one could expect immediate error; I tested that with completely killing the server, then calling executePlan, and never getting an actual error before trying to call next()... The error is only thrown on the first `next()` or `hasNext()` call of the resulting iterator. So in scala not catching and retrying here, but at the first iterator invocation is fine. So in https://github.com/apache/spark/pull/42228/files#diff-2efc03ab3edd5e5f78652b1454b31fd4917113de09a64fbdc7352f150c685628R89 and also in https://github.com/apache/spark/pull/41829/files#diff-79d952ace19b8b9d4b04e010653aba35e4aeaca957946cc68414b7a766deea99R68 doesn't wrap the first call
   we do not retry.
   
   But it's a good callout that it needs checking if python GRPC behaves the same, or maybe just defensively wrap it in retry anyway (and do the same in scala just in case it's a GRPC internal quirk that we shouldn't depend on), or at least it deserves a comment.
   
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281309494


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient

Review Comment:
   it causes a circular import (because `SparkConnectClient` also imports `ExecutePlanResponseReattachableIterator`)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] grundprinzip commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "grundprinzip (via GitHub)" <gi...@apache.org>.
grundprinzip commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281096015


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(

Review Comment:
   attempt is of type `AttemptManager` which contains a `_retry_state` that has a _count. We can make the retry state visible in the attempt manager if you want to avoid having a first try variable



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient

Review Comment:
   why the import here?



##########
python/pyspark/sql/connect/client/core.py:
##########
@@ -606,26 +622,35 @@ def __init__(
             "initial_backoff": 50,
             "max_backoff": 60000,
         }
-        if retryPolicy:
-            self._retry_policy.update(retryPolicy)
+        if retry_policy:
+            self._retry_policy.update(retry_policy)
 
         # Generate a unique session ID for this client. This UUID must be unique to allow
         # concurrent Spark sessions of the same user. If the channel is closed, creating
         # a new client will create a new session ID.
         self._session_id = str(uuid.uuid4())
         if self._builder.userId is not None:
             self._user_id = self._builder.userId
-        elif userId is not None:
-            self._user_id = userId
+        elif user_id is not None:
+            self._user_id = user_id
         else:
             self._user_id = os.getenv("USER", None)
 
         self._channel = self._builder.toChannel()
         self._closed = False
         self._stub = grpc_lib.SparkConnectServiceStub(self._channel)
         self._artifact_manager = ArtifactManager(self._user_id, self._session_id, self._channel)
+        self._use_reattachable_execute = use_reattachable_execute
         # Configure logging for the SparkConnect client.
 
+    def disable_reattachable_execute(self) -> "SparkConnectClient":

Review Comment:
   I think this will probably need some flagging to avoid that this is done while a query is currently being executed so that we know what to do. Or if the information returned from the query is enough to independently understand if it needs to be resumed.



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   So in the case of the target resource throwing a retriable error, this will already raise an exception and break the retry logic. It looks like the current retry handling can only deal with subsequent errors in the handling of the response stream but not the initial error itself.



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   @juliuszsompolski is this the same for the current scala client?



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if first_try:
+                        # on first try, we use the existing iterator.
+                        first_try = False
+                    else:
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not has_next and not self._result_complete:

Review Comment:
   Just readability.
   
   ```suggestion
                       if not self._result_complete and not has_next:
   ```



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if first_try:

Review Comment:
   or maybe `attempt.first_try` (added to attempt manager)



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if first_try:
+                        # on first try, we use the existing iterator.
+                        first_try = False
+                    else:
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not has_next and not self._result_complete:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(

Review Comment:
   This could raise itself with a retriable error.



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:

Review Comment:
   I would add a comment that this assumes that this is part of the oneof and set to none if it's not set in this response



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281312421


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(

Review Comment:
   Yup, this is the time that this context manager shines :-)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281246364


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   ... but what I write here implies that if the error was indeed during the initial ExecutePlan that didn't reach the server, and we catch it on the first hasNext() later, then Reattach won't work, because the query won't be on the server, so it will fail with INVALID_HANDLE.OPERATION_NOT_FOUND. So this indeed means that the case it won't work if retry of the initial ExecutePlan is needed, and wrapping the retry here won't help for that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281278430


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   So now I have 3 PRs:
   * https://github.com/apache/spark/pull/42281 adds some comments in scala to explain that GRPC throws errors deferred to the iterator functions, and the limitation of retry of the original execute didn't reach the server
   * https://github.com/apache/spark/pull/42282 fixes the retry in case original execute didn't reach the server
   * https://github.com/apache/spark/pull/42274 does that plus does overkill retries in case the assumption that calling executePlan and reattachExecute won't throw is wrong.
   
   I would suggest merging the first, and discussing this corner case later.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1314102126


##########
python/pyspark/testing/connectutils.py:
##########
@@ -170,6 +170,10 @@ def conf(cls):
         # Disable JVM stack trace in Spark Connect tests to prevent the
         # HTTP header size from exceeding the maximum allowed size.
         conf.set("spark.sql.pyspark.jvmStacktrace.enabled", "false")
+        # Make the server terminate reattachable streams every 1 second and 123 bytes,
+        # to make the tests exercise reattach.
+        conf.set("spark.connect.execute.reattachable.senderMaxStreamDuration", "1s")
+        conf.set("spark.connect.execute.reattachable.senderMaxStreamSize", "123")

Review Comment:
   That should be fixed in the lastest master branch.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44599][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1279954713


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,166 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+from pyspark.sql.connect.client.core import SparkConnectClient
+from pyspark.sql.connect.client.core import Retrying
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        self._operation_id = str(uuid.uuid4())
+        self._stub = stub
+        request.reattach_options.reattachable = True  # type: ignore[attr-defined]
+        self._initial_request = request
+        self._response_complete = False
+        self._iterator = self._stub.ExecutePlan(self._initial_request)
+
+        self._last_response_id: Optional[str] = None
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without responseComplete
+        self._has_next()
+
+        # Get next response, possibly triggering reattach in case of stream error.
+        first_try = True
+        ret: Optional[pb2.ExecutePlanResponse] = None
+        for attempt in Retrying(can_retry=SparkConnectClient.retry_exception, **self._retry_policy):
+            with attempt:
+                if first_try:
+                    # on first try, we use the initial iterator.
+                    first_try = False
+                else:
+                    # Error retry reattach: After an error, attempt to
+                    self._iterator = self._stub.ReattachExecute(
+                        self._create_reattach_execute_request()
+                    )
+                ret = self._current
+
+        if ret is None:
+            raise StopIteration()
+
+        assert ret is not None
+        self._last_response_id = ret.response_id
+        if ret.response_complete:
+            self._response_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        if self._response_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    if not has_next and not self._response_complete:

Review Comment:
   heads up: ResponseComplete renamed to ResultComplete



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,166 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+from pyspark.sql.connect.client.core import SparkConnectClient
+from pyspark.sql.connect.client.core import Retrying
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        self._operation_id = str(uuid.uuid4())
+        self._stub = stub
+        request.reattach_options.reattachable = True  # type: ignore[attr-defined]
+        self._initial_request = request
+        self._response_complete = False
+        self._iterator = self._stub.ExecutePlan(self._initial_request)
+
+        self._last_response_id: Optional[str] = None
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without responseComplete
+        self._has_next()
+
+        # Get next response, possibly triggering reattach in case of stream error.
+        first_try = True
+        ret: Optional[pb2.ExecutePlanResponse] = None
+        for attempt in Retrying(can_retry=SparkConnectClient.retry_exception, **self._retry_policy):
+            with attempt:
+                if first_try:
+                    # on first try, we use the initial iterator.
+                    first_try = False
+                else:
+                    # Error retry reattach: After an error, attempt to
+                    self._iterator = self._stub.ReattachExecute(
+                        self._create_reattach_execute_request()
+                    )
+                ret = self._current
+
+        if ret is None:
+            raise StopIteration()
+
+        assert ret is not None
+        self._last_response_id = ret.response_id
+        if ret.response_complete:
+            self._response_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        if self._response_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    if not has_next and not self._response_complete:
+                        while not has_next:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._response_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        request = self._create_release_execute_request(until_response_id)
+        for attempt in Retrying(can_retry=SparkConnectClient.retry_exception, **self._retry_policy):
+            with attempt:
+                self._stub.ReleaseExecute(request)

Review Comment:
   is it possible to make the ReleaseExecute async - the idea is that client just "fires-and-forget" them as help to server to not do too much buffering, but doesn't get blocked on them.



##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,166 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+from pyspark.sql.connect.client.core import SparkConnectClient
+from pyspark.sql.connect.client.core import Retrying
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        self._operation_id = str(uuid.uuid4())
+        self._stub = stub
+        request.reattach_options.reattachable = True  # type: ignore[attr-defined]
+        self._initial_request = request
+        self._response_complete = False
+        self._iterator = self._stub.ExecutePlan(self._initial_request)
+
+        self._last_response_id: Optional[str] = None
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without responseComplete
+        self._has_next()
+
+        # Get next response, possibly triggering reattach in case of stream error.
+        first_try = True
+        ret: Optional[pb2.ExecutePlanResponse] = None
+        for attempt in Retrying(can_retry=SparkConnectClient.retry_exception, **self._retry_policy):
+            with attempt:
+                if first_try:
+                    # on first try, we use the initial iterator.
+                    first_try = False
+                else:
+                    # Error retry reattach: After an error, attempt to
+                    self._iterator = self._stub.ReattachExecute(
+                        self._create_reattach_execute_request()
+                    )
+                ret = self._current
+
+        if ret is None:
+            raise StopIteration()
+
+        assert ret is not None
+        self._last_response_id = ret.response_id
+        if ret.response_complete:
+            self._response_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        if self._response_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    if not has_next and not self._response_complete:
+                        while not has_next:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._response_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        request = self._create_release_execute_request(until_response_id)
+        for attempt in Retrying(can_retry=SparkConnectClient.retry_exception, **self._retry_policy):
+            with attempt:
+                self._stub.ReleaseExecute(request)
+
+    def _create_reattach_execute_request(self) -> pb2.ReattachExecuteRequest:
+        release = pb2.ReattachExecuteRequest(
+            session_id=self._initial_request.session_id,
+            user_context=self._initial_request.user_context,
+            operation_id=self._initial_request.operation_id,
+        )
+
+        if self._initial_request.client_type:
+            release.client_type = self._initial_request.client_type
+
+        return release
+
+    def _create_release_execute_request(
+        self, until_response_id: Optional[str]
+    ) -> pb2.ReattachExecuteRequest:
+        release = pb2.ReattachExecuteRequest(
+            session_id=self._initial_request.session_id,
+            user_context=self._initial_request.user_context,
+            operation_id=self._initial_request.operation_id,
+        )
+
+        if self._initial_request.client_type:
+            release.client_type = self._initial_request.client_type
+
+        if not until_response_id:
+            release.release_type = (  # type: ignore[attr-defined]
+                pb2.ReleaseExecuteRequest.ReleaseType.RELEASE_UNTIL_RESPONSE
+            )
+        else:
+            release.release_type = (  # type: ignore[attr-defined]
+                pb2.ReleaseExecuteRequest.ReleaseType.RELEASE_ALL
+            )
+            release.until_response_id = until_response_id  # type: ignore[attr-defined]

Review Comment:
   heads up: changed to not have release_type enum + a oneof, but just a single oneof.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281250905


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(

Review Comment:
   retrying the failure of initial operation starting is tricky, because:
   - if the initial operation reached the server, retry of ExecutePlan would fail with INVALID_HANDLE.OPERATION_ALREADY_EXISTS; in that case ReattachPlan should be used. And this is what happens here.
   - but if the initial operation didn't reach the server, then the ReattachPlan will fail with INVALID_HANDLE.OPERATION_NOT_FOUND. This could be improved by making it switch to retrying the ExecutePlan then
   But I think this is a border case that can be a followup or decided it's not worth it.
   
   I believe in the state as is, we will get an INVALID_HANDLE.OPERATION_NOT_FOUND error in case the original ExecutePlan never reached the server. In that case, we could improve it by trying to call ExecutePlan again. But that would have to be caught not here, but during the next() calls.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281316234


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,225 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.HasField("result_complete"):
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    # on first try, we use the existing iterator.
+                    if not attempt.is_first_try():
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not self._result_complete and not has_next:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._result_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                            if first_loop:
+                                # 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.
+                                first_loop = False
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        """
+        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.
+        """
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        request = self._create_release_execute_request(until_response_id)
+
+        def target() -> None:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    self._stub.ReleaseExecute(request)
+
+        threading.Thread(target=target).start()

Review Comment:
   I can't find the symmetry way of doing StreamObserver in Python. I know this isn't super nice but it would at least work.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon closed pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon closed pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect
URL: https://github.com/apache/spark/pull/42235


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on pull request #42235: [SPARK-44599][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on PR #42235:
URL: https://github.com/apache/spark/pull/42235#issuecomment-1659375618

   It's tracked by https://issues.apache.org/jira/browse/SPARK-44424 already as well.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281168403


##########
python/pyspark/sql/connect/client/core.py:
##########
@@ -606,26 +622,35 @@ def __init__(
             "initial_backoff": 50,
             "max_backoff": 60000,
         }
-        if retryPolicy:
-            self._retry_policy.update(retryPolicy)
+        if retry_policy:
+            self._retry_policy.update(retry_policy)
 
         # Generate a unique session ID for this client. This UUID must be unique to allow
         # concurrent Spark sessions of the same user. If the channel is closed, creating
         # a new client will create a new session ID.
         self._session_id = str(uuid.uuid4())
         if self._builder.userId is not None:
             self._user_id = self._builder.userId
-        elif userId is not None:
-            self._user_id = userId
+        elif user_id is not None:
+            self._user_id = user_id
         else:
             self._user_id = os.getenv("USER", None)
 
         self._channel = self._builder.toChannel()
         self._closed = False
         self._stub = grpc_lib.SparkConnectServiceStub(self._channel)
         self._artifact_manager = ArtifactManager(self._user_id, self._session_id, self._channel)
+        self._use_reattachable_execute = use_reattachable_execute
         # Configure logging for the SparkConnect client.
 
+    def disable_reattachable_execute(self) -> "SparkConnectClient":

Review Comment:
   This is used only when creating ExecutePlanResponseReattachableIterator, and once that's created, it will know what to do even if this gets flipped.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281320062


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,225 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.HasField("result_complete"):
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    # on first try, we use the existing iterator.
+                    if not attempt.is_first_try():
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not self._result_complete and not has_next:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(
+                                self._create_reattach_execute_request()
+                            )
+                            # shouldn't change
+                            assert not self._result_complete
+                            try:
+                                self._current = next(self._iterator)
+                            except StopIteration:
+                                pass
+                            has_next = self._current is not None
+                            if first_loop:
+                                # 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.
+                                first_loop = False
+                    return has_next
+            return False
+
+    def _release_execute(self, until_response_id: Optional[str]) -> None:
+        """
+        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.
+        """
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        request = self._create_release_execute_request(until_response_id)
+
+        def target() -> None:
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    self._stub.ReleaseExecute(request)
+
+        threading.Thread(target=target).start()

Review Comment:
   This is fine. Maybe would have been even cleaner this way in scala, because the current code there of invoking an async execution, and then chaining another async execution from the onError of it is actually a bit funky.
   A thread with retry loop over sync requests would be simpler code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281310308


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:

Review Comment:
   Actually I just used a different method to make this clear. (will push them soon)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] juliuszsompolski commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "juliuszsompolski (via GitHub)" <gi...@apache.org>.
juliuszsompolski commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1281153667


##########
python/pyspark/sql/connect/client/reattach.py:
##########
@@ -0,0 +1,228 @@
+#
+# 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.
+#
+from pyspark.sql.connect.utils import check_dependencies
+
+check_dependencies(__name__)
+
+import uuid
+from collections.abc import Generator
+from typing import Optional, Dict, Any, Iterator
+import threading
+
+import pyspark.sql.connect.proto as pb2
+import pyspark.sql.connect.proto.base_pb2_grpc as grpc_lib
+
+
+class ExecutePlanResponseReattachableIterator(Generator):
+    """
+    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
+    """
+
+    def __init__(
+        self,
+        request: pb2.ExecutePlanRequest,
+        stub: grpc_lib.SparkConnectServiceStub,
+        retry_policy: Dict[str, Any],
+    ):
+        self._request = request
+        self._retry_policy = retry_policy
+        if request.operation_id:
+            self._operation_id = request.operation_id
+        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.
+            self._operation_id = str(uuid.uuid4())
+
+        self._stub = stub
+        request.request_options.append(
+            pb2.ExecutePlanRequest.RequestOption(
+                reattach_options=pb2.ReattachOptions(reattachable=True)
+            )
+        )
+        self._initial_request = request
+
+        # ResponseId of the last response returned by next()
+        self._last_returned_response_id: Optional[str] = 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.
+        self._result_complete = False
+
+        # Initial iterator comes from ExecutePlan request.
+        self._iterator: Iterator[pb2.ExecutePlanResponse] = self._stub.ExecutePlan(
+            self._initial_request
+        )
+
+        # Current item from this iterator.
+        self._current: Optional[pb2.ExecutePlanResponse] = None
+
+    def send(self, value: Any) -> pb2.ExecutePlanResponse:
+        # will trigger reattach in case the stream completed without result_complete
+        if not self._has_next():
+            raise StopIteration()
+
+        ret = self._current
+        assert ret is not None
+
+        self._last_returned_response_id = ret.response_id
+        if ret.result_complete:
+            self._result_complete = True
+            self._release_execute(None)  # release all
+        else:
+            self._release_execute(self._last_returned_response_id)
+        self._current = None
+        return ret
+
+    def _has_next(self) -> bool:
+        from pyspark.sql.connect.client.core import SparkConnectClient
+        from pyspark.sql.connect.client.core import Retrying
+
+        if self._result_complete:
+            # After response complete response
+            return False
+        else:
+            first_try = True
+            for attempt in Retrying(
+                can_retry=SparkConnectClient.retry_exception, **self._retry_policy
+            ):
+                with attempt:
+                    if first_try:
+                        # on first try, we use the existing iterator.
+                        first_try = False
+                    else:
+                        # on retry, the iterator is borked, so we need a new one
+                        self._iterator = self._stub.ReattachExecute(
+                            self._create_reattach_execute_request()
+                        )
+
+                    if self._current is None:
+                        try:
+                            self._current = next(self._iterator)
+                        except StopIteration:
+                            pass
+
+                    has_next = self._current is not None
+
+                    # Graceful reattach:
+                    # If iterator ended, but there was no ResponseComplete, it means that
+                    # there is more, and we need to reattach. While ResponseComplete didn't
+                    # arrive, we keep reattaching.
+                    first_loop = True
+                    if not has_next and not self._result_complete:
+                        while not has_next or first_loop:
+                            self._iterator = self._stub.ReattachExecute(

Review Comment:
   Like in https://github.com/apache/spark/pull/42235/files#r1281120432, in scala it wouldn't, but we could be defensive about it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] allisonwang-db commented on a diff in pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "allisonwang-db (via GitHub)" <gi...@apache.org>.
allisonwang-db commented on code in PR #42235:
URL: https://github.com/apache/spark/pull/42235#discussion_r1313969873


##########
python/pyspark/testing/connectutils.py:
##########
@@ -170,6 +170,10 @@ def conf(cls):
         # Disable JVM stack trace in Spark Connect tests to prevent the
         # HTTP header size from exceeding the maximum allowed size.
         conf.set("spark.sql.pyspark.jvmStacktrace.enabled", "false")
+        # Make the server terminate reattachable streams every 1 second and 123 bytes,
+        # to make the tests exercise reattach.
+        conf.set("spark.connect.execute.reattachable.senderMaxStreamDuration", "1s")
+        conf.set("spark.connect.execute.reattachable.senderMaxStreamSize", "123")

Review Comment:
   @HyukjinKwon I saw this error when running unit tests locally: `org.apache.spark.sql.AnalysisException: Cannot modify the value of a static config: spark.connect.execute.reattachable.senderMaxStreamDuration.`
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] [spark] HyukjinKwon commented on pull request #42235: [SPARK-44424][CONNECT][PYTHON] Python client for reattaching to existing execute in Spark Connect

Posted by "HyukjinKwon (via GitHub)" <gi...@apache.org>.
HyukjinKwon commented on PR #42235:
URL: https://github.com/apache/spark/pull/42235#issuecomment-1663083079

   Merged to master and branch-3.5.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org