Skip to content

avoid Client._handle_report cancelling itself on Client._close - #5672

Merged
fjetter merged 2 commits into
dask:mainfrom
graingert:gen-coroutine-not-awaited
Jan 25, 2022
Merged

fjetter merged 2 commits into
dask:mainfrom
graingert:gen-coroutine-not-awaited

Conversation

@graingert

Copy link
Copy Markdown
Member

in #4617 and #5666
a asyncio.gather call isn't correctly waited on and logs the following
asyncio unhandled error:

_GatheringFuture exception was never retrieved
future: <_GatheringFuture finished exception=CancelledError()>
asyncio.exceptions.CancelledError

this exception is happening because on reconnect _close cancels itself
before calling gather:

coroutines = set(self.coroutines)
for f in self.coroutines:
# cancel() works on asyncio futures (Tornado 5)
# but is a no-op on Tornado futures
with suppress(RuntimeError):
f.cancel()
if f.cancelled():
coroutines.remove(f)
del self.coroutines[:]

_handle_report() calls _reconnect() calls _close() which then cancels itself (edited)

self.coroutines can only ever contain 1 task - _handle_report and so
can be removed in favour of explicitly tracking the _handle_report
task.

  • Closes #xxxx
  • Tests added / passed
  • Passes pre-commit run --all-files

@GPUtester

Copy link
Copy Markdown
Collaborator

Can one of the admins verify this patch?

@graingert

Copy link
Copy Markdown
Member Author

I made a test for this but didn't submit it because it happens intermittently due to the gc not collecting the _GatheringFuture soon enough.

From 1aa4df8993083a8a64e57a653d9e29c0a016337d Mon Sep 17 00:00:00 2001
From: Thomas Grainger <[email protected]>
Date: Thu, 20 Jan 2022 11:57:55 +0000
Subject: [PATCH] add test for _GatheringFuture self-cancel

---
 distributed/tests/test_client.py | 44 ++++++++++++++++++++++++++------
 1 file changed, 36 insertions(+), 8 deletions(-)

diff --git a/distributed/tests/test_client.py b/distributed/tests/test_client.py
index fbdfec48..d7e4f9cb 100644
--- a/distributed/tests/test_client.py
+++ b/distributed/tests/test_client.py
@@ -16,7 +16,7 @@ import warnings
 import weakref
 import zipfile
 from collections import deque
-from contextlib import suppress
+from contextlib import suppress, contextmanager
 from functools import partial
 from operator import add
 from threading import Semaphore
@@ -3782,15 +3782,43 @@ def test_reconnect(loop):
     c.close()
 
 
+class UnhandledException(Exception):
+    pass
+
+
+
+@contextmanager
+def _catch_unhandled_exceptions() -> Generator[None, None, None]:
+    loop = asyncio.get_running_loop()
+    ctx: dict[str, object] | None = None
+
+    old_handler = loop.get_exception_handler()
+
+    @loop.set_exception_handler
+    def _(loop: object, context: dict[str, object]) -> None:
+        nonlocal ctx
+        ctx = context
+
+    try:
+        yield
+    finally:
+        loop.set_exception_handler(old_handler)
+    if ctx:
+        raise UnhandledException(ctx["message"]) from ctx.get("exception")
+
+
+
+
 @gen_cluster(client=True, nthreads=[], client_kwargs={"timeout": 0.5})
 async def test_reconnect_timeout(c, s):
-    with captured_logger(logging.getLogger("distributed.client")) as logger:
-        await s.close()
-        while c.status != "closed":
-            await c._update_scheduler_info()
-            await asyncio.sleep(0.05)
-    text = logger.getvalue()
-    assert "Failed to reconnect" in text
+    with _catch_unhandled_exceptions():
+        with captured_logger(logging.getLogger("distributed.client")) as logger:
+            await s.close()
+            while c.status != "closed":
+                await c._update_scheduler_info()
+                await asyncio.sleep(0.05)
+        text = logger.getvalue()
+        assert "Failed to reconnect" in text
 
 
 @pytest.mark.avoid_ci(reason="hangs on github actions ubuntu-latest CI")
-- 
2.25.1

in dask#4617 and dask#5666
a asyncio.gather call isn't correctly waited on and logs the following
asyncio unhandled error:

```
_GatheringFuture exception was never retrieved
future: <_GatheringFuture finished exception=CancelledError()>
asyncio.exceptions.CancelledError
```

this exception is happening because on reconnect `_close` cancels itself
before calling gather:
https://github.com/dask/distributed/blob/feac52b49292781e78beff8226407f3a5f2e563e/distributed/client.py#L1335-L1343
`_handle_report()` calls `_reconnect()` calls `_close()` which then cancels itself (edited)

`self.coroutines` can only ever contain 1 task - `_handle_report` and so
can be removed in favour of explicitly tracking the `_handle_report`
task.
@graingert
graingert force-pushed the gen-coroutine-not-awaited branch from ff9bd24 to f6afc6d Compare January 21, 2022 11:52
@graingert

Copy link
Copy Markdown
Member Author

the test failures seem to be unrelated to this change #5680

@graingert
graingert marked this pull request as ready for review January 21, 2022 15:52

@fjetter fjetter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This looks great, thank you @graingert !

Comment on lines +3791 to +3808
@contextmanager
def catch_unhandled_exceptions() -> Generator[None, None, None]:
loop = asyncio.get_running_loop()
ctx: dict[str, Any] | None = None

old_handler = loop.get_exception_handler()

@loop.set_exception_handler
def _(loop: object, context: dict[str, Any]) -> None:
nonlocal ctx
ctx = context

try:
yield
finally:
loop.set_exception_handler(old_handler)
if ctx:
raise UnhandledException(ctx["message"]) from ctx.get("exception")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Eventually, we might want to add this to

@contextmanager
def clean(threads=not WINDOWS, instances=True, timeout=1, processes=True):
with check_thread_leak() if threads else nullcontext():
with pristine_loop() as loop:
with check_process_leak(check=processes):
with check_instances() if instances else nullcontext():
with check_active_rpc(loop, timeout):
reset_config()
dask.config.set({"distributed.comm.timeouts.connect": "5s"})
# Restore default logging levels
# XXX use pytest hooks/fixtures instead?
for name, level in logging_levels.items():
logging.getLogger(name).setLevel(level)
yield loop
?

@fjetter
fjetter merged commit 867a54e into dask:main Jan 25, 2022
gjoseph92 pushed a commit to gjoseph92/distributed that referenced this pull request Feb 1, 2022
…5672)

in dask#4617 and dask#5666
a asyncio.gather call isn't correctly waited on and logs the following
asyncio unhandled error:

```
_GatheringFuture exception was never retrieved
future: <_GatheringFuture finished exception=CancelledError()>
asyncio.exceptions.CancelledError
```

this exception is happening because on reconnect `_close` cancels itself
before calling gather:
https://github.com/dask/distributed/blob/feac52b49292781e78beff8226407f3a5f2e563e/distributed/client.py#L1335-L1343
`_handle_report()` calls `_reconnect()` calls `_close()` which then cancels itself (edited)

`self.coroutines` can only ever contain 1 task - `_handle_report` and so
can be removed in favour of explicitly tracking the `_handle_report`
task.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants