@devries-cameron20 / composio-1 / commits / 27701dd54
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.

feat(py): add optional on_subscription_error for trigger subscriptions

Mirror the TypeScript API surface from the previous commit: - Triggers.subscribe accepts an optional on_subscription_error callback, threaded through _SubcriptionBuilder.connect and bound to pysher's pusher:subscription_error event on the trigger channel. - TriggerSubscription._handle_subscription_error logs the failure at the SDK boundary and invokes the callback with the parsed payload (or {'raw': frame} for malformed frames); callback exceptions are contained and logged so a faulty handler cannot tear down pysher's dispatch thread. - The parameter is optional; existing callers are unaffected. - Update the Python triggers reference and the subscribing-to-events guide. Python never bound pusher:subscription_error at all, so subscription failures after connect() were previously invisible to hosts.

jkomyno committed Sep 15, 2026 at 16:58 UTC 27701dd541e2cf92b6b28b0289e9a6adc3a12d06
4 files changed +158 -6
docs/content/docs/setting-up-triggers/subscribing-to-events.mdx
+8
@@ -66,6 +66,14 @@ await composio.triggers.subscribe(
66 );
67 ```
68
69 +In Python, pass the equivalent `on_subscription_error` keyword:
70 +
71 +```python
72 +subscription = composio.triggers.subscribe(
73 + on_subscription_error=lambda error: print("Trigger subscription failed:", error)
74 +)
75 +```
76 +
77 ### Forward to your local handler with the CLI (recommended)
78
79 The Composio CLI streams realtime events and forwards each one to your local URL, signed exactly like production. No public URL, no tunnel, and it runs your real handler (and [`parse()`](#handling-events)) end to end.
docs/content/reference/sdk-reference/python/triggers.mdx
+2 -1
@@ -123,7 +123,7 @@ def create(slug: str, user_id: str | None = ..., connected_account_id: str | Non
123 Subscribe to a trigger and receive trigger events.
124
125 ```python
126 -def subscribe(timeout: float = ...) -> TriggerSubscription
126 +def subscribe(timeout: float = ..., on_subscription_error: Optional[Callable[[Dict[str, Any]], None]] = ...) -> TriggerSubscription
127 ```
128
129 **Parameters**
@@ -131,6 +131,7 @@ def subscribe(timeout: float = ...) -> TriggerSubscription
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. |
135
136 **Returns**
137
python/composio/core/models/triggers.py
+57 -3
@@ -465,6 +465,8 @@ class TriggerEventFilters(te.TypedDict):
465
466 TriggerCallback = t.Callable[[TriggerEvent], None]
467
468 +SubscriptionErrorCallback = t.Callable[[t.Dict[str, t.Any]], None]
469 +
470
471 # Realtime trigger frames can carry message bodies / PII, so the raw frame is
472 # never logged in full — only a bounded preview when it fails to parse.
@@ -606,6 +608,7 @@ class TriggerSubscription(Resource):
608 self._alive = False
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
613 def handle(
614 self, **filters: te.Unpack[TriggerEventFilters]
@@ -809,6 +812,30 @@ class TriggerSubscription(Resource):
812 )
813 _ = [future.result() for future in awaitables]
814
815 + def _handle_subscription_error(self, event: str) -> None:
816 + """Handle a ``pusher:subscription_error`` frame.
817 +
818 + Logs the failure at the SDK boundary and invokes the optional
819 + ``on_subscription_error`` callback registered through
820 + ``Triggers.subscribe``. Callback exceptions are contained and logged
821 + so a faulty handler cannot tear down the pysher dispatch thread
822 + (pysher invokes bound callbacks without a try/except).
823 + """
824 + self.logger.error(f"Trigger subscription error: {_truncate_frame(event)}")
825 + callback = self._on_subscription_error
826 + if callback is None:
827 + return
828 + try:
829 + payload: t.Dict[str, t.Any] = json.loads(event)
830 + except Exception:
831 + payload = {"raw": event}
832 + try:
833 + callback(payload)
834 + except Exception:
835 + self.logger.error(
836 + f"Error in subscription error callback:\n {traceback.format_exc()}"
837 + )
838 +
839 def is_alive(self) -> bool:
840 """Check if subscription is live."""
841 return self._alive
@@ -990,6 +1017,10 @@ class _SubcriptionBuilder(WithLogger):
1017 event_name="chunked-trigger_to_client",
1018 callback=subscription._handle_chunked_events,
1019 )
1020 + channel.bind(
1021 + event_name="pusher:subscription_error",
1022 + callback=subscription._handle_subscription_error,
1023 + )
1024 subscription.set_alive()
1025 subscription._channel = channel # pylint: disable=protected-access
1026 subscription._connection = ( # pylint: disable=protected-access
@@ -1011,7 +1042,11 @@ class _SubcriptionBuilder(WithLogger):
1042 auto_sub=True,
1043 )
1044
1014 - def connect(self, timeout: float = 15.0) -> TriggerSubscription:
1045 + def connect(
1046 + self,
1047 + timeout: float = 15.0,
1048 + on_subscription_error: t.Optional[SubscriptionErrorCallback] = None,
1049 + ) -> TriggerSubscription:
1050 """Connect to Pusher channel for given client ID."""
1051 self.logger.debug("Creating trigger subscription")
1052 project_info = self.internal.get_sdk_realtime_credentials()
@@ -1030,6 +1065,12 @@ class _SubcriptionBuilder(WithLogger):
1065 subscription=self.subscription,
1066 ),
1067 )
1068 + # Set before ``pusher.connect()``: the subscription_error handler runs
1069 + # on pysher's websocket thread once the channel subscribes, so the
1070 + # callback must already be in place.
1071 + self.subscription._on_subscription_error = ( # pylint: disable=protected-access
1072 + on_subscription_error
1073 + )
1074 pusher.connect()
1075
1076 # Wait for connection to get established. On timeout, tear down the
@@ -1349,14 +1390,27 @@ class Triggers(Resource):
1390 user_id=none_to_omit(user_id),
1391 )
1392
1352 - def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:
1393 + def subscribe(
1394 + self,
1395 + timeout: float = 15.0,
1396 + on_subscription_error: t.Optional[SubscriptionErrorCallback] = None,
1397 + ) -> TriggerSubscription:
1398 """
1399 Subscribe to a trigger and receive trigger events.
1400
1401 :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.
1408 :return: The trigger subscription handler.
1409 """
1359 - return _SubcriptionBuilder(client=self._client).connect(timeout=timeout)
1410 + return _SubcriptionBuilder(client=self._client).connect(
1411 + timeout=timeout,
1412 + on_subscription_error=on_subscription_error,
1413 + )
1414
1415 def verify_webhook(
1416 self,
python/tests/test_triggers.py
+91 -2
@@ -496,7 +496,9 @@ class TestTriggers:
496 result = triggers.subscribe(timeout=20.0)
497
498 mock_builder_class.assert_called_once_with(client=mock_client)
499 - mock_builder.connect.assert_called_once_with(timeout=20.0)
499 + mock_builder.connect.assert_called_once_with(
500 + timeout=20.0, on_subscription_error=None
501 + )
502 assert result == mock_subscription
503
504 def test_subscribe_with_default_timeout(self, triggers, mock_client):
@@ -511,7 +513,29 @@ class TestTriggers:
513
514 result = triggers.subscribe()
515
514 - mock_builder.connect.assert_called_once_with(timeout=15.0)
516 + mock_builder.connect.assert_called_once_with(
517 + timeout=15.0, on_subscription_error=None
518 + )
519 + assert result == mock_subscription
520 +
521 + def test_subscribe_passes_subscription_error_callback(self, triggers, mock_client):
522 + """The optional on_subscription_error callback reaches the builder."""
523 + with patch(
524 + "composio.core.models.triggers._SubcriptionBuilder"
525 + ) as mock_builder_class:
526 + mock_builder = Mock()
527 + mock_subscription = Mock()
528 + mock_builder.connect.return_value = mock_subscription
529 + mock_builder_class.return_value = mock_builder
530 + on_subscription_error = Mock()
531 +
532 + result = triggers.subscribe(
533 + timeout=5.0, on_subscription_error=on_subscription_error
534 + )
535 +
536 + mock_builder.connect.assert_called_once_with(
537 + timeout=5.0, on_subscription_error=on_subscription_error
538 + )
539 assert result == mock_subscription
540
541
@@ -1795,6 +1819,71 @@ class TestSubscriptionBuilderConnectTimeout:
1819 pusher.disconnect.assert_not_called()
1820
1821
1822 +class TestSubscriptionErrorHandler:
1823 + """Tests for TriggerSubscription._handle_subscription_error."""
1824 +
1825 + @pytest.fixture
1826 + def subscription(self):
1827 + """Create a TriggerSubscription with a mock client."""
1828 + return TriggerSubscription(client=Mock())
1829 +
1830 + def test_invokes_callback_with_parsed_payload(self, subscription):
1831 + """The callback receives the subscription error payload as a dict."""
1832 + callback = Mock()
1833 + subscription._on_subscription_error = callback
1834 +
1835 + subscription._handle_subscription_error('{"type": "AuthError", "status": 401}')
1836 +
1837 + callback.assert_called_once_with({"type": "AuthError", "status": 401})
1838 +
1839 + def test_malformed_frame_reaches_callback_as_raw(self, subscription):
1840 + """A non-JSON frame is logged, not raised, and passed as ``{'raw': ...}``."""
1841 + callback = Mock()
1842 + subscription._on_subscription_error = callback
1843 +
1844 + subscription._handle_subscription_error("not valid json {")
1845 +
1846 + callback.assert_called_once_with({"raw": "not valid json {"})
1847 +
1848 + def test_callback_exception_is_contained(self, subscription):
1849 + """A faulty handler is logged, never rethrown into pysher's thread."""
1850 + subscription._on_subscription_error = Mock(side_effect=RuntimeError("boom"))
1851 +
1852 + subscription._handle_subscription_error('{"error": "auth failed"}')
1853 +
1854 + def test_no_callback_is_a_no_op(self, subscription):
1855 + """Without a registered callback the frame is only logged."""
1856 + subscription._handle_subscription_error('{"error": "auth failed"}')
1857 +
1858 + def test_connection_handler_binds_subscription_error(self):
1859 + """The builder binds ``pusher:subscription_error`` to the handler."""
1860 + client = Mock()
1861 + client.base_url = "https://api.example.com"
1862 + builder = _SubcriptionBuilder(client=client)
1863 + channel = Mock()
1864 + pusher = Mock()
1865 + pusher.subscribe.return_value = channel
1866 +
1867 + handler = builder._get_connection_handler(
1868 + project_id="p", pusher=pusher, subscription=builder.subscription
1869 + )
1870 + handler("connection-payload")
1871 +
1872 + bound = {
1873 + call.kwargs["event_name"]: call.kwargs["callback"]
1874 + for call in channel.bind.call_args_list
1875 + }
1876 + assert (
1877 + bound["pusher:subscription_error"]
1878 + == builder.subscription._handle_subscription_error
1879 + )
1880 + assert bound["trigger_to_client"] == builder.subscription._handle_event
1881 + assert (
1882 + bound["chunked-trigger_to_client"]
1883 + == builder.subscription._handle_chunked_events
1884 + )
1885 +
1886 +
1887 class TestPusherChannelAuth:
1888 """Tests for the hardened pysher channel-auth request."""
1889