Skip to content

fix(langgraph): handle CancelledError in AsyncBackgroundExecutor cleanup#6974

Open
weiguang li (OiPunk) wants to merge 1 commit intolangchain-ai:mainfrom
OiPunk:codex/langgraph-6950-cancelled-error-cleanup
Open

fix(langgraph): handle CancelledError in AsyncBackgroundExecutor cleanup#6974
weiguang li (OiPunk) wants to merge 1 commit intolangchain-ai:mainfrom
OiPunk:codex/langgraph-6950-cancelled-error-cleanup

Conversation

@OiPunk
Copy link

Summary

  • Handle CancelledError in AsyncBackgroundExecutor.__aexit__ to prevent random crashes during astream cleanup
  • In Python 3.11+, CancelledError inherits BaseException and propagates into asyncio.wait's internal waiter when the parent task is cancelled, breaking the cleanup flow
  • Wrap asyncio.wait(tasks) in try/except: on cancellation, cancel remaining background tasks to avoid orphaned coroutines
  • Skip exception checks for tasks that haven't completed (avoids InvalidStateError)

fixes #6950

Changes

  • libs/langgraph/langgraph/pregel/_executor.py: Added CancelledError handling in __aexit__, plus a task.done() guard before checking task exceptions
  • libs/langgraph/tests/test_executor_async.py: 5 new unit tests covering cancellation during cleanup, normal exit, task exceptions, and cancel-on-exit behavior

Test plan

  • All 5 new tests pass locally
  • CI passes

AI-assisted review, AI-assisted testing

🤖 Generated with Claude Code

In Python 3.11+, CancelledError inherits BaseException and can propagate
into asyncio.wait's internal waiter when the parent task is cancelled
during AsyncPregelLoop.__aexit__, causing random crashes in production.

Wrap asyncio.wait in try/except to gracefully handle cancellation during
cleanup: cancel remaining background tasks and skip exception checks for
tasks that haven't completed yet.

fixes langchain-ai#6950

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant