Skip to content

The agent that grows with you

fix(tui_gateway): drain in-flight turns before finalizing sessions on compute-host shutdown

briandevans1fba2dbe85f0
diff --git a/tests/tui_gateway/test_compute_host_phase1.py b/tests/tui_gateway/test_compute_host_phase1.py
index cc1b6347137..c7cb621ceca 100644
--- a/tests/tui_gateway/test_compute_host_phase1.py
+++ b/tests/tui_gateway/test_compute_host_phase1.py
@@ -8,6 +8,7 @@ from pathlib import Path
import pytest
+from tui_gateway import server
from tui_gateway.compute_host import ComputeHost, _default_workers
from tui_gateway.host_supervisor import (
MUTATOR_ROUTE_TABLE,
@@ -132,3 +133,71 @@ def _make_compress_host_session(events: list) -> dict:
}
+def _record_finalize(monkeypatch, events: list[str]) -> None:
+ """Give ``flush_all_sessions`` one session and record when it finalizes."""
+ monkeypatch.setattr(server, "_sessions", {"s1": {"session_key": "s1"}}, raising=False)
+ monkeypatch.setattr(
+ server,
+ "_finalize_session",
+ lambda _session, end_reason="tui_close": events.append(f"finalize:{end_reason}"),
+ raising=False,
+ )
+
+
+def _register_turn(host: ComputeHost, fn) -> None:
+ """Submit a turn exactly the way ``_handle_turn_start`` does."""
+ future = host._executor.submit(fn)
+ with host._turn_futures_lock:
+ host._turn_futures.add(future)
+ future.add_done_callback(host._turn_futures.discard)
+
+
+def test_shutdown_drains_in_flight_turn_before_finalizing_sessions(monkeypatch):
+ events: list[str] = []
+ _record_finalize(monkeypatch, events)
+
+ host = ComputeHost(stdout=io.StringIO(), heartbeat_secs=0)
+ running = threading.Event()
+
+ def _turn() -> None:
+ running.set()
+ time.sleep(0.3)
+ events.append("turn_end")
+
+ _register_turn(host, _turn)
+ assert running.wait(timeout=5.0)
+
+ host.shutdown(reason="sigterm", wait=3.0)
+
+ # ``_finalize_session`` latches on ``session["_finalized"]``, so its single
+ # run has to observe the finished turn or the tail is unpersistable.
+ assert events == ["turn_end", "finalize:compute_host_sigterm"]
+
+
+def test_shutdown_still_finalizes_when_the_drain_deadline_expires(monkeypatch):
+ events: list[str] = []
+ _record_finalize(monkeypatch, events)
+
+ host = ComputeHost(stdout=io.StringIO(), heartbeat_secs=0)
+ release = threading.Event()
+ running = threading.Event()
+
+ def _stuck_turn() -> None:
+ running.set()
+ release.wait(timeout=30.0)
+
+ _register_turn(host, _stuck_turn)
+ assert running.wait(timeout=5.0)
+
+ try:
+ started = time.monotonic()
+ host.shutdown(reason="sigterm", wait=1.0)
+ elapsed = time.monotonic() - started
+ finally:
+ release.set()
+
+ # A turn that outlives the window must not cost the flush entirely: the
+ # supervisor's SIGKILL lands on the same deadline this budget comes from,
+ # so the drain has to stop short and leave the finalize room to run.
+ assert events == ["finalize:compute_host_sigterm"]
+ assert elapsed < 1.0
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 1f255533bd7..e9fbe93ec03 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -124,6 +124,14 @@ def _build_sha() -> str:
return "unknown"
+# Slice of ``ComputeHost.shutdown``'s budget held back for the post-drain
+# finalize. ``HostSupervisor._terminate_pid`` SIGKILLs the host
+# ``_SHUTDOWN_TIMEOUT_SECS`` (10s — the same value as ``shutdown``'s default
+# ``wait``) after SIGTERM, so a drain allowed to consume the whole budget would
+# leave the flush racing that kill and persist nothing at all.
+_FLUSH_RESERVE_SECS = 1.0
+
+
class ComputeHost:
def __init__(
self,
@@ -167,15 +175,34 @@ class ComputeHost:
self._executor.shutdown(wait=False, cancel_futures=True)
def shutdown(self, *, reason: str = "shutdown", wait: float = 10.0) -> None:
+ """Drain in-flight turns, then finalize every session.
+
+ Order matters. ``_finalize_session`` is a one-shot latch: it sets
+ ``session["_finalized"]`` and every later call returns immediately, so
+ the flush gets exactly one chance to snapshot the session. Running it
+ before the drain meant that chance was spent while turns were still
+ producing output — the tail was unpersistable, ``on_session_end`` fired
+ with ``interrupted=True`` against a session that was still running, and
+ the active-session lease was released out from under a live turn. The
+ drain loop exists precisely so that work survives; finalizing first
+ defeated it.
+
+ ``_FLUSH_RESERVE_SECS`` of the budget — but never more than half of it,
+ so a short explicit ``wait`` still gets a real drain — is withheld from
+ the drain, so the flush still runs when in-flight turns outlast the
+ window. ``wait`` itself is unchanged, so this adds no shutdown latency
+ and no new exposure to the supervisor's kill escalation.
+ """
self._closed.set()
- self.flush_all_sessions(reason=reason)
- deadline = time.monotonic() + max(0.0, wait)
+ budget = max(0.0, wait)
+ deadline = time.monotonic() + budget - min(_FLUSH_RESERVE_SECS, budget / 2.0)
while time.monotonic() < deadline:
with self._turn_futures_lock:
pending = [f for f in self._turn_futures if not f.done()]
if not pending:
break
time.sleep(0.05)
+ self.flush_all_sessions(reason=reason)
self._executor.shutdown(wait=False, cancel_futures=True)
def flush_all_sessions(self, *, reason: str = "shutdown") -> None: