@devries-cameron20 / composio Mirror · read-only / commits / a3f6b9c8f
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, 18:30 UTC

fix(py/triggers): swallow malformed chunked frame instead of tearing down subscription (#3892)

## Problem TriggerSubscription._handle_chunked_events is bound directly as a Pysher channel callback. Pysher channel dispatch has no local exception boundary, so malformed chunk frames reached websocket-client error handling and marked the realtime connection failed. The normal payload parser already skips malformed frames, but the chunked path did not. ## Fix - Validate that each decoded frame is an object with string id/chunk, integer non-boolean index, and boolean final fields. - Contain decoder, validation, and reassembly failures at the callback boundary and log only a bounded frame preview. - Clear partial state only when the frame carries a validated string id, allowing that id to be reused safely. - Preserve the valid chunk reassembly path and fix the Chunked docstring typo. ## Regression coverage Tests cover invalid JSON, non-object frames, missing fields, unhashable ids, wrong field types, unexpected decoder failures, and successful same-id reassembly immediately after a bad frame clears partial state. ## Verification - nox -s tst -- tests/test_triggers.py: 83 passed - make chk: Ruff and mypy passed --------- Signed-off-by: Checo <sergio@checo.cc> Co-authored-by: Checo <sergio@checo.cc> Co-authored-by: jkomyno <alberto@composio.dev>

Checo committed Jul 28, 2026 at 22:38 UTC a3f6b9c8f2450a6a1f324a43ab2d591beaabc9a9
2 files changed +114 -10
python/composio/core/models/triggers.py
+39 -10
@@ -426,7 +426,7 @@ _ = {
426
427
428 class _ChunkedTriggerEventData(te.TypedDict):
429 - """Cunked trigger event data model."""
429 + """Chunked trigger event data model."""
430
431 id: str
432 index: int
@@ -668,15 +668,44 @@ class TriggerSubscription(Resource):
668 return None
669
670 def _handle_chunked_events(self, event: str) -> None:
671 - """Handle chunked events."""
672 - data = _ChunkedTriggerEventData(**json.loads(event)) # type: ignore
673 - if data["id"] not in self._chunks:
674 - self._chunks[data["id"]] = {}
675 -
676 - self._chunks[data["id"]][data["index"]] = data["chunk"]
677 - if data["final"]:
678 - _chunks = self._chunks.pop(data["id"])
679 - self._handle_event(event="".join([_chunks[idx] for idx in sorted(_chunks)]))
671 + """Handle chunked events without letting malformed frames escape Pysher."""
672 + chunk_id: t.Optional[str] = None
673 + try:
674 + raw_data = json.loads(event)
675 + if not isinstance(raw_data, dict):
676 + raise TypeError("chunked payload must be an object")
677 +
678 + raw_id = raw_data.get("id")
679 + chunk_id = raw_id if isinstance(raw_id, str) else None
680 + index = raw_data.get("index")
681 + chunk = raw_data.get("chunk")
682 + final = raw_data.get("final")
683 + if (
684 + chunk_id is None
685 + or not isinstance(index, int)
686 + or isinstance(index, bool)
687 + or not isinstance(chunk, str)
688 + or not isinstance(final, bool)
689 + ):
690 + raise TypeError("chunked payload has invalid fields")
691 +
692 + data = t.cast(_ChunkedTriggerEventData, raw_data)
693 + if data["id"] not in self._chunks:
694 + self._chunks[data["id"]] = {}
695 +
696 + self._chunks[data["id"]][data["index"]] = data["chunk"]
697 + if data["final"]:
698 + _chunks = self._chunks.pop(data["id"])
699 + self._handle_event(
700 + event="".join([_chunks[idx] for idx in sorted(_chunks)])
701 + )
702 + except Exception as e:
703 + if chunk_id is not None:
704 + self._chunks.pop(chunk_id, None)
705 + self.logger.warning(
706 + f"Error parsing chunked trigger payload: {e}; "
707 + f"frame: {_truncate_frame(event)}"
708 + )
709
710 def _filters_match(
711 self,
python/tests/test_triggers.py
+75
@@ -1589,6 +1589,81 @@ class TestTriggerSubscriptionParsing:
1589 assert str(len(long)) in truncated
1590
1591
1592 +class TestChunkedEventResilience:
1593 + """A malformed chunked frame must never tear down the subscription.
1594 +
1595 + ``_handle_chunked_events`` is bound directly as a pysher channel callback,
1596 + and pysher invokes bound callbacks without a try/except. Before the fix,
1597 + any malformed frame (bad JSON, missing key, wrong type) propagated up and
1598 + killed the subscription — the same failure mode already guarded against in
1599 + ``_parse_payload``.
1600 + """
1601 +
1602 + @pytest.fixture
1603 + def subscription(self):
1604 + """Create a TriggerSubscription with a mock client."""
1605 + return TriggerSubscription(client=Mock())
1606 +
1607 + def test_malformed_json_does_not_raise(self, subscription):
1608 + """A non-JSON frame is logged and skipped, not raised."""
1609 + # Must not raise — pysher's dispatch loop has no try/except.
1610 + subscription._handle_chunked_events("not valid json {")
1611 + # No chunks were buffered for the bad frame.
1612 + assert subscription._chunks == {}
1613 +
1614 + @pytest.mark.parametrize(
1615 + "event",
1616 + [
1617 + [],
1618 + {"id": "evt-1", "index": 0},
1619 + {"id": [], "index": 0, "chunk": "x", "final": True},
1620 + {"id": "evt-1", "index": "zero", "chunk": "x", "final": True},
1621 + {"id": "evt-1", "index": True, "chunk": "x", "final": True},
1622 + {"id": "evt-1", "index": 0, "chunk": 1, "final": True},
1623 + {"id": "evt-1", "index": 0, "chunk": "x", "final": "true"},
1624 + ],
1625 + )
1626 + def test_invalid_frame_is_skipped(self, subscription, event):
1627 + """Missing or wrongly typed fields are skipped without dispatching."""
1628 + with patch.object(subscription, "_handle_event") as mock_handle:
1629 + subscription._handle_chunked_events(json.dumps(event))
1630 +
1631 + mock_handle.assert_not_called()
1632 + assert subscription._chunks == {}
1633 +
1634 + def test_decoder_failure_does_not_raise(self, subscription):
1635 + """Unexpected decoder failures are contained at the callback boundary."""
1636 + with patch(
1637 + "composio.core.models.triggers.json.loads", side_effect=RecursionError
1638 + ):
1639 + subscription._handle_chunked_events("[]")
1640 +
1641 + assert subscription._chunks == {}
1642 +
1643 + def test_valid_chunks_reassemble_after_bad_frame_for_same_id(self, subscription):
1644 + """A bad frame clears partial state so the same id can be reused."""
1645 + with patch.object(subscription, "_handle_event") as mock_handle:
1646 + subscription._handle_chunked_events(
1647 + json.dumps(
1648 + {"id": "evt-1", "index": 0, "chunk": "stale", "final": False}
1649 + )
1650 + )
1651 + subscription._handle_chunked_events(
1652 + json.dumps(
1653 + {"id": "evt-1", "index": "bad", "chunk": "x", "final": False}
1654 + )
1655 + )
1656 + subscription._handle_chunked_events(
1657 + json.dumps({"id": "evt-1", "index": 0, "chunk": "hel", "final": False})
1658 + )
1659 + subscription._handle_chunked_events(
1660 + json.dumps({"id": "evt-1", "index": 1, "chunk": "lo", "final": True})
1661 + )
1662 +
1663 + mock_handle.assert_called_once_with(event="hello")
1664 + assert subscription._chunks == {}
1665 +
1666 +
1667 class TestTriggerSubscriptionStop:
1668 """Tests for TriggerSubscription.stop lifecycle handling."""
1669