Skip to content

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): swallow malformed chunked frame instead of tearing down subscription (#3892)

Checoa3f6b9c8f245
diff --git a/python/composio/core/models/triggers.py b/python/composio/core/models/triggers.py
index 17033b288..125334aeb 100644
--- a/python/composio/core/models/triggers.py
+++ b/python/composio/core/models/triggers.py
@@ -426,7 +426,7 @@ _ = {
class _ChunkedTriggerEventData(te.TypedDict):
- """Cunked trigger event data model."""
+ """Chunked trigger event data model."""
id: str
index: int
@@ -668,15 +668,44 @@ class TriggerSubscription(Resource):
return None
def _handle_chunked_events(self, event: str) -> None:
- """Handle chunked events."""
- data = _ChunkedTriggerEventData(**json.loads(event)) # type: ignore
- if data["id"] not in self._chunks:
- self._chunks[data["id"]] = {}
-
- self._chunks[data["id"]][data["index"]] = data["chunk"]
- if data["final"]:
- _chunks = self._chunks.pop(data["id"])
- self._handle_event(event="".join([_chunks[idx] for idx in sorted(_chunks)]))
+ """Handle chunked events without letting malformed frames escape Pysher."""
+ chunk_id: t.Optional[str] = None
+ try:
+ raw_data = json.loads(event)
+ if not isinstance(raw_data, dict):
+ raise TypeError("chunked payload must be an object")
+
+ raw_id = raw_data.get("id")
+ chunk_id = raw_id if isinstance(raw_id, str) else None
+ index = raw_data.get("index")
+ chunk = raw_data.get("chunk")
+ final = raw_data.get("final")
+ if (
+ chunk_id is None
+ or not isinstance(index, int)
+ or isinstance(index, bool)
+ or not isinstance(chunk, str)
+ or not isinstance(final, bool)
+ ):
+ raise TypeError("chunked payload has invalid fields")
+
+ data = t.cast(_ChunkedTriggerEventData, raw_data)
+ if data["id"] not in self._chunks:
+ self._chunks[data["id"]] = {}
+
+ self._chunks[data["id"]][data["index"]] = data["chunk"]
+ if data["final"]:
+ _chunks = self._chunks.pop(data["id"])
+ self._handle_event(
+ event="".join([_chunks[idx] for idx in sorted(_chunks)])
+ )
+ except Exception as e:
+ if chunk_id is not None:
+ self._chunks.pop(chunk_id, None)
+ self.logger.warning(
+ f"Error parsing chunked trigger payload: {e}; "
+ f"frame: {_truncate_frame(event)}"
+ )
def _filters_match(
self,
diff --git a/python/tests/test_triggers.py b/python/tests/test_triggers.py
index 107968cbe..29b5873f7 100644
--- a/python/tests/test_triggers.py
+++ b/python/tests/test_triggers.py
@@ -1589,6 +1589,81 @@ class TestTriggerSubscriptionParsing:
assert str(len(long)) in truncated
+class TestChunkedEventResilience:
+ """A malformed chunked frame must never tear down the subscription.
+
+ ``_handle_chunked_events`` is bound directly as a pysher channel callback,
+ and pysher invokes bound callbacks without a try/except. Before the fix,
+ any malformed frame (bad JSON, missing key, wrong type) propagated up and
+ killed the subscription — the same failure mode already guarded against in
+ ``_parse_payload``.
+ """
+
+ @pytest.fixture
+ def subscription(self):
+ """Create a TriggerSubscription with a mock client."""
+ return TriggerSubscription(client=Mock())
+
+ def test_malformed_json_does_not_raise(self, subscription):
+ """A non-JSON frame is logged and skipped, not raised."""
+ # Must not raise — pysher's dispatch loop has no try/except.
+ subscription._handle_chunked_events("not valid json {")
+ # No chunks were buffered for the bad frame.
+ assert subscription._chunks == {}
+
+ @pytest.mark.parametrize(
+ "event",
+ [
+ [],
+ {"id": "evt-1", "index": 0},
+ {"id": [], "index": 0, "chunk": "x", "final": True},
+ {"id": "evt-1", "index": "zero", "chunk": "x", "final": True},
+ {"id": "evt-1", "index": True, "chunk": "x", "final": True},
+ {"id": "evt-1", "index": 0, "chunk": 1, "final": True},
+ {"id": "evt-1", "index": 0, "chunk": "x", "final": "true"},
+ ],
+ )
+ def test_invalid_frame_is_skipped(self, subscription, event):
+ """Missing or wrongly typed fields are skipped without dispatching."""
+ with patch.object(subscription, "_handle_event") as mock_handle:
+ subscription._handle_chunked_events(json.dumps(event))
+
+ mock_handle.assert_not_called()
+ assert subscription._chunks == {}
+
+ def test_decoder_failure_does_not_raise(self, subscription):
+ """Unexpected decoder failures are contained at the callback boundary."""
+ with patch(
+ "composio.core.models.triggers.json.loads", side_effect=RecursionError
+ ):
+ subscription._handle_chunked_events("[]")
+
+ assert subscription._chunks == {}
+
+ def test_valid_chunks_reassemble_after_bad_frame_for_same_id(self, subscription):
+ """A bad frame clears partial state so the same id can be reused."""
+ with patch.object(subscription, "_handle_event") as mock_handle:
+ subscription._handle_chunked_events(
+ json.dumps(
+ {"id": "evt-1", "index": 0, "chunk": "stale", "final": False}
+ )
+ )
+ subscription._handle_chunked_events(
+ json.dumps(
+ {"id": "evt-1", "index": "bad", "chunk": "x", "final": False}
+ )
+ )
+ subscription._handle_chunked_events(
+ json.dumps({"id": "evt-1", "index": 0, "chunk": "hel", "final": False})
+ )
+ subscription._handle_chunked_events(
+ json.dumps({"id": "evt-1", "index": 1, "chunk": "lo", "final": True})
+ )
+
+ mock_handle.assert_called_once_with(event="hello")
+ assert subscription._chunks == {}
+
+
class TestTriggerSubscriptionStop:
"""Tests for TriggerSubscription.stop lifecycle handling."""