Skip to content

agent-server: a logging call can wedge the event loop and amplify memory (rich traceback render) #5373

Closed

Description

@HussainShibli

Summary

openhands/agent_server/sockets.py:376 calls logger.exception("error_in_subscription", stack_info=True)
on the events-websocket error path. When the exception being logged has a pathological chain, rich's
traceback/stack renderer does not return — and because that call runs on the event loop's MainThread,
the whole agent-server stops servicing: the accept backlog grows (we measured ~400 Recv-Q), /alive,
/server_info and the chat APIs time out, and RSS climbs without bound. The process then cannot even be
stopped gracefully: SIGTERM is ignored and systemd has to reach TimeoutStopUSec and SIGKILL it.

A logging call should not be able to make the server unresponsive, whatever shape the exception is.

Observed impact (two occurrences, one local deployment)

wedge A wedge B
duration ~44 min (03:50:08–04:34:38Z) ~20 min (11:38:54–11:58:30Z)
RSS grew to 25.6 GB (earlyoom SIGTERM ×5 ignored → SIGKILL) 8.7 GB peak, stopped only by SIGKILL after the 45 s timeout
external symptom 826 ingress HTTP 502s /server_info + chat APIs timing out, UI apparently broken

The frozen stack (verbatim, from py-spy dump)

39 consecutive dumps over wedge B were identical; MainThread, read bottom-up:

app (starlette/middleware/errors.py:151)
  ... agent_server/middleware.py:109 ...
    events_socket (agent_server/sockets.py:376)
      logger.exception("error_in_subscription", stack_info=True)
        logging.exception → error → _log → handle → callHandlers → handle
          emit (rich/logging.py:152)
            from_exception (rich/traceback.py:401)
              extract (rich/traceback.py:595)      <-- never returns

app.log immediately before wedge B shows the trigger shape: an events websocket disconnected and
reconnected, the server began resending a ~29-minute event backlog, then a message was handled, tools
initialised, and then silence — with the MainThread parked in the renderer above.

Local mitigation (workaround, not a fix)

This workflow's own switch bounds it: LOG_RICH_TRACEBACKS=false
(openhands/sdk/logger/logger.py:45). With it, the same pathological exception logs in ~0 s instead of
never returning, and ordinary logging still works. Two problems with relying on that:

  1. an environment switch should not be the only thing between a logger.exception(...) call and an
    unresponsive server;
  2. it disables rich tracebacks server-wide, i.e. you pay for the workaround everywhere to protect one
    hot error path.

What we'd ask for

  1. Never render tracebacks synchronously on the event loop. Move the render off the loop, bound it, or
    cap the rendered output, so no exception shape can starve the server.
  2. Harden this specific call site. stack_info=True in a hot error path (a socket send failing, i.e.
    routinely a client disconnect) is a lot of rendering work for a routine event; and the surrounding
    except Exception: logger.info("Event websocket disconnected") already treats the condition as benign.
  3. Guard the renderer against cyclic/self-referential exception chains. In our case the trigger looks
    like a cyclic __context__; rich/traceback.py:595 extract walking that is our best explanation for
    "never returns" plus the memory amplification. Worth a cap or a visited-set regardless of cause.

Environment

openhands-agent-server==1.49.6, openhands-sdk==1.49.6, rich==15.0.0, Python 3.12.3, Linux. We have a
repro harness for this (a stub peer that produces the pathological exception + a driver) and are happy to
share it or test a candidate fix against the deployment where both wedges happened.

Related

Same class as OpenHands/OpenHands#17794 (a healthy-but-unresponsive :18000 is the failure mode; that issue
covers the launcher treating the port-holder as an error). This one is the defect that produces the
unresponsive server
in the first place, and our watchdog's logs are what identified it. Note our
conclusion that the MCP-connection path is not the culprit: a blackholed MCP peer fails in ~5 s, so the
timeout/close path cannot account for minutes-to-tens-of-minutes of silence — the renderer can.


This issue was created by an AI agent (OpenHands) on behalf of @HussainShibli.


OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

Root cause is confirmed, not speculative. With rich==15.0.0, Traceback.from_exception() never returns for an exception whose __context__/__cause__ chain is cyclic, and memory grows until the process is killed — reproducing the reported wedge: the logging call runs on the event loop's MainThread, starves the server, and the process can only be ended by SIGKILL. Two components are involved: openhands/agent_server/sockets.py calls logger.exception(..., stack_info=True) on the events-websocket error path (line ~376), and openhands/sdk/logger/logger.py installs a server-wide RichHandler(rich_tracebacks=True) that renders synchronously inside the logging call.

Bounded scope: (1) make the events-websocket error path incapable of wedging the server, and (2) bound/guard traceback rendering so that no exception shape — cyclic context, pathologically deep chain, or repeated causes — can make a single logging call block the event loop or grow memory without bound, with a regression test.

Explicit non-goals: changing the OpenHands :18000 launcher/port-holder behavior tracked separately in OpenHands/OpenHands#17794; the MCP-connection path (the reporter measured a blackholed MCP peer failing in ~5 s, so it cannot account for the minutes-long silence); fixing rich upstream (this repo can only guard its own handler configuration); a general re-architecture that moves all logging off the event loop; and treating LOG_RICH_TRACEBACKS=false as the fix — that is the existing workaround, and it disables rich tracebacks server-wide.

Steps to Reproduce

  1. Run the agent server (or any process that calls openhands.sdk.logger.setup_logging) with the default logging configuration — LOG_RICH_TRACEBACKS unset or true, so the root RichHandler renders tracebacks.
  2. Construct an exception whose __context__/__cause__ chain is cyclic (self-referential), matching the shape the reporter associates with the events-websocket wedge.
  3. Log it through the handler — logger.exception(..., stack_info=True) at openhands/agent_server/sockets.py:~376, or directly via Traceback.from_exception + Console.print.
  4. Observed: the render does not return; RSS climbs until the process is OOM/SIGKILLed, and a server running on the event loop stops serving /alive, /server_info, and the chat APIs.

The reporter has a repro harness (a stub peer that produces the pathological exception plus a driver) and offers to share it or to test a candidate fix against the deployment where both wedges occurred.

Acceptance Criteria

  • With the default server logging configuration (LOG_RICH_TRACEBACKS unset or true), logging an exception with a cyclic __context__/__cause__ chain returns in bounded time and bounded memory: a deterministic test constructs such an exception, invokes the logging path, and the call completes rather than hanging, with no unbounded RSS growth.
  • The same bound holds for a pathologically deep exception chain and for a chain with repeated/duplicated causes — not only for the cyclic shape.
  • The events-websocket error path (openhands/agent_server/sockets.py, events_socket) never performs an unbounded synchronous traceback/stack render; a failing websocket.send_json or client disconnect is still handled as benign (Event websocket disconnected) without a rich-rendered stack_info=True line.
  • The error path still sends the ServerErrorEvent to the client when the socket is open; hardening the render must not drop client-visible error reporting.
  • While the pathological logging path is exercised, the server keeps serving: /alive, /server_info, and the conversation REST endpoints respond within their normal latency, and no wedge occurs (an automated test in the repository's existing server/stress structure).
  • With the pathological path exercised, the process terminates on SIGTERM within the configured stop timeout instead of requiring SIGKILL.
  • Existing logging behavior is preserved: ordinary (non-pathological) exceptions still render rich tracebacks when LOG_RICH_TRACEBACKS=true; LOG_RICH_TRACEBACKS=false and the JSON/CI console mode are unchanged; uvicorn access-log routing is unchanged.
  • A regression test is added under the repository's existing test layout (for example tests/agent_server/ or the SDK logger tests, optionally as a budgeted stress test in tests/agent_server/stress/) and fails against the pre-fix code.
  • If the fix introduces a new logging configuration knob (for example a cap on rendered traceback depth or size), it is documented alongside the other LOG_* environment variables; if no new knob is introduced, no documentation change is required.

Activity

  1. added
    bug
    priority:high
    ready-for-dev
    on Sep 29, 2026
  2. enyst commented on Oct 11, 2026

    @enyst
    Member

    Related reproduction: #5633 shows Rich blocking the event loop for about 5 seconds on an ordinary finite LLM error chain in _run_and_publish.

    That complements this issue's cyclic/pathological chain on the events-WebSocket path. A traversal guard can fix the infinite cycle while still leaving finite rendering on the loop slow, so neither report subsumes the other's acceptance case. Both remain open; #5653 links the two.

    Posted by Codex on behalf of @enyst.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpriority:highready-for-dev

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions