Skip to content

The agent that grows with you

fix: retain runtime locks while scheduler threads survive cleanup

Teknium954d5e9919ca
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index fb56a2049b3..01fca5ccce6 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -324,7 +324,8 @@ def _start_gateway_start_cron_and_housekeeping(runner):
cron_thread = threading.Thread(
target=cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, daemon=True,
name="cron-scheduler")
- cron_thread.start()
+ from gateway.runtime_ownership import process_ownership
+ process_ownership.start_writer(cron_thread)
# External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually
# API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.
@@ -350,7 +351,7 @@ def _start_gateway_start_cron_and_housekeeping(runner):
kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),
"cron_provider": cron_provider, "runner": runner},
daemon=True, name="gateway-housekeeping")
- housekeeping_thread.start()
+ process_ownership.start_writer(housekeeping_thread)
return cron_stop, cron_provider, cron_thread, housekeeping_thread
diff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.py
index 67d60d7f263..72105b54370 100644
--- a/gateway/runtime_ownership.py
+++ b/gateway/runtime_ownership.py
@@ -22,6 +22,7 @@ def canonical_home(home: Path) -> Path:
class ProfileOwnership:
def __init__(self):
self._handles: dict[Path, object] = {}
+ self._writers: list[threading.Thread] = []
self._mutex = threading.RLock()
@property
@@ -76,8 +77,19 @@ class ProfileOwnership:
_release_file_lock(handle)
handle.close()
+ def start_writer(self, thread: threading.Thread) -> None:
+ """Register before starting so partial startup cannot forget a live writer."""
+ with self._mutex:
+ self._writers.append(thread)
+ thread.start()
+
def close(self) -> None:
with self._mutex:
+ # A timed-out daemon can still write during finally/atexit. Keep the
+ # handles alive; process exit releases them atomically in the OS.
+ if any(thread.is_alive() for thread in self._writers):
+ return
+ self._writers.clear()
for home in reversed(self.homes):
self.release(home)
diff --git a/tests/gateway/test_runtime_writer_drain.py b/tests/gateway/test_runtime_writer_drain.py
new file mode 100644
index 00000000000..ce509b6698b
--- /dev/null
+++ b/tests/gateway/test_runtime_writer_drain.py
@@ -0,0 +1,82 @@
+"""Real startup threads retain runtime exclusion after a drain deadline."""
+import asyncio
+import os
+import subprocess
+import sys
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+
[email protected]('partial_start', [False, True])
+def test_live_runtime_writers_prevent_final_lock_release(tmp_path, monkeypatch, partial_start):
+ import gateway.run as run
+ from gateway.run_bootstrap import _start_gateway_start_cron_and_housekeeping
+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock
+ from cron import scheduler_provider
+
+ home = tmp_path / 'runtime'
+ home.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ gate = threading.Event()
+ started = threading.Event()
+ threads = []
+
+ class Provider:
+ name = 'fixture'
+ def start(self, stop, **kwargs):
+ started.set()
+ gate.wait(20)
+
+ provider = Provider()
+ monkeypatch.setattr(scheduler_provider, 'resolve_cron_scheduler', lambda: provider)
+ monkeypatch.setattr(scheduler_provider, 'scheduler_for_profile_mode', lambda p, **kw: p)
+ monkeypatch.setattr(run, '_start_gateway_housekeeping', lambda *a, **kw: gate.wait(20))
+ original_start = threading.Thread.start
+
+ def start_thread(thread):
+ if thread.name == 'gateway-housekeeping' and partial_start:
+ raise RuntimeError('owned thread-start failure')
+ threads.append(thread)
+ return original_start(thread)
+
+ monkeypatch.setattr(threading.Thread, 'start', start_thread)
+ runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False), adapters={})
+
+ async def start():
+ return _start_gateway_start_cron_and_housekeeping(runner)
+
+ probe = '''
+from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock
+claimed = acquire_gateway_runtime_lock()
+print('CLAIMED', claimed)
+if claimed:
+ release_gateway_runtime_lock()
+'''
+
+ def contender():
+ result = subprocess.run([sys.executable, '-c', probe], env=os.environ.copy(),
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip()
+
+ assert acquire_gateway_runtime_lock()
+ try:
+ if partial_start:
+ with pytest.raises(RuntimeError, match='owned thread-start failure'):
+ asyncio.run(start())
+ else:
+ asyncio.run(start())
+ assert started.wait(5)
+ assert contender() == 'CLAIMED False'
+ release_gateway_runtime_lock()
+ assert contender() == 'CLAIMED False', 'final cleanup unlocked while a runtime writer survived'
+ finally:
+ gate.set()
+ for thread in threads:
+ thread.join(5)
+ assert not thread.is_alive()
+ release_gateway_runtime_lock()
+ assert contender() == 'CLAIMED True'