Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions tests/tools/test_process_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import signal
import subprocess
import sys
import threading
import time
import pytest
from unittest.mock import MagicMock, patch
Expand Down Expand Up @@ -266,6 +267,31 @@ def test_wait_returns_when_reader_blocked(self, registry):
except (ProcessLookupError, PermissionError):
pass

def test_wait_wakes_when_session_moves_to_finished(self, registry):
"""wait() should not sleep for the old 1s polling tick after exit."""
s = _make_session(sid="proc_wait_event", output="done")
registry._running[s.id] = s

def finish_later():
time.sleep(0.05)
s.exited = True
s.exit_code = 0
with patch.object(registry, "_write_checkpoint"):
registry._move_to_finished(s)

t = threading.Thread(target=finish_later)
t.start()
start = time.monotonic()
try:
result = registry.wait(s.id, timeout=5)
finally:
t.join(timeout=1)
elapsed = time.monotonic() - start

assert result["status"] == "exited", result
assert result["exit_code"] == 0
assert elapsed < 0.3, f"wait() should wake on completion; took {elapsed:.3f}s"


# =========================================================================
# Read log
Expand Down
9 changes: 8 additions & 1 deletion tools/process_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ class ProcessSession:
_watch_cooldown_until: float = field(default=0.0, repr=False)
_watch_strike_candidate: bool = field(default=False, repr=False)
_watch_consecutive_strikes: int = field(default=0, repr=False)
_completion_event: threading.Event = field(default_factory=threading.Event, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock)
_reader_thread: Optional[threading.Thread] = field(default=None, repr=False)
_pty: Any = field(default=None, repr=False) # ptyprocess handle (when use_pty=True)
Expand Down Expand Up @@ -870,6 +871,7 @@ def _move_to_finished(self, session: ProcessSession):
with self._lock:
was_running = self._running.pop(session.id, None) is not None
self._finished[session.id] = session
session._completion_event.set()
self._write_checkpoint()

# Only enqueue completion notification on the FIRST move. Without
Expand Down Expand Up @@ -1093,6 +1095,8 @@ def wait(self, session_id: str, timeout: int = None) -> dict:

while time.monotonic() < deadline:
session = self._refresh_detached_session(session)
if session is None:
return {"status": "not_found", "error": f"No process with ID {session_id}"}
# Reconcile against real child state — guards against orphaned-
# pipe reader hangs where the reader is blocked but the direct
# child has already exited (issue #17327).
Expand All @@ -1118,7 +1122,10 @@ def wait(self, session_id: str, timeout: int = None) -> dict:
result["timeout_note"] = timeout_note
return result

time.sleep(1)
remaining = deadline - time.monotonic()
if remaining <= 0:
break
session._completion_event.wait(timeout=min(1.0, remaining))

result = {
"status": "timeout",
Expand Down
Loading