Files
PaperClipAI/packages/paperclip-runner/test/support/private-host-control.py
T
DottaandClaude Opus 5.5 17ccf6bd2e fix(runner-tests): stop the host-control test wrapper from aborting at exit (#22624)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The paperclip-runner package has a live test that starts the native
runner through a Python wrapper, `test/support/private-host-control.py`
> - The wrapper has a daemon thread that reads frames from stdin. This
thread stays blocked in `readline` after the native child exits
> - At interpreter shutdown, Python must close stdin. The blocked thread
holds the stdin buffer lock, so Python aborts with "could not acquire
lock ... at interpreter shutdown, possibly due to daemon threads"
(SIGABRT)
> - On macOS, each abort opens a "Python quit unexpectedly" dialog. Long
unattended agent sessions run this test many times and leave tens of
dialogs (59 crash reports on one machine)
> - This pull request makes the wrapper exit with `os._exit` after it
flushes its receipts
> - The benefit is a clean wrapper exit and no crash dialogs on
developer machines

## Linked Issues or Issue Description

**What happened?**
Each run of `src/live/runnerd-codex-transport-release-resume.test.ts`
aborts its Python wrapper with SIGABRT at exit. On macOS each abort
opens a crash dialog. The crash reports show `_enter_buffered_busy` in
`_io__Buffered_close` during `_Py_Finalize`, with a `forward` thread
blocked in `_buffered_readline`.

**Expected behavior**
The wrapper exits with code 0 and no crash report after it emits the
`exited` receipt.

**Steps to reproduce**
1. On macOS or Linux, start `python3
test/support/private-host-control.py /bin/sh -c "sleep 0.3"` in a new
process group with stdin as an open pipe.
2. Keep stdin open after the child exits.
3. The wrapper ends with SIGABRT.

**Paperclip version or commit**
master at cb4129a918

## What Changed

- `private-host-control.py`: exit with `os._exit(status)` after `main()`
or `cleanup()`. This skips interpreter finalization. `emit()` already
flushes every receipt, so no output is lost.
- `src/live/private-host-control-wrapper.test.ts`: new regression test.
It starts the wrapper with stdin open and expects exit code 0 and no
signal.

## Verification

- Red: with the old wrapper, the new test fails with `{ code: null,
signal: 'SIGABRT' }`.
- Green: with the fix, `npx vitest run
src/live/private-host-control-wrapper.test.ts` passes 3 of 3 runs.
- A manual reproduction script gave exit -6 before the fix and exit 0 (3
of 3) after it.

## Risks

Low risk. The change affects only a test-support wrapper. `os._exit`
skips `atexit` handlers and buffer flushes. The wrapper registers no
`atexit` handlers, and it flushes stdout after each write.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:11:35 -06:00

134 lines
4.6 KiB
Python

"""Test-only unnamed fd4 handoff; stdout contains bounded control receipts only."""
import fcntl
import json
import os
import signal
import socket
import subprocess
import sys
import threading
LIMIT = 16 * 1024
def process_identity(pid):
if sys.platform.startswith("linux"):
with open(f"/proc/{pid}/stat") as state:
fields = state.read(4096).rsplit(")", 1)[1].split()
return f"{int(fields[2])}:{int(fields[19])}"
if sys.platform == "darwin":
import ctypes
class BsdInfo(ctypes.Structure):
_fields_ = [("prefix", ctypes.c_uint32 * 12),
("comm", ctypes.c_char * 16), ("name", ctypes.c_char * 32),
("suffix", ctypes.c_uint32 * 6),
("seconds", ctypes.c_uint64), ("micros", ctypes.c_uint64)]
info = BsdInfo()
lib = ctypes.CDLL("/usr/lib/libproc.dylib")
# PROC_PIDTBSDINFO includes PGID and microsecond process birth identity.
if lib.proc_pidinfo(pid, 3, 0, ctypes.byref(info), ctypes.sizeof(info)) != ctypes.sizeof(info) or info.prefix[3] != pid:
raise OSError("process identity unavailable")
return f"{info.suffix[1]}:{info.seconds}:{info.micros}"
raise OSError("unsupported test host")
def cleanup():
pid, group = int(sys.argv[2]), int(sys.argv[3])
expected = sys.argv[4]
if pid <= 1 or group <= 1 or not expected.startswith(f"{group}:") or process_identity(pid) != expected:
raise OSError("process ownership changed")
os.killpg(group, signal.SIGKILL)
def emit(value):
sys.stdout.write(json.dumps(value) + "\n")
sys.stdout.flush()
def main():
left, right = socket.socketpair()
# Duplicate above fd4 before closing originals: either original may be fd4.
parent_fd = fcntl.fcntl(left.fileno(), fcntl.F_DUPFD_CLOEXEC, 5)
child_fd = fcntl.fcntl(right.fileno(), fcntl.F_DUPFD_CLOEXEC, 5)
left.close()
right.close()
parent = socket.socket(fileno=parent_fd)
os.dup2(child_fd, 4, inheritable=True)
os.close(child_fd)
try:
child = subprocess.Popen(
sys.argv[1:] + ["--host-control-fd", "4"],
pass_fds=(4,), stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=sys.stderr,
)
finally:
os.close(4)
def close_channel(*_):
try:
parent.shutdown(socket.SHUT_RDWR)
except OSError:
pass
parent.close()
signal.signal(signal.SIGTERM, close_channel)
output = threading.Lock()
try:
identity = process_identity(child.pid)
if not identity.startswith(f"{os.getpgrp()}:"):
raise OSError("unexpected native group")
except Exception:
close_channel()
try:
child.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(os.getpgrp(), signal.SIGKILL)
raise
emit({"fixture": "started", "pid": child.pid, "identity": identity})
def forward():
try:
parent.settimeout(10)
reader = parent.makefile("rb")
while True:
frame = sys.stdin.buffer.readline(LIMIT + 1)
if not frame:
break
if len(frame) > LIMIT or not frame.endswith(b"\n"):
break
with output:
parent.sendall(frame)
reply = reader.readline(LIMIT + 1)
if not reply or len(reply) > LIMIT or not reply.endswith(b"\n"):
break
sys.stdout.buffer.write(reply)
sys.stdout.buffer.flush()
except (OSError, ValueError):
pass
finally:
close_channel()
threading.Thread(target=forward, daemon=True).start()
# Never report completion based on the wrapper's own lifetime.
code = child.wait()
with output:
emit({"fixture": "exited", "code": code if code >= 0 else None,
"signal": signal.Signals(-code).name if code < 0 else None})
if __name__ == "__main__":
status = 0
try:
if len(sys.argv) == 5 and sys.argv[1] == "--cleanup":
cleanup()
else:
main()
except Exception:
# Do not reflect subprocess arguments, ticket frames, or provider output.
status = 1
# The forward thread may still be blocked in stdin.readline holding the
# stdin buffer lock. Normal interpreter shutdown would then abort while
# closing stdin (SIGABRT plus a macOS crash dialog), so skip finalization.
# emit() already flushed every receipt.
os._exit(status)