Repository navigation
fix(agent-server): suppress noisy traceback when sending events to a … - #3182
Conversation
…disconnected websocket The pub/sub callback in the events / bash-events websocket endpoints can fire after the peer has gone away. Starlette then raises 'RuntimeError: Cannot call "send" once a close message has been sent.' which we were logging via logger.exception, producing a full traceback on every disconnect race. Pre-check WebSocketState.DISCONNECTED in _send_event / _send_bash_event and downgrade RuntimeError / WebSocketDisconnect from send() to a debug-level log. Other unexpected exceptions still log a full traceback. Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
all-hands-bot
left a comment
There was a problem hiding this comment.
LGTM! Clean pragmatic fix for noisy disconnect tracebacks.
Risk Assessment: 🟢 LOW
Only affects error-path logging. Defense-in-depth (state check + exception handling) properly handles disconnect races without hiding unexpected errors. Well-tested with coverage for both pre-check and exception-catch paths.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The PR successfully eliminates noisy exception tracebacks when websockets disconnect during event publishing, replacing them with clean debug-level logs.
Does this PR achieve its stated goal?
Yes. The PR achieves its goal of suppressing noisy tracebacks when sending events to disconnected websockets. I verified this by running the actual code on both the main branch (showing the bug) and the PR branch (showing the fix). The before/after comparison demonstrates that RuntimeError exceptions from websocket disconnect races are now logged at DEBUG level without stack traces, while the old code logged them via logger.exception with full tracebacks.
| Phase | Result |
|---|---|
| Environment Setup | ✅ Built successfully with make build |
| CI Status | ✅ All required checks passing (7/7) |
| Functional Verification | ✅ Fix verified with before/after comparison |
Functional Verification
Verification Approach
Created a test script that simulates the exact race condition scenarios described in the PR:
- Scenario 1: Pub/sub callback fires when websocket is already DISCONNECTED
- Scenario 2: RuntimeError raised during send() due to disconnect race
Test 1: Reproduce the bug on main branch
Step 1 — Establish baseline (main branch without the fix):
Checked out main branch and ran verification script:
git checkout main
OPENHANDS_SUPPRESS_BANNER=1 uv run python verify_websocket_logging.pyOutput from main branch (BEFORE fix):
Scenario 1: Websocket already DISCONNECTED
Is websocket connected? True
send_json called: True
Scenario 2: RuntimeError during send (race condition)
Captured logs:
ERROR - openhands.agent_server.sockets - error_sending_event: MessageEvent(...)
Traceback (most recent call last):
File ".../openhands/agent_server/sockets.py", line 418, in _send_event
await websocket.send_json(dumped)
...
RuntimeError: Cannot call "send" once a close message has been sent.
Stack (most recent call last):
...
[Full stack trace with 15+ lines]
Interpretation: This confirms the bug exists on main:
- Scenario 1: No pre-check exists, so send_json is attempted even on disconnected sockets
- Scenario 2: RuntimeError is logged at ERROR level via
logger.exception()with a full multi-line traceback and stack info
Test 2: Verify the fix on PR branch
Step 2 — Apply the PR's changes:
Checked out the PR branch:
git checkout openhands/fix-websocket-send-after-disconnectStep 3 — Re-run the same verification:
OPENHANDS_SUPPRESS_BANNER=1 uv run python verify_websocket_logging.pyOutput from PR branch (AFTER fix):
Scenario 1: Websocket already DISCONNECTED
Is websocket connected? False
send_json called: False
Captured logs:
DEBUG - openhands.agent_server.sockets - skip_sending_event_socket_disconnected: MessageEvent(...)
Scenario 2: RuntimeError during send (race condition)
Is websocket connected? True
Captured logs:
DEBUG - openhands.agent_server.sockets - error_sending_event_disconnected: MessageEvent(...) (Cannot call "send" once a close message has been sent.)
Log analysis:
- Has DEBUG level: True
- Has ERROR/CRITICAL level: False
- Has full traceback: False
Interpretation: The fix works as designed:
- Scenario 1:
_is_websocket_connected()pre-check detects DISCONNECTED state and returns early with a DEBUG log, preventing the send attempt entirely - Scenario 2: RuntimeError is now caught specifically and logged at DEBUG level as a single-line message without a traceback
- No more noisy exception logs cluttering production logs
Code Changes Verified
The key changes work exactly as documented:
- New helper function
_is_websocket_connected()checks WebSocketState.DISCONNECTED on both application_state and client_state - Modified
_send_event():- Pre-checks connection state before attempting send
- Catches
RuntimeErrorandWebSocketDisconnectspecifically → logs at DEBUG level - Other exceptions still logged with full traceback via
logger.exception()
- Modified
_send_bash_event(): Same pattern applied for consistency
CI Verification
All required CI checks passing:
Check OpenAPI Schema pass 35s
agent-server-tests pass 49s
build-binary-and-test pass 2m53s
cross-tests pass 1m30s
pre-commit pass 1m18s
sdk-tests pass 8s
tools-tests pass 8s
The new unit tests specifically verify:
test_websocket_subscriber_skips_send_when_disconnected: Confirms send_json is NOT called when state is DISCONNECTEDtest_websocket_subscriber_send_runtime_error_not_logged_as_exception: Confirms RuntimeError is logged at debug level, NOT via logger.exception
Issues Found
None.
OpenHands#3182) Co-authored-by: openhands <openhands@all-hands.dev>
OpenHands#3182) Co-authored-by: openhands <openhands@all-hands.dev>
…disconnected websocket
The pub/sub callback in the events / bash-events websocket endpoints can fire after the peer has gone away. Starlette then raises 'RuntimeError: Cannot call "send" once a close message has been sent.' which we were logging via logger.exception, producing a full traceback on every disconnect race.
Pre-check WebSocketState.DISCONNECTED in _send_event / _send_bash_event and downgrade RuntimeError / WebSocketDisconnect from send() to a debug-level log. Other unexpected exceptions still log a full traceback.
Why
Summary
Issue Number
How to Test
Video/Screenshots
Type
Notes
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:95f115f-pythonRun
All tags pushed for this build
About Multi-Architecture Support
95f115f-python) is a multi-arch manifest supporting both amd64 and arm6495f115f-python-amd64) are also available if needed