Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(codex): backstop idle eviction for stuck-active transports (#627) (#628)

Qi Qi4d621ef0aac0
diff --git a/config/v2_config.py b/config/v2_config.py
index 13dab0a86..02d288096 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -26,6 +26,28 @@ logger = logging.getLogger(__name__)
CONFIG_LOCK = threading.RLock()
DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600
+
+# Absolute-time backstop for evicting a Codex transport whose turn is stuck
+# "active" forever (e.g. the ``codex app-server`` wedged or silently
+# disconnected after ``turn/start`` but before ``turn/completed``, so
+# ``_active_turns`` is never cleared). Without this, ``evict_idle_transports``
+# treats an active turn as an ABSOLUTE veto and the wedged app-server process
+# leaks until service restart (mirrors the Claude leak in #622/#623).
+#
+# A transport with an active turn is force-evicted once it has been idle for
+# ``max(idle_timeout * MULTIPLIER, FLOOR_SECONDS)``. Set the multiplier <= 0 to
+# disable the backstop entirely.
+#
+# TRADE-OFF: this cap is driven purely by ``last_activity`` (refreshed on every
+# Codex notification), so it CANNOT distinguish a genuinely wedged turn from a
+# legitimately long, fully-silent one. A single tool/MCP run or model "thinking"
+# phase that emits no notifications for longer than the cap will be misjudged as
+# stuck and have its transport torn down. The multiplier defaults higher than a
+# typical tool-run assumption, and the floor guarantees a >= 30 min window even
+# when ``idle_timeout`` is configured small, to keep that false-positive rare.
+DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER = 3
+DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS = 1800
+
DEFAULT_OPENCODE_ERROR_RETRY_LIMIT = 1
DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14
MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 4c530225a..ec166c7d9 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -9,6 +9,10 @@ import time
from pathlib import Path
from typing import Any, Dict, Optional
+from config.v2_config import (
+ DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS,
+ DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER,
+)
from core.avibe_cloud import avibe_cloud_url_available
from core.services.session_fork import pending_native_fork_source
from core.system_prompt_injection import (
@@ -408,6 +412,13 @@ class CodexAgent(BaseAgent):
if not hasattr(self, "_session_locks"):
self._session_locks = {}
+ # Absolute-time backstop: a transport whose turn is stuck "active"
+ # forever (turn/completed never arrives — wedged/silently-disconnected
+ # app-server) would otherwise be vetoed from eviction indefinitely and
+ # leak its app-server process until restart (#622/#623 analog). Once it
+ # has been idle past this cap, force-evict it despite the active turn.
+ stuck_active_cap = self._stuck_active_idle_eviction_cap(idle_timeout)
+
now = time.monotonic()
evicted = 0
@@ -416,10 +427,14 @@ class CodexAgent(BaseAgent):
if transport is None:
self._transport_last_activity.pop(cwd, None)
continue
- if self._has_active_turns_for_cwd(cwd):
- continue
idle_for = now - last_activity
- if idle_for < idle_timeout:
+ has_active = self._has_active_turns_for_cwd(cwd)
+ if not self._is_transport_evictable(
+ has_active=has_active,
+ idle_for=idle_for,
+ idle_timeout=idle_timeout,
+ stuck_active_cap=stuck_active_cap,
+ ):
continue
lock = self._transport_locks.setdefault(cwd, asyncio.Lock())
@@ -428,15 +443,30 @@ class CodexAgent(BaseAgent):
current_last_activity = self._transport_last_activity.get(cwd)
if current_transport is None or current_transport is not transport:
continue
- if self._has_active_turns_for_cwd(cwd):
- continue
if current_last_activity is None:
continue
+ # Recheck from CURRENT state inside the lock: activity (and the
+ # active-turn flag) may have changed between the two passes.
idle_for = time.monotonic() - current_last_activity
- if idle_for < idle_timeout:
+ has_active = self._has_active_turns_for_cwd(cwd)
+ if not self._is_transport_evictable(
+ has_active=has_active,
+ idle_for=idle_for,
+ idle_timeout=idle_timeout,
+ stuck_active_cap=stuck_active_cap,
+ ):
continue
- logger.info("Evicting idle Codex transport for cwd=%s after %.1fs idle", cwd, idle_for)
+ if has_active:
+ logger.warning(
+ "Force-evicting stuck-active Codex transport for cwd=%s after %.1fs idle "
+ "(active turn exceeded stuck-active cap of %.1fs; app-server presumed wedged)",
+ cwd,
+ idle_for,
+ stuck_active_cap,
+ )
+ else:
+ logger.info("Evicting idle Codex transport for cwd=%s after %.1fs idle", cwd, idle_for)
try:
await transport.stop()
except Exception as exc:
@@ -448,6 +478,12 @@ class CodexAgent(BaseAgent):
self._cwd_inodes().pop(cwd, None)
for base_session_id in list(self._session_mgr.sessions_for_cwd(cwd)):
+ # A force-evicted stuck-active turn never emitted a terminal
+ # result, so the Workbench status and SSE/runtime gate are
+ # still owned by that turn. Settle it through the same
+ # terminal-result path as normal completions before dropping
+ # turn state. No-op for sessions with no active turn.
+ await self._settle_stuck_active_request(base_session_id)
# Keep the persisted thread mapping so a later transport restart
# can resume the same Codex conversation for this Slack thread.
self._session_mgr.invalidate_thread(base_session_id)
@@ -459,6 +495,90 @@ class CodexAgent(BaseAgent):
return evicted
+ async def _settle_stuck_active_request(self, base_session_id: str) -> None:
+ """Settle a turn we are about to force-reap.
+
+ ``_start_turn`` marks the AgentService runtime turn started; it is
+ normally settled by a terminal result, which also flips Workbench
+ ``agent_status`` out of ``running``. The stuck-active force-eviction path
+ has no backend terminal event, so emit a silent error result here. The
+ terminal-result path is token-guarded by its owner, so a no-op
+ (already-settled or no active turn) is safe.
+ """
+ get_active = getattr(self._turn_registry, "get_active_turn", None)
+ active_turn = get_active(base_session_id) if callable(get_active) else None
+ if not active_turn:
+ return
+
+ request = None
+ get_for_turn = getattr(self._turn_registry, "get_request_for_turn", None)
+ if callable(get_for_turn):
+ request = get_for_turn(active_turn)
+ if request is None:
+ get_latest = getattr(self._turn_registry, "get_latest_request", None)
+ if callable(get_latest):
+ request = get_latest(base_session_id)
+
+ context = getattr(request, "context", None)
+ if context is None:
+ return
+ controller = getattr(self, "controller", None)
+ emit = getattr(controller, "emit_agent_message", None)
+ if callable(emit):
+ try:
+ await emit(context, "result", "", is_error=True, level="silent")
+ return
+ except Exception:
+ logger.warning(
+ "Failed to emit silent terminal result for force-evicted Codex turn %s",
+ active_turn,
+ exc_info=True,
+ )
+
+ # Best-effort fallback for narrow test doubles or partial controllers:
+ # release the runtime gate even if the Workbench status path is absent.
+ release = getattr(self._event_handler, "_release_stream_turn", None)
+ if callable(release):
+ release(context)
+
+ def _stuck_active_idle_eviction_cap(self, idle_timeout: float) -> Optional[float]:
+ """Idle cap after which an *active* transport is force-evicted.
+
+ Returns ``None`` when the backstop is disabled (multiplier <= 0), in
+ which case an active turn remains an absolute veto. Otherwise a
+ transport with an active turn is force-evicted once it has been idle for
+ ``max(idle_timeout * multiplier, floor)`` — the floor keeps the window
+ sane even when ``idle_timeout`` is configured very small.
+ """
+ multiplier = DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER
+ if multiplier <= 0:
+ return None
+ floor = max(0.0, float(DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_FLOOR_SECONDS))
+ return max(idle_timeout * multiplier, floor)
+
+ def _is_transport_evictable(
+ self,
+ *,
+ has_active: bool,
+ idle_for: float,
+ idle_timeout: float,
+ stuck_active_cap: Optional[float],
+ ) -> bool:
+ """Decide whether an idle transport is eligible for eviction.
+
+ Pure decision (no lookups), so callers evaluate the active-turn flag
+ exactly once. An idle transport with no active turn is evictable once it
+ crosses the normal ``idle_timeout``. A transport with an active turn is
+ normally vetoed, but is force-evictable once it crosses
+ ``stuck_active_cap`` (the absolute-time backstop) — the only path that
+ reaps a wedged app-server whose ``turn/completed`` never arrived.
+ """
+ if has_active:
+ if stuck_active_cap is None:
+ return False
+ return idle_for >= stuck_active_cap
+ return idle_for >= idle_timeout
+
# ------------------------------------------------------------------
# Transport management
# ------------------------------------------------------------------
@@ -564,7 +684,15 @@ class CodexAgent(BaseAgent):
# Wire up callbacks
transport.on_notification(self._on_notification)
- transport.on_server_request(self._on_server_request)
+ # Bind the cwd so any server request (e.g. an auto-approval) refreshes
+ # this transport's activity: a server request IS app-server liveness,
+ # and unlike notifications it isn't always tied to a resolvable
+ # turn/thread in params. Without this a turn that thinks silently and
+ # then asks for approval near the stuck-active cap could be wrongly
+ # force-evicted by the next sweep.
+ transport.on_server_request(
+ lambda req_id, method, params, _cwd=cwd: self._on_server_request(_cwd, req_id, method, params)
+ )
await transport.start()
self._transports[cwd] = transport
@@ -1102,11 +1230,15 @@ class CodexAgent(BaseAgent):
async def _on_server_request(
self,
+ cwd: str,
req_id: int | str,
method: str,
params: Dict[str, Any],
) -> Dict[str, Any]:
"""Handle server requests — auto-approve all."""
+ # A server request means this app-server is alive and actively driving a
+ # turn, so count it as activity for the stuck-active idle backstop.
+ self._touch_transport_activity(cwd)
if method in (
"item/commandExecution/requestApproval",
"item/fileChange/requestApproval",
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 2c2999e57..91815ec7f 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -565,6 +565,217 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent._transport_last_activity["/tmp/work"], 950.0)
agent.sessions.clear_agent_session_mapping.assert_not_called()
+ @staticmethod
+ def _make_evict_agent(*, active_turn, last_activity=0.0):
+ """Build a bare CodexAgent wired for evict_idle_transports tests."""
+ agent = object.__new__(CodexAgent)
+ stop_calls = []
+
+ async def stop_transport():
+ stop_calls.append("stop")
+
+ agent._transports = {"/tmp/work": SimpleNamespace(stop=stop_transport)}
+ agent._transport_last_activity = {"/tmp/work": last_activity}
+ agent._transport_locks = {"/tmp/work": asyncio.Lock()}
+ invalidated = []
+ cleared_turns = []
+ agent._session_mgr = SimpleNamespace(
+ sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
+ invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
+ )
+ request = SimpleNamespace(context="ctx-1", base_session_id="session-1")
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda base_session_id: active_turn,
+ has_pending_turn_start=lambda base_session_id: False,
+ get_request_for_turn=lambda turn_id: request if turn_id == active_turn else None,
+ get_latest_request=lambda base_session_id: request,
+ clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
+ )
+ release_calls = []
+ agent._event_handler = SimpleNamespace(
+ _release_stream_turn=lambda context: release_calls.append(context),
+ release_calls=release_calls,
+ )
+ agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
+ agent._session_locks = {"session-1": asyncio.Lock()}
+ agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+ return agent, stop_calls, invalidated, cleared_turns
+
+ async def test_evict_idle_transports_force_evicts_stuck_active_transport(self):
+ # active turn that has been idle WAY past the stuck-active cap
+ # (max(600*3, 1800) = 1800s) must be force-evicted — the leak fix.
+ agent, stop_calls, invalidated, cleared_turns = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+
+ with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 1)
+ self.assertEqual(stop_calls, ["stop"])
+ self.assertEqual(invalidated, ["session-1"])
+ self.assertEqual(cleared_turns, ["session-1"])
+ self.assertEqual(agent._transports, {})
+ self.assertEqual(agent._transport_last_activity, {})
+ # Force-reaped stuck turns must settle Workbench status + runtime gate
+ # through the shared terminal-result chokepoint.
+ agent.controller.emit_agent_message.assert_awaited_once_with(
+ "ctx-1", "result", "", is_error=True, level="silent"
+ )
+ self.assertEqual(agent._event_handler.release_calls, [])
+
+ async def test_evict_idle_transports_force_evict_release_falls_back_to_latest_request(self):
+ # Defensive path: if the active turn has no per-turn request mapping,
+ # the runtime gate is still settled via get_latest_request.
+ agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+ fallback_request = SimpleNamespace(context="ctx-latest", base_session_id="session-1")
+ agent._turn_registry.get_request_for_turn = lambda turn_id: None
+ agent._turn_registry.get_latest_request = lambda base_session_id: fallback_request
+
+ with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 1)
+ self.assertEqual(stop_calls, ["stop"])
+ agent.controller.emit_agent_message.assert_awaited_once_with(
+ "ctx-latest", "result", "", is_error=True, level="silent"
+ )
+ self.assertEqual(agent._event_handler.release_calls, [])
+
+ async def test_evict_idle_transports_keeps_active_transport_under_stuck_cap(self):
+ # active turn idle past idle_timeout (600) but under the cap (1800):
+ # still vetoed, NOT force-evicted.
+ agent, stop_calls, _invalidated, cleared_turns = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+
+ with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 0)
+ self.assertEqual(stop_calls, [])
+ self.assertIn("/tmp/work", agent._transports)
+ self.assertEqual(cleared_turns, [])
+
+ async def test_evict_idle_transports_stuck_cap_floor_dominates_small_timeout(self):
+ # With a tiny idle_timeout (100s) the multiplier window (300s) is below
+ # the 1800s floor, so the floor governs: idle 1000s < 1800s stays vetoed.
+ agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+
+ with patch.object(_MODULE.time, "monotonic", return_value=1000.0):
+ evicted = await agent.evict_idle_transports(100)
+
+ self.assertEqual(evicted, 0)
+ self.assertEqual(stop_calls, [])
+ self.assertIn("/tmp/work", agent._transports)
+
+ async def test_evict_idle_transports_stuck_backstop_disabled(self):
+ # multiplier <= 0 disables the backstop: an active turn is an absolute
+ # veto again, no matter how long it has been idle.
+ agent, stop_calls, _invalidated, cleared_turns = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+
+ with patch.object(_MODULE, "DEFAULT_CODEX_STUCK_ACTIVE_IDLE_EVICTION_MULTIPLIER", 0):
+ with patch.object(_MODULE.time, "monotonic", return_value=1_000_000.0):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 0)
+ self.assertEqual(stop_calls, [])
+ self.assertIn("/tmp/work", agent._transports)
+ self.assertEqual(cleared_turns, [])
+
+ async def test_evict_idle_transports_force_evict_skips_when_activity_refreshed(self):
+ # Race: pass 1 sees a stuck-active candidate (idle past the 1800s cap),
+ # but a fresh notification updates last_activity before the locked
+ # recheck. The recheck recomputes idle from current state and bails.
+ agent, stop_calls, _invalidated, _cleared = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+ lock = asyncio.Lock()
+ await lock.acquire()
+ agent._transport_locks = {"/tmp/work": lock}
+
+ with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
+ eviction_task = asyncio.create_task(agent.evict_idle_transports(600))
+ await asyncio.sleep(0)
+ # fresh activity: idle recomputed as 2000-1900=100s, well under cap
+ agent._transport_last_activity["/tmp/work"] = 1900.0
+ lock.release()
+ evicted = await eviction_task
+
+ self.assertEqual(evicted, 0)
+ self.assertEqual(stop_calls, [])
+ self.assertIn("/tmp/work", agent._transports)
+
+ async def test_evict_idle_transports_reclassifies_when_turn_clears_between_passes(self):
+ # Race: pass 1 sees a stuck-active candidate, but the turn completes
+ # (active flag clears) before the locked recheck while activity stays
+ # stale. The recheck reclassifies it as a NORMAL idle eviction.
+ agent, stop_calls, invalidated, cleared_turns = self._make_evict_agent(
+ active_turn="turn-1", last_activity=0.0
+ )
+ lock = asyncio.Lock()
+ await lock.acquire()
+ agent._transport_locks = {"/tmp/work": lock}
+
+ with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
+ eviction_task = asyncio.create_task(agent.evict_idle_transports(600))
+ await asyncio.sleep(0)
+ # turn finished between the two passes; activity unchanged (stale)
+ agent._turn_registry.get_active_turn = lambda base_session_id: None
+ lock.release()
+ evicted = await eviction_task
+
+ self.assertEqual(evicted, 1)
+ self.assertEqual(stop_calls, ["stop"])
+ self.assertEqual(invalidated, ["session-1"])
+ self.assertEqual(cleared_turns, ["session-1"])
+ # reclassified as normal idle: the prior turn already settled itself,
+ # so no spurious terminal result or runtime-gate release fires here.
+ agent.controller.emit_agent_message.assert_not_awaited()
+ self.assertEqual(agent._event_handler.release_calls, [])
+
+ async def test_evict_idle_transports_force_evict_preserves_state_when_stop_fails(self):
+ # Stuck-active force-eviction path: if transport.stop() raises, the
+ # transport and its bookkeeping must be left intact (next sweep retries).
+ agent = object.__new__(CodexAgent)
+ invalidated = []
+ cleared_turns = []
+
+ async def stop_transport():
+ raise RuntimeError("boom")
+
+ transport = SimpleNamespace(stop=stop_transport)
+ lock = asyncio.Lock()
+ agent._transports = {"/tmp/work": transport}
+ agent._transport_last_activity = {"/tmp/work": 0.0}
+ agent._transport_locks = {"/tmp/work": lock}
+ agent._session_mgr = SimpleNamespace(
+ sessions_for_cwd=lambda cwd: ["session-1"] if cwd == "/tmp/work" else [],
+ invalidate_thread=lambda base_session_id: invalidated.append(base_session_id),
+ )
+ agent._turn_registry = SimpleNamespace(
+ get_active_turn=lambda base_session_id: "turn-1",
+ has_pending_turn_start=lambda base_session_id: False,
+ clear_session=lambda base_session_id: cleared_turns.append(base_session_id),
+ )
+ agent._session_locks = {"session-1": asyncio.Lock()}
+ agent.sessions = SimpleNamespace(clear_agent_session_mapping=Mock())
+
+ with patch.object(_MODULE.time, "monotonic", return_value=2000.0):
+ evicted = await agent.evict_idle_transports(600)
+
+ self.assertEqual(evicted, 0)
+ self.assertIs(agent._transports["/tmp/work"], transport)
+ self.assertEqual(agent._transport_last_activity["/tmp/work"], 0.0)
+ self.assertEqual(invalidated, [])
+ self.assertEqual(cleared_turns, [])
+
async def test_get_or_create_transport_fast_path_waits_for_transport_lock(self):
agent = object.__new__(CodexAgent)
lock = asyncio.Lock()
@@ -1911,6 +2122,49 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])
return agent
+ async def test_server_request_refreshes_transport_activity(self):
+ # An auto-approved server request must refresh the bound cwd's activity
+ # so the stuck-active idle backstop doesn't force-evict a live turn that
+ # recently asked for approval.
+ agent = self._agent()
+ agent._transport_last_activity = {"/tmp/work": 0.0}
+
+ with patch.object(_MODULE.time, "monotonic", return_value=1234.0):
+ result = await agent._on_server_request(
+ "/tmp/work",
+ 7,
+ "item/commandExecution/requestApproval",
+ {"itemId": "item-1"},
+ )
+
+ self.assertEqual(result, {"approved": True})
+ self.assertEqual(agent._transport_last_activity["/tmp/work"], 1234.0)
+
+ async def test_get_or_create_transport_binds_cwd_into_server_request_cb(self):
+ # The server-request callback registered on the transport must carry the
+ # cwd, so invoking it (as the transport would) refreshes that cwd.
+ import tempfile
+
+ agent = self._agent()
+ captured = {}
+
+ with tempfile.TemporaryDirectory() as cwd:
+ fresh = SimpleNamespace(
+ is_initialized=True,
+ start=AsyncMock(),
+ on_notification=Mock(),
+ on_server_request=Mock(side_effect=lambda cb: captured.update(cb=cb)),
+ )
+ with patch.object(_MODULE, "CodexTransport", return_value=fresh):
+ await agent._get_or_create_transport(cwd)
+
+ self.assertIn("cb", captured)
+ with patch.object(_MODULE.time, "monotonic", return_value=999.0):
+ result = await captured["cb"](1, "item/fileChange/requestApproval", {"itemId": "x"})
+
+ self.assertEqual(result, {"approved": True})
+ self.assertEqual(agent._transport_last_activity[cwd], 999.0)
+
async def test_cached_transport_evicted_when_cwd_inode_changes(self):
import tempfile