Skip to content

The agent that grows with you

fix(gateway): don't report HTTP 500 for an upgrade its handler already refused

unsupportedpastelsf21dd1870b34
diff --git a/gateway/run_api.py b/gateway/run_api.py
index aa58cabb741..cbb599dcacc 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -257,10 +257,11 @@ class GatewayRuntimeAPI:
async def __call__(self, scope, receive, send):
if scope['type'] != 'websocket' or scope.get('path') != '/api/ws':
return await self._serve(scope, receive, send)
- accepted = False
+ started = accepted = False
async def send_watched(message):
- nonlocal accepted
+ nonlocal started, accepted
+ started = True
accepted = accepted or message.get('type') == 'websocket.accept'
await send(message)
@@ -269,10 +270,12 @@ class GatewayRuntimeAPI:
except Exception as exc:
# Uvicorn answers an upgrade that raised before accept with HTTP 500 and logs it only to
# its own logger, never gateway.log: the dialing cron worker or managed worker sees a bare
- # InvalidStatus (#139922). Name the cause here; uvicorn still sends the 500.
+ # InvalidStatus (#139922). Name the cause here; uvicorn still sends the 500, but only when
+ # nothing was sent yet: a handler that had closed the upgrade already got its 403 out.
if not accepted:
- logger.error('Gateway refused a session WebSocket upgrade from %s with HTTP 500: %s: %s',
+ logger.error('Gateway refused a session WebSocket upgrade from %s %s: %s: %s',
scope.get('hermes.gateway_socket_peer') or scope.get('client'),
+ 'after its handler had refused it' if started else 'with HTTP 500',
type(exc).__name__, exc, exc_info=True)
raise
diff --git a/tests/gateway/test_session_ws_upgrade_failure_logged.py b/tests/gateway/test_session_ws_upgrade_failure_logged.py
index 12fff664fd2..4589deeacd5 100644
--- a/tests/gateway/test_session_ws_upgrade_failure_logged.py
+++ b/tests/gateway/test_session_ws_upgrade_failure_logged.py
@@ -107,3 +107,31 @@ def test_a_failed_session_upgrade_is_logged_with_its_cause(tmp_path):
# One line per refused dial (the cron turn's and the worker's), each naming the cause.
assert len(refused) == 2, log
assert all("NameError: name 'Path' is not defined" in line for line in refused), refused
+
+
[email protected]('refused_first', [False, True])
+async def test_the_log_line_names_the_status_the_dialer_got(caplog, refused_first):
+ """Uvicorn answers 500 only when the handler raised before sending anything; a handler that had
+ already closed the upgrade got its own refusal (403) out, so the line must not claim a 500."""
+ from gateway.run_api import GatewayRuntimeAPI
+
+ api = GatewayRuntimeAPI(None, None, None)
+
+ async def fail(scope, receive, send):
+ if refused_first:
+ await send({'type': 'websocket.close', 'code': 1008})
+ raise RuntimeError('late failure')
+
+ api._serve = fail
+ sent = []
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {'type': 'websocket', 'path': '/api/ws', 'client': ('127.0.0.1', 5)}
+ with caplog.at_level('ERROR', logger='gateway.run_api'), pytest.raises(RuntimeError, match='late failure'):
+ await api(scope, None, send)
+ [line] = [record.getMessage() for record in caplog.records if 'session WebSocket upgrade' in record.getMessage()]
+ assert 'RuntimeError: late failure' in line
+ assert ('HTTP 500' in line) is not refused_first, line