dongjoon-hyun commented on code in PR #60423:
URL: https://github.com/apache/spark/pull/60423#discussion_r4565855918


##########
python/pyspark/sql/tests/connect/streaming/test_listener.py:
##########
@@ -74,6 +75,55 @@ def test_rejects_unexpected_response(self):
                 self.assertEqual(error.exception.getCondition(), 
"UNKNOWN_RESPONSE")
 
 
[email protected](not should_test_connect, connect_requirement_message)
+class StreamingQueryListenerBusCloseTests(unittest.TestCase):
+    def test_close_removes_every_listener_and_server_listener_once(self):
+        listener_added = 
pb2.StreamingQueryListenerEventsResult(listener_bus_listener_added=True)
+        manager = mock.Mock()
+        manager._session.client.is_closed = False
+        manager._session.client.execute_command_as_iterator.return_value = 
iter(
+            [{"streaming_query_listener_events_result": listener_added}]
+        )
+        listener_bus = StreamingQueryListenerBus(manager)
+        listeners = [object(), object(), object()]
+        for listener in listeners:
+            listener_bus.append(listener)
+
+        listener_bus.close()
+
+        self.assertEqual(listener_bus._listener_bus, [])
+        self.assertIsNone(listener_bus._execution_thread)
+        
manager._session.client.execute_command_as_iterator.assert_called_once()
+        manager._session.client.execute_command.assert_called_once()
+        remove_cmd = manager._session.client.execute_command.call_args[0][0]
+        bus_cmd = remove_cmd.streaming_query_listener_bus_command
+        self.assertTrue(bus_cmd.remove_listener_bus_listener)
+
+    def 
test_close_with_a_closed_client_clears_the_listeners_without_a_removal(self):

Review Comment:
   **[4] Both tests call `close()` on a mocked bus, so nothing covers the path 
from [1]: `stop()`, then garbage collection.**
   
   This test sets `is_closed` by hand. A test against the Connect server, for 
example in `test_parity_listener.py`, could create `self.spark.newSession()`, 
add two listeners, call `stop()`, wait for the handler thread to end, drop the 
session and run `gc.collect()`, and then check that no "Failed to remove the 
listener" warning was raised. That would also catch a later change in `stop()` 
or in the server's cleanup that brings the warning back.



##########
python/pyspark/sql/connect/streaming/query.py:
##########
@@ -287,7 +287,19 @@ def __init__(self, sqm: "StreamingQueryManager") -> None:
         self._bus_lock = Lock()
 
     def close(self) -> None:
-        for listener in self._listener_bus:
+        if self._sqm._session.client.is_closed:
+            # The client is closed, e.g. by SparkSession.stop(), whose release 
of the session
+            # already removed the server side listener, so no removal can or 
needs to be sent.
+            # Only clear the local listeners; the handler thread ends with the 
event stream.
+            with self._thread_lock:
+                with self._bus_lock:
+                    self._listener_bus.clear()

Review Comment:
   **[6] Nit: these two lines repeat the error path of `_query_event_handler` 
(L436-437).**
   
   A small helper that both places call with `_bus_lock` held, for example 
`_clear_local_listeners()`, would keep them in sync. It should not take 
`_thread_lock`, since the handler thread must never acquire it.



##########
python/pyspark/sql/tests/connect/streaming/test_listener.py:
##########
@@ -74,6 +75,55 @@ def test_rejects_unexpected_response(self):
                 self.assertEqual(error.exception.getCondition(), 
"UNKNOWN_RESPONSE")
 
 
[email protected](not should_test_connect, connect_requirement_message)
+class StreamingQueryListenerBusCloseTests(unittest.TestCase):
+    def test_close_removes_every_listener_and_server_listener_once(self):
+        listener_added = 
pb2.StreamingQueryListenerEventsResult(listener_bus_listener_added=True)
+        manager = mock.Mock()
+        manager._session.client.is_closed = False
+        manager._session.client.execute_command_as_iterator.return_value = 
iter(
+            [{"streaming_query_listener_events_result": listener_added}]
+        )
+        listener_bus = StreamingQueryListenerBus(manager)
+        listeners = [object(), object(), object()]
+        for listener in listeners:
+            listener_bus.append(listener)
+
+        listener_bus.close()
+
+        self.assertEqual(listener_bus._listener_bus, [])
+        self.assertIsNone(listener_bus._execution_thread)
+        
manager._session.client.execute_command_as_iterator.assert_called_once()
+        manager._session.client.execute_command.assert_called_once()
+        remove_cmd = manager._session.client.execute_command.call_args[0][0]
+        bus_cmd = remove_cmd.streaming_query_listener_bus_command
+        self.assertTrue(bus_cmd.remove_listener_bus_listener)
+
+    def 
test_close_with_a_closed_client_clears_the_listeners_without_a_removal(self):
+        # After SparkSession.stop(), the release of the session has removed 
the server side
+        # listener and the client is closed, so close() sends no removal and 
warns nothing.
+        listener_added = 
pb2.StreamingQueryListenerEventsResult(listener_bus_listener_added=True)
+        manager = mock.Mock()
+        manager._session.client.is_closed = False
+        manager._session.client.execute_command_as_iterator.return_value = 
iter(
+            [{"streaming_query_listener_events_result": listener_added}]
+        )
+        manager._session.client.execute_command.side_effect = 
RuntimeError("closed client")
+        listener_bus = StreamingQueryListenerBus(manager)
+        for listener in [object(), object()]:
+            listener_bus.append(listener)
+        manager._session.client.is_closed = True

Review Comment:
   **[5] Nit: the handler thread that `append()` started is never joined in 
this test.**
   
   `close()` only drops the reference here, so the thread can outlive the test, 
and `warnings.catch_warnings` is process-wide. It ends at once because the 
mocked stream is exhausted, but joining it before setting `is_closed` would 
also match the real state: `__del__` runs only after the handler thread has 
ended (see [2]).
   
   ```python
           listener_bus._execution_thread.join(timeout=10)
           manager._session.client.is_closed = True
   ```



##########
python/pyspark/sql/connect/streaming/query.py:
##########
@@ -287,7 +287,19 @@ def __init__(self, sqm: "StreamingQueryManager") -> None:
         self._bus_lock = Lock()
 
     def close(self) -> None:
-        for listener in self._listener_bus:
+        if self._sqm._session.client.is_closed:
+            # The client is closed, e.g. by SparkSession.stop(), whose release 
of the session
+            # already removed the server side listener, so no removal can or 
needs to be sent.
+            # Only clear the local listeners; the handler thread ends with the 
event stream.
+            with self._thread_lock:
+                with self._bus_lock:
+                    self._listener_bus.clear()
+                    self._execution_thread = None
+            return
+        # remove() deletes from _listener_bus, so iterate over a snapshot 
taken under the lock.
+        with self._bus_lock:
+            listeners = list(self._listener_bus)
+        for listener in listeners:

Review Comment:
   **[2] `close()` cannot run while the handler thread is alive, so the 
three-listener case in the PR description does not happen through `__del__`.**
   
   The handler thread runs `self._query_event_handler`, so its frame keeps 
`self` reachable, and with it `self._sqm._session`. A `SparkSession` with a 
running handler is therefore never collected, and `__del__` (session.py:930), 
the only caller of `close()`, runs only after the handler has ended. The 
handler ends in one of two ways:
   
   - With an error. Then it has already cleared `_listener_bus`, and `close()` 
has nothing to remove.
   - Normally, when the server sends `ResultComplete` from 
`ServerSideListenerHolder.cleanUp()`, for example after `stop()` releases the 
session. Then the server-side listener is already gone.
   
   So when this loop runs on an open client, the server-side listener is 
already gone, and the `remove_listener_bus_listener` command has nothing to 
remove. The case in the description, where three listeners leave the 
server-side listener and the handler thread alive after `close()`, needs a 
direct call to `close()`.
   
   Could the PR description say that, in practice, the user-facing change is 
the closed-client case from [1]? As far as I can tell, the snapshot matters 
only for a direct call to `close()`.



##########
python/pyspark/sql/connect/streaming/query.py:
##########
@@ -287,7 +287,19 @@ def __init__(self, sqm: "StreamingQueryManager") -> None:
         self._bus_lock = Lock()
 
     def close(self) -> None:
-        for listener in self._listener_bus:
+        if self._sqm._session.client.is_closed:
+            # The client is closed, e.g. by SparkSession.stop(), whose release 
of the session
+            # already removed the server side listener, so no removal can or 
needs to be sent.

Review Comment:
   **[3] `is_closed` does not always mean that the session was released, so the 
reason in this comment does not always hold.**
   
   `_closed` is also set without `close()`, on `INVALID_HANDLE.SESSION_CHANGED` 
(core.py:2449) and on a server-side session ID mismatch (core.py:2539). The 
channel then stays open, and this client released nothing. `stop()` also closes 
the client when `release_session()` fails, and only logs that. Skipping the 
removal is still right in these cases, because a closed client cannot send it. 
I gave the same reason in [1], so the gap is in my suggestion too. The note 
about the handler thread holds for `__del__` because of [2], not because the 
client is closed.
   
   Maybe:
   
   ```python
               # No removal can be sent on a closed client. After 
SparkSession.stop(), releasing
               # the session has already removed the server side listener. 
SparkSession.__del__
               # calls this only after the handler thread has ended, so only 
clear the local state.
   ```



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to