Skip to content

Automate browser based workflows with AI

fix(SKY-11132): handle ClientDisconnect in raw-request logging middleware (#6659)

Aaron Perez595164f9b2ba
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index 955f7592f..f51635344 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -21,7 +21,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
-from starlette.requests import HTTPConnection, Request
+from starlette.requests import ClientDisconnect, HTTPConnection, Request
from starlette_context.middleware import RawContextMiddleware
from starlette_context.plugins.base import Plugin
@@ -391,6 +391,13 @@ def create_api_app() -> FastAPI:
content={"detail": detail},
)
+ @fastapi_app.exception_handler(ClientDisconnect)
+ async def handle_client_disconnect(request: Request, exc: ClientDisconnect) -> Response:
+ # Client closed the connection mid-request (e.g. while a route reads the body).
+ # There is no one to respond to, so return a quiet 499 instead of letting it
+ # fall through to the 500 handler and pollute error tracking.
+ return Response(status_code=499)
+
@fastapi_app.exception_handler(Exception)
async def unexpected_exception(request: Request, exc: Exception) -> JSONResponse:
LOG.exception("Unexpected error in agent server.", exc_info=exc)
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index d81896ed4..f96db6a60 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -6,13 +6,14 @@ import typing
import structlog
from starlette.concurrency import iterate_in_threadpool
+from starlette.requests import ClientDisconnect
+from starlette.responses import Response
from skyvern.config import settings
if typing.TYPE_CHECKING: # pragma: no cover - import only for type hints
from typing import Awaitable, Callable
- from fastapi import Response
from starlette.requests import Request
LOG = structlog.get_logger()
@@ -174,7 +175,15 @@ async def log_raw_request_middleware(request: Request, call_next: Callable[[Requ
return await call_next(request)
start_time = time.monotonic()
- body_bytes = await request.body()
+ try:
+ body_bytes = await request.body()
+ except ClientDisconnect:
+ # The client closed the connection before the body finished streaming, so no
+ # response will reach it. Short-circuit with a benign 499 instead of letting
+ # the disconnect escape this BaseHTTPMiddleware (which wraps it in an
+ # ExceptionGroup) and surface as an unhandled error in tracking.
+ LOG.info("api.client_disconnect", method=request.method, path=request.url.path)
+ return Response(status_code=499)
# ensure downstream handlers can access body again
try:
request._body = body_bytes # type: ignore[attr-defined]
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 692373920..2f57bb27b 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -1,11 +1,12 @@
from __future__ import annotations
import json
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
+from starlette.requests import ClientDisconnect
from skyvern.forge import request_logging
from skyvern.forge.request_logging import (
@@ -458,3 +459,37 @@ class TestMiddlewareLogVolume:
client = TestClient(_make_app())
client.post("/tasks")
log_mock.info.assert_not_called()
+
+
+class TestClientDisconnectDuringBodyRead:
+ """A client closing the connection mid-body must not surface as an unhandled error."""
+
+ @pytest.mark.asyncio
+ async def test_disconnect_short_circuits_without_error_log(self, log_mock: MagicMock) -> None:
+ request = MagicMock()
+ request.method = "POST"
+ request.url.path = "/v1/tasks"
+ request.body = AsyncMock(side_effect=ClientDisconnect())
+ call_next = AsyncMock()
+
+ response = await log_raw_request_middleware(request, call_next)
+
+ assert response.status_code == 499
+ call_next.assert_not_awaited()
+ log_mock.error.assert_not_called()
+ log_mock.exception.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_disconnect_when_logging_disabled_still_calls_downstream(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(request_logging.settings, "LOG_RAW_API_REQUESTS", False)
+ request = MagicMock()
+ request.body = AsyncMock(side_effect=ClientDisconnect())
+ sentinel = MagicMock()
+ call_next = AsyncMock(return_value=sentinel)
+
+ response = await log_raw_request_middleware(request, call_next)
+
+ assert response is sentinel
+ request.body.assert_not_awaited()