Skip to content

Fix correct client shutdown#76

Open
0zd0 wants to merge 1 commit intohydrogram:devfrom
0zd0:dev
Open

Fix correct client shutdown#76
0zd0 wants to merge 1 commit intohydrogram:devfrom
0zd0:dev

Conversation

@0zd0
Copy link

@0zd0 0zd0 commented Mar 16, 2026

Description

This PR improves the client shutdown and termination logic to ensure reliable resource cleanup.

Previously, the shutdown sequence relied on internal flags (is_initialized, is_connected) that might not update fast enough when managed via a fast-paced UI (e.g., Streamlit). This caused the client to remain active in the background or hang for 10 seconds due to recv_task not being cancelled correctly.

Removing explicit exceptions makes resource cleanup idempotent. In an asynchronous environment, a shutdown signal can arrive at any stage, even during partial initialization. By allowing methods to return normally rather than throwing errors, we ensure that the cleanup chain is not interrupted. This allows the library to always release resources (sockets and tasks) without leaving “zombies” running in the background.

Key changes:

  • Made terminate and disconnect idempotent by checking for object existence instead of volatile flags.
  • Ensured recv_task is explicitly cancelled and awaited before closing the connection.
  • Fixed a race condition where errors during shutdown prevented full resource cleanup.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

The changes were tested using a Streamlit-based management UI by rapidly toggling the bot's state.

  • Verified that rapid "Start -> Stop" sequences result in immediate socket closure without the 10-second MTProto timeout.
  • Confirmed that no ConnectionError or AttributeError is raised if stop() is called before the client is fully initialized.

Test Configuration

  • Operating System: macOS
  • Python Version: 3.14

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My changes generate no new warnings
  • New and existing unit tests pass locally with my changes

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.

1 participant