Skip to content

Commit dd2fe54

Browse files
samluryemeta-codesync[bot]
authored andcommitted
Clean future cancellation handling (#1687)
Summary: Pull Request resolved: #1687 The implementation of `monarch.actor.Future` uses `loop.call_soon_threadsafe` to set a value/exception on an underlying asyncio future. But if the caller cancelled the asyncio future before `call_soon_threadsafe` executes the callback, then `asyncio.exceptions.InvalidStateError` will be logged, which is noisy and misleading. This diff solves the issue by checking whether the future is already resolved/cancelled from inside the callback. ghstack-source-id: 319407775 exported-using-ghexport Reviewed By: zdevito Differential Revision: D85693875 fbshipit-source-id: eb515cd65e78fcbb853909af3ba96196c1315c98
1 parent 5afdea6 commit dd2fe54

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

python/monarch/_src/actor/future.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,12 +138,20 @@ def __await__(self) -> Generator[Any, Any, R]:
138138
fut = loop.create_future()
139139
self._status = _Asyncio(fut)
140140

141+
def set_result(fut, value):
142+
if not fut.cancelled():
143+
fut.set_result(value)
144+
145+
def set_exception(fut, e):
146+
if not fut.cancelled():
147+
fut.set_exception(e)
148+
141149
async def mark_complete():
142150
try:
143-
func, value = fut.set_result, await coro
151+
func, value = set_result, await coro
144152
except Exception as e:
145-
func, value = fut.set_exception, e
146-
loop.call_soon_threadsafe(func, value)
153+
func, value = set_exception, e
154+
loop.call_soon_threadsafe(func, fut, value)
147155

148156
PythonTask.from_coroutine(mark_complete()).spawn()
149157
return fut.__await__()

0 commit comments

Comments
 (0)