Skip to content

Commit f972b9b

Browse files
Kasper JungeRalphify
authored andcommitted
refactor: extract _cleanup_agent helper to deduplicate process shutdown sequence
The streaming and blocking capture paths both performed the same four-step cleanup (kill process, close pipe fds, drain threads, finalize pipes) inline. Extract into _cleanup_agent so the sequence is defined once and both callers stay in sync if it ever needs to change. Co-authored-by: Ralphify <noreply@ralphify.co>
1 parent 01ee104 commit f972b9b

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/ralphify/_agent.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -456,10 +456,7 @@ def _run_agent_streaming(
456456
_kill_process_group(proc)
457457
proc.wait()
458458
finally:
459-
_ensure_process_dead(proc)
460-
_close_pipes(proc)
461-
_drain_readers(stderr_thread, writer_thread)
462-
_finalize_pipes(proc)
459+
_cleanup_agent(proc, stderr_thread, writer_thread)
463460

464461
stdout = "".join(stream.stdout_lines)
465462
stderr = "".join(stderr_lines)
@@ -561,6 +558,26 @@ def _drain_readers(
561558
)
562559

563560

561+
def _cleanup_agent(
562+
proc: subprocess.Popen[Any],
563+
*threads: threading.Thread | None,
564+
) -> None:
565+
"""Perform the full four-step shutdown for a piped agent subprocess.
566+
567+
1. Kill the process if still running and wait for exit.
568+
2. Close parent-side pipe fds to unblock reader threads.
569+
3. Join reader/writer threads to drain remaining output.
570+
4. Finalize Python pipe objects to suppress GC warnings.
571+
572+
Used in ``finally`` blocks of the streaming and blocking capture
573+
paths, which previously duplicated this exact sequence inline.
574+
"""
575+
_ensure_process_dead(proc)
576+
_close_pipes(proc)
577+
_drain_readers(*threads)
578+
_finalize_pipes(proc)
579+
580+
564581
def _run_agent_blocking(
565582
cmd: list[str],
566583
prompt: str,
@@ -681,10 +698,7 @@ def _run_agent_blocking(
681698
_ensure_process_dead(proc)
682699
raise
683700
finally:
684-
_ensure_process_dead(proc)
685-
_close_pipes(proc)
686-
_drain_readers(stdout_thread, stderr_thread, writer_thread)
687-
_finalize_pipes(proc)
701+
_cleanup_agent(proc, stdout_thread, stderr_thread, writer_thread)
688702

689703
stdout = "".join(stdout_lines) if stdout_lines is not None else None
690704
stderr = "".join(stderr_lines) if stderr_lines is not None else None

0 commit comments

Comments
 (0)