Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions tests/tui_gateway/test_compute_host_phase1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import pytest

from tui_gateway import compute_host, server
from tui_gateway.compute_host import ComputeHost, _default_workers
from tui_gateway.host_supervisor import (
MUTATOR_ROUTE_TABLE,
Expand Down Expand Up @@ -132,3 +133,118 @@ class _Agent:
}


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):
wait = 1.0
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=wait)
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 < wait


def test_shutdown_drain_sleep_never_overshoots_the_reserve(monkeypatch):
"""The drain's per-tick sleep must be bounded by the time left to it.

A flat tick overshoots the drain deadline by up to one tick, eating the
reserve held back for ``flush_all_sessions``; for a small ``wait`` that is
the whole reserve. Asserting on the *requested* sleep totals rather than on
wall-clock keeps this deterministic: each sleep is clamped to the remaining
time, so the sum can never exceed the drain budget however the scheduler
interleaves.
"""
wait = 0.34
drain_budget = wait - min(compute_host._FLUSH_RESERVE_SECS, wait / 2.0)

events: list[str] = []
_record_finalize(monkeypatch, events)

slept: list[float] = []
real_sleep = time.sleep

def _recording_sleep(seconds: float) -> None:
slept.append(seconds)
real_sleep(seconds)

monkeypatch.setattr(compute_host.time, "sleep", _recording_sleep)

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:
host.shutdown(reason="sigterm", wait=wait)
finally:
release.set()

assert events == ["finalize:compute_host_sigterm"]
assert slept, "the drain loop should have ticked at least once"
assert sum(slept) <= drain_budget + 1e-6
41 changes: 37 additions & 4 deletions tui_gateway/compute_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -167,15 +175,40 @@ def close(self) -> None:
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)
while time.monotonic() < deadline:
budget = max(0.0, wait)
deadline = time.monotonic() + budget - min(_FLUSH_RESERVE_SECS, budget / 2.0)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
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)
# Bounded by ``remaining``: a flat 0.05s sleep would overshoot the
# deadline and eat into the reserve it is there to protect, which
# for a small ``wait`` can be the whole of it.
time.sleep(min(0.05, remaining))
self.flush_all_sessions(reason=reason)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the drain deadline expires with a future still running, this invokes the one-shot _finalize_session while that turn remains live; shutdown(wait=False) below does not join it. That retains the same persistence/lifecycle race for long turns. Please establish a terminal turn state before finalizing this session, or retain it unfinalized for recovery.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and thanks — the reserve only relocated the race past the deadline rather than removing it. Fixed in 036195851, taking your second option (retain unfinalized for recovery).

The blocker was that _turn_futures was a bare set[Future], so on deadline expiry the drain could tell that something was still running but not whose — leaving flush_all_sessions no choice but to finalize everything. It's now a dict[Future, str] mapping each in-flight turn to its sid, captured at both submit sites (_handle_turn_start, _handle_spike_turn_start) from the sid already in scope. That's the same key space as server._sessions, which _ensure_server_session looks up by sid directly, so no new identity plumbing was needed.

On expiry, shutdown now computes the sids whose futures are still running and passes them to flush_all_sessions(skip_sids=...). Those sessions are left unfinalized — one-shot latch unspent, active_session_lease unreleased — so they stay recoverable. Sessions with no live turn finalize in the same pass exactly as before.

Unchanged: wait semantics, the min(_FLUSH_RESERVE_SECS, budget / 2.0) reserve, and the min(0.05, remaining) sleep bound. No added shutdown latency. The done-callback now pops under _turn_futures_lock rather than relying on set.discard as a bare callback, so entries still can't accumulate.

Tests in tests/tui_gateway/test_compute_host_phase1.py:

  • test_shutdown_retains_a_live_turns_session_when_the_drain_deadline_expires — replaces test_shutdown_still_finalizes_when_the_drain_deadline_expires, which asserted the behaviour you flagged. Two sessions, one with a turn outliving the window: the live one is retained, the idle one still flushes, and the call still returns inside wait.
  • test_shutdown_retains_live_sessions_within_the_stdin_closed_budget — new, pinned to the wait=2.0 stdin_closed path, the tightest budget any caller uses and where the reserve has least room. Also asserts the drain still consumes its full window.
  • test_shutdown_drains_in_flight_turn_before_finalizing_sessions — extended to guard the other direction: a turn that did drain must still finalize, so the skip can't over-reach into completed work. It also now asserts _turn_futures empties, covering the container change.

Both new assertions were verified to fail against the previous flush behaviour and pass with the fix. flush_all_sessions has exactly one call site repo-wide, and all three shutdown callers (orphan, sigterm, stdin_closed) funnel through it, so this covers every path of the concern.

self._executor.shutdown(wait=False, cancel_futures=True)

def flush_all_sessions(self, *, reason: str = "shutdown") -> None:
Expand Down
Loading