Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250#!/bin/bash# Smoke tests for pyrepl, against a throwaway daemon that does not touch your# real sessions. Usage: ./test_pyrepl.sh (exit status = number of failures)HERE=$(cd "$(dirname "$0")" && pwd)TMP=$(mktemp -d)export XDG_RUNTIME_DIR=$TMP/run XDG_STATE_HOME=$TMP/state XDG_CONFIG_HOME=$TMP/configmkdir -m 700 "$XDG_RUNTIME_DIR"P() { ${PYTHON:-} "$HERE/pyrepl" "$@"; } # PYTHON=/path/to/python3.X: run the client (and daemon) on ittrap 'P stop >/dev/null 2>&1; rm -rf "$TMP"' EXITfails=0
check() { # check NAME EXPECTED-REGEX ACTUAL if grep -qE -- "$2" <<<"$3"; then echo "ok $1" else echo "FAIL $1"; echo " expected /$2/, got:"; sed 's/^/ | /' <<<"${3:0:600}" fails=$((fails + 1)) fi}
check "expression value" "Out\[1\]: 42" "$(P exec t '6 * 7')"check "state persists" "Out\[[0-9]+\]: 43" "$(P exec t 'x = 43' >/dev/null; P exec t 'x')"check "print captured" "^hello$" "$(P exec t 'print("hello")')"check "subprocess output" "from-subprocess" "$(P exec t 'import subprocess; subprocess.run(["echo", "from-subprocess"]); None')"check "traceback, own frames hidden" "^Traceback.*" "$(P exec t '1/0' | head -1)"check "no worker.py frames" "^none$" "$(P exec t '1/0' | grep -c worker.py | sed 's/^0$/none/')"check "sys.exit survives" "SystemExit" "$(P exec t 'import sys; sys.exit(3)')"check "stdout.buffer" "^é$" "$(P exec t 'import sys; sys.stdout.buffer.write("é\n".encode()); None')"check "utf-8 across reads" "^0$" "$(P exec t 'import os; os.write(1, ("a" + "é" * 100000).encode()); None' | grep -o '�' | wc -l)"
start=$(date +%s)out=$(P exec t 'for i in range(200000): print(i)' -t 120 | tail -2)check "200k prints" "199999" "$out"check "200k prints < 30s" "^ok$" "$( (( $(date +%s) - start < 30 )) && echo ok)"
check "timeout returns" "still running" "$(P exec t 'import time; time.sleep(3); "slept"' -t 0.5)"check "busy session" "still running cell" "$(P exec t '1')"check "wait collects" "slept" "$(P wait t -t 10)"check "interrupt" "KeyboardInterrupt" "$(P exec t 'time.sleep(60)' -t 0.5 >/dev/null; P interrupt t)"check "alive after interrupt" "Out\[[0-9]+\]: 'alive'" "$(P exec t '"alive"')"
for _ in $(seq 10); do P exec t 'sum(range(1000))' -t 5 >/dev/null & P interrupt t >/dev/null; wait; donecheck "interrupt races" "'still alive'" "$(P exec t '"still alive"')"
check "forked children printing" "'forks ok'" "$(P exec t 'import osfor k in range(10): if os.fork() == 0: for j in range(50): print(str(k) * 5000) os._exit(0)for k in range(10): os.wait()"forks ok"' -t 20 | tail -1)"check "child falling out of a cell" "'parent'" "$(P exec t 'pid = os.fork()who = "child" if pid == 0 else "parent"if pid: os.waitpid(pid, 0)who' -t 10 >/dev/null; P exec t 'who')"
P exec d 'import os, time; time.sleep(1); os.kill(os.getpid(), 9)' -t 0.2 >/dev/null; sleep 2check "wait on dead session" "killed by SIGKILL" "$(P wait d)"check "death reported on reuse" "Nothing was carried over" "$(P exec d '1')"check "kill" "killed" "$(P kill d)"check "sessions" "^t pid" "$(P sessions)"check "bad name" "session names are" "$(P exec 'a/b' '1')"check "state dir private" "^drwx------" "$(ls -ld "$XDG_STATE_HOME/pyrepl")"
py36=/usr/bin/python3.6[ -x $py36 ] || py36=/usr/bin/python3check "worker on $($py36 -V 2>&1)" "Out\[1\]: 42" "$(P exec old '6 * 7' --python $py36)"
mcp=$(printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"exec","arguments":{"session":"ma","code":"import time; time.sleep(2); 1"}}}' \ '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"exec","arguments":{"session":"mb","code":"2"}}}' \ | (cat; sleep 3) | P mcp)check "mcp tools/list" '"name": "interrupt"' "$mcp"check "mcp parallel calls" '"id": 4.*' "$(grep -n '"id": [34]' <<<"$mcp" | head -1)"
check "malformed mcp line" '"id": 2, "result"' "$(printf '%s\n' '[1,2]' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":null}' \ '{"jsonrpc":"2.0","id":2,"method":"ping"}' | P mcp)"
# Each of these used to kill or wedge a session.check "print from __del__" "'gc ok'" "$(P exec g 'class C: def __init__(self): self.me = self def __del__(self): print("bye")for i in range(3000): C(); print(i)"gc ok"' -t 20 | tail -1)"check "thread churning globals" "'churn ok'" "$(P exec h 'import threading, timestop = Falsedef churn(): i = 0 while not stop: globals()["tmp%d" % (i % 50)] = i; globals().pop("tmp%d" % ((i + 25) % 50), None); i += 1threading.Thread(target=churn, daemon=True).start()for k in range(500): globals()["big%d" % k] = k' >/dev/null for _ in $(seq 15); do P exec h '1' >/dev/null; done; P exec h 'stop = True; "churn ok"')"check "surrogate in error" "ValueError" "$(P exec u 'raise ValueError("caf" + chr(0xdce9))')"check "surrogate in code" "Out\[[0-9]+\]: 2" "$(P exec u 's = "\udce9"' >/dev/null; P exec u '1 + 1')"check "surrogate cell reaches the session" "^Traceback" "$(P exec u "$(printf 'x = "\xed\xb3\xa9"')")" # python's own error, not the pipe'scheck "realtime signal death" "killed by signal|SIGRTMIN|SIGRT" \ "$(P exec r 'import os, signal; os.kill(os.getpid(), signal.SIGRTMIN + 2)' -t 5)"check "death with a forked child alive" "ended|killed by SIGKILL" "$(P exec f 'import os, timeif os.fork() == 0: time.sleep(30); os._exit(0)time.sleep(0.5); os.kill(os.getpid(), 9)' -t 5)"check "-t 0 returns at once" "still running" "$(P exec z 'import time; time.sleep(2)' -t 0)"P wait z >/dev/nullP exec z 'import os; fds = len(os.listdir("/proc/%d/fd" % os.getppid()))' -t 5 >/dev/nullfor _ in $(seq 5); do P exec "bad$RANDOM" '1' --python /nonexistent/python >/dev/null; donecheck "no fd leak on failed create" "Out\[[0-9]+\]: True" \ "$(P exec z 'len(os.listdir("/proc/%d/fd" % os.getppid())) <= fds + 1')"
# The toolkit and the memory tool.check "tk preloaded" "^\+b$" "$(P exec k 'diff("a\n", "b\n", text=True)' | grep '^+b')"check "tk results print as text" ": created /" "$(P exec k 'write("'"$TMP"'/w.txt", "x\n")')"check "grep without rg" "tk.py:[0-9]+:def grep" "$(P exec k 'import shutil; shutil.which = lambda *a, **k: None; grep(r"^def grep\(", "'"$HERE"'", glob="*.py")')"check "sudo: no default askpass" "no askpass program" "$(env -u SUDO_ASKPASS "$HERE/pyrepl" exec na 'tk._askpass("x")' 2>&1)"M() { (cd "$TMP" && printf '%s\n' "{\"jsonrpc\":\"2.0\",\"id\":$1,\"method\":\"tools/call\",\"params\":{\"name\":\"memory\",\"arguments\":$2}}" \ | CLAUDE_CONFIG_DIR=$TMP/claude P mcp); } # calls in one stream run in parallel: one eachG=$TMP/g; mkdir -p $G/sub $G/.hid/in $G/node_modulesfor f in a.py b.txt sub/c.py .d.py .hid/in/h.py node_modules/n.py; do echo needle > $G/$f; doneGR() { P exec k 'import shutil; shutil.which = lambda *a, **k: None[f[len("'$G'/"):] for f in sorted(grep("needle", '"$1"', files=True))]'; } # GNU grep path, rg or notcheck "grep glob" ": \['b\.txt'\]" "$(GR '"'$G'", glob="*.txt"')"check "grep type and !globs" ": \['sub/c\.py'\]" "$(GR '"'$G'", type="py", glob=["!a.py", "!node_modules"]')"check "grep under a hidden dir" ": \['\.hid/in/h\.py'\]" "$(GR '"'$G'/.hid/in"')"check "grep a subdir" ": \['sub/c\.py'\]" "$(GR '"'$G'/sub"')"check "grep a list of paths" ": \['b\.txt', 'sub/c\.py'\]" "$(GR '["'$G'/sub", "'$G'/b.txt"]')"mem=$(M 1 '{"op":"write","name":"fact","content":"---\nname: fact\ndescription: d\n---\nbody\n","index":"a hook"}' M 2 '{"op":"list"}'; M 3 '{"op":"read","name":"../x"}')check "memory write + index" "fact.md\) — a hook" "$(cat "$TMP"/claude/projects/*/memory/MEMORY.md)"check "memory list" "fact.md d" "$(grep '"id": 2' <<<"$mem")"par=$(cd "$TMP" && for k in $(seq 20); do printf '{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"memory","arguments":{"op":"write","name":"p%d","content":"x","index":"h%d"}}}\n' $k $k $kdone | CLAUDE_CONFIG_DIR=$TMP/claude P mcp | grep -c '"isError": false')check "parallel memory writes" "^20 21$" "$par $(cat "$TMP"/claude/projects/*/memory/MEMORY.md | wc -l)"check "memory refuses paths" '"id": 3.*no paths.*"isError": true' "$(grep '"id": 3' <<<"$mem")"
# read is raw, readn numbered; files between sessions (one of them on python 3.6).printf 'a\r\nb\nc\n' > "$TMP/r.txt"check "read is raw" "Out\[[0-9]+\]: True" "$(P exec k 'read("'"$TMP"'/r.txt") == "a\r\nb\nc\n" and read("'"$TMP"'/r.txt", 2, 1) == "b\n"')"check "readn numbers lines" "^ 2 b$" "$(P exec k 'readn("'"$TMP"'/r.txt")')"printf 'x%.0s' $(seq 3000) > "$TMP/src.bin"; chmod 750 "$TMP/src.bin"check "push/pull with python 3.6" "^ok True True True 0o750$" "$(P exec k 'import os; o = session("old")o.push(b"hi\0there", "'"$TMP"'/sub/b.bin"); o.push("'"$TMP"'/src.bin", "'"$TMP"'/dst.bin")tk._CHUNK = 1000 # several chunks each wayo.pull("'"$TMP"'/dst.bin", "'"$TMP"'/back.bin")print("ok", o.pull("'"$TMP"'/sub/b.bin") == b"hi\0there", read("'"$TMP"'/back.bin") == read("'"$TMP"'/src.bin"), not glob("*.pyrepl-part", "'"$TMP"'"), oct(os.stat("'"$TMP"'/back.bin").st_mode & 0o777))')"check "pull a directory" "IsADirectoryError.*tar it" "$(P exec k 'session("old").pull("'"$TMP"'")')"printf 'secret\n' > "$TMP/sec"; chmod 600 "$TMP/sec"; ln -s sec "$TMP/sec.link"check "overwrite keeps mode and link; pull makes dirs" "^ok 0o600 True b'new' 0o640$" "$(P exec k 'o = session("old")o.push(b"new", "'"$TMP"'/sec.link"); os.chmod("'"$TMP"'/src.bin", 0o640)o.pull("'"$TMP"'/src.bin", "'"$TMP"'/deep/er/x.bin")print("ok", oct(os.stat("'"$TMP"'/sec").st_mode & 0o777), os.path.islink("'"$TMP"'/sec.link"), open("'"$TMP"'/sec", "rb").read(), oct(os.stat("'"$TMP"'/deep/er/x.bin").st_mode & 0o777))')"check "pull with tk rebound over there" "Out\[[0-9]+\]: b'new'" "$(P exec old 'tk = None' >/dev/null; P exec k 'session("old").pull("'"$TMP"'/sec")')"check "lines split on \\n only" "Out\[[0-9]+\]: True" "$(printf 'a\fb\nc\n' > "$TMP/ff"; P exec k 'read("'"$TMP"'/ff", 2, 1) == "c\n"')"check "sudo(host=) refused" "use a root session" "$(P exec k 'sudo("id", host="h")')"# pyrepl's modules: `from pyrepl import NAME`, the user's folder first, never preloaded.MD=$XDG_CONFIG_HOME/pyrepl/modules; mkdir -p "$MD"printf '"""Greets people."""\nfrom tk import sh\ndef hi(n): return "hi " + n\n' > "$MD/greet.py"check "module not preloaded" "NameError" "$(P exec xm 'greet')"check "module imports" "'hi bo'" "$(P exec xm 'from pyrepl import greet; greet.hi("bo")')"printf '"""Greets people."""\ndef hi(n): return "hello " + n\n' > "$MD/greet.py"check "module reload" "'hello bo'" "$(P exec xm 'import importlib; importlib.reload(greet).hi("bo")')"check "module missing" "ModuleNotFoundError" "$(P exec xm 'import pyrepl.nosuchmod_x')"check "bare names are not modules" "ModuleNotFoundError" "$(P exec xm 'import greet')"check "module function to another session" "'hello cy'" "$(P exec xm 'session("xm2").call(greet.hi, "cy")')"check "module on $($py36 -V 2>&1)" "'hello py'" "$(P exec old 'from pyrepl import greet; greet.hi("py")')"check "a pyrepl/ dir in cwd can't shadow it" "'hi from the real one'" "$(mkdir -p "$TMP/cwd/pyrepl"; printf 'raise SystemExit("shadow")\n' > "$TMP/cwd/pyrepl/__init__.py" printf '"""Greets people."""\ndef hi(n): return "hi from the real one"\n' > "$MD/greet.py" P exec xm3 'import os; os.chdir("'"$TMP"'/cwd"); import sys; sys.path.insert(0, ""); from pyrepl import greet; greet.hi(1)')"check "a user module shadows a shipped one" "'mine'" "$(printf 'def who(): return "mine"\n' > "$MD/git.py"; P exec xm4 'from pyrepl import git; git.who()'; rm "$MD/git.py")"check "modules() lists both" "git .*greet .*Greets.*systemd" "$(P exec xm 'modules()' | tr '\n' ' ')"check "git module" "Out\[[0-9]+\]: True" "$(P exec gm 'from pyrepl import git; import subprocess[c.sha for c in git.at("'"$HERE"'").log(20)] == subprocess.run(["git", "-C", "'"$HERE"'", "log", "--format=%H", "-n", "20"], stdout=subprocess.PIPE, universal_newlines=True).stdout.split()')"check "git module is callable" "git version" "$(P exec gm 'git("--version")')"check "systemd module" "sshd.service" "$(P exec sm 'from pyrepl import systemd; systemd.props("sshd").Id')"check "systemd refuses system writes as a user" "needs root" "$(P exec sm 'systemd.restart("sshd")')"check "mcp instructions list them" "greet: Greets people" \ "$(printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | P mcp)"
# Swap: idle sessions go to disk and come back on the next exec.mkdir -p "$TMP/swapcwd"P exec sw 'import os, socket, threading, timeos.chdir("'"$TMP"'/swapcwd")data = {"a": [1, 2, 3]}def twice(v): return helper(v) * 2def helper(v): return v + 1sock = socket.socket()threading.Thread(target=time.sleep, args=(30,), name="sleeper", daemon=True).start()' >/dev/nullP exec sw 'time.sleep(0.3); print("unread output"); "unread result"' -t 0 >/dev/null; sleep 1check "swap on request" "Swapped to disk.*lost: sock" "$(P swap sw)"check "swapped worker is gone" "SWAPPED to disk" "$(P sessions)"check "swapped, not live" "swapped to disk.*brings it back" "$(P wait sw)"out=$(P exec sw 'print(data, twice(1), os.getcwd()); "sock" in globals()')check "restore note" "Restored session 'sw'.*Lost.*sock \(socket\).*sleeper.*unread result.*nobody had read" "$out"check "restore hands over unread output" "^unread output" "$out"check "restore brings it all back" "^\{'a': \[1, 2, 3\]\} 4 $TMP/swapcwd$" "$(grep "^{" <<<"$out")"check "restore drops the unpicklable" "Out\[[0-9]+\]: False" "$out"check "swap file gone after restore" "^0$" "$(ls "$XDG_STATE_HOME"/pyrepl/*/swap/ | wc -l)"check "swap refuses a busy bg job" "bg job" "$(P exec sw 'j = bg("sleep 30")' >/dev/null; P swap sw; P exec sw 'j.kill()' >/dev/null)"P swap sw >/dev/nullcheck "kill deletes a swap" "Deleted its swap" "$(P kill sw)"check "killed swap is gone" "no live session" "$(P wait sw)"P exec sw2 'x = 5' >/dev/null; P swap sw2 >/dev/nullcheck "swapped name keeps its host" "swapped out and ran on this host" "$(P exec sw2 '1' --host nosuchhost)"SW=$(echo "$XDG_STATE_HOME"/pyrepl/*/swap)check "swap files are 0600, dir 0700" "^600 600 700$" "$(stat -c %a "$SW/sw2.blob" "$SW/sw2.json" "$SW" | xargs)"P exec sw4 'z = 1' >/dev/null; P swap sw4 >/dev/null; chmod 644 "$SW/sw4.blob"check "a loosened swap is not loaded" "not a private file.*new, empty session" "$(P exec sw4 '1' | tr '\n' ' ')"check "nothing of it loaded" "NameError" "$(P exec sw4 'z')"P kill sw4 >/dev/null; P exec sw4 'z = 1' >/dev/null; P swap sw4 >/dev/nullmv "$SW/sw4.json" "$TMP/sw4.json"; ln -s "$TMP/sw4.json" "$SW/sw4.json"check "a symlinked swap is not even listed" "^0$" "$(P sessions | grep -c sw4)"rm "$SW/sw4.json" "$SW/sw4.blob"P exec sw5 'w = 1' >/dev/null; P exec sw5 'import time; time.sleep(0.3); print("kept"); j = bg("sleep 30"); "res"' -t 0 >/dev/null; sleep 1check "a failed swap keeps unread work" "bg job.*kept.*Out\[[0-9]+\]: 'res'" "$( { P swap sw5; P wait sw5; } | tr '\n' ' ')"P exec sw5 'j.kill()' >/dev/null# The sweep, with swap times shrunk in the config (read at each sweep).mkdir -p "$XDG_CONFIG_HOME/pyrepl"echo '{"swap_after_hours": 0.0005, "swap_keep_days": 1}' > "$XDG_CONFIG_HOME/pyrepl/config.json"P exec sw3 'y = 7' >/dev/null; sleep 2.5check "sweep swaps the idle" "swapped .*sw3" "$(P swap)"check "swept session restores" "Restored.*Out\[[0-9]+\]: 7" "$(P exec sw3 'y' | tr '\n' ' ')"echo '{"swap_after_hours": 0, "swap_keep_days": 0.00002}' > "$XDG_CONFIG_HOME/pyrepl/config.json"sleep 2; P swap >/dev/nullcheck "expired swap deleted" "deleted unrestored.*Nothing was carried over" "$(P exec sw2 '1')"rm "$XDG_CONFIG_HOME/pyrepl/config.json"# A graceful stop swaps every session out; the next daemon brings them back.P exec st1 'kept = [1, 2]' >/dev/null; P exec st2 'import time; time.sleep(60)' -t 0 >/dev/nullout=$(P stop)check "stop swaps sessions" "swapped to disk: .*st1" "$out"check "stop names the lost" "lost\) st2: busy" "$out"check "stop returns when gone" "^stopped$" "$(tail -1 <<<"$out")"check "next daemon restores" "Restored session 'st1'.*Out\[[0-9]+\]: \[1, 2\]" "$(P exec st1 'kept' | tr '\n' ' ')"check "the busy one is a death" "pyrepld stopped.*Nothing was carried over" "$(P exec st2 '1')"P exec st3 'x = 1' >/dev/null# This test's daemon only, by the pid in its own log: never pkill by path,# that matches the user's real pyrepld too.dpid=$(sed -n 's/.*pyrepld listening on .* pid \([0-9]*\)$/\1/p' "$XDG_RUNTIME_DIR/pyrepl/pyrepld.log" | tail -1)[ -n "$dpid" ] && grep -q "XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR" "/proc/$dpid/environ" 2>/dev/null \ && kill -TERM "$dpid"; sleep 3check "SIGTERM swaps too" "Restored session 'st3'.*Out\[[0-9]+\]: 1" "$(P exec st3 'x' | tr '\n' ' ')"
echo "$fails failure(s)"exit $fails