Skip to content

Commit e669c74

Browse files
test(session): protocol smoke + real-PTY tests (PR-B-4)
Two new test files covering the Phase 1 transport modules, plus two genuine production bugs in PTYTransport surfaced by writing them. tests/test_transport_protocol.py (17 tests) - Event dataclass fields + frozen semantics (5 event types). - TransportEventT union guarded against accidental add/remove — 5 elements exactly (Stopped merged Exited+Cancelled, not 4 not 6). - SessionConfig frozen; field set matches the public contract. - SessionAlreadyActiveError inherits RuntimeError (so generic handlers still catch) but has its own class (so route layer can map to HTTP 409 without swallowing other RuntimeErrors). - AgentSessionTransport Protocol exposes the expected method surface. tests/test_pty_transport.py (15 tests) - _build_child_env unit tests: passes plain keys, strips *_PASSWORD case-insensitively, strips *_SECRET / *_TOKEN suffixes (but not the SAFE_TOKENIZED_VALUE false-positive case), strips the STUDYLOOP_TEST_AGENT_CMD fuzz-injection hatch, deny-list membership sanity check. - Failure paths: missing binary → FileNotFoundError; double-start → RuntimeError("called twice"); reuse-after-end → RuntimeError; end() idempotent on already-ended transport. - Happy path with real pty.fork() + /bin/cat: * start() emits Started first. * send_input(b"hello\n") round-trips via OutputBytes (tolerates the PTY echo mode — cat sees its own echo AND our write). * Child exit (tested with /bin/sh -c "sleep 0.2; exit 0" because /usr/bin/true exits so fast that SIGCHLD can fire before _register_pid gets a chance) emits Stopped(returncode=0, reason="exit") AND events() closes promptly via the queue sentinel. * resize() round-trips TIOCSWINSZ without raising. * cancel() emits Stopped(reason="cancel"), exactly once. - Context manager: async-with calls end() and second end() is a no-op. Production bugs fixed (caught during TDD of the cancel + exit tests) pty.py — SIGCHLD handler registered per-loop, not process-globally The prior code tracked install state with a module-level bool, so once the handler was installed on ANY event loop it claimed registration forever. When the loop was replaced (new FastAPI lifespan, pytest-asyncio function-scope, any lifecycle that recreates the loop), subsequent PTY children's exits were silently lost — SIGCHLD had no handler on the new loop. Fix: remember the loop we registered against and re-install whenever get_running_loop() returns a different object. Single long-running loop (production FastAPI) = one-time install as before; test isolation now works. pty.py — cancel() no longer double-emits Stopped cancel() used to push Stopped(reason="cancel") + None from its own coroutine, AFTER waiting for the grace window. Meanwhile SIGCHLD was already firing inside that grace window, calling on_exit(), which pushed Stopped(reason="exit") + None first. events() consumed "exit" and closed the queue before "cancel" could be delivered — callers got reason="exit" even for user-initiated cancellations. Fix: set a _cancel_requested flag in cancel() BEFORE signalling; on_exit checks the flag and emits the correct reason. cancel() no longer pushes events itself — SIGCHLD is the single source of truth for Stopped. Full suite: 1974 passed (up from 1942 pre-PR-B-4), zero regressions. Ruff clean, format clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent c845a76 commit e669c74

3 files changed

Lines changed: 553 additions & 13 deletions

File tree

‎packages/studyloop/src/studyloop/session/transports/pty.py‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@
8181
# Blocker B6.
8282

8383
_pid_callbacks: dict[int, Callable[[int], None]] = {}
84-
_sigchld_registered = False
84+
_registered_loop: asyncio.AbstractEventLoop | None = None
8585

8686

8787
def _sigchld_reaper() -> None:
@@ -104,13 +104,24 @@ def _sigchld_reaper() -> None:
104104

105105

106106
def _ensure_sigchld_registered() -> None:
107-
"""Register the SIGCHLD handler on the running event loop, once."""
108-
global _sigchld_registered
109-
if _sigchld_registered:
110-
return
107+
"""Install the SIGCHLD handler on the currently-running event loop.
108+
109+
The handler is installed once per event loop — safe for production
110+
(single long-running loop, so this is effectively a one-time install)
111+
and for tests (pytest-asyncio creates a fresh loop per test; without
112+
re-registration, exits from the second test onward are silently lost).
113+
114+
The prior design tracked install state with a single bool, which went
115+
stale as soon as the loop was replaced. We now remember the loop we
116+
registered against and re-register whenever ``get_running_loop()``
117+
returns a different object.
118+
"""
119+
global _registered_loop
111120
loop = asyncio.get_running_loop()
121+
if _registered_loop is loop:
122+
return
112123
loop.add_signal_handler(signal.SIGCHLD, _sigchld_reaper)
113-
_sigchld_registered = True
124+
_registered_loop = loop
114125

115126

116127
def _register_pid(pid: int, callback: Callable[[int], None]) -> None:
@@ -210,6 +221,7 @@ def __init__(
210221
self._build_launch_cmd = build_launch_cmd
211222
self._state: _Running | None = None
212223
self._ended = False
224+
self._cancel_requested = False
213225

214226
# ---- AgentSessionTransport ---------------------------------------------
215227

@@ -266,7 +278,12 @@ def on_exit(wait_status: int) -> None:
266278
returncode = -os.WTERMSIG(wait_status)
267279
else:
268280
returncode = None
269-
self._put_event(Stopped(returncode=returncode, reason="exit"))
281+
# cancel() sets _cancel_requested before signalling; the child's
282+
# exit would otherwise be reported as a natural "exit" from the
283+
# UI's point of view. Flag flip lets the single Stopped event
284+
# carry the right reason without us needing to emit two.
285+
reason = "cancel" if self._cancel_requested else "exit"
286+
self._put_event(Stopped(returncode=returncode, reason=reason))
270287
self._put_event(None) # sentinel ends events()
271288

272289
_register_pid(pid, on_exit)
@@ -320,19 +337,21 @@ async def cancel(self) -> None:
320337
state = self._state
321338
if state is None or self._ended:
322339
return
340+
# Flip the flag BEFORE signalling so the SIGCHLD handler's on_exit
341+
# sees it and emits Stopped(reason="cancel") — not "exit". Double-
342+
# emitting here races the handler and trips callers that expect
343+
# exactly one Stopped before the event stream closes.
344+
self._cancel_requested = True
323345
try:
324346
os.kill(state.pid, signal.SIGTERM)
325347
except ProcessLookupError:
326348
return
327-
# Give the child a moment to exit cleanly. If SIGCHLD fires during
328-
# the wait, the reader task will see the fd close and exit.
349+
# Give the child a moment to handle SIGTERM. If it's still alive
350+
# after the grace window, escalate to SIGKILL. Either way the
351+
# SIGCHLD reaper emits the single Stopped event when it fires.
329352
await asyncio.sleep(_SIGKILL_GRACE_S)
330353
with contextlib.suppress(ProcessLookupError):
331354
os.kill(state.pid, signal.SIGKILL)
332-
# Downgrade the Stopped reason emitted by on_exit from "exit" to
333-
# "cancel" — but only if nothing has been emitted yet.
334-
self._put_event(Stopped(returncode=None, reason="cancel"))
335-
self._put_event(None)
336355

337356
async def end(self) -> None:
338357
if self._ended:

0 commit comments

Comments
 (0)