Skip to content

The agent that grows with you

fix(gateway): rebind webhook and api_server over TIME_WAIT after a restart on macOS

TheBlueHouse752d99b7cf5d19
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 2798bf10373..899cb9589e3 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -137,6 +137,7 @@ from gateway.browser_control_broker import (
from gateway.platforms._shared import coerce_port as _coerce_port
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
+from gateway.platforms.tcp_site import start_tcp_site
logger = logging.getLogger(__name__)
@@ -4019,24 +4020,16 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
self._wire_plugin_handlers(self._app)
self._runner = web.AppRunner(self._app)
await self._runner.setup()
- # Bind directly (a pre-probe raced the bind, misreporting TIME_WAIT as "in use").
- # SO_REUSEADDR off on macOS (BSD can split traffic between two listeners).
# Bind directly instead of probing 127.0.0.1 first — the old single-family pre-probe raced the
# real bind and reported a TIME_WAIT socket as "in use" (#10297), failing gateway restarts for
- # up to ~60s. SO_REUSEADDR is platform-dependent (same rationale as the webhook adapter,
- # #65482): - macOS (BSD semantics): two sockets with SO_REUSEADDR can silently split traffic
- # while both report success — disable. - Linux: SO_REUSEADDR only permits rebinding past
- # TIME_WAIT (a second live listener needs SO_REUSEPORT, never set), so keep the default
- # (enabled) for instant restart rebinds.
+ # up to ~60s. Platform-dependent SO_REUSEADDR and the macOS TIME_WAIT rebind live in
+ # start_tcp_site; the loop below covers a predecessor still holding the port for a moment.
try:
- # A restart's predecessor may still hold the port for a moment after its PID is gone.
# aiohttp registers a site with its runner before binding, so a failed start leaves the
# site registered: rebuild the runner per attempt rather than reach into its internals.
for attempt in range(_BIND_ATTEMPTS):
- self._site = web.TCPSite(
- self._runner, self._host, self._port, reuse_address=False if sys.platform == "darwin" else None)
try:
- await self._site.start()
+ self._site = await start_tcp_site(self._runner, self._host, self._port, log_tag=self.name)
break
except OSError as exc:
if exc.errno != errno.EADDRINUSE or attempt == _BIND_ATTEMPTS - 1:
diff --git a/gateway/platforms/tcp_site.py b/gateway/platforms/tcp_site.py
new file mode 100644
index 00000000000..6160075a5a4
--- /dev/null
+++ b/gateway/platforms/tcp_site.py
@@ -0,0 +1,65 @@
+"""Bind an aiohttp ``TCPSite`` for the HTTP-serving adapters (webhook, api_server): exclusive on macOS,
+yet able to rebind over a lingering TIME_WAIT socket right after a gateway restart."""
+
+import asyncio
+import errno
+import logging
+import socket
+import sys
+from typing import Optional
+
+from aiohttp import web
+
+logger = logging.getLogger(__name__)
+
+_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::"})
+
+
+def is_wildcard_host(host: Optional[str]) -> bool:
+ """True for the dual-stack default (None/"") and the per-family wildcards."""
+ return not host or host.strip() in _WILDCARD_HOSTS
+
+
+def has_live_listener(host: str, port: int) -> bool:
+ """Blocking probe: True when something accepts connections on ``host:port``. Refused = nobody listens;
+ any other failure (timeout, unroutable) is treated as live so the caller stays exclusive."""
+ try:
+ with socket.create_connection((host, port), timeout=1.0):
+ return True
+ except ConnectionRefusedError:
+ return False
+ except OSError:
+ return True
+
+
+async def start_tcp_site(runner: web.BaseRunner, host: Optional[str], port: int, *, log_tag: str) -> web.TCPSite:
+ """Bind ``host:port`` on ``runner`` and return the started site; raises OSError when unavailable.
+
+ SO_REUSEADDR: on macOS (BSD) two wildcard/specific sockets can silently split traffic while
+ both report success → disable. On Linux it only permits rebinding past TIME_WAIT (a quick
+ restart would otherwise fail to bind for ~60s) → keep the default.
+
+ The macOS exclusive bind also refuses the port while a server-side TIME_WAIT socket lingers
+ (2*MSL = 30s after the previous gateway closed a connection first — its shutdown, or any
+ ``Connection: close`` request), so a ``/restart`` re-binding within seconds failed with
+ EADDRINUSE although nobody was listening. Preventing the TIME_WAIT at close time (SO_LINGER 0)
+ would reset in-flight senders and misses the per-request case, hence the bind-side retry: for an
+ explicit host, ``has_live_listener`` refused proves the address is free (the kernel still
+ rejects an exact duplicate even with SO_REUSEADDR, and a foreign wildcard listener answers the
+ probe), so one retry with reuse_address=True is safe. A wildcard host keeps the strict path: a
+ foreign listener on a non-loopback interface could not be probed, so it must keep winning."""
+ exclusive = sys.platform == "darwin"
+ site = web.TCPSite(runner, host, port, reuse_address=False if exclusive else None)
+ try:
+ await site.start()
+ except OSError as exc:
+ if not exclusive or exc.errno != errno.EADDRINUSE or is_wildcard_host(host):
+ raise
+ if await asyncio.to_thread(has_live_listener, host, port):
+ raise
+ await site.stop() # aiohttp registers a site before binding: drop the dead one from the runner
+ logger.info("[%s] %s:%d busy without a live listener (TIME_WAIT from the previous gateway); "
+ "rebinding with SO_REUSEADDR", log_tag, host, port)
+ site = web.TCPSite(runner, host, port, reuse_address=True)
+ await site.start()
+ return site
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index c5332331b45..8f361e725f1 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -17,7 +17,6 @@ import logging
import os
import re
import subprocess
-import sys
import time
from collections import deque
from contextlib import nullcontext, suppress
@@ -34,6 +33,7 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
+from gateway.platforms.tcp_site import start_tcp_site
from gateway.platforms.webhook_coalesce import WebhookCoalescer, validate_coalesce_config
from gateway.platforms.webhook_filters import DEFAULT_SCRIPT_TIMEOUT_SECONDS, WebhookRouteProcessor
from gateway.response_filters import is_autonomous_silence_response
@@ -231,13 +231,8 @@ class WebhookAdapter(BasePlatformAdapter):
app.router.add_route("*", "/p/{profile}/{tail:.*}", self._handle_profile_ingress)
self._runner = web.AppRunner(app)
await self._runner.setup()
- # SO_REUSEADDR: on macOS (BSD) two wildcard/specific sockets can silently split traffic while
- # both report success → disable. On Linux it only permits rebinding past TIME_WAIT (a quick
- # restart would otherwise fail to bind for ~60s) → keep the default.
- site = web.TCPSite(self._runner, self._host, self._port,
- reuse_address=False if sys.platform == "darwin" else None)
try:
- await site.start()
+ await start_tcp_site(self._runner, self._host, self._port, log_tag="webhook")
except OSError as exc:
await self._runner.cleanup()
self._runner = None
diff --git a/tests/gateway/test_api_server_bind_guard.py b/tests/gateway/test_api_server_bind_guard.py
index 4a7788ebb70..967d46e5d4f 100644
--- a/tests/gateway/test_api_server_bind_guard.py
+++ b/tests/gateway/test_api_server_bind_guard.py
@@ -145,6 +145,27 @@ class TestBindMechanics:
await second.disconnect()
+ @pytest.mark.macos_only # the exclusive bind (reuse_address=False) is a Darwin-only path
+ @pytest.mark.asyncio
+ async def test_rebind_over_time_wait(self):
+ """A port held only by a server-side TIME_WAIT socket (the previous gateway closed a
+ connection first) must not fail the bind on macOS, where address reuse is disabled."""
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ client = socket.create_connection(("127.0.0.1", port))
+ accepted, _ = listener.accept()
+ accepted.close() # the side closing first enters TIME_WAIT
+ client.close()
+ listener.close()
+ adapter = self._make_adapter(port)
+ try:
+ assert await adapter.connect() is True
+ assert adapter.has_fatal_error is False
+ finally:
+ await adapter.disconnect()
+
@pytest.mark.asyncio
async def test_port_conflict_sets_non_retryable_fatal_error(self):
"""A real port conflict (EADDRINUSE) must set a non-retryable fatal
diff --git a/tests/gateway/test_webhook_adapter.py b/tests/gateway/test_webhook_adapter.py
index 22cd20a7b67..1ced2268af5 100644
--- a/tests/gateway/test_webhook_adapter.py
+++ b/tests/gateway/test_webhook_adapter.py
@@ -965,6 +965,60 @@ class TestDualStackBind:
await adapter.disconnect()
+class TestExclusiveBindTimeWait:
+ """macOS binds the listener with ``reuse_address=False`` (exclusive dual-stack bind). On BSD that
+ also refuses the port while a TIME_WAIT connection from the previous gateway lingers (2*MSL = 30s):
+ a ``/restart`` re-binds within seconds and used to fail with EADDRINUSE although nobody was
+ listening (observed on 127.0.0.1:8644; the reconnect watcher only recovered ~50s later)."""
+
+ @staticmethod
+ def _adapter_on(port: int) -> WebhookAdapter:
+ return _make_adapter(
+ routes={"r1": {"secret": "real-secret-abc123", "prompt": "x"}},
+ host="127.0.0.1",
+ port=port,
+ )
+
+ @pytest.mark.macos_only # the exclusive bind (reuse_address=False) is a Darwin-only path
+ @pytest.mark.asyncio
+ async def test_explicit_host_rebinds_over_time_wait(self):
+ """A port held only by a server-side TIME_WAIT socket must not block the bind."""
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ client = socket.create_connection(("127.0.0.1", port))
+ accepted, _ = listener.accept()
+ accepted.close() # the side closing first enters TIME_WAIT: the server side, as on gateway shutdown
+ client.close()
+ listener.close()
+ adapter = self._adapter_on(port)
+ try:
+ with patch.object(adapter, "_reload_dynamic_routes"):
+ assert await adapter.connect() is True
+ assert adapter.is_connected is True
+ finally:
+ await adapter.disconnect()
+
+ @pytest.mark.asyncio
+ async def test_explicit_host_still_rejects_live_listener(self):
+ """The TIME_WAIT retry must not weaken exclusivity: a live listener on the same address wins."""
+ blocker = await asyncio.start_server(
+ lambda _reader, _writer: None, host="127.0.0.1", port=0, reuse_address=False
+ )
+ port = blocker.sockets[0].getsockname()[1]
+ adapter = self._adapter_on(port)
+ try:
+ with patch.object(adapter, "_reload_dynamic_routes"):
+ assert await adapter.connect() is False
+ assert adapter._runner is None
+ assert adapter.is_connected is False
+ finally:
+ await adapter.disconnect()
+ blocker.close()
+ await blocker.wait_closed()
+
+
# Regression coverage for #72041: profile-bound webhook authentication
class TestMultiplexProfileWebhookAuthentication:
@staticmethod