@devries-cameron20 / composio-1 / commits / 2a2d77a76
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(py/triggers): stop() deadlock + subscribe() timeout connection leak (#3890)

Fixes #3858 (both bugs reported there). Bug 1 — TriggerSubscription.stop() deadlocks when called from a trigger callback. pysher's Connection.disconnect runs socket.close() then join(timeout) on the websocket thread, but callbacks execute on that same thread's dispatch path (_handle_event blocks on the callback's future.result()), so joining the thread from within a callback that runs on it deadlocks the whole process and _alive is never cleared, so a main thread parked in wait_forever() never exits. Fix: clear _alive synchronously (so wait_forever unblocks immediately) and run disconnect() on a daemon thread, breaking the reentrancy while still closing the socket. Bug 2 — _SubcriptionBuilder.connect() leaks a websocket thread on timeout. The deadline path raised ComposioSDKTimeoutError without calling pusher.disconnect(), so pysher's run loop kept redialing every reconnect_interval for the life of the process — one leaked thread per timed-out subscribe(), and if a leaked connection later succeeded it would authenticate and subscribe the channel of an abandoned TriggerSubscription, silently consuming events. Fix: wrap the wait loop in try/except so the timeout path tears the connection down before re-raising. Added regression tests (TestTriggerSubscriptionStop and TestSubscriptionBuilderConnectTimeout) that reproduce both failure modes offline with mocked pusher connections; all 73 tests in tests/test_triggers.py pass, ruff check + format clean. --------- Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com> Co-authored-by: jkomyno <alberto.schiabel@gmail.com>

Checo committed Jul 28, 2026 at 20:29 UTC 2a2d77a7644bd947abf858535173188df247ca64
2 files changed +169 -13
python/composio/core/models/triggers.py
+39 -13
@@ -5,6 +5,7 @@ import functools
5 import hashlib
6 import hmac
7 import json
8 +import threading
9 import time
10 import traceback
11 import typing as t
@@ -779,9 +780,26 @@ class TriggerSubscription(Resource):
780 time.sleep(1)
781
782 def stop(self) -> None:
782 - """Stop the trigger listener."""
783 - self._connection.disconnect()
783 + """Stop the trigger listener.
784 +
785 + ``_alive`` is cleared first so a main thread parked in
786 + ``wait_forever`` unblocks immediately. The connection disconnect is
787 + then run off the calling thread: ``pysher.Connection.disconnect`` does
788 + ``socket.close(); join(timeout)`` on the websocket thread, but the
789 + documented usage runs ``stop()`` from inside a trigger callback, which
790 + pysher dispatches on that very websocket thread (``_handle_event``
791 + blocks on the callback's ``future.result()``). Joining the thread from
792 + a callback that runs on it deadlocks the whole process. Tearing the
793 + connection down on a background thread breaks that reentrancy while
794 + still ensuring the socket is closed.
795 + """
796 self._alive = False
797 + thread = threading.Thread(
798 + target=self._connection.disconnect,
799 + name="composio-trigger-disconnect",
800 + daemon=True,
801 + )
802 + thread.start()
803
804 def restart(self) -> None:
805 """Restart the subscription connection"""
@@ -864,18 +882,26 @@ class _SubcriptionBuilder(WithLogger):
882 )
883 pusher.connect()
884
867 - # Wait for connection to get established
885 + # Wait for connection to get established. On timeout, tear down the
886 + # connection before raising: pysher's run loop reconnects every
887 + # ``reconnect_interval`` until ``disconnect`` is called, so a plain
888 + # raise would leak a websocket thread (and, if it eventually connects,
889 + # silently subscribe a forgotten channel) for the life of the process.
890 deadline = time.time() + timeout
869 - while time.time() < deadline:
870 - if not self.subscription.is_alive():
871 - time.sleep(0.5)
872 - continue
873 -
874 - self.subscription._pusher = pusher # pylint: disable=protected-access
875 - return self.subscription
876 - raise ComposioSDKTimeoutError(
877 - "Timed out while waiting for trigger listener to be established"
878 - )
891 + try:
892 + while time.time() < deadline:
893 + if not self.subscription.is_alive():
894 + time.sleep(0.5)
895 + continue
896 +
897 + self.subscription._pusher = pusher # pylint: disable=protected-access
898 + return self.subscription
899 + raise ComposioSDKTimeoutError(
900 + "Timed out while waiting for trigger listener to be established"
901 + )
902 + except Exception:
903 + pusher.disconnect()
904 + raise
905
906
907 class Triggers(Resource):
python/tests/test_triggers.py
+130
@@ -4,6 +4,7 @@ import base64
4 import hashlib
5 import hmac
6 import json
7 +import threading
8 import time
9 from datetime import datetime, timezone
10 from unittest.mock import Mock, patch
@@ -15,9 +16,11 @@ from composio_client import NotFoundError, omit
16 from composio import exceptions
17 from composio.core.models.triggers import (
18 _MAX_LOGGED_FRAME_CHARS,
19 + ComposioSDKTimeoutError,
20 Triggers,
21 TriggerSubscription,
22 WebhookVersion,
23 + _SubcriptionBuilder,
24 _truncate_frame,
25 )
26
@@ -1584,3 +1587,130 @@ class TestTriggerSubscriptionParsing:
1587 assert len(truncated) < len(long)
1588 assert truncated.startswith("y" * _MAX_LOGGED_FRAME_CHARS)
1589 assert str(len(long)) in truncated
1590 +
1591 +
1592 +class TestTriggerSubscriptionStop:
1593 + """Tests for TriggerSubscription.stop lifecycle handling."""
1594 +
1595 + @pytest.fixture
1596 + def subscription(self):
1597 + """Create a TriggerSubscription with a mock client."""
1598 + sub = TriggerSubscription(client=Mock())
1599 + sub._alive = True
1600 + return sub
1601 +
1602 + def test_stop_clears_alive_synchronously(self, subscription):
1603 + """``_alive`` is cleared before ``stop`` returns, not after disconnect.
1604 +
1605 + A main thread parked in ``wait_forever`` checks ``_alive`` every
1606 + second; clearing it synchronously (rather than after a potentially
1607 + blocking ``disconnect``) lets that loop exit promptly.
1608 + """
1609 + disconnect_started = threading.Event()
1610 +
1611 + def blocking_disconnect():
1612 + disconnect_started.set()
1613 + # Block so we can prove _alive was cleared without waiting on
1614 + # the disconnect.
1615 + threading.Event().wait(timeout=5)
1616 +
1617 + subscription._connection = Mock()
1618 + subscription._connection.disconnect = blocking_disconnect
1619 +
1620 + subscription.stop()
1621 +
1622 + # _alive is False the moment stop() returns, even though disconnect
1623 + # is still running in the background.
1624 + assert subscription.is_alive() is False
1625 + assert disconnect_started.wait(timeout=2)
1626 +
1627 + def test_stop_does_not_block_on_slow_disconnect(self, subscription):
1628 + """``stop()`` returns even if ``disconnect`` would block forever.
1629 +
1630 + pysher's ``Connection.disconnect`` joins the websocket thread. When
1631 + ``stop()`` is called from a callback that pysher dispatches on that
1632 + same thread, the join deadlocks. Running the disconnect on a daemon
1633 + thread breaks the reentrancy: ``stop`` returns immediately even when
1634 + ``disconnect`` never completes.
1635 + """
1636 + started = threading.Event()
1637 + never_set = threading.Event()
1638 +
1639 + def blocking_disconnect():
1640 + started.set()
1641 + # Simulate pysher joining a thread that never finishes (the
1642 + # deadlock state from the bug report).
1643 + never_set.wait(timeout=5)
1644 +
1645 + subscription._connection = Mock()
1646 + subscription._connection.disconnect = blocking_disconnect
1647 +
1648 + # If stop() were to call disconnect() inline it would block here.
1649 + subscription.stop()
1650 +
1651 + # stop() returned control and the disconnect is running in the
1652 + # background.
1653 + assert subscription.is_alive() is False
1654 + assert started.wait(timeout=2)
1655 +
1656 +
1657 +class TestSubscriptionBuilderConnectTimeout:
1658 + """Tests for _SubcriptionBuilder.connect timeout teardown."""
1659 +
1660 + def _make_builder(self, pusher: Mock) -> _SubcriptionBuilder:
1661 + """Build a _SubcriptionBuilder with a patched pusher factory."""
1662 + client = Mock()
1663 + client.base_url = "https://api.example.com"
1664 + with patch.object(
1665 + _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1666 + ):
1667 + b = _SubcriptionBuilder(client=client)
1668 + b.subscription = Mock()
1669 + b.subscription.is_alive.return_value = False
1670 + b.internal = Mock()
1671 + b.internal.get_sdk_realtime_credentials.return_value = Mock(
1672 + project_id="p", pusher_key="k", pusher_cluster="c"
1673 + )
1674 + b._get_connection_handler = Mock( # type: ignore[method-assign]
1675 + return_value=lambda *a, **k: None
1676 + )
1677 + return b
1678 +
1679 + def test_connect_disconnects_pusher_on_timeout(self):
1680 + """On timeout, the partially-connected pusher is torn down.
1681 +
1682 + pysher's connection loop redials every ``reconnect_interval`` until
1683 + ``disconnect`` is called. If ``connect`` raises without disconnecting,
1684 + each timed-out attempt leaks a websocket thread for the life of the
1685 + process. The fix wraps the wait loop in try/except so the timeout
1686 + path disconnects before re-raising.
1687 + """
1688 + pusher = Mock()
1689 + builder = self._make_builder(pusher)
1690 + # subscription.is_alive() returns False, so the wait loop never
1691 + # returns early -> the deadline elapses -> timeout path runs.
1692 + builder.subscription.is_alive.return_value = False
1693 +
1694 + with (
1695 + patch.object(
1696 + _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1697 + ),
1698 + pytest.raises(ComposioSDKTimeoutError),
1699 + ):
1700 + builder.connect(timeout=0.1)
1701 +
1702 + pusher.disconnect.assert_called_once()
1703 +
1704 + def test_connect_returns_subscription_without_disconnecting(self):
1705 + """On success, the pusher stays connected and is attached to the sub."""
1706 + pusher = Mock()
1707 + builder = self._make_builder(pusher)
1708 + builder.subscription.is_alive.return_value = True
1709 +
1710 + with patch.object(
1711 + _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1712 + ):
1713 + result = builder.connect(timeout=2.0)
1714 +
1715 + assert result is builder.subscription
1716 + pusher.disconnect.assert_not_called()