Raise exception if sync method on async checkpointer is called from main thread

- The thread running the event loop can block waiting for a coro to run, only background threads can
This commit is contained in:
Nuno Campos
2024-09-23 08:41:57 -07:00
parent 68d378def5
commit e71c24ea9b
2 changed files with 24 additions and 0 deletions
@@ -153,6 +153,18 @@ class AsyncSqliteSaver(BaseCheckpointSaver[str]):
Returns:
Optional[CheckpointTuple]: The retrieved checkpoint tuple, or None if no matching checkpoint was found.
"""
try:
# check if we are in the main thread, only bg threads can block
# we don't check in other methods to avoid the overhead
if asyncio.get_running_loop() is self.loop:
raise asyncio.InvalidStateError(
"Synchronous calls to AsyncSqliteSaver are only allowed from a "
"different thread. From the main thread, use the async interface."
"For example, use `await checkpointer.aget_tuple(...)` or `await "
"graph.ainvoke(...)`."
)
except RuntimeError:
pass
return asyncio.run_coroutine_threadsafe(
self.aget_tuple(config), self.loop
).result()