Skip to content

The agent that grows with you

fix(relay): re-dial once with a fresh token before treating a 4401 as revocation (#102602)

Ben Barclayfef0e16fe19b
diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.py
index ac8244bf943..f6bdaa97d5b 100644
--- a/gateway/relay/ws_transport.py
+++ b/gateway/relay/ws_transport.py
@@ -72,6 +72,11 @@ def _env_disconnect_budget_s() -> float:
budget = max(0.0, float(raw))
return budget
+# Close REASON a connector attaches to a 4401 when the upgrade token merely
+# EXPIRED (vs. the secret being revoked). A 4401 with this reason is never a
+# revocation. Connectors predating the reason send plain "unauthorized".
+_RELAY_EXPIRED_CLOSE_REASON = "expired"
+
def _ws_dial_url(url: str) -> str:
"""Normalize the configured connector BASE URL to the ``ws(s)://…/relay`` dial target.
@@ -375,6 +380,31 @@ class WebSocketRelayTransport:
# A 4401 BEFORE any handshake is a cold-start race and stays retryable.
self._handshake_succeeded = False
self._auth_revoked = False
+ # Expired-vs-revoked ambiguity: the connector closes 4401 for BOTH a
+ # revoked secret and a merely EXPIRED upgrade token (make_upgrade_token
+ # TTL is 300s). A scale-to-zero suspend that lands between minting the
+ # token and the connector verifying it produces exactly that (incident
+ # 2026-09-02: dial froze mid-flight, resumed with a stale token, got
+ # 4401, and the gateway latched "revoked" -> relay_disabled until a
+ # manual restart — the secret was never revoked). So a post-handshake
+ # 4401 first earns ONE immediate re-dial with a freshly minted token;
+ # only a 4401 against that fresh token latches revocation. This task
+ # slot holds that one-shot retry (separate from the backoff supervisor).
+ self._auth_retry: Optional[asyncio.Task[None]] = None
+ # Connection generation (bumped per dial) and the generation opened BY
+ # the fresh-token re-dial. A 4401 on that generation is the second
+ # strike (revocation); a 4401 on any later generation is provisional
+ # again. Generation-based (not a flag) so a descriptor-then-4401 on the
+ # retry connection still counts as the refusal of the fresh token.
+ self._dial_generation = 0
+ self._auth_retry_generation: Optional[int] = None
+ # Set by a provisional 4401; consumed by the next dial whose token
+ # reaches an auth outcome (upgrade accepted → that generation is the
+ # retry; upgrade 4401'd → judged in _latch_if_fresh_token_refused). A
+ # marker, not a dedicated dialer, so the retry can never race a
+ # supervisor that is already mid-dial; and it survives non-auth connect
+ # failures so a network blip cannot un-mark the real fresh-token dial.
+ self._auth_retry_pending = False
# ── lifecycle ────────────────────────────────────────────────────────
async def connect(self) -> bool:
@@ -383,8 +413,9 @@ class WebSocketRelayTransport:
async def _dial_and_start(self) -> None:
"""Open the socket, start the reader, send hello(s). Used by connect() and
- by the reconnect supervisor on a re-dial."""
+ by the reconnect supervisor / fresh-token retry on a re-dial."""
self._descriptor_ready = asyncio.get_running_loop().create_future()
+ self._dial_generation += 1
# Fresh handshake generation: a reconnected connector re-sends one
# descriptor per hello, so stale descriptors must not survive.
self._descriptor = None
@@ -399,6 +430,14 @@ class WebSocketRelayTransport:
if headers:
kwargs["additional_headers"] = headers
self._ws = await websockets.connect(self._url, **kwargs) # type: ignore[union-attr]
+ if self._auth_retry_pending:
+ # The upgrade was ACCEPTED, so this connection's freshly minted token
+ # reached an auth outcome: it is the fresh-token retry generation. A
+ # 4401 on it (after the descriptor) is the second strike. Stamped
+ # here, not before connect(), so a non-auth connect failure (network,
+ # timeout) leaves the marker for the dial that actually gets judged.
+ self._auth_retry_generation = self._dial_generation
+ self._auth_retry_pending = False
self._reader = asyncio.create_task(self._read_loop(), name="relay-ws-reader")
# One hello PER fronted identity; the connector accumulates them (first
# sets the session default). The FIRST descriptor resolves handshake().
@@ -416,6 +455,12 @@ class WebSocketRelayTransport:
except Exception: # noqa: BLE001
logger.debug("relay command manifest build failed", exc_info=True)
await self._send(hello)
+ # The reader that this dial installed may have died while the hellos were
+ # in flight (the reader does not arm a dialer while one is live — that is
+ # THIS dial's job). Report it as a failed dial so the caller re-dials;
+ # returning "connected" here would leave no dialer and a dead transport.
+ if self._reader.done():
+ raise ConnectionError("relay ws closed during hello")
def _upgrade_headers(self) -> Dict[str, str]:
"""``Authorization: Bearer <signed token>`` for the WS upgrade, or {} when
@@ -443,8 +488,10 @@ class WebSocketRelayTransport:
if grace > 0:
with contextlib.suppress(Exception): # grace is best-effort
await asyncio.wait(pending, timeout=grace)
- for attr in ("_supervisor", "_reader"):
- task = getattr(self, attr)
+ # getattr default: some teardown tests build the transport via
+ # object.__new__, so _auth_retry may be absent.
+ for attr in ("_supervisor", "_auth_retry", "_reader"):
+ task = getattr(self, attr, None)
if task is not None:
task.cancel()
await _await_bounded(task)
@@ -644,6 +691,10 @@ class WebSocketRelayTransport:
# it still points at THIS socket (a re-dial may have installed a fresh one).
ws = self._ws
buf = ""
+ generation = self._dial_generation
+ # Set when this reader's close was a provisional post-handshake 4401 that
+ # earns the one-shot fresh-token re-dial instead of the backoff supervisor.
+ auth_retry_scheduled = False
try:
if ws is None:
# Lifecycle bug, not a normal path. Fall through to the finally so
@@ -651,7 +702,7 @@ class WebSocketRelayTransport:
logger.error("relay ws read loop started with no socket")
return
try:
- async for chunk in self._ws:
+ async for chunk in ws:
buf += chunk if isinstance(chunk, str) else chunk.decode("utf-8")
# Newline-delimited frames; keep any trailing partial line.
*lines, buf = buf.split("\n")
@@ -659,24 +710,52 @@ class WebSocketRelayTransport:
if line.strip():
await self._handle_frame(line)
except Exception as exc: # noqa: BLE001 - log + let the task end; reconnection handled below
+ # A post-handshake 4401 is a revocation ONLY if it also hits a fresh
+ # token: an EXPIRED token gets the same 4401 (a scale-to-zero suspend
+ # mid-dial makes that routine), so the first one is provisional —
+ # re-dial once, now, with a fresh token. Reason "expired" is never a
+ # revocation.
if self._close_code_of(exc) == _RELAY_UNAUTHORIZED_CLOSE_CODE and self._handshake_succeeded:
- self._auth_revoked = True
- if not self._closing:
+ reason = self._close_reason_of(exc)
+ if reason == _RELAY_EXPIRED_CLOSE_REASON:
+ if not self._closing:
+ logger.warning(
+ "relay ws closed 4401 with reason 'expired' — upgrade token "
+ "expired, not revoked; reconnecting normally"
+ )
+ elif generation == self._auth_retry_generation:
+ self._auth_revoked = True
+ if not self._closing:
+ logger.warning(
+ "relay ws closed 4401 (unauthorized) again on a re-dial with a "
+ "freshly minted token — treating as a revoked relay credential "
+ "(opt-out); not reconnecting"
+ )
+ elif not self._closing:
+ auth_retry_scheduled = True
+ self._auth_retry_pending = True
logger.warning(
"relay ws closed 4401 (unauthorized) after a successful handshake — "
- "treating as a revoked relay credential (opt-out); not reconnecting"
+ "re-dialing once with a fresh upgrade token before treating it as "
+ "a revoked credential (the token may simply have expired)"
)
elif not self._closing:
logger.warning("relay ws read loop ended: %s", exc)
- # Socket closed. Unless this was a deliberate disconnect() or a terminal
- # revocation (re-dialing a dead credential just spins), arm the
- # supervisor: it re-dials and starts a fresh reader.
- if (
- self._reconnect
- and not self._closing
- and not self._auth_revoked
- and (self._supervisor is None or self._supervisor.done())
- ):
+ # Socket closed. Exactly ONE dialer may be live at a time: the reader
+ # that dies while a dialer is already mid-dial (socket installed,
+ # hello still in flight) must NOT start a second one — that dialer's
+ # own failure handling re-dials, and the pending flag above makes
+ # that re-dial the fresh-token retry. A provisional 4401 with no
+ # dialer live takes the immediate fresh-token re-dial (no backoff);
+ # any other close arms the backoff supervisor unless this was a
+ # deliberate disconnect() or a terminal revocation.
+ if self._closing or self._dialer_running():
+ pass
+ elif auth_retry_scheduled:
+ self._auth_retry = asyncio.create_task(
+ self._redial_with_fresh_token(), name="relay-ws-auth-retry"
+ )
+ elif self._reconnect and not self._auth_revoked:
self._supervisor = asyncio.create_task(self._reconnect_loop(), name="relay-ws-reconnect")
finally:
# Drop the dead handle (identity-guarded) so every `_ws is None`
@@ -693,6 +772,13 @@ class WebSocketRelayTransport:
lambda fut: fut.set_result({"success": False, "error": "relay transport connection lost"})
)
+ def _dialer_running(self) -> bool:
+ """True while the backoff supervisor or the fresh-token retry is live."""
+ return any(
+ task is not None and not task.done()
+ for task in (self._supervisor, getattr(self, "_auth_retry", None))
+ )
+
@staticmethod
def _close_code_of(exc: BaseException) -> Optional[int]:
"""WebSocket close code from a raised exception, or None. websockets'
@@ -705,6 +791,70 @@ class WebSocketRelayTransport:
code = getattr(exc, "code", None)
return code if isinstance(code, int) else None
+ @staticmethod
+ def _close_reason_of(exc: BaseException) -> Optional[str]:
+ """Sibling of _close_code_of: the peer's Close frame reason string
+ (``.rcvd``/``.sent`` preferred, deprecated ``.reason`` fallback), or
+ None when unknown."""
+ for attr in ("rcvd", "sent"):
+ frame = getattr(exc, attr, None)
+ reason = getattr(frame, "reason", None)
+ if isinstance(reason, str):
+ return reason
+ reason = getattr(exc, "reason", None)
+ return reason if isinstance(reason, str) else None
+
+ async def _redial_with_fresh_token(self) -> None:
+ """One-shot, immediate re-dial after a provisional post-handshake 4401.
+
+ Bypasses the reconnect backoff on purpose: the suspected cause is an
+ upgrade token that aged past its TTL (scale-to-zero suspend mid-dial),
+ and _dial_and_start() mints a fresh one on every call. Outcomes:
+ - dial + handshake succeed: the new reader takes over, nothing else
+ changes;
+ - the connector 4401s the fresh token (at the upgrade, or after a
+ descriptor on that connection): revocation — _auth_revoked latches;
+ - the dial fails for any other reason (network, timeout, or the socket
+ dropping during hello): hand off to the normal backoff supervisor,
+ exactly as an unexpected close would.
+ Never raises out."""
+ if self._closing:
+ return
+ try:
+ await self._dial_and_start()
+ logger.info("relay ws re-dialed with a fresh upgrade token after 4401")
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 - fall back to the backoff supervisor
+ if self._closing:
+ return
+ if self._latch_if_fresh_token_refused(exc):
+ return
+ logger.warning("relay ws fresh-token re-dial failed: %s", exc)
+ if self._reconnect and not (self._supervisor and not self._supervisor.done()):
+ self._supervisor = asyncio.create_task(
+ self._reconnect_loop(), name="relay-ws-reconnect"
+ )
+
+ def _latch_if_fresh_token_refused(self, exc: BaseException) -> bool:
+ """Judge a dial failure while a fresh-token retry is pending. A 4401 at
+ the UPGRADE surfaces as the dial exception rather than in a reader: with
+ reason "expired" the token merely aged (not a revocation — the marker is
+ consumed, nothing latches); with any other reason the fresh token was
+ refused, i.e. the second strike — latch revocation and report True. A
+ non-auth failure leaves the marker in place for the next dial."""
+ if not self._auth_retry_pending or self._close_code_of(exc) != _RELAY_UNAUTHORIZED_CLOSE_CODE:
+ return False
+ self._auth_retry_pending = False
+ if self._close_reason_of(exc) == _RELAY_EXPIRED_CLOSE_REASON:
+ return False
+ self._auth_revoked = True
+ logger.warning(
+ "relay ws fresh-token re-dial rejected with 4401 — treating as a "
+ "revoked relay credential (opt-out); not reconnecting"
+ )
+ return True
+
async def _reconnect_loop(self) -> None:
"""Re-dial with capped exponential backoff until a dial succeeds (its reader
takes over) or disconnect(). Never raises out. After go_dormant() start from
@@ -723,6 +873,8 @@ class WebSocketRelayTransport:
logger.info("relay ws reconnected")
return
except Exception as exc: # noqa: BLE001 - keep retrying on dial failure
+ if self._latch_if_fresh_token_refused(exc):
+ return
logger.warning("relay ws reconnect failed: %s", exc)
backoff = min(backoff * 2, self._reconnect_max_backoff_s)
diff --git a/tests/gateway/relay/test_ws_transport.py b/tests/gateway/relay/test_ws_transport.py
index fe5cbc367ac..06d5a0f2cbd 100644
--- a/tests/gateway/relay/test_ws_transport.py
+++ b/tests/gateway/relay/test_ws_transport.py
@@ -181,7 +181,11 @@ class _Revoking4401Server:
@pytest.mark.asyncio
async def test_4401_after_handshake_is_terminal_no_reconnect():
"""A 4401 close AFTER a successful handshake = a revoked credential (opt-out):
- the transport latches auth_revoked and does NOT spin the reconnect supervisor."""
+ the transport latches auth_revoked and does NOT spin the reconnect supervisor.
+
+ Since the expired-token fix, the transport first re-dials ONCE with a fresh
+ token; this stub 4401s every dial, so that retry is also refused and the
+ latch still lands — the terminal contract is unchanged."""
srv = _Revoking4401Server(send_descriptor_first=True)
await srv.start()
try:
@@ -208,3 +212,354 @@ async def test_4401_after_handshake_is_terminal_no_reconnect():
await srv.stop()
+# ── Expired upgrade token vs revoked secret (incident 2026-09-02) ─────────────
+
+
+class _ExpiredToken4401Server:
+ """Connector stub for the expired-vs-revoked ambiguity. Every dial gets a
+ descriptor on hello (the upgrade itself is never refused). After the
+ descriptor the stub closes 4401 on the dials whose 1-based index is in
+ ``close_4401_on`` (``None`` = every dial) with the given reason; other dials
+ stay open and serve as a normal connector. ``dials`` counts connections."""
+
+ def __init__(self, *, close_4401_on: set[int] | None, reason: str = "unauthorized"):
+ self._server = None
+ self.url = ""
+ self.dials = 0
+ self._close_on = close_4401_on
+ self._reason = reason
+
+ async def start(self):
+ self._server = await websockets.serve(self._handle, "127.0.0.1", 0)
+ port = next(iter(self._server.sockets)).getsockname()[1]
+ self.url = f"ws://127.0.0.1:{port}"
+
+ async def stop(self):
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+ async def _handle(self, ws):
+ self.dials += 1
+ dial = self.dials
+ async for raw in ws:
+ for line in str(raw).split("\n"):
+ if not line.strip():
+ continue
+ frame = json.loads(line)
+ if frame.get("type") == "hello":
+ await ws.send(json.dumps({"type": "descriptor", "descriptor": DESCRIPTOR}) + "\n")
+ if self._close_on is None or dial in self._close_on:
+ await asyncio.sleep(0.05) # let the descriptor land first
+ await ws.close(code=4401, reason=self._reason)
+ return
+
+
+def _transport(url: str) -> WebSocketRelayTransport:
+ return WebSocketRelayTransport(
+ url, "discord", "appShared",
+ gateway_id="gw-x", upgrade_secret="secret-x",
+ reconnect=True, reconnect_backoff_s=5.0, # slow: proves the retry bypasses backoff
+ )
+
+
+async def _wait_until(pred, *, timeout_s: float = 2.0) -> bool:
+ deadline = asyncio.get_running_loop().time() + timeout_s
+ while asyncio.get_running_loop().time() < deadline:
+ if pred():
+ return True
+ await asyncio.sleep(0.02)
+ return pred()
+
+
+async def test_4401_after_handshake_redials_once_with_fresh_token_and_recovers():
+ """A single post-handshake 4401 (an expired upgrade token after a scale-to-zero
+ suspend) must NOT latch revocation: the transport re-dials immediately with a
+ fresh token, the connector accepts it, and the relay stays live."""
+ srv = _ExpiredToken4401Server(close_4401_on={1})
+ await srv.start()
+ t = _transport(srv.url)
+ try:
+ await t.connect()
+ await t.handshake()
+ assert srv.dials == 1
+ # The 4401 close lands, the fresh-token re-dial connects (well inside the
+ # 5s reconnect backoff, so this is the immediate retry, not the supervisor).
+ assert await _wait_until(lambda: srv.dials == 2 and t._descriptor is not None)
+ assert t.auth_revoked is False
+ # The new reader is running against a live socket; no fatal state.
+ assert t._reader is not None and not t._reader.done()
+ assert t._ws is not None
+ assert t._supervisor is None
+ await asyncio.sleep(0.2)
+ assert srv.dials == 2 # exactly one re-dial, no extra spinning
+ assert t.auth_revoked is False
+ finally:
+ await t.disconnect()
+ await srv.stop()
+
+
+async def test_4401_on_fresh_token_redial_latches_revocation_after_exactly_one_retry():
+ """If the connector 4401s the FRESH token too, the secret really is gone:
+ latch auth_revoked after exactly one retry (2 dials total) and stop."""
+ srv = _ExpiredToken4401Server(close_4401_on=None)
+ await srv.start()
+ t = _transport(srv.url)
+ try:
+ await t.connect()
+ await t.handshake()
+ assert await _wait_until(lambda: t.auth_revoked)
+ assert srv.dials == 2
+ assert t._supervisor is None
+ await asyncio.sleep(0.2)
+ assert srv.dials == 2 # terminal: no further dials
+ assert t._supervisor is None
+ finally:
+ await t.disconnect()
+ await srv.stop()
+
+
+async def test_4401_with_reason_expired_never_latches_and_reconnects_normally():
+ """A connector that labels the close reason 'expired' is explicitly saying the
+ token aged out: never a revocation, even repeatedly — take the normal
+ reconnect path (backoff supervisor) instead."""
+ srv = _ExpiredToken4401Server(close_4401_on={1}, reason="expired")
+ await srv.start()
+ t = _transport(srv.url)
+ t._reconnect_backoff_s = 0.05 # normal path: should reconnect via the supervisor
+ try:
+ await t.connect()
+ await t.handshake()
+ assert await _wait_until(lambda: t._supervisor is not None)
+ assert t.auth_revoked is False
+ assert await _wait_until(lambda: srv.dials == 2 and t._descriptor is not None)
+ assert t.auth_revoked is False
+ assert t._reader is not None and not t._reader.done()
+ finally:
+ await t.disconnect()
+ await srv.stop()
+
+
+async def test_4401_with_reason_expired_repeated_still_never_latches():
+ """Even a second 'expired' 4401 in a row is not a revocation."""
+ srv = _ExpiredToken4401Server(close_4401_on={1, 2}, reason="expired")
+ await srv.start()
+ t = _transport(srv.url)
+ t._reconnect_backoff_s = 0.05
+ try:
+ await t.connect()
+ await t.handshake()
+ assert await _wait_until(lambda: srv.dials == 3 and t._descriptor is not None)
+ assert t.auth_revoked is False
+ finally:
+ await t.disconnect()
+ await srv.stop()
+
+
+
+
+async def test_provisional_4401_never_starts_a_second_dialer_while_the_supervisor_is_mid_dial(monkeypatch):
+ """Only ONE dialer may be live. A reader that dies with a provisional 4401
+ while the backoff supervisor is already mid-dial (socket installed, hello in
+ flight) must not start the fresh-token retry as a second concurrent dialer
+ — two dialers replace each other's socket/reader and can leave the
+ transport attached to the wrong socket. The supervisor's own re-dial carries
+ the fresh token instead, so exactly two dials happen in total."""
+ import gateway.relay.ws_transport as mod
+
+ class _Close4401(Exception):
+ code = 4401
+ reason = "unauthorized"
+
+ class _FirstWS:
+ """The supervisor's first dial: its reader 4401s while hello is in flight,
+ then the hello itself fails (the connector dropped this connection)."""
+
+ def __init__(self, second_dial_done: asyncio.Event):
+ self.release_reader = asyncio.Event()
+ self.second_dial_done = second_dial_done
+
+ async def send(self, _data):
+ self.release_reader.set()
+ await asyncio.wait_for(self.second_dial_done.wait(), 1)
+ raise RuntimeError("dial lost during hello")
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ await self.release_reader.wait()
+ raise _Close4401()
+
+ async def close(self):
+ pass
+
+ class _IdleWS:
+ def __init__(self):
+ self.stop = asyncio.Event()
+
+ async def send(self, _data):
+ pass
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ await self.stop.wait()
+ raise StopAsyncIteration
+
+ async def close(self):
+ self.stop.set()
+
+ second_dial_done = asyncio.Event()
+ sockets = [_FirstWS(second_dial_done), _IdleWS(), _IdleWS()]
+ dials: list = []
+
+ async def fake_connect(*_args, **_kwargs):
+ ws = sockets[len(dials)]
+ dials.append(ws)
+ if len(dials) == 2:
+ second_dial_done.set()
+ return ws
+
+ monkeypatch.setattr(mod.websockets, "connect", fake_connect)
+ t = WebSocketRelayTransport(
+ "ws://unused", "discord", "bot", reconnect=True,
+ reconnect_backoff_s=0, reconnect_max_backoff_s=0,
+ )
+ t._handshake_succeeded = True
+ t._supervisor = asyncio.create_task(t._reconnect_loop())
+ try:
+ assert await _wait_until(lambda: len(dials) >= 2)
+ await asyncio.sleep(0.1) # give a racing second dialer time to show itself
+ assert len(dials) == 2, "a second dialer ran alongside the supervisor"
+ assert t._ws is sockets[1], "the transport must be attached to the live socket"
+ assert t._reader is not None and not t._reader.done()
+ assert not t.auth_revoked
+ # The supervisor's re-dial carried the fresh token: a 4401 on it is terminal.
+ assert t._auth_retry_generation == t._dial_generation
+ finally:
+ await t.disconnect(budget_s=0)
+
+
+class _FakeCloseError(Exception):
+ """Stand-in for websockets' ConnectionClosed: carries a close code + reason."""
+
+ def __init__(self, code: int, reason: str = ""):
+ super().__init__(f"closed {code} {reason}")
+ self.code = code
+ self.reason = reason
+
+
+class _FakeWS:
+ """Scriptable socket for dialer-ownership tests. ``hello`` decides what
+ happens when the transport sends its hello: a callable is awaited (and may
+ raise); ``reader`` decides what the reader sees: an exception to raise once
+ released, or None to idle until close()."""
+
+ def __init__(self, *, reader: Exception | None = None, hello=None):
+ self._reader_exc = reader
+ self._hello = hello
+ self.released = asyncio.Event()
+ self.stopped = asyncio.Event()
+
+ async def send(self, _data):
+ self.released.set()
+ if self._hello is not None:
+ await self._hello(self)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ await self.released.wait()
+ if self._reader_exc is not None:
+ raise self._reader_exc
+ await self.stopped.wait()
+ raise StopAsyncIteration
+
+ async def close(self):
+ self.released.set()
+ self.stopped.set()
+
+
+def _scripted_connect(monkeypatch, outcomes: list):
+ """Patch websockets.connect to pop ``outcomes`` in order: an Exception is
+ raised (connect-time failure), anything else is returned as the socket.
+ Returns the dial log."""
+ import gateway.relay.ws_transport as mod
+
+ dials: list = []
+
+ async def fake_connect(*_args, **_kwargs):
+ item = outcomes[len(dials)]
+ dials.append(item)
+ if isinstance(item, Exception):
+ raise item
+ return item
+
+ monkeypatch.setattr(mod.websockets, "connect", fake_connect)
+ return dials
+
+
+def _fake_transport() -> WebSocketRelayTransport:
+ t = WebSocketRelayTransport(
+ "ws://unused", "discord", "bot", reconnect=True,
+ reconnect_backoff_s=0, reconnect_max_backoff_s=0,
+ )
+ t._handshake_succeeded = True
+ return t
+
+
+async def test_fresh_token_retry_socket_dropping_during_hello_still_reconnects(monkeypatch):
+ """Mirror of the supervisor race: the auth-retry is the only live dialer and
+ its fresh socket's reader dies (non-4401) after the hello was sent but before
+ the dial returns. The reader must not arm a dialer (one is live) — so the
+ DIAL itself must notice its reader is gone, report failure, and hand off to
+ the supervisor. Otherwise the transport ends with no socket, no reader and
+ no dialer: silently dead."""
+ first = _FakeWS(reader=_FakeCloseError(1006, "lost"))
+
+ async def hello_then_let_reader_die(ws):
+ # hello send succeeds; the reader (released by send) raises and finishes
+ # BEFORE _dial_and_start returns, so _ws is already None on return.
+ await asyncio.sleep(0.02)
+
+ first._hello = hello_then_let_reader_die
+ second = _FakeWS()
+ dials = _scripted_connect(monkeypatch, [first, second])
+ t = _fake_transport()
+ t._auth_retry_pending = True
+ t._auth_retry = asyncio.create_task(t._redial_with_fresh_token())
+ try:
+ assert await _wait_until(lambda: len(dials) == 2 and t._ws is second)
+ assert t._reader is not None and not t._reader.done()
+ assert not t.auth_revoked
+ finally:
+ await t.disconnect(budget_s=0)
+
+
+async def test_network_failure_on_the_retry_dial_does_not_unmark_it(monkeypatch):
+ """The fresh-token marker must survive connect-time failures that never
+ reached authentication (network, timeout). If a blip consumed it, the NEXT
+ dial — the one whose fresh token actually gets judged — would be unmarked
+ and its 4401 read as another first strike, so a real revocation would never
+ latch (unbounded provisional retries)."""
+ refused = _FakeWS(reader=_FakeCloseError(4401, "unauthorized"))
+ dials = _scripted_connect(monkeypatch, [RuntimeError("network blip"), refused, _FakeWS(), _FakeWS()])
+ t = _fake_transport()
+ t._auth_retry_pending = True
+ t._auth_retry = asyncio.create_task(t._redial_with_fresh_token())
+ try:
+ assert await _wait_until(lambda: t.auth_revoked)
+ assert len(dials) == 2, "the 4401 on the first judged fresh token must be terminal"
+ assert not t._dialer_running()
+ finally:
+ await t.disconnect(budget_s=0)
diff --git a/tests/gateway/relay/test_ws_transport_hardening.py b/tests/gateway/relay/test_ws_transport_hardening.py
index f8b48a0030d..5ae62b3f3cc 100644
--- a/tests/gateway/relay/test_ws_transport_hardening.py
+++ b/tests/gateway/relay/test_ws_transport_hardening.py
@@ -295,6 +295,9 @@ async def test_send_after_terminal_4401_revocation_fails_fast():
fake = _DroppingWS(close_code=4401)
t._ws = fake
t._handshake_succeeded = True # prior handshake -> 4401 is a revocation
+ # This socket IS the fresh-token re-dial (the one-shot expired-token retry
+ # already happened), so its 4401 is the terminal second strike.
+ t._auth_retry_generation = t._dial_generation
await _run_reader_to_exit(t, fake)
assert t._auth_revoked is True