Skip to content

Automate browser based workflows with AI

Keep the raw-request line for unhandled-exception requests under the 16 KiB log split (SKY-17308) (#8700)

Shuchang Zhenga997dfc97360
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index 07322dd8f..5ee8ae4e5 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import re
+import sys
import time
import typing
from contextvars import ContextVar
@@ -21,6 +22,7 @@ from skyvern.forge.log_redaction import (
redact_sensitive_fields,
strip_artifact_url_query,
)
+from skyvern.forge.sdk.forge_log import exception_log_fields
if typing.TYPE_CHECKING: # pragma: no cover - import only for type hints
from typing import Awaitable, Callable
@@ -230,7 +232,10 @@ def _log_unhandled_request(
start_time: float,
) -> None:
"""Emit the raw-request row after the server error handler selects a response."""
+ exc = sys.exc_info()[1]
try:
+ # No traceback: the server error handler already logs it, and with one this row can pass the
+ # container log driver's 16 KiB line limit and be split into fragments that lose every field.
LOG.error(
"api.raw_request",
method=method,
@@ -239,8 +244,8 @@ def _log_unhandled_request(
client_ip=client_ip,
body=body,
headers=headers,
- exc_info=True,
duration_seconds=time.monotonic() - start_time,
+ **(exception_log_fields(exc) if exc is not None else {}),
**_organization_log_fields(),
)
except Exception:
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 02bef137c..5133a9ebc 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -1,18 +1,23 @@
from __future__ import annotations
+import io
import json
+import logging
import typing
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
+import psycopg.errors
import pytest
+import structlog
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.testclient import TestClient
+from sqlalchemy.exc import OperationalError
from starlette.requests import ClientDisconnect, Request
from starlette.types import ASGIApp, Receive, Scope, Send
-from skyvern.forge import api_app, request_logging
+from skyvern.forge import api_app, forge_app_initializer, request_logging
from skyvern.forge.log_redaction import (
REDACTED,
SENSITIVE_FIELDS,
@@ -33,6 +38,7 @@ from skyvern.forge.request_logging import (
log_raw_request_middleware,
set_request_organization,
)
+from skyvern.forge.sdk.forge_log import setup_logger
# ---------------------------------------------------------------------------
# _client_ip_from_headers
@@ -844,7 +850,7 @@ class TestMiddlewareLogVolume:
call = log_mock.error.call_args
assert call.args == ("api.raw_request",)
assert call.kwargs["body"] == REDACTED
- assert call.kwargs["exc_info"] is True
+ assert call.kwargs["error_type"] == "builtins.ValueError"
assert call.kwargs["status_code"] == 500
assert call.kwargs["duration_seconds"] >= 0
assert "SYNTHETIC_SECRET" not in repr(call)
@@ -1132,6 +1138,110 @@ class TestMiddlewareLogVolume:
log_mock.info.assert_not_called()
+# The API's container log driver splits a longer stdout line into partial records that Datadog
+# indexes as unparsed text, so the row loses @status_code and @path.
+_LOG_DRIVER_LINE_LIMIT_BYTES = 16 * 1024
+# Deep enough that the traceback alone passes the limit, as production pool-timeout errors do.
+_ROUTE_CALL_DEPTH = 25
+_TEST_ORGANIZATION_ID = "o_385835488455492960"
+
+
+def rendered_log_stream(monkeypatch: pytest.MonkeyPatch) -> typing.Iterator[io.StringIO]:
+ monkeypatch.setattr(request_logging.settings, "LOG_RAW_API_REQUESTS", True)
+ monkeypatch.setattr(request_logging.settings, "JSON_LOGGING", True)
+ root_logger = logging.getLogger()
+ saved_handlers = root_logger.handlers[:]
+ saved_structlog_config = structlog.get_config()
+ setup_logger()
+ # create_api_app configures logging once per process; keep it from replacing this handler.
+ monkeypatch.setattr(forge_app_initializer, "_SERVER_LOGGING_CONFIGURED", True)
+ stream = io.StringIO()
+ handler = root_logger.handlers[0]
+ assert isinstance(handler, logging.StreamHandler)
+ handler.setStream(stream)
+ try:
+ yield stream
+ finally:
+ root_logger.handlers[:] = saved_handlers
+ structlog.configure(**saved_structlog_config)
+
+
+def _raise_from_depth(depth: int) -> None:
+ if depth == 0:
+ raise RuntimeError("connection pool exhausted")
+ _call_deeper(depth - 1)
+
+
+def _call_deeper(depth: int) -> None:
+ # Alternating frames keep the traceback from collapsing into "[Previous line repeated]".
+ _raise_from_depth(depth)
+
+
+def _raw_request_lines(stream: io.StringIO) -> list[tuple[str, dict]]:
+ lines = [line for line in stream.getvalue().splitlines() if line]
+ records = [(line, json.loads(line)) for line in lines]
+ return [(line, record) for line, record in records if record.get("msg", "").startswith("api.raw_request")]
+
+
+class TestRenderedRawRequestLine:
+ """Each failed request must reach the log collector as one parseable api.raw_request line."""
+
+ @pytest.mark.parametrize(
+ ("path", "client_status", "error_type"),
+ [
+ ("/_test_raw_request/raises", 500, "builtins.RuntimeError"),
+ ("/_test_raw_request/database-unavailable", 503, None),
+ ("/_test_raw_request/returns-500", 500, None),
+ ("/_test_raw_request/stream-raises", 200, "builtins.RuntimeError"),
+ ],
+ ids=["unhandled-exception", "database-unavailable", "handled-500", "exception-after-stream-start"],
+ )
+ def test_api_app_failure_logs_one_line_the_collector_keeps_whole(
+ self, rendered_log_stream: io.StringIO, path: str, client_status: int, error_type: str | None
+ ) -> None:
+ app = api_app.create_api_app()
+
+ @app.post("/_test_raw_request/raises")
+ async def raises() -> None:
+ set_request_organization(_TEST_ORGANIZATION_ID, "Test Org")
+ _raise_from_depth(_ROUTE_CALL_DEPTH)
+
+ @app.post("/_test_raw_request/database-unavailable")
+ async def database_unavailable() -> None:
+ set_request_organization(_TEST_ORGANIZATION_ID, "Test Org")
+ raise OperationalError(
+ "SELECT 1", {}, psycopg.errors.ConnectionFailure("server closed the connection unexpectedly")
+ )
+
+ @app.post("/_test_raw_request/returns-500")
+ async def returns_500() -> JSONResponse:
+ set_request_organization(_TEST_ORGANIZATION_ID, "Test Org")
+ return JSONResponse(status_code=500, content={"detail": "failed"})
+
+ @app.post("/_test_raw_request/stream-raises")
+ async def stream_raises() -> StreamingResponse:
+ set_request_organization(_TEST_ORGANIZATION_ID, "Test Org")
+
+ async def events() -> typing.AsyncIterator[bytes]:
+ yield b"data: first\n\n"
+ _raise_from_depth(_ROUTE_CALL_DEPTH)
+
+ return StreamingResponse(events(), media_type="text/event-stream")
+
+ response = TestClient(app, raise_server_exceptions=False).post(path)
+
+ assert response.status_code == client_status
+ [(line, record)] = _raw_request_lines(rendered_log_stream)
+ assert len(line.encode()) <= _LOG_DRIVER_LINE_LIMIT_BYTES
+ assert record["level"] == "error"
+ assert record["path"] == path
+ assert record["status_code"] == client_status
+ assert record["organization_id"] == _TEST_ORGANIZATION_ID
+ assert record["duration_seconds"] >= 0
+ assert record.get("error_type") == error_type
+
+
class TestClientDisconnectDuringBodyRead:
"""A client closing the connection mid-body must not surface as an unhandled error."""