From e71c24ea9b70a700d8f0f605bf78c9c680423041 Mon Sep 17 00:00:00 2001 From: Nuno Campos Date: Mon, 23 Sep 2024 08:41:57 -0700 Subject: [PATCH] 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 --- .../langgraph/checkpoint/postgres/aio.py | 12 ++++++++++++ .../langgraph/checkpoint/sqlite/aio.py | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/libs/checkpoint-postgres/langgraph/checkpoint/postgres/aio.py b/libs/checkpoint-postgres/langgraph/checkpoint/postgres/aio.py index 5a5206f3c..59ee7cbf9 100644 --- a/libs/checkpoint-postgres/langgraph/checkpoint/postgres/aio.py +++ b/libs/checkpoint-postgres/langgraph/checkpoint/postgres/aio.py @@ -393,6 +393,18 @@ class AsyncPostgresSaver(BasePostgresSaver): 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 AsyncPostgresSaver 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() diff --git a/libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py b/libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py index d2347006e..21cde06e0 100644 --- a/libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py +++ b/libs/checkpoint-sqlite/langgraph/checkpoint/sqlite/aio.py @@ -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()