Skip to content

The agent that grows with you

fix(gateway): restart-failure counter edits are serialized

Maciej Lisiewski54039dee383f
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index 98f8d6dbce3..2dc8610f33e 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1314,11 +1314,8 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):
def _increment_restart_failure_counts(self, active_session_keys: set) -> None:
"""Increment persisted restart-failure counters for active sessions; drop the rest (loop broken)."""
- from utils import atomic_json_write
- path = self._stuck_loop_counts_path()
- counts = self._read_json_counts(path) or {}
- with suppress(Exception):
- atomic_json_write(path, {key: counts.get(key, 0) + 1 for key in active_session_keys}, indent=None)
+ from gateway.stuck_loop_counts import increment_restart_failure_counts
+ increment_restart_failure_counts(self._stuck_loop_counts_path(), active_session_keys)
def _suspend_stuck_loop_sessions(self) -> int:
"""Suspend sessions active across too many restarts (startup, AFTER crash-turn recovery)."""
@@ -1349,22 +1346,13 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):
async def _clear_restart_failure_count(self, session_key: str) -> None:
"""Clear a completed session's restart-failure counter off-loop (atomic_json_write fsyncs)."""
- from utils import atomic_json_write
+ from gateway.stuck_loop_counts import clear_restart_failure_count
path = self._stuck_loop_counts_path()
if not path.exists():
return
- # The whole read/mutate/write is guarded (as on main): a corrupt counters file
- # (non-dict JSON) must never raise out of a session-completion path.
- try:
- counts = self._read_json_counts(path) or {}
- if session_key in counts:
- del counts[session_key]
- if counts:
- await asyncio.to_thread(atomic_json_write, path, counts, indent=None)
- else:
- path.unlink(missing_ok=True)
- except Exception:
- pass
+ # Load/mutate/save run whole in one worker under the counters lock: a split read-on-loop /
+ # write-off-loop let two completing sessions rewrite each other's stale snapshot.
+ await asyncio.to_thread(clear_restart_failure_count, path, session_key)
# Restart orchestration
@staticmethod
diff --git a/gateway/stuck_loop_counts.py b/gateway/stuck_loop_counts.py
new file mode 100644
index 00000000000..4b9c7ee9c73
--- /dev/null
+++ b/gateway/stuck_loop_counts.py
@@ -0,0 +1,56 @@
+"""Persisted per-session restart-failure counters (``.restart_failure_counts``, #7536).
+
+Every load/mutate/save of the file runs under one lock: session completions clear their
+counter from worker threads concurrently, and an unserialized pair rewrites a stale snapshot
+that resurrects the other session's counter.
+"""
+
+import json
+import logging
+import threading
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+# Nothing re-acquires it while held, so a plain Lock suffices.
+_COUNTS_LOCK = threading.Lock()
+
+
+def _read_counts(path: Path) -> dict:
+ """Parsed counters, or {} when the file is missing, unreadable or not a JSON object."""
+ try:
+ counts = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return {}
+ return counts if isinstance(counts, dict) else {}
+
+
+def increment_restart_failure_counts(path: Path, active_session_keys: set) -> None:
+ """Increment the counters of sessions active at shutdown; drop the rest (their loop is broken)."""
+ from utils import atomic_json_write
+ with _COUNTS_LOCK:
+ counts = _read_counts(path)
+ try:
+ atomic_json_write(path, {key: counts.get(key, 0) + 1 for key in active_session_keys}, indent=None)
+ except Exception:
+ logger.debug("Could not write restart-failure counters to %s", path, exc_info=True)
+
+
+def clear_restart_failure_count(path: Path, session_key: str) -> None:
+ """Drop a completed session's counter; removes the file once no counter is left.
+
+ Blocking (``atomic_json_write`` fsyncs): callers on the event loop run it via ``asyncio.to_thread``.
+ """
+ from utils import atomic_json_write
+ with _COUNTS_LOCK:
+ counts = _read_counts(path)
+ if session_key not in counts:
+ return
+ del counts[session_key]
+ try:
+ if counts:
+ atomic_json_write(path, counts, indent=None)
+ else:
+ path.unlink(missing_ok=True)
+ except Exception:
+ logger.debug("Could not clear restart-failure counter in %s", path, exc_info=True)
diff --git a/tests/gateway/test_stuck_loop.py b/tests/gateway/test_stuck_loop.py
index 0a7dab1ea32..d79e14d17b1 100644
--- a/tests/gateway/test_stuck_loop.py
+++ b/tests/gateway/test_stuck_loop.py
@@ -5,12 +5,17 @@ gets stuck, gateway restarts, same session gets stuck again), the session
is auto-suspended on startup so the user gets a clean slate.
"""
+import asyncio
import json
+import threading
+from pathlib import Path
from unittest.mock import MagicMock
import pytest
from tests.gateway.restart_test_helpers import make_restart_runner
+from tests.lock_contention import ContentionObservedLock
+from tests.waiting import wait_until
@pytest.fixture
@@ -63,4 +68,48 @@ class TestStuckLoopDetection:
assert suspended == 0
assert mock_entry.suspended is False
-
+ def test_concurrent_clears_do_not_resurrect_each_others_counter(self, runner_with_home, monkeypatch):
+ """Two sessions completing at once each clear their counter; neither may rewrite the other's
+ stale snapshot (race audit lostupdate-6: a resurrected counter can later auto-suspend a healthy session)."""
+ import gateway.stuck_loop_counts as counts_module
+ import utils
+ runner, home = runner_with_home
+ path = home / runner._STUCK_LOOP_FILE
+ counts_lock = ContentionObservedLock()
+ monkeypatch.setattr(counts_module, "_COUNTS_LOCK", counts_lock)
+ path.write_text(json.dumps({"session:a": 2, "session:b": 2}))
+ reads = []
+ second_read = threading.Event()
+ real_read_text = Path.read_text
+
+ def counting_read_text(self, *args, **kwargs):
+ if self == path:
+ reads.append(self)
+ if len(reads) == 2:
+ second_read.set()
+ return real_read_text(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", counting_read_text)
+ real_write = utils.atomic_json_write
+ first_write = threading.Event()
+
+ def parked_write(target, data, **kwargs):
+ if not first_write.is_set():
+ first_write.set()
+ # Unserialized clears let the other session read the not-yet-rewritten file here;
+ # serialized ones are seen blocking on the counters lock instead.
+ wait_until(lambda: second_read.is_set() or counts_lock.contended.is_set(),
+ what="the other clear read the file or blocked on the counters lock")
+ return real_write(target, data, **kwargs)
+
+ monkeypatch.setattr(utils, "atomic_json_write", parked_write)
+
+ async def complete_both():
+ await asyncio.gather(
+ runner._clear_restart_failure_count("session:a"),
+ runner._clear_restart_failure_count("session:b"),
+ )
+
+ asyncio.run(complete_both())
+ remaining = json.loads(real_read_text(path)) if path.exists() else {}
+ assert remaining == {}