@devries-cameron20 / composio Mirror · read-only / commits / c2e70f66a
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 12:15 UTC

fix(py): route establish-time subscription failures through on_subscription_error

pysher performs the channel-auth request synchronously inside pusher.subscribe(), so an auth rejection raised on the websocket thread before pusher:subscription_error could ever be bound or fire. The new on_subscription_error callback was skipped for exactly the failures it documents, and callers waited out the full connect timeout for a generic ComposioSDKTimeoutError. - _connection_handler catches subscribe() failures and routes them through the error path (log + callback with {'error': ...}). - The failure is recorded on the subscription and the connect() wait loop re-raises it on its next poll, so subscribe() fails promptly with the underlying error and still tears down the pusher. - Update the Python reference, guide, and docstrings; add regression coverage for the handler routing, the failure record, and fast-fail. Addresses the Cursor Bugbot comment on triggers.py:1023.

jkomyno committed Sep 16, 2026 at 14:54 UTC c2e70f66a6c79df467e75db6ebf445e476928d1b
4 files changed +147 -14
docs/content/docs/setting-up-triggers/subscribing-to-events.mdx
+1 -1
@@ -66,7 +66,7 @@ await composio.triggers.subscribe(
66 );
67 ```
68
69 -In Python, pass the equivalent `on_subscription_error` keyword:
69 +In Python, pass the equivalent `on_subscription_error` keyword. Failures raised while establishing the subscription (such as an auth rejection) invoke the callback and then re-raise from `subscribe()` instead of timing out:
70
71 ```python
72 subscription = composio.triggers.subscribe(
docs/content/reference/sdk-reference/python/triggers.mdx
+1 -1
@@ -131,7 +131,7 @@ def subscribe(timeout: float = ..., on_subscription_error: Optional[Callable[[Di
131 | Name | Type |
132 |------|------|
133 | `timeout?` | `float` |
134 -| `on_subscription_error?` | `Optional[Callable[[Dict[str, Any]], None]]` — Optional callback invoked with the raw Pusher subscription error payload when the channel subscription fails (for example on auth or permission rejection). The subscription is still returned; this callback is the only programmatic signal of the failure. Exceptions raised inside the callback are contained and logged, never rethrown. |
134 +| `on_subscription_error?` | `Optional[Callable[[Dict[str, Any]], None]]` — Optional callback invoked when the channel subscription fails: with the raw Pusher payload for asynchronous `pusher:subscription_error` events, or with `{"error": ...}` for failures raised while establishing the subscription (for example an auth rejection — pysher performs channel auth synchronously). Establish-time failures also make `subscribe()` raise the underlying error promptly instead of waiting out the timeout. Exceptions raised inside the callback are contained and logged, never rethrown. |
135
136 **Returns**
137
python/composio/core/models/triggers.py
+55 -12
@@ -609,6 +609,7 @@ class TriggerSubscription(Resource):
609 self._chunks: t.Dict[str, t.Dict[int, str]] = {}
610 self._callbacks: t.List[t.Tuple[TriggerCallback, TriggerEventFilters]] = []
611 self._on_subscription_error: t.Optional[SubscriptionErrorCallback] = None
612 + self._connection_error: t.Optional[Exception] = None
613
614 def handle(
615 self, **filters: te.Unpack[TriggerEventFilters]
@@ -812,6 +813,34 @@ class TriggerSubscription(Resource):
813 )
814 _ = [future.result() for future in awaitables]
815
816 + def _fail_subscription(self, error: Exception) -> None:
817 + """Record an establish-time subscription failure and notify the callback.
818 +
819 + Used for failures that happen before any channel event can fire:
820 + pysher performs the channel-auth request synchronously inside
821 + ``pusher.subscribe()``, so auth failures raise on the websocket thread
822 + instead of arriving as ``pusher:subscription_error`` frames. The
823 + pending ``connect()`` wait loop re-raises the recorded error instead
824 + of spinning to its timeout.
825 + """
826 + self.logger.error(f"Trigger subscription error: {error}")
827 + self._connection_error = error
828 + callback = self._on_subscription_error
829 + if callback is None:
830 + return
831 + try:
832 + callback({"error": str(error)})
833 + except Exception:
834 + self.logger.error(
835 + f"Error in subscription error callback:\n {traceback.format_exc()}"
836 + )
837 +
838 + def _raise_on_connection_error(self) -> None:
839 + """Raise the recorded establish-time failure, if any."""
840 + error = self._connection_error
841 + if error is not None:
842 + raise error
843 +
844 def _handle_subscription_error(self, event: str) -> None:
845 """Handle a ``pusher:subscription_error`` frame.
846
@@ -1003,12 +1032,22 @@ class _SubcriptionBuilder(WithLogger):
1032 subscription: TriggerSubscription,
1033 ) -> t.Callable[[str], None]:
1034 def _connection_handler(_: str) -> None:
1006 - channel = t.cast(
1007 - PusherChannel,
1008 - pusher.subscribe(
1009 - channel_name=f"private-{project_id}_triggers",
1010 - ),
1011 - )
1035 + try:
1036 + channel = t.cast(
1037 + PusherChannel,
1038 + pusher.subscribe(
1039 + channel_name=f"private-{project_id}_triggers",
1040 + ),
1041 + )
1042 + except Exception as e:
1043 + # pysher performs the channel-auth request synchronously inside
1044 + # ``subscribe()``: an auth failure raises here on the websocket
1045 + # thread before ``pusher:subscription_error`` can fire or
1046 + # ``set_alive()`` can run. Surface it through the error path
1047 + # and let the pending ``connect()`` fail fast; the wait loop's
1048 + # teardown disconnects the pusher.
1049 + subscription._fail_subscription(e) # pylint: disable=protected-access
1050 + return
1051 channel.bind(
1052 event_name="trigger_to_client",
1053 callback=subscription._handle_event,
@@ -1081,6 +1120,7 @@ class _SubcriptionBuilder(WithLogger):
1120 deadline = time.time() + timeout
1121 try:
1122 while time.time() < deadline:
1123 + self.subscription._raise_on_connection_error() # pylint: disable=protected-access
1124 if not self.subscription.is_alive():
1125 time.sleep(0.5)
1126 continue
@@ -1399,12 +1439,15 @@ class Triggers(Resource):
1439 Subscribe to a trigger and receive trigger events.
1440
1441 :param timeout: The timeout to wait for the subscription to be established.
1402 - :param on_subscription_error: Optional callback invoked with the raw Pusher
1403 - subscription error payload when the channel subscription fails (for
1404 - example on auth or permission rejection). The subscription is still
1405 - returned; this callback is the only programmatic signal of the
1406 - failure. Exceptions raised inside the callback are contained and
1407 - logged, never rethrown.
1442 + :param on_subscription_error: Optional callback invoked when the channel
1443 + subscription fails: with the raw Pusher payload for asynchronous
1444 + ``pusher:subscription_error`` events (for example a later permission
1445 + rejection), or with ``{"error": ...}`` for failures raised while
1446 + establishing the subscription (for example an auth rejection —
1447 + pysher performs channel auth synchronously). Establish-time failures
1448 + also make ``subscribe()`` raise the underlying error promptly
1449 + instead of waiting out the timeout. Exceptions raised inside the
1450 + callback are contained and logged, never rethrown.
1451 :return: The trigger subscription handler.
1452 """
1453 return _SubcriptionBuilder(client=self._client).connect(
python/tests/test_triggers.py
+90
@@ -1818,6 +1818,36 @@ class TestSubscriptionBuilderConnectTimeout:
1818 assert result is builder.subscription
1819 pusher.disconnect.assert_not_called()
1820
1821 + def test_connect_raises_recorded_failure_fast(self):
1822 + """An establish-time failure raises promptly instead of timing out.
1823 +
1824 + The connection handler records the failure (for example a channel-auth
1825 + rejection raised inside ``pusher.subscribe()``); the wait loop must
1826 + surface it on its next poll and tear down the pusher, not spin until
1827 + the deadline and report a generic timeout.
1828 + """
1829 + pusher = Mock()
1830 + builder = self._make_builder(pusher)
1831 + failure = RuntimeError("auth rejected")
1832 + # The connection handler records the failure; on the mocked
1833 + # subscription this is the wait loop's re-raise hook.
1834 + builder.subscription._raise_on_connection_error.side_effect = failure
1835 + builder._get_connection_handler = Mock( # type: ignore[method-assign]
1836 + return_value=lambda *a, **k: None
1837 + )
1838 +
1839 + started = time.monotonic()
1840 + with (
1841 + patch.object(
1842 + _SubcriptionBuilder, "_get_pusher_instance", return_value=pusher
1843 + ),
1844 + pytest.raises(RuntimeError, match="auth rejected"),
1845 + ):
1846 + builder.connect(timeout=15.0)
1847 +
1848 + assert time.monotonic() - started < 5.0
1849 + pusher.disconnect.assert_called_once()
1850 +
1851
1852 class TestSubscriptionErrorHandler:
1853 """Tests for TriggerSubscription._handle_subscription_error."""
@@ -1855,6 +1885,41 @@ class TestSubscriptionErrorHandler:
1885 """Without a registered callback the frame is only logged."""
1886 subscription._handle_subscription_error('{"error": "auth failed"}')
1887
1888 + def test_fail_subscription_invokes_callback_and_records_error(self, subscription):
1889 + """Establish-time failures reach the callback as ``{'error': ...}``."""
1890 + callback = Mock()
1891 + subscription._on_subscription_error = callback
1892 +
1893 + subscription._fail_subscription(RuntimeError("auth rejected"))
1894 +
1895 + callback.assert_called_once_with({"error": "auth rejected"})
1896 + assert subscription._connection_error is not None
1897 +
1898 + def test_fail_subscription_without_callback_only_records(self, subscription):
1899 + """The failure is recorded even when no callback is registered."""
1900 + subscription._fail_subscription(RuntimeError("auth rejected"))
1901 +
1902 + assert subscription._connection_error is not None
1903 +
1904 + def test_fail_subscription_contains_callback_exception(self, subscription):
1905 + """A faulty callback cannot break the failure path."""
1906 + subscription._on_subscription_error = Mock(side_effect=RuntimeError("boom"))
1907 +
1908 + subscription._fail_subscription(RuntimeError("auth rejected"))
1909 +
1910 + assert subscription._connection_error is not None
1911 +
1912 + def test_raise_on_connection_error_raises_recorded_error(self, subscription):
1913 + """The wait loop re-raises the recorded failure."""
1914 + subscription._fail_subscription(RuntimeError("auth rejected"))
1915 +
1916 + with pytest.raises(RuntimeError, match="auth rejected"):
1917 + subscription._raise_on_connection_error()
1918 +
1919 + def test_raise_on_connection_error_is_noop_when_healthy(self, subscription):
1920 + """No recorded failure means the wait loop proceeds normally."""
1921 + subscription._raise_on_connection_error()
1922 +
1923 def test_connection_handler_binds_subscription_error(self):
1924 """The builder binds ``pusher:subscription_error`` to the handler."""
1925 client = Mock()
@@ -1883,6 +1948,31 @@ class TestSubscriptionErrorHandler:
1948 == builder.subscription._handle_chunked_events
1949 )
1950
1951 + def test_connection_handler_routes_subscribe_failure_to_error_path(self):
1952 + """Auth failures inside ``pusher.subscribe()`` reach the error path.
1953 +
1954 + pysher performs the channel-auth request synchronously inside
1955 + ``subscribe()``; without this routing the callback is skipped and the
1956 + caller waits out the connect timeout for a generic error.
1957 + """
1958 + client = Mock()
1959 + client.base_url = "https://api.example.com"
1960 + builder = _SubcriptionBuilder(client=client)
1961 + callback = Mock()
1962 + builder.subscription._on_subscription_error = callback
1963 + pusher = Mock()
1964 + pusher.subscribe.side_effect = exceptions.TriggerSubscriptionAuthError(
1965 + "auth failed"
1966 + )
1967 +
1968 + handler = builder._get_connection_handler(
1969 + project_id="p", pusher=pusher, subscription=builder.subscription
1970 + )
1971 + handler("connection-payload") # must not raise
1972 +
1973 + callback.assert_called_once_with({"error": "auth failed"})
1974 + assert builder.subscription.is_alive() is False
1975 +
1976
1977 class TestPusherChannelAuth:
1978 """Tests for the hardened pysher channel-auth request."""