:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(max): close upstream connection if synthesize response construction fails (#59575)
Paul D'Ambraefc982bbbb6b
diff --git a/ee/api/hands_free.py b/ee/api/hands_free.pyindex 0e72328242b4..f24a041ff271 100644--- a/ee/api/hands_free.py+++ b/ee/api/hands_free.py@@ -218,15 +218,24 @@ class MaxHandsFreeViewSet(TeamAndOrgViewSetMixin, GenericViewSet):upstream.close()raise HandsFreeProviderError(f"Hands-free provider returned {upstream.status_code}.")- HANDS_FREE_SYNTHESIZE_COUNTER.labels(outcome="ok").inc()- HANDS_FREE_SYNTHESIZE_CHARS_COUNTER.inc(len(text))-- def stream_and_close() -> Any:- try:- yield from upstream.iter_content(chunk_size=4096)- finally:- upstream.close()-- response = StreamingHttpResponse(stream_and_close(), content_type="audio/mpeg")- response["Cache-Control"] = "no-store"+ # Anything between the upstream 200 and returning the StreamingHttpResponse can+ # raise (a counter labels() call, the StreamingHttpResponse constructor, the+ # header assignment). Without an explicit close on those paths the connection+ # only releases when the unconsumed generator is garbage collected — which is+ # not guaranteed to be prompt under load. Guard the whole block.+ try:+ HANDS_FREE_SYNTHESIZE_COUNTER.labels(outcome="ok").inc()+ HANDS_FREE_SYNTHESIZE_CHARS_COUNTER.inc(len(text))++ def stream_and_close() -> Any:+ try:+ yield from upstream.iter_content(chunk_size=4096)+ finally:+ upstream.close()++ response = StreamingHttpResponse(stream_and_close(), content_type="audio/mpeg")+ response["Cache-Control"] = "no-store"+ except Exception:+ upstream.close()+ raisereturn responsediff --git a/ee/api/test/test_hands_free.py b/ee/api/test/test_hands_free.pyindex 4c6850652e35..6d088cce8d8b 100644--- a/ee/api/test/test_hands_free.py+++ b/ee/api/test/test_hands_free.py@@ -128,3 +128,22 @@ class TestMaxHandsFreeAPI(APIBaseTest):self.client.logout()response = self.client.post(self._synthesize_url(), data={"text": "hello"}, format="json")assert response.status_code in (401, 403)++ @patch("ee.api.hands_free.StreamingHttpResponse")+ @patch("ee.api.hands_free.requests.post")+ def test_synthesize_closes_upstream_when_response_construction_fails(+ self, mock_post: MagicMock, mock_streaming_response: MagicMock+ ) -> None:+ # Upstream returns 200 (so close isn't called on the error-status path) but the+ # StreamingHttpResponse constructor blows up before we can return. Without the+ # try/except in synthesize the upstream connection would leak — Django would+ # surface a 500 to the client and the requests connection would only release on+ # GC of the unconsumed iter_content generator.+ upstream = MagicMock(status_code=200)+ mock_post.return_value = upstream+ mock_streaming_response.side_effect = RuntimeError("django blew up")++ response = self.client.post(self._synthesize_url(), data={"text": "hello"}, format="json")++ assert response.status_code == 500+ upstream.close.assert_called_once()