Repository navigation
fix(gateway/photon): survive runtime platform outages — supervised reconnect watcher, reliable re-queue, configurable sidecar ready timeout #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
c738c4b
f80517f
d9b10b9
d63b30c
5fa5dcf
0b5d453
d7fabf7
fe7e10f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2921,6 +2921,8 @@ def __init__(self, config: Optional[GatewayConfig] = None): | |
| # Track platforms that failed to connect for background reconnection. | ||
| # Key: Platform enum, Value: {"config": platform_config, "attempts": int, "next_retry": float} | ||
| self._failed_platforms: Dict[Platform, Dict[str, Any]] = {} | ||
| # Supervised reconnect-watcher task (see _start_reconnect_watcher). | ||
| self._reconnect_watcher_task: Optional[asyncio.Task] = None | ||
|
|
||
| # Track pending /update prompt responses per session. | ||
| # Key: session_key, Value: True when a prompt is waiting for user input. | ||
|
|
@@ -3971,8 +3973,21 @@ async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> Non | |
|
|
||
| # Queue retryable failures for background reconnection | ||
| if adapter.fatal_error_retryable: | ||
| # Plugin/runtime-registered platforms can be absent from the | ||
| # static config map — fall back to the config the adapter was | ||
| # built with. A silent drop here left photon stuck on "retrying" | ||
| # with nothing ever retrying (2026-07-30, 3-day iMessage outage). | ||
| platform_config = self.config.platforms.get(adapter.platform) | ||
| if platform_config and adapter.platform not in self._failed_platforms: | ||
| if platform_config is None: | ||
| platform_config = getattr(adapter, "config", None) | ||
|
Comment on lines
4387
to
+4389
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a runtime-fatal adapter belongs to a secondary multiplexed profile and the default profile does not configure that platform, this fallback puts the secondary profile's config into the global retry queue. AGENTS.md reference: AGENTS.md:L147-L154 Useful? React with 👍 / 👎. |
||
| if platform_config is None: | ||
| logger.error( | ||
| "%s fatal error is retryable but no platform config is " | ||
| "available — cannot queue for reconnection; platform " | ||
| "stays down until gateway restart", | ||
| adapter.platform.value, | ||
| ) | ||
| elif adapter.platform not in self._failed_platforms: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When Photon reports a runtime failure from AGENTS.md reference: AGENTS.md:L84-L87 Useful? React with 👍 / 👎. |
||
| self._failed_platforms[adapter.platform] = { | ||
| "config": platform_config, | ||
| "attempts": 0, | ||
|
|
@@ -3982,6 +3997,17 @@ async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> Non | |
| "%s queued for background reconnection", | ||
| adapter.platform.value, | ||
| ) | ||
| else: | ||
| # Already queued (e.g. a second fatal from the same outage) — | ||
| # refresh the retry clock so the watcher acts promptly instead | ||
| # of waiting out a stale backoff, unless the operator paused it. | ||
| info = self._failed_platforms[adapter.platform] | ||
| if not info.get("paused"): | ||
| info["next_retry"] = time.monotonic() | ||
| logger.info( | ||
| "%s already queued for reconnection — retry refreshed", | ||
| adapter.platform.value, | ||
| ) | ||
|
|
||
| if not self.adapters and not self._failed_platforms: | ||
| self._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected" | ||
|
|
@@ -7172,7 +7198,7 @@ async def start(self) -> bool: | |
| len(self._failed_platforms), | ||
| ", ".join(p.value for p in self._failed_platforms), | ||
| ) | ||
| asyncio.create_task(self._platform_reconnect_watcher()) | ||
| self._start_reconnect_watcher() | ||
|
|
||
| # Start background handoff watcher — picks up CLI sessions marked | ||
| # handoff_state='pending' in state.db and re-binds them to the | ||
|
|
@@ -7651,6 +7677,62 @@ def _active_profile_name(self) -> str: | |
| # self state, so inheriting the mixin keeps every self._kanban_* call site | ||
| # working unchanged while lifting ~1,000 LOC out of this file. | ||
|
|
||
| _WATCHER_RESTART_DELAY = 5.0 # base delay before respawning a crashed watcher | ||
| _WATCHER_RESTART_DELAY_CAP = 300.0 # backoff ceiling for a crash-looping watcher | ||
| _WATCHER_STABLE_RUN_S = 60.0 # a run this long clears the crash streak | ||
|
|
||
| def _start_reconnect_watcher(self) -> None: | ||
| """Spawn the reconnect watcher under supervision. | ||
|
|
||
| The watcher used to be a bare ``asyncio.create_task`` — any exception | ||
| escaping the loop killed it silently and nothing ever reconnected | ||
| again for the life of the gateway, while platform state stayed on | ||
| "retrying" (2026-07-30 photon outage). The done-callback respawns it, | ||
| backing off exponentially if it crash-loops (never giving up — a capped | ||
| slow respawn beats recreating the permanent silent outage). | ||
| """ | ||
| self._watcher_started_at = time.monotonic() | ||
| task = asyncio.create_task(self._platform_reconnect_watcher()) | ||
| self._reconnect_watcher_task = task | ||
| task.add_done_callback(self._on_reconnect_watcher_done) | ||
|
|
||
| def _watcher_restart_backoff(self) -> float: | ||
| streak = getattr(self, "_watcher_crash_streak", 0) | ||
| return min( | ||
| self._WATCHER_RESTART_DELAY * (2 ** min(streak, 8)), | ||
| self._WATCHER_RESTART_DELAY_CAP, | ||
| ) | ||
|
|
||
| def _on_reconnect_watcher_done(self, task: "asyncio.Task") -> None: | ||
| if task.cancelled() or not self._running: | ||
| return | ||
| ran_for = time.monotonic() - getattr(self, "_watcher_started_at", 0.0) | ||
| if ran_for >= self._WATCHER_STABLE_RUN_S: | ||
| self._watcher_crash_streak = 0 | ||
| delay = self._watcher_restart_backoff() | ||
| self._watcher_crash_streak = getattr(self, "_watcher_crash_streak", 0) + 1 | ||
| exc = task.exception() | ||
| if exc is not None: | ||
| logger.error( | ||
| "Platform reconnect watcher crashed (%s) — restarting in %.0fs", | ||
| exc, | ||
| delay, | ||
| exc_info=exc, | ||
| ) | ||
| else: | ||
| logger.error( | ||
| "Platform reconnect watcher exited unexpectedly — " | ||
| "restarting in %.0fs", | ||
| delay, | ||
| ) | ||
| asyncio.get_running_loop().call_later( | ||
| delay, self._maybe_restart_reconnect_watcher | ||
| ) | ||
|
|
||
| def _maybe_restart_reconnect_watcher(self) -> None: | ||
| if self._running: | ||
| self._start_reconnect_watcher() | ||
|
|
||
| async def _platform_reconnect_watcher(self) -> None: | ||
| """Background task that periodically retries connecting failed platforms. | ||
|
|
||
|
|
@@ -7665,8 +7747,6 @@ async def _platform_reconnect_watcher(self) -> None: | |
| automatically — auto-pausing a recovered platform was the cause of | ||
| bots silently staying dead after a transient DNS failure. | ||
| """ | ||
| _BACKOFF_CAP = 300 # 5 minutes max between retries | ||
|
|
||
| await asyncio.sleep(10) # initial delay — let startup finish | ||
| while self._running: | ||
| if not self._failed_platforms: | ||
|
|
@@ -7679,11 +7759,33 @@ async def _platform_reconnect_watcher(self) -> None: | |
| await asyncio.sleep(1) | ||
| continue | ||
|
|
||
| now = time.monotonic() | ||
| for platform in list(self._failed_platforms.keys()): | ||
| await self._reconnect_pass() | ||
|
|
||
| # Check every 10 seconds for platforms that need reconnection | ||
| for _ in range(10): | ||
| if not self._running: | ||
| return | ||
| await asyncio.sleep(1) | ||
|
|
||
| async def _reconnect_pass(self) -> None: | ||
| """One retry sweep over the failed-platform queue. | ||
|
|
||
| Extracted from the watcher loop for unit-testability. Tolerates | ||
| concurrent mutation of ``_failed_platforms``: a platform removed | ||
| while an earlier entry's reconnect was being awaited used to raise | ||
| KeyError outside the per-attempt try/except, killing the watcher. | ||
| """ | ||
| _BACKOFF_CAP = 300 # 5 minutes max between retries | ||
| now = time.monotonic() | ||
| for platform in list(self._failed_platforms.keys()): | ||
| if not self._running: | ||
| return | ||
| info = self._failed_platforms[platform] | ||
| info = self._failed_platforms.get(platform) | ||
| if info is None: | ||
| # Removed concurrently (reconnected via another path or | ||
| # unqueued) while an earlier entry's reconnect was | ||
| # awaited — skip, never KeyError. | ||
| continue | ||
| # Skip paused platforms entirely — they need explicit | ||
| # /platform resume to come back. | ||
| if info.get("paused"): | ||
|
|
@@ -7835,12 +7937,6 @@ async def _platform_reconnect_watcher(self) -> None: | |
| # resolution failure, etc.) is inherently transient — keep | ||
| # retrying at the backoff cap rather than auto-pausing. | ||
|
|
||
| # Check every 10 seconds for platforms that need reconnection | ||
| for _ in range(10): | ||
| if not self._running: | ||
| return | ||
| await asyncio.sleep(1) | ||
|
|
||
| async def stop( | ||
| self, | ||
| *, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,7 @@ | |
| import base64 | ||
| import json | ||
| import logging | ||
| import math | ||
| import os | ||
| import re | ||
| import secrets | ||
|
|
@@ -91,6 +92,27 @@ | |
| # connect path indefinitely. | ||
| _NPM_REINSTALL_TIMEOUT = 600 | ||
|
|
||
| # Sidecar readiness window. Healthy baseline startup is ~3s, but the node | ||
| # process's module import + top-level Spectrum init stretches well past 15s | ||
| # when the host is under load (observed at loadavg 25+ on 2026-08-02, where | ||
| # the old hardcoded 15s window failed every reconnect attempt). | ||
| _DEFAULT_SIDECAR_READY_TIMEOUT = 60.0 | ||
| # Upper bound: past this the sidecar is dead, not slow — an unbounded wait | ||
| # would stall the whole reconnect pass on one platform. | ||
| _MAX_SIDECAR_READY_TIMEOUT = 600.0 | ||
|
|
||
|
|
||
| def _sidecar_ready_timeout() -> float: | ||
| """Readiness window in seconds; PHOTON_SIDECAR_READY_TIMEOUT overrides.""" | ||
| raw = os.environ.get("PHOTON_SIDECAR_READY_TIMEOUT", "") | ||
| try: | ||
|
Comment on lines
+105
to
+108
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This introduces a user-facing environment variable for a non-secret behavioral timeout, bypassing the project's configuration and setup UX. Define the Photon readiness timeout in AGENTS.md reference: AGENTS.md:L102-L107 Useful? React with 👍 / 👎. |
||
| value = float(raw) | ||
| except ValueError: | ||
| return _DEFAULT_SIDECAR_READY_TIMEOUT | ||
| if not math.isfinite(value) or value <= 0: | ||
| return _DEFAULT_SIDECAR_READY_TIMEOUT | ||
|
Comment on lines
+108
to
+113
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Values such as Useful? React with 👍 / 👎. |
||
| return min(value, _MAX_SIDECAR_READY_TIMEOUT) | ||
|
|
||
| # Photon / Envoy / spectrum-ts error substrings that indicate a transient | ||
| # upstream overload rather than a permanent failure. These are not in the | ||
| # core _RETRYABLE_ERROR_PATTERNS because they are specific to this adapter. | ||
|
|
@@ -981,8 +1003,10 @@ async def _start_sidecar(self) -> None: | |
| self._supervise_sidecar(self._sidecar_proc) | ||
| ) | ||
|
|
||
| # Wait for /healthz to come up — give it up to 15s on cold start. | ||
| deadline = time.time() + 15.0 | ||
| # Wait for /healthz to come up. Env-configurable: the sidecar's | ||
| # cold start is ~3s idle but scales with host load. | ||
| ready_timeout = _sidecar_ready_timeout() | ||
| deadline = time.time() + ready_timeout | ||
|
Comment on lines
+1025
to
+1026
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The new 60-second default is still wrapped by AGENTS.md reference: AGENTS.md:L155-L164 Useful? React with 👍 / 👎. |
||
| last_err: Optional[Exception] = None | ||
| async with httpx.AsyncClient(timeout=2.0) as client: | ||
| while time.time() < deadline: | ||
|
|
@@ -1002,7 +1026,8 @@ async def _start_sidecar(self) -> None: | |
| last_err = e | ||
| await asyncio.sleep(0.2) | ||
| raise RuntimeError( | ||
| f"Photon sidecar did not become ready within 15s: {last_err}" | ||
| f"Photon sidecar did not become ready within " | ||
| f"{ready_timeout:.0f}s: {last_err}" | ||
| ) | ||
|
|
||
| async def _supervise_sidecar(self, proc: subprocess.Popen) -> None: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """pre_tool_call hook args carry the terminal session's effective cwd | ||
| (repo_ecosystem_agents#700): the consent-boundary plugin's script-file email | ||
| lane resolves RELATIVE script paths against args cwd/workdir — without this | ||
| enrichment the lane is inert whenever the model omits workdir.""" | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| sys.path.insert(0, str(Path(__file__).resolve().parents[2])) | ||
|
|
||
| from agent.tool_executor import _hook_args_with_terminal_cwd # noqa: E402 | ||
|
|
||
|
|
||
| class _Env: | ||
| def __init__(self, cwd): | ||
| self.cwd = cwd | ||
|
|
||
|
|
||
| def test_terminal_without_workdir_gains_session_cwd(monkeypatch): | ||
| import tools.terminal_tool as tt | ||
| monkeypatch.setattr(tt, "get_active_env", lambda tid: _Env("/srv/daemon")) | ||
| args = {"command": "python3 send.py"} | ||
| out = _hook_args_with_terminal_cwd("terminal", args, "t1") | ||
| assert out["cwd"] == "/srv/daemon" | ||
| assert "cwd" not in args # original execution args never mutated | ||
|
|
||
|
|
||
| def test_explicit_workdir_wins(monkeypatch): | ||
| import tools.terminal_tool as tt | ||
| monkeypatch.setattr(tt, "get_active_env", lambda tid: _Env("/other")) | ||
| args = {"command": "x", "workdir": "/explicit"} | ||
| assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args | ||
|
|
||
|
|
||
| def test_non_terminal_passthrough(monkeypatch): | ||
| args = {"command": "x"} | ||
| assert _hook_args_with_terminal_cwd("todo", args, "t1") is args | ||
|
|
||
|
|
||
| def test_no_env_or_error_degrades_to_original(monkeypatch): | ||
| import tools.terminal_tool as tt | ||
| monkeypatch.setattr(tt, "get_active_env", lambda tid: None) | ||
| args = {"command": "x"} | ||
| assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args | ||
| def boom(tid): | ||
| raise RuntimeError("env store down") | ||
| monkeypatch.setattr(tt, "get_active_env", boom) | ||
| assert _hook_args_with_terminal_cwd("terminal", args, "t1") is args |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Terminal calls never reach this concurrent hook:
_should_parallelize_tool_batch()returns false for every terminal batch becauseterminalis neither parallel-safe nor path-scoped, and single calls are also always sequential. Consequently the intended consent-boundary fix remains inert in production whileexecute_tool_calls_sequential()still passes the original args; apply the enrichment at that hook call as well and exercise the real dispatch path in the test.AGENTS.md reference: AGENTS.md:L54-L57
Useful? React with 👍 / 👎.