The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(gateway): cache the macOS system-proxy probe instead of forking per chunk
John Paul Soliva16b18ce60243
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 38ec5bc31fe..4eb1ab4c08f 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -259,25 +259,56 @@ def is_network_accessible(host: str) -> bool:return True+# ``scutil --proxy`` is a fork+exec (~11 ms measured) and resolve_proxy_url runs it on the SEND path —+# per chunk of an outbound message and per media attachment, not once per adapter. The answer is an+# OS-level network setting that changes when someone edits Network Settings or joins a VPN, so it is+# cached briefly rather than per call. The TTL is the staleness a proxy change can suffer; a send that+# goes out on a stale answer fails and is retried, which is the same outcome as any transient proxy error.+# No lock: a race costs one extra fork and both answers are equally current.+_MACOS_PROXY_TTL_SECONDS = 60.0+_macos_proxy_cache: "tuple[float, str | None] | None" = None++def _detect_macos_system_proxy() -> str | None:"""Read the macOS system HTTP(S) proxy via ``scutil --proxy``: ``http://host:port``- when an HTTP(S) proxy is enabled, else None (non-macOS or any subprocess error)."""+ when an HTTP(S) proxy is enabled, else None (non-macOS or any subprocess error).++ Memoised for ``_MACOS_PROXY_TTL_SECONDS``; call :func:`reset_macos_proxy_cache` to force a re-read.+ """+ global _macos_proxy_cache+if sys.platform != "darwin":return None+ cached = _macos_proxy_cache+ now = time.monotonic()+ if cached is not None and (now - cached[0]) < _MACOS_PROXY_TTL_SECONDS:+ return cached[1]try:out = subprocess.check_output(["scutil", "--proxy"], timeout=3, text=True, encoding='utf-8',errors='replace', stderr=subprocess.DEVNULL)except Exception:+ # Cache the failure too: a broken/slow scutil must not re-fork on every chunk.+ _macos_proxy_cache = (now, None)return Noneprops = {key.strip(): val.strip()for key, sep, val in (line.strip().partition(" : ") for line in out.splitlines()) if sep}# Prefer HTTPS, fall back to HTTP+ resolved = Nonefor enable_key, host_key, port_key in (("HTTPSEnable", "HTTPSProxy", "HTTPSPort"), ("HTTPEnable", "HTTPProxy", "HTTPPort")):if props.get(enable_key) == "1" and props.get(host_key) and props.get(port_key):- return f"http://{props[host_key]}:{props[port_key]}"- return None+ resolved = f"http://{props[host_key]}:{props[port_key]}"+ break+ _macos_proxy_cache = (now, resolved)+ return resolved+++def reset_macos_proxy_cache() -> None:+ """Drop the memoised ``scutil --proxy`` answer so the next call re-reads it."""+ global _macos_proxy_cache++ _macos_proxy_cache = Nonedef should_bypass_proxy(target_hosts: str | list[str] | tuple[str, ...] | set[str] | None) -> bool:diff --git a/tests/gateway/test_proxy_mode.py b/tests/gateway/test_proxy_mode.pyindex d5979343191..8c8d02607a3 100644--- a/tests/gateway/test_proxy_mode.py+++ b/tests/gateway/test_proxy_mode.py@@ -162,6 +162,71 @@ class TestResolveProxyUrl:assert resolve_proxy_url(target_hosts=["149.154.167.220"]) is None+class TestMacosProxyProbeCache:+ """``scutil --proxy`` is a ~11 ms fork and resolve_proxy_url runs it on the SEND path —+ per chunk of an outbound message and per media attachment."""++ SCUTIL_OUT = "<dictionary> {\n HTTPEnable : 1\n HTTPProxy : 10.0.0.1\n HTTPPort : 3128\n}"++ @pytest.fixture(autouse=True)+ def _isolate(self, monkeypatch):+ import gateway.platforms.base as base+ monkeypatch.setattr(base.sys, "platform", "darwin")+ base.reset_macos_proxy_cache()+ yield+ base.reset_macos_proxy_cache()++ def _count_forks(self, monkeypatch):+ import gateway.platforms.base as base+ calls = []++ def fake(*a, **kw):+ calls.append(a)+ return self.SCUTIL_OUT+ monkeypatch.setattr(base.subprocess, "check_output", fake)+ return base, calls++ def test_repeated_probes_fork_scutil_once(self, monkeypatch):+ base, calls = self._count_forks(monkeypatch)+ results = [base._detect_macos_system_proxy() for _ in range(10)]+ assert len(calls) == 1, f"expected 1 scutil fork for 10 probes, got {len(calls)}"+ assert results == ["http://10.0.0.1:3128"] * 10++ def test_expired_ttl_re_reads(self, monkeypatch):+ base, calls = self._count_forks(monkeypatch)+ clock = {"t": 1000.0}+ monkeypatch.setattr(base.time, "monotonic", lambda: clock["t"])+ base._detect_macos_system_proxy()+ clock["t"] += base._MACOS_PROXY_TTL_SECONDS + 1+ base._detect_macos_system_proxy()+ assert len(calls) == 2++ def test_a_failing_scutil_is_not_re_forked_every_call(self, monkeypatch):+ """A broken or slow scutil must not cost a fork per chunk either."""+ import gateway.platforms.base as base+ calls = []++ def boom(*a, **kw):+ calls.append(a)+ raise OSError("scutil unavailable")+ monkeypatch.setattr(base.subprocess, "check_output", boom)+ assert [base._detect_macos_system_proxy() for _ in range(5)] == [None] * 5+ assert len(calls) == 1++ def test_reset_forces_a_re_read(self, monkeypatch):+ base, calls = self._count_forks(monkeypatch)+ base._detect_macos_system_proxy()+ base.reset_macos_proxy_cache()+ base._detect_macos_system_proxy()+ assert len(calls) == 2++ def test_non_darwin_never_forks(self, monkeypatch):+ base, calls = self._count_forks(monkeypatch)+ monkeypatch.setattr(base.sys, "platform", "linux")+ assert base._detect_macos_system_proxy() is None+ assert calls == []++class TestRunAgentProxyDispatch:"""Test that _run_agent() delegates to proxy when configured."""