Skip to content

The agent that grows with you

fix(gateway): close ambiguous recovery cleanup gaps

Dominic Bejarc5e032c804de
diff --git a/gateway/run.py b/gateway/run.py
index 163870dc582..dfd72d37003 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -10778,6 +10778,17 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
except Exception:
logger.debug("Failed to cancel gateway loop floor timer", exc_info=True)
+ async def _consume_clean_shutdown_marker(self, marker_path) -> int:
+ """Discard orphan turn markers before consuming a clean-exit receipt.
+
+ If either persistence or marker removal fails, startup must fail closed.
+ Continuing with the old receipt would let a later unclean exit masquerade
+ as clean and discard genuinely interrupted turns.
+ """
+ discarded = await self.async_session_store.discard_active_turn_markers()
+ marker_path.unlink()
+ return discarded
+
async def _recover_unclean_sessions(self) -> tuple[int, int]:
"""Recover exact active turns, then run the legacy recency fallback."""
exact = 0
@@ -11146,18 +11157,19 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
if _clean_marker.exists():
logger.info("Previous gateway exited cleanly — skipping session suspension")
try:
- discarded = await self.async_session_store.discard_active_turn_markers()
- if discarded:
- logger.info(
- "Discarded %d orphan active-turn marker(s) after clean shutdown",
- discarded,
- )
+ discarded = await self._consume_clean_shutdown_marker(_clean_marker)
except Exception as exc:
- logger.warning("Clean-start marker cleanup failed: %s", exc)
- try:
- _clean_marker.unlink()
- except Exception:
- pass
+ logger.error(
+ "Clean-start marker cleanup failed; refusing startup so the "
+ "clean-exit receipt cannot mask a later unclean exit: %s",
+ exc,
+ )
+ raise RuntimeError("clean-start recovery cleanup failed") from exc
+ if discarded:
+ logger.info(
+ "Discarded %d orphan active-turn marker(s) after clean shutdown",
+ discarded,
+ )
else:
exact, fallback = await self._recover_unclean_sessions()
recovered = exact + fallback
diff --git a/tests/gateway/test_active_turn_recovery.py b/tests/gateway/test_active_turn_recovery.py
index 87609fd82f5..bd859325c53 100644
--- a/tests/gateway/test_active_turn_recovery.py
+++ b/tests/gateway/test_active_turn_recovery.py
@@ -9,7 +9,7 @@ marker, compare-and-swap cleanup, and promotion into the existing
from datetime import datetime, timedelta
from types import SimpleNamespace
from typing import Any, cast
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
import pytest
@@ -356,6 +356,48 @@ def test_clean_startup_discards_orphan_markers_without_resuming(tmp_path):
assert recovered.active_turn_started_at is None
+async def test_clean_shutdown_marker_is_not_consumed_when_discard_fails(tmp_path):
+ marker = tmp_path / ".clean_shutdown"
+ marker.write_text("clean", encoding="utf-8")
+ runner = object.__new__(GatewayRunner)
+ async_store = MagicMock()
+ async_store.discard_active_turn_markers = AsyncMock(
+ side_effect=OSError("state store unavailable")
+ )
+
+ with patch.object(
+ GatewayRunner,
+ "async_session_store",
+ new_callable=PropertyMock,
+ return_value=async_store,
+ ):
+ with pytest.raises(OSError, match="state store unavailable"):
+ await runner._consume_clean_shutdown_marker(marker)
+
+ assert marker.exists()
+
+
+async def test_clean_shutdown_marker_is_unlinked_after_durable_discard(tmp_path):
+ marker = tmp_path / ".clean_shutdown"
+ marker.write_text("clean", encoding="utf-8")
+ runner = object.__new__(GatewayRunner)
+ async_store = MagicMock()
+ async_store.discard_active_turn_markers = AsyncMock(return_value=2)
+
+ with patch.object(
+ GatewayRunner,
+ "async_session_store",
+ new_callable=PropertyMock,
+ return_value=async_store,
+ ):
+ discarded = await runner._consume_clean_shutdown_marker(marker)
+
+ assert discarded == 2
+ assert not marker.exists()
+
+
@pytest.mark.asyncio
async def test_runner_active_turn_carrier_clears_the_exact_resolved_key():
runner = object.__new__(GatewayRunner)
diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py
index 2de785123da..82ae7e33686 100644
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@ -898,6 +898,54 @@ class TestCheckpoint:
recovered = registry.recover_from_checkpoint()
assert recovered == 0
+ def test_recover_dead_wrapper_retries_unreaped_systemd_scope(
+ self, registry, tmp_path, monkeypatch
+ ):
+ checkpoint = tmp_path / "procs.json"
+ entry = {
+ "session_id": "proc_dead_scope",
+ "command": "daemonize",
+ "pid": 999999999,
+ "pid_scope": "host",
+ "host_start_time": 123.0,
+ "systemd_unit": "hermes-worker-proc_dead_scope.scope",
+ }
+ checkpoint.write_text(json.dumps([entry]))
+ monkeypatch.setattr(registry, "_host_pid_is_ours", lambda *_args: False)
+ monkeypatch.setattr(registry, "_is_host_pid_alive", lambda *_args: False)
+
+ with patch("tools.process_registry.CHECKPOINT_PATH", checkpoint), patch(
+ "tools.process_registry._stop_systemd_unit", return_value=False
+ ) as stop_unit:
+ assert registry.recover_from_checkpoint() == 0
+
+ stop_unit.assert_called_once_with(entry["systemd_unit"])
+ assert json.loads(checkpoint.read_text()) == [entry]
+
+ def test_recover_dead_wrapper_drops_reaped_systemd_scope(
+ self, registry, tmp_path, monkeypatch
+ ):
+ checkpoint = tmp_path / "procs.json"
+ entry = {
+ "session_id": "proc_dead_scope",
+ "command": "daemonize",
+ "pid": 999999999,
+ "pid_scope": "host",
+ "host_start_time": 123.0,
+ "systemd_unit": "hermes-worker-proc_dead_scope.scope",
+ }
+ checkpoint.write_text(json.dumps([entry]))
+ monkeypatch.setattr(registry, "_host_pid_is_ours", lambda *_args: False)
+ monkeypatch.setattr(registry, "_is_host_pid_alive", lambda *_args: False)
+
+ with patch("tools.process_registry.CHECKPOINT_PATH", checkpoint), patch(
+ "tools.process_registry._stop_systemd_unit", return_value=True
+ ) as stop_unit:
+ assert registry.recover_from_checkpoint() == 0
+
+ stop_unit.assert_called_once_with(entry["systemd_unit"])
+ assert json.loads(checkpoint.read_text()) == []
+
def test_recovery_skips_explicit_sandbox_backed_entries(self, registry, tmp_path):
checkpoint = tmp_path / "procs.json"
@@ -1848,17 +1896,49 @@ class TestSystemdCgroupIsolation:
f"hermes-worker-{session.id}-pipe-fallback.scope"
)
+ def test_pty_spawn_failure_does_not_fallback_when_scope_reap_fails(
+ self, registry, monkeypatch
+ ):
+ """Do not launch a duplicate command while the failed PTY scope may live."""
+ from ptyprocess import PtyProcess
+
+ monkeypatch.setattr("tools.process_registry._find_shell", lambda: "/bin/bash")
+ monkeypatch.setattr(
+ "tools.process_registry._systemd_run_user_scope_available",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ "gateway.restart.is_gateway_supervisor_process",
+ lambda: True,
+ )
+ monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")
+
+ with patch.object(
+ PtyProcess,
+ "spawn",
+ side_effect=RuntimeError("PTY wrapper failed after scope creation"),
+ ), patch("subprocess.Popen") as pipe_spawn, patch(
+ "tools.process_registry._stop_systemd_unit", return_value=False
+ ) as stop_unit:
+ with pytest.raises(RuntimeError, match="could not be reaped"):
+ registry.spawn_local("codex", cwd="/tmp", use_pty=True)
+
+ stop_unit.assert_called_once()
+ pipe_spawn.assert_not_called()
+
def test_worker_memory_limit_honors_local_guard_mb_override(self, monkeypatch):
import tools.process_registry as pr
monkeypatch.setenv("TERMINAL_LOCAL_MEMORY_MAX_MB", "123")
monkeypatch.setattr("shutil.which", lambda name: "/usr/bin/systemd-run")
- argv = pr._build_systemd_scope_argv(
- ["/bin/bash", "-lc", "true"],
- unit_suffix="test",
- )
+ with patch("tools.process_registry.logger.warning") as warning:
+ argv = pr._build_systemd_scope_argv(
+ ["/bin/bash", "-lc", "true"],
+ unit_suffix="test",
+ )
+ warning.assert_not_called()
assert f"MemoryMax={123 * 1024 * 1024}" in argv
def test_worker_memory_limit_caps_oversized_local_guard_override(
diff --git a/tools/process_registry.py b/tools/process_registry.py
index bfd64771531..a99c71dd15a 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -119,18 +119,21 @@ def _worker_memory_max_bytes() -> int:
override_bound: Optional[int] = None
override = os.getenv("TERMINAL_LOCAL_MEMORY_MAX_MB", "").strip()
if override:
+ override_valid = False
try:
parsed = int(override) * 1024 * 1024
if parsed >= _MIN_WORKER_MEMORY_MAX_BYTES:
override_bound = parsed
+ override_valid = True
except ValueError:
pass
- logger.warning(
- "Ignoring invalid TERMINAL_LOCAL_MEMORY_MAX_MB=%r; "
- "expected an integer representing at least %d MiB",
- override,
- _MIN_WORKER_MEMORY_MAX_BYTES // (1024 * 1024),
- )
+ if not override_valid:
+ logger.warning(
+ "Ignoring invalid TERMINAL_LOCAL_MEMORY_MAX_MB=%r; "
+ "expected an integer representing at least %d MiB",
+ override,
+ _MIN_WORKER_MEMORY_MAX_BYTES // (1024 * 1024),
+ )
candidates: List[int] = []
try:
@@ -1052,7 +1055,11 @@ class ProcessRegistry:
except Exception as e:
logger.warning("PTY spawn failed (%s), falling back to pipe mode", e)
if pty_scope_attempted and session.systemd_unit:
- _stop_systemd_unit(session.systemd_unit)
+ if not _stop_systemd_unit(session.systemd_unit):
+ raise RuntimeError(
+ "PTY scope could not be reaped; refusing pipe fallback "
+ "to avoid duplicate command execution"
+ ) from e
session.systemd_unit = ""
# Standard Popen path (non-PTY or PTY fallback)
@@ -2420,7 +2427,10 @@ class ProcessRegistry:
# ----- Checkpoint (crash recovery) -----
- def _write_checkpoint(self):
+ def _write_checkpoint(
+ self,
+ extra_entries: Optional[List[Dict[str, Any]]] = None,
+ ):
"""Write running process metadata to checkpoint file atomically."""
try:
with self._lock:
@@ -2460,6 +2470,13 @@ class ProcessRegistry:
"notify_on_complete": s.notify_on_complete,
"watch_patterns": s.watch_patterns,
})
+ if extra_entries:
+ tracked_ids = {item.get("session_id") for item in entries}
+ entries.extend(
+ item
+ for item in extra_entries
+ if item.get("session_id") not in tracked_ids
+ )
# Atomic write to avoid corruption on crash
from utils import atomic_json_write
@@ -2482,6 +2499,7 @@ class ProcessRegistry:
return 0
recovered = 0
+ unresolved_scope_entries: List[Dict[str, Any]] = []
for entry in entries:
pid = entry.get("pid")
if not pid:
@@ -2515,6 +2533,15 @@ class ProcessRegistry:
"an unrelated process; refusing to adopt it.",
entry.get("session_id", "?"), pid,
)
+ systemd_unit = entry.get("systemd_unit", "")
+ if systemd_unit and not _stop_systemd_unit(systemd_unit):
+ logger.warning(
+ "Could not reap persisted scope %s for dead wrapper pid %s; "
+ "retaining checkpoint entry for the next startup",
+ systemd_unit,
+ pid,
+ )
+ unresolved_scope_entries.append(entry)
continue
session = ProcessSession(
@@ -2559,7 +2586,7 @@ class ProcessRegistry:
"notify_on_complete": session.notify_on_complete,
})
- self._write_checkpoint()
+ self._write_checkpoint(extra_entries=unresolved_scope_entries)
return recovered