"""Check remote relay, streaming jobs and degraded boot without SSH credentials. Malformed frames cannot come from the normal daemon. Feed them into the real remote reader to catch abandoned handshake and call futures on reader exits. """ import asyncio import contextlib import hashlib import inspect import io import json import shlex import shutil import struct import os import sys import tempfile import tarfile import time import subprocess import unittest from pathlib import Path from typing import cast from unittest.mock import patch from urllib.request import build_opener ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "python")) from albedo_api import PythonApi # noqa: E402 import albedo_capture # noqa: E402 import albedo_cells # noqa: E402 from albedo_capture import Capture # noqa: E402 import albedo_ssh # noqa: E402 import albedo_uv # noqa: E402 from albedo_plugins import remote, run as local_run # noqa: E402 sys.path.insert(0, str(ROOT / "test")) import hypothesis_profiles # noqa: E402 import scratch # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 from fixtures.uv_release.uv_release_support import UvRelease # noqa: E402 # Temporary workspaces and homes go under this run's scratch directory, which # is removed at exit. scratch.claim("harness") class FakeHostError(Exception): def __init__(self, code, message): super().__init__(message) self.code, self.message = code, message def fake_ssh_path() -> str: """A loopback ssh: option pairs, target, then run the command locally.""" script = Path(tempfile.mkdtemp(prefix="albedo-fake-ssh-")) / "ssh" script.write_text( "#!/bin/sh\n" "while [ $# -gt 0 ]; do\n" ' case "$1" in\n' " -*) shift 2 ;;\n" " *) break ;;\n" " esac\n" "done\n" "shift\n" 'exec sh -c "$*"\n' ) script.chmod(0o755) return str(script) FAKE_SSH = fake_ssh_path() notices = [] # every jobs.completed notice that reached the daemon async def daemon_host(method, args): if method == "jobs.completed": notices.append(args) return None if method == "work.list": return [ { "id": 1, "title": "from-the-daemon", "notes": "", "status": "open", "parent": None, "session": None, "run": None, "revision": 1, } ] if method == "work.get": raise FakeHostError("missing", f"no work item {args['id']}") return {} class RemotePluginTest(unittest.IsolatedAsyncioTestCase): def setUp(self): remote.configured.clear() remote.connections.clear() notices.clear() self.home = tempfile.mkdtemp(prefix="albedo-remote-home-") self.workspace = tempfile.mkdtemp(prefix="albedo-remote-ws-") os.chdir(self.workspace) self.environment = patch.dict( os.environ, { "HOME": self.home, "PATH": str(Path(FAKE_SSH).parent) + os.pathsep + os.environ["PATH"], "ALBEDO_HOME": os.path.join(self.home, ".albedo"), "ALBEDO_SSH": "loopback", "SHELL": "/bin/sh", }, ) self.enterContext(patch("urllib.request._opener", build_opener(UvRelease()))) self.environment.start() self.addCleanup(self.environment.stop) self.addCleanup(os.chdir, ROOT) async def asyncSetUp(self): self.loop = asyncio.get_running_loop() self.events = [] self.api = PythonApi( self.loop, daemon_host, FakeHostError, Capture, 64 * 1024, self.events.append, lambda close: None, lambda cls: None, 2, ["run", "files", "work", "skills", "remote"], ) self.namespace = {} remote.setup(self.api) self.remote = remote.Remote() async def connect(self, **kwargs): return await self.remote.connect(python=sys.executable, **kwargs) async def test_an_idle_connection_closes_its_channel_and_reader(self): with patch.dict(os.environ, {"ALBEDO_REMOTE_IDLE_SECONDS": "1"}): connection = await self.connect(modules=["run"]) self.addAsyncCleanup(connection.close) assert connection._idle_watch is not None await asyncio.wait_for(asyncio.shield(connection._idle_watch), 10) self.assertTrue(connection.closed) self.assertNotIn(connection, remote.connections) self.assertIsNotNone(connection._process.returncode) with self.assertRaisesRegex(remote.RemoteError, "minutes idle.*connect again"): connection.run("echo", "do not run") async def test_reader_exits_fail_handshake_and_calls(self): frames = [ [], None, {}, {"type": "unknown"}, {"type": "ready", "pid": True, "pgid": None, "leader": None}, {"type": "startup_error"}, {"type": "invoked", "id": "call", "ok": 1, "value": None}, {"type": "invoked", "id": "call", "ok": True}, {"type": "invoked", "id": [], "ok": True, "value": None}, {"type": "invoked", "id": "call", "ok": False, "error": []}, { "type": "invoked", "id": "call", "ok": False, "error": {"ename": "Error", "evalue": "bad", "traceback": [1]}, }, {"type": "invoked", "id": "call", "ok": True, "handle": 1}, {"type": "invoked", "id": "call", "ok": True, "handle": "h", "state": []}, {"type": "mirror", "handle": "h", "exit_code": True}, {"type": "mirror", "handle": "h", "timed_out": 1}, {"type": "introspected", "id": "call", "names": [], "handles": [None]}, {"type": "call", "id": "x", "method": "work.list", "args": []}, {"type": "trace", "id": []}, {"type": "cleanup", "module": None}, {"type": "job_stop", "id": "x", "ok": 1}, ] payloads = [json.dumps(frame).encode() for frame in frames] + [b"{bad json"] wires = [struct.pack(">I", len(data)) + data for data in payloads] wires += [struct.pack(">I", remote.MAX_FRAME + 1), b"", b"\x00\x00"] for wire in wires: with self.subTest(wire=wire[:160]): connection, stream, call = self.reader_connection() stream.feed_data(wire) stream.feed_eof() await self.assert_reader_lost(connection, call) def test_uv_staging_when_ssh_loses_remote_exit_status(self) -> None: # Some SSH routes return success even when the remote test -x failed. ssh = Path(self.home) / "ssh" ssh.write_text(f'#!/bin/sh\n"{FAKE_SSH}" "$@"\nexit 0\n') ssh.chmod(0o755) data = io.BytesIO() payload = b"#!/bin/sh\necho staged-uv\n" with tarfile.open(fileobj=data, mode="w:gz") as archive: member = tarfile.TarInfo("uv-x86_64-unknown-linux-musl/uv") member.size = len(payload) archive.addfile(member, io.BytesIO(payload)) with ( patch.dict( os.environ, {"PATH": self.home + os.pathsep + os.environ["PATH"]} ), patch.object( albedo_uv, "latest_release", side_effect=["1.2.3", "1.2.3", "1.2.4"] ), patch.object(albedo_uv, "_archive", return_value=data.getvalue()) as fetch, ): for release in ("1.2.3", "1.2.3", "1.2.4"): path = albedo_uv.ensure_uv("loopback", "Linux", "x86_64", self.home) self.assertIn(release, Path(path).parts) self.assertEqual(subprocess.check_output([path]), b"staged-uv\n") self.assertEqual(fetch.call_count, 2) def reader_connection(self): connection = remote.RemoteConnection({"host": "loopback"}) stream = asyncio.StreamReader() connection._stdout = stream connection._handshake = self.loop.create_future() call = self.loop.create_future() connection._pending["call"] = call return connection, stream, call async def assert_reader_lost(self, connection, call, *, cancel=False): reader = self.loop.create_task(connection._read_frames()) if cancel: await asyncio.sleep(0) reader.cancel() with self.assertRaises(asyncio.CancelledError): await asyncio.wait_for(reader, 1) else: await asyncio.wait_for(reader, 1) with self.assertRaises(remote.RemoteBootError): await asyncio.wait_for(connection._handshake, 1) with self.assertRaises(remote.RemoteLost): await asyncio.wait_for(call, 1) self.assertTrue(connection.closed) async def test_cancellation_and_unexpected_reader_errors_fail_futures(self): connection, _, call = self.reader_connection() await self.assert_reader_lost(connection, call, cancel=True) connection, stream, call = self.reader_connection() stream.set_exception(RuntimeError("unexpected read failure")) await self.assert_reader_lost(connection, call) async def test_ignored_events_and_extra_fields_allow_a_following_reply(self): connection, stream, call = self.reader_connection() frames = [ {"type": "trace", "id": "cell", "trace": None}, {"type": "done", "id": "cell", "unused": []}, {"type": "cleanup", "module": "plugin", "failures": None}, {"type": "ready", "pid": 1, "pgid": None, "leader": None, "extra": []}, { "type": "invoked", "id": "call", "ok": True, "value": [None, True, {"x": 1}], "extra": [], }, ] for frame in frames: data = json.dumps(frame).encode() stream.feed_data(struct.pack(">I", len(data)) + data) stream.feed_eof() await asyncio.wait_for(connection._read_frames(), 1) self.assertEqual((await call)["value"], [None, True, {"x": 1}]) self.assertEqual((await connection._handshake)["type"], "ready") def test_settings_validate_strings_and_preserve_fallback_and_precedence(self): home = Path(os.environ["ALBEDO_HOME"]) home.mkdir() settings = home / "extensions.json" self.assertEqual(remote._settings(), {}) for field in ("host", "remoteCwd", "python"): for value in (None, 1, True, [], {}): with self.subTest(field=field, value=value): settings.write_text(json.dumps({"remote": {field: value}})) with self.assertRaisesRegex(remote.RemoteError, field): remote._settings() values = { "host": "settings-host", "remoteCwd": "/remote", "python": "python-custom", } settings.write_text(json.dumps({"ssh": {**values, "unrelated": []}})) self.assertEqual(remote._settings(), values) self.assertEqual(remote.resolve()["host"], "loopback") remote.remote.configure("configured:/configured") self.assertEqual(remote.resolve()["host"], "configured") target = remote.resolve("explicit:/path", "/override", "python-explicit") self.assertEqual( target, { "host": "explicit", "remote_cwd": "/override", "python": "python-explicit", }, ) # A remote section saved with only some keys still takes the rest # from ssh, so saving one setting never drops the others. settings.write_text( json.dumps({"remote": {"host": "remote-host"}, "ssh": values}) ) self.assertEqual(remote._settings(), {**values, "host": "remote-host"}) # ssh takes a URI target with a port; its path is the remote cwd self.assertEqual( remote.parse_target("ssh://me@box:2222/srv/app"), {"host": "ssh://me@box:2222", "remote_cwd": "/srv/app"}, ) self.assertEqual( remote.parse_target("ssh://box:2222"), {"host": "ssh://box:2222", "remote_cwd": None}, ) async def test_workspace_python_sees_host_packages_after_locked_packages( self, ) -> None: workspace = Path(self.workspace, "working directory") workspace.mkdir() host_env = workspace / "host venv" subprocess.run( ["uv", "venv", "--python", sys.executable, str(host_env)], check=True, capture_output=True, ) host_python = host_env / "bin/python" site = Path( subprocess.check_output( [ host_python, "-c", "import sysconfig; print(sysconfig.get_path('purelib'))", ], text=True, ).strip() ) (site / "host_only.py").write_text("value = 'from selected venv'\n") (site / "dill.py").write_text("raise RuntimeError('unlocked host dill')\n") extra_site = workspace / "nix packages" / "site-packages" extra_site.mkdir(parents=True) (extra_site / "nix_only.py").write_text( "value = 'from another site directory'\n" ) (site / "nix_paths.pth").write_text( f"import site; site.addsitedir({str(extra_site)!r})\n" ) candidate = "./host venv/bin/python" rem = await self.remote.connect(python=candidate, remote_cwd=str(workspace)) self.addAsyncCleanup(rem.close) self.assertIsNone(rem.degraded) result = await asyncio.to_thread( albedo_ssh.probe, "loopback", candidate=candidate, remote_cwd=str(workspace) ) self.assertEqual(result["state"], "ready", result) job = rem.run( str(result["executable"]), "-c", "import os, dill, host_only, nix_only; " "print(os.getcwd(), host_only.value, nix_only.value, dill.__file__, sep=chr(10))", ) await job cwd, host_value, extra_value, dill_file = job.tail().splitlines() self.assertEqual(Path(cwd), workspace.resolve()) self.assertEqual(host_value, "from selected venv") self.assertEqual(extra_value, "from another site directory") env = Path(str(result["executable"])).parents[1] self.assertTrue(Path(dill_file).is_relative_to(env), dill_file) async def test_ambient_pythonpath_keeps_project_imports_behind_locked_dill( self, ) -> None: ambient = Path(self.workspace, "ambient") package = ambient / "ambient_fixture" package.mkdir(parents=True) (ambient / "dill.py").write_text( "raise RuntimeError('ambient dill was loaded')\n" ) (package / "check.py").write_text( "from pathlib import Path\n" "import sys, dill\n" "def setup(api):\n" " assert Path(dill.__file__).is_relative_to(sys.prefix), dill.__file__\n" " return {}\n" ) with patch.dict(os.environ, PYTHONPATH=str(ambient), UV_LINK_MODE="symlink"): rem = await self.connect(modules=["run", "ambient_fixture.check"]) self.addAsyncCleanup(rem.close) self.assertIsNone(rem.degraded) job = rem.run("printenv", "PYTHONPATH") await job self.assertEqual(job.tail().strip(), str(ambient)) async def test_previous_healthy_interpreter_is_reused_without_uv_lookup( self, ) -> None: workspace = Path(self.workspace) venvs = [workspace / name for name in ("first", "second")] for venv in venvs: subprocess.run( ["uv", "venv", "--python", sys.executable, str(venv)], check=True, capture_output=True, ) candidate = workspace / "selected-python" def select(venv: Path) -> None: candidate.write_text(f'#!/bin/sh\nexec "{venv}/bin/python" "$@"\n') candidate.chmod(0o755) def probe() -> dict[str, object]: return albedo_ssh.probe("loopback", candidate=str(candidate)) select(venvs[0]) first = probe() self.assertEqual(first["state"], "ready", first) select(venvs[1]) second = probe() self.assertEqual(second["state"], "ready", second) self.assertNotEqual(first["executable"], second["executable"]) select(venvs[0]) with patch.object( albedo_uv, "ensure_uv", side_effect=OSError("uv unavailable") ) as ensure: warm = await asyncio.gather(*(asyncio.to_thread(probe) for _ in range(3))) ensure.assert_not_called() for result in warm: self.assertEqual(result["state"], "ready", result) self.assertEqual(result["executable"], first["executable"]) async def test_explicit_missing_python_or_cwd_explains_degraded_boot(self) -> None: cases = [ ( "./missing-python", self.workspace, "requested remote Python './missing-python'", ), ( sys.executable, str(Path(self.workspace, "missing cwd")), "cannot enter remote working directory", ), ] for python, cwd, expected in cases: with self.subTest(python=python, cwd=cwd): with contextlib.redirect_stdout(io.StringIO()) as output: rem = await self.remote.connect(python=python, remote_cwd=cwd) self.addAsyncCleanup(rem.close) self.assertIsNotNone(rem.degraded) self.assertIn(expected, output.getvalue()) def test_failed_repair_reports_uv_error_and_preserves_previous_environment( self, ) -> None: def probe() -> dict[str, object]: return albedo_ssh.probe("loopback", candidate=sys.executable) first = probe() self.assertEqual(first["state"], "ready", first) previous = Path(str(first["executable"])).parents[1] # An interrupted or damaged publication can leave a launcher and a # marker while the locked package itself is unusable. dill = next(previous.glob("lib*/python*/site-packages/dill/__init__.py")) dill.rename(dill.with_suffix(".broken")) executable = shutil.which("uv") if executable is None: raise RuntimeError("loopback SSH tests need the development shell's uv") uv = Path(self.home, "uv-fails-sync") uv.write_text( "#!/bin/sh\n" 'if [ "$1" = sync ]; then echo "fixture wheel unavailable" >&2; exit 42; fi\n' f'exec {shlex.quote(executable)} "$@"\n' ) uv.chmod(0o755) with patch.object(albedo_uv, "ensure_uv", return_value=str(uv)): failed = probe() self.assertEqual(failed["state"], "unsupported", failed) self.assertIn("uv sync exited with status 42", str(failed["detail"])) self.assertIn("fixture wheel unavailable", str(failed["detail"])) repaired = probe() self.assertEqual(repaired["state"], "ready", repaired) self.assertNotEqual(repaired["executable"], first["executable"]) self.assertTrue((previous / "bin/python").exists()) self.assertTrue(dill.with_suffix(".broken").exists()) self.assertEqual(probe()["executable"], repaired["executable"]) async def test_a_host_that_needs_a_sign_in_names_the_command_for_it(self): locked = Path(tempfile.mkdtemp(prefix="albedo-locked-ssh-")) / "ssh" locked.write_text( "#!/bin/sh\necho 'box: Permission denied (publickey).' >&2\nexit 255\n" ) locked.chmod(0o755) with patch.object(remote, "ssh_base", lambda target: [str(locked)]): with self.assertRaises(remote.RemoteError) as raised: await self.connect(host="ssh://box:2222") message = str(raised.exception) self.assertIn("needs a person to sign in", message) self.assertIn("ssh -M -fN -o ControlPath=", message) self.assertIn(" ssh://box:2222`", message) async def test_connect_boots_the_kernel_and_answers_every_tool(self): rem = await self.connect() self.addCleanup(rem.close) self.assertIn("kernel", repr(rem)) self.assertIn("run", (await rem.tools())["names"]) text = await rem.files.read("/etc/hosts") self.assertIsInstance(text, str) # The call is synchronous like local run; the reference settles on await. job = rem.run( sys.executable, "-c", "import time; print('loopback-echo', flush=True); time.sleep(0.2)", ) self.assertIn("pending", repr(job)) self.assertIsNone(job.poll()) self.assertEqual(job.tail(), "") awaited = await job self.assertIs(awaited, job) self.assertEqual(job.poll(), 0) self.assertEqual(job.exit_code, 0) self.assertEqual(job.returncode, 0) # subprocess's spelling answers too self.assertFalse(job.timed_out) self.assertIsNotNone(job.duration) self.assertGreaterEqual(job.duration, 0.2) self.assertEqual(job.tail(), "loopback-echo\n") self.assertIsNotNone(job.id) self.assertIn("tail", dir(job)) # dir() mixes local and mirrored names ending = await job.stop # awaiting an uncalled method runs it self.assertTrue(ending.gone) async def test_a_job_awaited_here_does_not_wake_the_session(self): rem = await self.connect() self.addCleanup(rem.close) # The await crosses a round trip after the call's own reply; over a slow # link a quick job is done by then, and its wake must not reach the # idle session a backgrounded cell's waiting loop leaves behind. send = rem._send async def slow_link(frame): if frame.get("await"): await asyncio.sleep(0.5) await send(frame) with patch.object(rem, "_send", slow_link): job = rem.run("true") await job self.assertEqual(job.exit_code, 0) rem.run("echo", "left-unread") for _ in range(100): if notices: break await asyncio.sleep(0.05) [notice] = notices self.assertEqual( [fact["command"] for fact in notice["jobs"]], ["echo left-unread"] ) # That job lives in the remote kernel's jobs, not the model's. self.assertIn("rem.output.read(", notice["text"]) self.assertNotIn("jobs[", notice["text"]) async def test_an_await_cut_short_leaves_the_job_waking_the_session(self): rem = await self.connect() self.addCleanup(rem.close) # A cell deadline cancels the await here; the interrupt must reach the # remote kernel's await too, or neither side ever sends the wake. job = rem.run(sys.executable, "-c", "import time; time.sleep(1)") for _ in range(100): if job.id is not None: break await asyncio.sleep(0.05) with self.assertRaises(asyncio.TimeoutError): await asyncio.wait_for(job, 0.2) for _ in range(100): if notices: break await asyncio.sleep(0.05) [notice] = notices self.assertEqual([fact["id"] for fact in notice["jobs"]], [job.id]) async def test_a_call_that_fails_unawaited_says_so_on_its_reference(self): rem = await self.connect() self.addCleanup(rem.close) # Left to wake the session, a job that never started must not look # pending forever. job = rem.run("true", timeout=0) for _ in range(100): if "failed" in repr(job): break await asyncio.sleep(0.05) self.assertIn("timeout is in seconds", repr(job)) with self.assertRaisesRegex( remote.RemoteExecutionError, "timeout is in seconds" ): _ = job.id with self.assertRaisesRegex( remote.RemoteExecutionError, "timeout is in seconds" ): await job async def test_a_file_larger_than_a_command_line_writes_and_reads_back(self): rem = await self.connect() self.addCleanup(rem.close) # Past macOS's whole ARG_MAX and Linux's 128 KiB per argument, so the # text must travel on stdin rather than in the remote command. content = "".join(f"line {index} ü\n" for index in range(150_000)) await rem.write("big.lock", content) self.assertEqual(Path(self.workspace, "big.lock").read_text(), content) self.assertEqual(await rem.read("big.lock"), content) async def test_binary_stdin_and_bytes_writes_cross_intact(self): rem = await self.connect() self.addCleanup(rem.close) # Vent 9: bytes arguments crossed as {"__bytes__": b64} markers that # the remote kernel passed through as dicts, so run(..., stdin=b"...") # refused its own stdin and rem.write(path, b"...") called .encode() # on bytes. Every byte value, so the round trip cannot pass by luck. payload = bytes(range(256)) * 64 job = rem.run( sys.executable, "-c", "import hashlib, sys; d = sys.stdin.buffer.read();" "print(len(d), hashlib.sha256(d).hexdigest());" "open('sink.bin', 'wb').write(d)", stdin=payload, ) await job self.assertEqual(job.exit_code, 0) count, digest = job.tail().split() self.assertEqual(int(count), len(payload)) self.assertEqual(digest, hashlib.sha256(payload).hexdigest()) self.assertEqual(Path(self.workspace, "sink.bin").read_bytes(), payload) blob = b"\x00\xff\xfe" + bytes(range(256)) await rem.write("blob.bin", blob) self.assertEqual(Path(self.workspace, "blob.bin").read_bytes(), blob) # A binary read decoded with errors="replace", so a PNG came back as # U+FFFD text and the model fell back to base64 through a capped read. self.assertEqual(await rem.read("blob.bin"), blob) async def test_awaiting_a_non_awaitable_remote_object_keeps_its_reference(self): rem = await self.connect() self.addCleanup(rem.close) # Vent 9: awaiting a call whose result is a live, non-awaitable object # (rem.browser.spawn() is the real case; a spawned Browser) made the # remote kernel `await` the settled object and raise TypeError, with # no handle back, so every retry leaked another process. The remote # jobs dict is the same shape: non-crossable, non-awaitable, retained. job = rem.run("echo", "vent-nine") live = await rem.jobs.copy() self.assertIn("remote reference", repr(live)) found = await live.get(job.id) # a method call on the live object self.assertEqual(found.exit_code, 0) async def test_an_unsettled_reference_argument_resolves_in_order(self): rem = await self.connect() self.addCleanup(rem.close) # Vent 9, the argument form: a reference still in flight crossed as # {"pending": id}, which the remote kernel passed through as a dict, # so run(..., stdin=) saw stdin it refuses. It must # resolve to the producer's own object, like a pending target. producer = rem.run(sys.executable, "-c", "print('pending-arg-fed', flush=True)") consumer = rem.run("cat", stdin=producer) await consumer self.assertEqual(consumer.exit_code, 0) self.assertEqual(consumer.tail().strip(), "pending-arg-fed") async def test_session_tools_relay_to_this_daemon(self): rem = await self.connect() self.addCleanup(rem.close) items = await rem.work.list() self.assertEqual(items[0]["title"], "from-the-daemon") with self.assertRaises(remote.RemoteExecutionError) as raised: await rem.work.get(99) self.assertEqual(raised.exception.ename, "WorkError") async def test_remote_jobs_pipe_and_read_lines_like_local_ones(self): rem = await self.connect() self.addCleanup(rem.close) Path(self.workspace, "sub").mkdir() Path(self.workspace, "sub", "notes.txt").write_text("b\na\nb\n") job = ( await rem.run("cat", "notes.txt", cwd="sub").pipe("sort").pipe("uniq", "-c") ) self.assertEqual(job.exit_code, 0) self.assertEqual(job.tail(lines=1).split(), ["2", "b"]) self.assertEqual((await job.head(lines=1)).split(), ["1", "a"]) async def test_a_whole_read_of_control_bytes_crosses_whole(self): # A whole read is at most 1 MiB, but JSON escapes a control byte to # six: 1 MiB of them was refused as over the remote result ceiling, # though the same read works locally. rem = await self.connect() self.addCleanup(rem.close) job = rem.run( sys.executable, "-c", "import sys; sys.stdout.buffer.write(b'\\x00' * 1048575)", ) await job self.assertEqual(await job.read(), "\x00" * 1048575) async def test_a_job_read_through_text_knows_how_it_ended(self): rem = await self.connect() self.addCleanup(rem.close) job = rem.run(sys.executable, "-c", "print('out'); raise SystemExit(3)") self.assertEqual(await job.text(check=False), "out\n") self.assertEqual(job.exit_code, 3) async def test_a_cells_running_remote_jobs_are_named_for_its_cancel(self): rem = await self.connect() self.addCleanup(rem.close) remote.current_cell = lambda: "cell-1" self.addCleanup(setattr, remote, "current_cell", None) job = rem.run("sleep", "30") for _ in range(100): if remote.cell_jobs("cell-1"): break await asyncio.sleep(0.05) [(_, command)] = remote.cell_jobs("cell-1") self.assertTrue(command.startswith("sleep 30 on "), command) self.assertEqual(remote.cell_jobs("cell-2"), []) await job.stop() async def test_a_kernel_that_cannot_boot_degrades_with_a_warning(self): warning = io.StringIO() with contextlib.redirect_stdout(warning): rem = await self.connect(modules=["definitely-not-a-module"]) self.addCleanup(rem.close) self.assertIn("degraded", repr(rem)) self.assertIn( "for pipes or shell syntax use rem.shell('git log --oneline | rg fix')", warning.getvalue(), ) Path(self.workspace, "sub").mkdir() parity = rem.run( sys.executable, "-c", "import os, sys; print(os.path.basename(os.getcwd()), os.environ['WHO'], sys.stdin.read())", cwd="sub", env={"WHO": "me"}, stdin="fed", ) await parity self.assertEqual(parity.tail(), "sub me fed\n") self.assertEqual(parity.head(lines=1), "sub me fed\n") piped = await rem.shell("printf 'b\\na\\nb\\n' | sort | uniq -c", cwd="sub") self.assertEqual(piped.exit_code, 0) self.assertEqual(piped.tail().split(), ["1", "a", "2", "b"]) self.assertEqual(piped.command, "printf 'b\\na\\nb\\n' | sort | uniq -c") with self.assertRaisesRegex(TypeError, "stdin is text or bytes"): rem.shell("cat", stdin=piped) job = rem.run("echo", "degraded-echo") await job self.assertEqual(job.poll(), 0) self.assertEqual(job.returncode, 0) # subprocess's spelling answers too self.assertIsNotNone(job.duration) self.assertFalse(job.timed_out) self.assertEqual(job.tail(), "degraded-echo\n") with self.assertRaises(AttributeError) as raised: rem.files self.assertIn("degraded to ssh command mode", str(raised.exception)) tools = await rem.tools() self.assertIn("degraded", tools) async def test_stop_remote_job_routes_to_connection_and_resolves(self): rem = await self.connect() self.addCleanup(rem.close) job = rem.run(sys.executable, "-c", "import time; time.sleep(60)") for _ in range(100): if job.id in rem._live: break await asyncio.sleep(0.05) self.assertIn(job.id, rem._live) result = await remote.stop_remote_job(job.id) self.assertEqual(result, {"ok": True}) for _ in range(100): if job.id not in rem._live: break await asyncio.sleep(0.05) self.assertNotIn(job.id, rem._live) async def test_stop_remote_job_unknown_returns_none(self): result = await remote.stop_remote_job("unknown-id") self.assertIsNone(result) async def test_lost_connection_clears_live_jobs_and_connections(self): connection, stream, call = self.reader_connection() remote.connections.append(connection) start = { "type": "job_start", "id": "ghost-job", "command": "python3 /content/run.py", "service": False, } data = json.dumps(start).encode() stream.feed_data(struct.pack(">I", len(data)) + data) stream.feed_eof() await self.assert_reader_lost(connection, call) self.assertEqual(connection._live, {}) self.assertEqual(list(self.remote.connections()), []) job_events = [e for e in self.events if e.get("type") == "jobs"] self.assertEqual([e["live"] for e in job_events], [1, 0]) self.assertEqual(job_events[-1]["items"], []) self.assertIsNone(await remote.stop_remote_job("ghost-job")) for _ in range(100): if notices: break await asyncio.sleep(0.01) self.assertEqual( len(notices), 1, "a job lost with its connection must wake the session" ) [fact] = notices[0]["jobs"] self.assertEqual(fact["id"], "ghost-job") self.assertEqual(fact["summary"], "connection lost, exit status unknown") self.assertEqual(fact["host"], "loopback") self.assertIn("ghost-job", notices[0]["text"]) async def test_a_reference_on_a_lost_connection_says_so_instead_of_running(self): connection, stream, call = self.reader_connection() reference = remote.RemoteRef(connection, handle="h") connection._mirrors["h"] = { "handle": "h", "job": "ghost-job", "exit_code": None, } stream.feed_eof() await self.assert_reader_lost(connection, call) with self.assertRaises(remote.RemoteLost): reference.poll() async def test_stop_remote_job_fallback_job_stops_locally(self): rem = await self.connect(modules=["definitely-not-a-module"]) self.addCleanup(rem.close) job = rem.run(sys.executable, "-c", "import time; time.sleep(60)") self.assertIn(job.id, remote._fallback_jobs) self.assertIn(job.id, remote._fallback_live) result = await remote.stop_remote_job(job.id) self.assertEqual(result, {"ok": True}) self.assertIn( "the remote command may still be running", job.tail(), ) self.assertNotIn(job.id, remote._fallback_jobs) self.assertNotIn(job.id, remote._fallback_live) async def outcome(call, *args, **kwargs) -> tuple[str, object]: """What a job read gave: its value, or the kind of error it refused with.""" try: value = call(*args, **kwargs) if inspect.isawaitable(value): value = await value except Exception as error: # noqa: BLE001 - the refusal is the result # A remote refusal arrives as RemoteExecutionError naming the # remote one. return ("refused", getattr(error, "ename", type(error).__name__)) return ("value", str(value)) def captured(job: object) -> Capture: """A local job's capture, with the spill state the kernel's capture keeps.""" return cast(Capture, getattr(job, "capture")) def end_processes(argv: list[bytes]) -> None: """Kill this user's processes whose command line is exactly `argv`.""" if Path("/proc").is_dir(): for entry in Path("/proc").iterdir(): try: if (entry / "cmdline").read_bytes().split(b"\0")[:-1] == argv: os.kill(int(entry.name), 9) except (OSError, ValueError): pass return # Darwin has no /proc; ps prints the command line space-joined. want = b" ".join(argv) listing = subprocess.run( ["ps", "-axww", "-o", "pid=", "-o", "command="], capture_output=True ) for line in listing.stdout.splitlines(): pid, _, cmd = line.strip().partition(b" ") if cmd == want: with contextlib.suppress(OSError, ValueError): os.kill(int(pid), 9) # Sizes on each side of the preview window, the whole-read and pipe replay # limit, and the in-memory retention, then small ones. EDGES = [0, 1, 65535, 65536, 65537, 1048575, 1048576, 1048577, 2097152 + 10] outputs = st.builds( lambda chunk, size: (chunk * (size // len(chunk) + 1))[:size], st.binary(min_size=1, max_size=40) | st.sampled_from([b"x", b"\x00", b"line \xce\xb1\n"]), st.sampled_from(EDGES) | st.integers(0, 3000), ) reads = st.lists( st.tuples(st.integers(-1, 2097162), st.sampled_from([0, 1, 9, 65536, 65537])), max_size=3, ) previews = st.lists( st.tuples( st.sampled_from(["head", "tail"]), st.integers(0, 70000), st.none() | st.integers(0, 3), ), max_size=3, ) class RemoteJobEquivalenceTest(unittest.TestCase): """A job run on a remote host, or by a connection that fell back to running each command over ssh, reads exactly like the same job run here: the same bytes saved, pages, previews and refusals, exit code, and stage outcomes. The host is this machine through a loopback ssh.""" @classmethod def setUpClass(cls): cls.home = tempfile.mkdtemp(prefix="albedo-remote-home-") cls.workspace = Path(tempfile.mkdtemp(prefix="albedo-remote-ws-")) environment = patch.dict( os.environ, { "HOME": cls.home, "PATH": str(Path(FAKE_SSH).parent) + os.pathsep + os.environ["PATH"], "ALBEDO_HOME": os.path.join(cls.home, ".albedo"), "ALBEDO_SSH": "loopback", "SHELL": "/bin/sh", }, ) environment.start() cls.addClassCleanup(environment.stop) opener = patch("urllib.request._opener", build_opener(UvRelease())) opener.start() cls.addClassCleanup(opener.stop) cls.loop = asyncio.new_event_loop() cls.addClassCleanup(cls.loop.close) # Jobs capture as the kernel's do, spilling past 1 MiB to a directory # the kernel names at boot. previous = albedo_capture.SPILL_DIR albedo_capture.prune_spills(tempfile.mkdtemp(prefix="albedo-spills-")) cls.addClassCleanup(setattr, albedo_capture, "SPILL_DIR", previous) api = PythonApi( cls.loop, daemon_host, FakeHostError, albedo_cells.background_capture, 64 * 1024, lambda _event: None, lambda close: None, lambda cls: None, 2, ["run", "files", "work", "skills", "remote"], ) remote.configured.clear() remote.connections.clear() remote.setup(api) local_run.setup(api) connect = remote.Remote().connect cls.rem = cls.run_async(connect(python=sys.executable)) cls.fallback = cls.run_async( connect(python=sys.executable, modules=["definitely-not-a-module"]) ) assert "degraded" in repr(cls.fallback), repr(cls.fallback) cls.addClassCleanup(lambda: cls.run_async(cls.fallback.close())) cls.addClassCleanup(lambda: cls.run_async(cls.rem.close())) cls.starts = { "local": local_run.run, "remote": cls.rem.run, "fallback": cls.fallback.run, } @classmethod def run_async(cls, coroutine): return cls.loop.run_until_complete(coroutine) def written(self, data: bytes) -> str: path = self.workspace / f"data-{hashlib.sha256(data).hexdigest()}" path.write_bytes(data) return str(path) async def observe(self, job, data, reads, previews, label): await job saved = Path(await job.save(str(self.workspace / f"saved-{label}"))) observed = { "exit": (job.exit_code, job.timed_out), "saved": saved.read_bytes() == data, "whole": await outcome(job.read), } for offset, limit in reads: observed[f"read {offset} {limit}"] = await outcome( job.read, offset=offset, limit=limit ) for kind, n, lines in previews: observed[f"{kind} {n} {lines}"] = await outcome( getattr(job, kind), n, lines=lines ) return observed @settings(max_examples=hypothesis_profiles.cases(15)) @given(outputs, st.integers(0, 255), reads, previews) def test_a_job_reads_the_same_wherever_it_ran(self, data, code, reads, previews): program = ( "import sys; sys.stdout.buffer.write(open(sys.argv[1], 'rb').read());" " sys.stdout.flush(); sys.exit(int(sys.argv[2]))" ) path = self.written(data) async def case(): seen = {} for label, start in self.starts.items(): job = start(sys.executable, "-c", program, path, str(code)) seen[label] = await self.observe(job, data, reads, previews, label) return seen seen = self.run_async(case()) self.assertTrue(seen["local"]["saved"]) self.assertEqual(seen["local"]["exit"], (code, False)) self.assertEqual(seen["remote"], seen["local"]) self.assertEqual(seen["fallback"], seen["local"]) @settings(max_examples=hypothesis_profiles.cases(10)) @given( outputs.filter(lambda data: len(data) <= 1048576), st.integers(0, 3), st.integers(0, 3), st.binary(max_size=200), ) def test_a_pipeline_ends_the_same_wherever_it_ran( self, data, upstream, downstream, stdin ): producer = ( "import sys; sys.stdin.buffer.read();" " sys.stdout.buffer.write(open(sys.argv[1], 'rb').read());" " sys.exit(int(sys.argv[2]))" ) copy = ( "import sys; sys.stdout.buffer.write(sys.stdin.buffer.read());" " sys.exit(int(sys.argv[1]))" ) path = self.written(data) async def case(): seen = {} for label in ("local", "remote"): start = self.starts[label] job = start( sys.executable, "-c", producer, path, str(upstream), stdin=stdin ).pipe(sys.executable, "-c", copy, str(downstream)) observed = await self.observe(job, data, [], [], label) stages = await job.stage_outcomes() observed["stages"] = [ (stage["exit_code"], stage["timed_out"]) for stage in stages ] seen[label] = observed return seen seen = self.run_async(case()) self.assertEqual( seen["local"]["stages"], [(upstream, False), (downstream, False)] ) self.assertTrue(seen["local"]["saved"]) self.assertEqual(seen["remote"], seen["local"]) def test_a_late_pipe_refuses_past_the_replay_limit_wherever_it_ran(self): program = ( 'import sys; sys.stdout.buffer.write(b"x" * (int(sys.argv[1]) - 1)' ' + b"\\xff")' ) count = "import sys; print(len(sys.stdin.buffer.read()))" async def case(start): exact = start(sys.executable, "-c", program, "1048576") await exact piped = await exact.pipe(sys.executable, "-c", count).text() over = start(sys.executable, "-c", program, "1048577") await over try: await over.pipe(sys.executable, "-c", count) except Exception as error: return piped.strip(), str(error) raise AssertionError("a late pipe past the replay limit was accepted") for label in ("local", "remote"): with self.subTest(label): piped, refusal = self.run_async(case(self.starts[label])) self.assertEqual(piped, "1048576") self.assertIn("pipe replay limit", refusal) self.assertIn("job.save(path)", refusal) def test_output_past_the_disk_cap_refuses_the_same_wherever_it_ran(self): # 16 MiB are kept on disk; past that, reads and saves refuse instead # of returning a prefix, and a save leaves its destination alone. program = "import sys; sys.stdout.buffer.write(b'c' * (16777216 + 1))" cap = 16777216 async def case(label): destination = self.workspace / f"kept-{label}" destination.write_bytes(b"keep me") job = self.starts[label](sys.executable, "-c", program) await job seen = { "end": await outcome(job.read, offset=cap + 1, limit=0), "whole": await outcome(job.read), "save": await outcome(job.save, str(destination)), "kept": await outcome(job.read, offset=cap - 10, limit=10), "lost": await outcome(job.read, offset=cap, limit=1), } self.assertEqual(destination.read_bytes(), b"keep me", label) return seen spills = Path(self.home, ".albedo-remote", "output") earlier = set(spills.iterdir()) if spills.is_dir() else set() local = self.run_async(case("local")) self.assertEqual(local["kept"], ("value", "c" * 10)) self.assertEqual(local["whole"], ("refused", "ValueError")) self.assertEqual(local["save"], ("refused", "ValueError")) self.assertEqual(local["lost"], ("refused", "ValueError")) for label in ("remote", "fallback"): with self.subTest(label): self.assertEqual(self.run_async(case(label)), local) # The remote kernel spills in its user's home: a shared /tmp directory # another user owns would refuse every spill. self.assertTrue(spills.is_dir() and set(spills.iterdir()) - earlier, spills) def test_a_pipe_attached_at_once_streams_past_retention(self): # Remotely the pipes ride in the run call's frame and are attached # before the job's output is read, however the frames cross the # channel; a pipe sent on its own could arrive after 1 MiB was read. program = "print('s' * 2000000, end='')" for label in ("local", "remote"): with self.subTest(label): whole = self.workspace / f"whole-{label}.txt" job = ( self.starts[label](sys.executable, "-c", program) .pipe("tee", str(whole)) .pipe("wc", "-c") ) self.assertEqual(self.run_async(job.text()).strip(), "2000000") self.assertEqual(whole.read_bytes(), b"s" * 2000000) def test_a_call_chained_on_a_failed_call_fails_with_it(self): # run() without a program refuses at once; the pipe that rode in its # frame must be answered with a failure, not left waiting an hour. job = self.rem.run().pipe("cat") with self.assertRaises(remote.RemoteError): self.run_async(asyncio.wait_for(job, 10)) def test_a_running_job_and_a_failed_rename_leave_the_destination(self): async def case(label): start = self.starts[label] kept = self.workspace / f"protected-{label}" kept.write_bytes(b"keep me") running = start(sys.executable, "-c", "import time; time.sleep(0.5)") early = await outcome(running.save, str(kept)) await running directory = self.workspace / f"not-a-file-{label}" directory.mkdir() (directory / "keep").write_bytes(b"preserved") before = set(self.workspace.iterdir()) into_directory = await outcome(running.save, str(directory)) self.assertEqual(set(self.workspace.iterdir()), before, label) self.assertEqual((directory / "keep").read_bytes(), b"preserved", label) self.assertEqual(kept.read_bytes(), b"keep me", label) return early, into_directory local = self.run_async(case("local")) self.assertEqual(local[0][0], "refused") self.assertEqual(local[1][0], "refused") self.assertEqual(self.run_async(case("remote")), local) def test_a_fallback_job_keeps_stdin_stderr_and_exit_status(self): program = ( "import hashlib, sys;" " print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest());" " print('stderr preserved', file=sys.stderr); sys.exit(7)" ) for data in ("héllo\n" * 10000, b"binary\x00\xff" * 20000): with self.subTest(kind=type(data).__name__): job = self.fallback.run(sys.executable, "-c", program, stdin=data) self.run_async(asyncio.wait_for(job, 5)) expected = data.encode() if isinstance(data, str) else data text = job.read() self.assertIn(hashlib.sha256(expected).hexdigest(), text) self.assertIn("stderr preserved", text) self.assertEqual((job.exit_code, job.timed_out), (7, False)) def test_a_fallback_deadline_ends_while_a_descendant_holds_output(self): # The loopback ssh's shell leaves its sleep holding stdout after the # client is killed: the deadline reports the client's exit instead of # waiting for an end of output that never comes. job = self.fallback.run("sleep", "8894", timeout=0.2) self.addCleanup(end_processes, [b"sleep", b"8894"]) self.run_async(asyncio.wait_for(job, 5)) self.assertTrue(job.timed_out) self.assertIsNotNone(job.exit_code) self.assertIn("the remote command may still be running", job.tail()) def test_a_spill_reads_live_and_a_damaged_one_refuses(self): # Past 1 MiB a job's output goes to a spill file: pages read it while # the job runs, and a spill that failed, shrank or vanished refuses a # page or a save rather than answer short. async def refuses(call, *args, message, **kwargs): try: value = call(*args, **kwargs) if inspect.isawaitable(value): await value except Exception as error: self.assertIn(message, str(error)) else: self.fail("accepted incomplete output") protected = self.workspace / "protected-spill.bin" protected.write_bytes(b"keep me") release = self.workspace / "release-writer" program = ( "import sys, time; from pathlib import Path;" " sys.stdout.buffer.write(b'x' * 2097152); sys.stdout.flush();" f" [time.sleep(0.01) for _ in iter(lambda: Path({str(release)!r}).exists(), True)];" " sys.stdout.buffer.write(b'end'); sys.stdout.flush()" ) async def live_spill(): live = local_run.run(sys.executable, "-c", program) while live.capture.seen < 2097152: await asyncio.sleep(0.01) self.assertIsNone(live.duration) self.assertEqual(live.read(offset=1048576 - 2, limit=10), "x" * 10) await refuses(live.save, protected, message="await job") spill = captured(live).spill assert spill is not None self.assertEqual(Path(spill).stat().st_mode & 0o077, 0) # The disk fails after a whole prefix reached the spill. with patch.object( captured(live)._spill_file, "write", side_effect=OSError("disk full") ): release.touch() await live self.assertIsNone(captured(live)._spill_file) self.assertEqual(live.tail(3), "end") await refuses( live.read, offset=1048576, limit=1, message="refusing incomplete output" ) await refuses(live.save, protected, message="refusing incomplete output") async def unopened_spill(): blocked = self.workspace / "not-a-spill-directory" blocked.write_text("blocked") with patch.object(albedo_capture, "SPILL_DIR", str(blocked)): failed = local_run.run( sys.executable, "-c", "print('f' * 2097152, end='')" ) await failed self.assertEqual(failed.tail(10), "f" * 10) self.assertIsNone(captured(failed).spill) await refuses( failed.read, offset=1048576, limit=1, message="refusing incomplete output", ) await refuses(failed.save, protected, message="refusing incomplete output") async def damaged_spill(damage): job = local_run.run(sys.executable, "-c", "print('s' * 2097152, end='')") await job path = captured(job).spill assert path is not None spill = Path(path) if damage == "shorten": spill.write_bytes(b"short") else: spill.unlink() message = "incomplete" if damage == "shorten" else "No such file" before = set(self.workspace.iterdir()) await refuses(job.read, offset=1048576, limit=10, message=message) await refuses(job.save, protected, message=message) self.assertEqual(set(self.workspace.iterdir()), before) self.run_async(live_spill()) self.run_async(unopened_spill()) for damage in ("shorten", "remove"): with self.subTest(damage): self.run_async(damaged_spill(damage)) self.assertEqual(protected.read_bytes(), b"keep me") def test_pruning_removes_only_expired_spill_files(self): previous = albedo_capture.SPILL_DIR self.addCleanup(setattr, albedo_capture, "SPILL_DIR", previous) directory = Path(tempfile.mkdtemp(prefix="albedo-prune-")) old, fresh = directory / "old.txt", directory / "fresh.txt" old.write_text("old") fresh.write_text("fresh") nested = directory / "nested" nested.mkdir() (nested / "keep.txt").write_text("keep") stale = time.time() - albedo_capture.SPILL_KEEP - 1 os.utime(old, (stale, stale)) os.utime(nested, (stale, stale)) albedo_capture.prune_spills(str(directory)) self.assertFalse(old.exists()) self.assertEqual(fresh.read_text(), "fresh") self.assertEqual((nested / "keep.txt").read_text(), "keep") if __name__ == "__main__": unittest.main()