Skip to content

Fix(session): Resolve race condition in automatic restart logic#210

Closed
Itsydv wants to merge 2 commits into
KurimuzonAkuma:devfrom
Itsydv:dev
Closed

Fix(session): Resolve race condition in automatic restart logic#210
Itsydv wants to merge 2 commits into
KurimuzonAkuma:devfrom
Itsydv:dev

Conversation

@Itsydv

@Itsydv Itsydv commented Aug 14, 2025

Copy link
Copy Markdown
Contributor

Previously, a network error (like TimeoutError or OSError) during an API call in invoke() would trigger an automatic session restart. However, the implementation of this feature was flawed, leading to a critical race condition.

The Issue:

The invoke() method created the restart() operation as a "fire-and-forget" background task and then immediately retried the failed request recursively. This meant that the session was attempting to send data over a network connection that was simultaneously being closed and reopened by the restart() task.

This conflict resulted in a fatal asyncio.RuntimeError: read() called while another coroutine is already waiting for incoming data, causing the client to go unresponsive.

The Fix:

This commit resolves the race condition by serializing the error handling, restart, and retry operations, ensuring they happen in the correct order. The fix consists of three main parts:

  1. asyncio.Lock for Mutual Exclusion: An asyncio.Lock (_restart_lock) has been added to the Session class. The restart() method is now wrapped in this lock, which guarantees that only one restart operation can execute at a time, even if multiple network errors occur in quick succession.

  2. Synchronous Restart in invoke(): The exception handler in the invoke() method has been modified to directly await self.restart(). This forces the function to pause and wait for the connection to be fully and cleanly re-established before proceeding.

  3. Cleaner Retry Loop: The recursive retry call (return await self.invoke(...)) has been replaced with a continue statement. After a successful restart, this cleanly re-enters the while True loop to attempt the request again on the new, stable connection.

@skrtdev

skrtdev commented Aug 19, 2025

Copy link
Copy Markdown
Contributor

You should change indent to 4 spaces to maintain consistence between files

@skrtdev skrtdev mentioned this pull request Aug 20, 2025
3 tasks
@KurimuzonAkuma

Copy link
Copy Markdown
Owner

Fixed in 0396151

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