"""Moving a session to another daemon, driven by the source daemon. The source's PATH holds a loopback ssh that runs each command locally with the "remote" host's ALBEDO_HOME set to the peer daemon's home (or to a fake older daemon's), so the relay the move stages and runs over ssh reads that daemon's daemon.json and calls it, as it would on vassago. Its login shell reads no profile, so the PATH the ssh sets is the host's. A host named `gone` cannot be reached, and `oldpy` has only Python 3.9 on an unsupported CPU. A test that creates the `stall` switch holds the relay at the first segment it forwards, so the source daemon can be stopped mid-copy. While the `slow` switch exists, the relay starts as late as on a host whose login profile takes seconds. """ import http.server import json import os import shlex import shutil import sqlite3 import tempfile import threading import unittest import urllib.error import urllib.parse from contextlib import closing from pathlib import Path from _transfer_support import ( executable, login_shell, preflight, read_move, remote_bin, settled_move, start_move, wait_for, ) from harness import ( Albedo, Provider, ROOT, exclusive_class, operation_id, peer_daemon, text, ) # How late the relay starts while the `slow` switch exists: past the 2.5 s # the preflight once allowed for it. SLOW_START = 2.75 FAKE_SSH = """#!/bin/sh printf '%s\\n' "$*" >> {log} query= while [ $# -gt 0 ]; do case "$1" in -o) shift 2 ;; -G) query=1; shift ;; -*) shift ;; *) break ;; esac done target=$1 shift [ -n "$query" ] && exit 0 if [ "$target" = gone ]; then echo "ssh: connect to host gone port 22: Connection refused" >&2 exit 255 fi daemon_home=$(cat {hosts}/"$target") run= case "$*" in *albedo_transfer_relay*) [ -e {stall} ] && run="python3 {hold}" [ -e {slow} ] && sleep {slow_start} ;; esac path={path} [ "$target" = oldpy ] && path={oldpy}:$path exec env -i HOME={home} ALBEDO_HOME="$daemon_home" PATH="$path" SHELL={login} $run /bin/sh -c "$*" """ # Runs the relay command, passing its frames through until the first segment # chunk, where it says so and holds until released (or a minute passes). HOLD = """ import os, subprocess, sys, time child = subprocess.Popen(sys.argv[1:], stdin=subprocess.PIPE) source, frames = sys.stdin.buffer, 0 while True: header = source.read(4) if len(header) < 4: break payload = source.read(int.from_bytes(header, "big")) if frames % 2 == 0 and b"/import/segments/" in payload: open({stalled!r}, "w").close() deadline = time.monotonic() + 60 while not os.path.exists({release!r}) and time.monotonic() < deadline: time.sleep(0.1) frames += 1 child.stdin.write(header + payload) child.stdin.flush() child.stdin.close() sys.exit(child.wait()) """ class OldDaemon(http.server.BaseHTTPRequestHandler): """A daemon from before this transfer protocol: it answers protocol 0.""" seen: list[str] = [] def do_GET(self): self.seen.append(f"GET {self.path}") body = json.dumps({"protocol": 0}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_PUT(self): self.seen.append(f"PUT {self.path}") self.send_response(500) self.end_headers() do_POST = do_PUT def log_message(self, format, *args): pass # exclusive: sets the daemon's PATH for the loopback ssh, and one test # restarts the source daemon @exclusive_class class MoveTests(unittest.TestCase): remote_home: Path hosts: Path ssh_log: Path stall: Path slow: Path stalled: Path release: Path def setUp(self): def prepare(app): # The switches and logs are this test's; the ssh on the daemon's # PATH, and the host's home the daemon remembers, stay put for the # class's tests and are rewritten to point here. root = Path(tempfile.mkdtemp(prefix="host-", dir=app.root)) self.remote_home = app.root / "remote-home" self.hosts = root / "hosts" self.ssh_log = root / "ssh.log" self.stall = root / "stall" self.slow = root / "slow" self.stalled = root / "stalled" self.release = root / "release" self.hosts.mkdir() local = app.root / "local-bin" for directory in (self.remote_home, local): directory.mkdir(exist_ok=True) remote = remote_bin(root / "remote-bin") oldpy = root / "oldpy-bin" oldpy.mkdir() executable( oldpy / "uname", '#!/bin/sh\n[ "$1" = -m ] && echo unsupported || echo Linux\n', ) executable(oldpy / "python3", "#!/bin/sh\necho 3.9\n") hold = root / "hold.py" hold.write_text( HOLD.format(stalled=str(self.stalled), release=str(self.release)) ) login = login_shell(local) path = app.daemon.env["PATH"] executable( local / "ssh", FAKE_SSH.format( log=self.ssh_log, hosts=self.hosts, stall=self.stall, slow=self.slow, slow_start=SLOW_START, hold=hold, home=self.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), oldpy=oldpy, login=login, ), ) app.daemon.env["PYTHONPATH"] = str(ROOT / "test/fixtures/uv_release") app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}" self.provider = Provider(lambda _request: text("done")) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.addCleanup(lambda: self.release.touch()) # The target runs the source's profiles unless a test says otherwise. self.target = peer_daemon( "move-target", prepare=lambda peer: shutil.copy( self.app.home / "config.json", peer.home / "config.json" ), ) for host in ("vassago", "oldpy"): (self.hosts / host).write_text(str(self.target.home)) self.destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home)) def session(self): session = self.app.session() self.app.prompt(session, "hello").close() self.app.idle(session) return session def preflight(self, session, target): return preflight(self.app, session, target) def move(self, session, transfer, target): return start_move(self.app, session, transfer, target) def read(self, transfer): return read_move(self.app, transfer) def settled(self, transfer, timeout=90): return settled_move(self.app, transfer, timeout) def exported(self, transfer): path = self.app.home / "albedo.sqlite" with closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) as db: return db.execute( "SELECT count(*) FROM transfers WHERE id=?", (transfer,) ).fetchone()[0] def test_move_keeps_provider_request_counters_local(self): session = self.session() trajectory = operation_id() with sqlite3.connect(self.app.home / "albedo.sqlite") as db: db.execute( "INSERT INTO antigravity_request_state(session,trajectory,next_request) VALUES(?,?,17)", (session, trajectory), ) transfer = operation_id() self.move(session, transfer, f"vassago:{self.destination}") moved = self.settled(transfer) self.assertEqual(moved["state"], "checklist", moved) for home, expected in [ (self.app.home, [(trajectory, 17)]), (self.target.home, []), ]: with closing( sqlite3.connect(f"file:{home / 'albedo.sqlite'}?mode=ro", uri=True) ) as db: self.assertEqual( db.execute( "SELECT trajectory,next_request FROM antigravity_request_state WHERE session=?", (session,), ).fetchall(), expected, ) def test_a_session_moves_and_the_source_copy_refuses_input(self): session = self.session() target = f"vassago:{self.destination}" found = self.preflight(session, target) self.assertTrue(found["available"], found) self.assertIsNone(found["reason"]) self.assertEqual(found["sessions"], [session]) self.assertEqual(found["target_daemon"]["host"], "vassago") self.assertEqual(found["target_daemon"]["home"], str(self.target.home)) self.assertIsInstance(found["target_daemon"]["protocol"], int) transfer = operation_id() started = self.move(session, transfer, target) self.assertEqual(started["session_id"], session) self.assertEqual(started["target"], target) # A repeat answers the same move. self.assertEqual(self.move(session, transfer, target)["id"], transfer) waiting = self.settled(transfer) self.assertEqual(waiting["state"], "checklist", waiting) self.assertEqual(waiting["bindings"], []) with self.app.api(f"/transfers/{transfer}/finish", {}) as response: moved = json.load(response) self.assertEqual(moved["state"], "active", moved) self.assertIsNone(moved["error"]) self.assertEqual(moved["target_session_id"], session) self.assertEqual(moved["target_home"], str(self.target.home)) progress = moved["progress"] self.assertGreater(progress["bytes_total"], 0) self.assertEqual(progress["bytes_done"], progress["bytes_total"]) with self.app.api(f"/sessions/{session}?tail=0") as response: record = json.load(response)["moved"] self.assertEqual(record["host"], "vassago") self.assertEqual(record["workspace"], target) self.assertEqual(record["transfer_id"], transfer) with self.app.api("/sessions") as response: [listed] = [s for s in json.load(response)["items"] if s["id"] == session] self.assertEqual(listed["moved"], record) with self.assertRaises(urllib.error.HTTPError) as refused: self.app.prompt(session, "still here?") self.assertEqual(refused.exception.code, 409) problem = json.load(refused.exception) self.assertEqual(problem["code"], "session_moved") self.assertIn("vassago", problem["detail"]) with self.target.api(f"/sessions/{session}?tail=0") as response: arrived = json.load(response) self.assertEqual(arrived["workspace"], str(self.destination)) self.assertIsNone(arrived["moved"]) # The target's token stays on the target: never in an ssh command line. self.assertNotIn(self.target.connection["token"], self.ssh_log.read_text()) def test_a_target_on_another_protocol_is_refused_before_export(self): OldDaemon.seen = [] server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), OldDaemon) self.addCleanup(server.server_close) threading.Thread(target=server.serve_forever, daemon=True).start() self.addCleanup(server.shutdown) old_home = self.remote_home / "old-albedo" old_home.mkdir() (old_home / "daemon.json").write_text( json.dumps({"port": server.server_address[1], "token": "old-token"}) ) (self.hosts / "vassago").write_text(str(old_home)) session = self.session() target = f"vassago:{self.destination}" found = self.preflight(session, target) self.assertFalse(found["available"], found) self.assertEqual(found["target_daemon"]["protocol"], 0) self.assertIn("vassago runs transfer protocol 0, this daemon", found["reason"]) self.assertIn("update albedo on vassago", found["reason"]) transfer = operation_id() self.move(session, transfer, target) failed = self.settled(transfer) self.assertEqual(failed["state"], "failed", failed) self.assertEqual(failed["error"]["code"], "transfer_protocol") self.assertEqual(failed["error"]["detail"], found["reason"]) self.assertEqual(self.exported(transfer), 0) self.assertFalse((self.app.home / "transfers" / transfer).exists()) self.assertEqual(set(OldDaemon.seen), {"GET /transfers/protocol"}) with self.app.api(f"/sessions/{session}?tail=0") as response: self.assertIsNone(json.load(response)["moved"]) def test_a_host_without_a_supported_runtime_fails_the_move_saying_so(self): session = self.session() transfer = operation_id() self.move(session, transfer, f"oldpy:{self.destination}") failed = self.settled(transfer) self.assertEqual(failed["state"], "failed", failed) self.assertEqual(failed["error"]["code"], "host_unsupported") self.assertEqual( failed["error"]["detail"], "oldpy can't run albedo's kernel: no Albedo uv bootstrap for Linux unsupported", ) self.assertEqual(self.exported(transfer), 0) def test_a_move_resumes_its_copy_after_the_source_daemon_restarts(self): session = self.session() target = f"vassago:{self.destination}" self.stall.touch() transfer = operation_id() self.move(session, transfer, target) wait_for(self.stalled.exists, message="the relay never forwarded a segment") self.assertEqual(self.read(transfer)["state"], "copying") self.stall.unlink() self.app.restart(crash=True) # The restarted daemon reads the ledger, not a client, and goes on. self.assertIn( self.read(transfer)["state"], ("copying", "activating", "checklist") ) moved = self.settled(transfer) self.assertEqual(moved["state"], "checklist", moved) relays = [ line for line in self.ssh_log.read_text().splitlines() if "albedo_transfer_relay" in line ] self.assertGreaterEqual(len(relays), 2) with self.target.api(f"/sessions/{session}?tail=0") as response: self.assertEqual(json.load(response)["id"], session) def target_profiles(self, **models): """Gives the target only these profiles, by name and model.""" source = json.loads((self.app.home / "config.json").read_text()) [profile] = source["providers"].values() providers = { name: {**profile, "model": model} for name, model in models.items() } (self.target.home / "config.json").write_text( json.dumps({"providers": providers, "active": next(iter(providers))}) ) def target_provider(self, session): path = self.target.home / "albedo.sqlite" with closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) as db: return db.execute( "SELECT provider FROM sessions WHERE id=?", (session,) ).fetchone()[0] def test_a_target_without_the_sessions_profile_is_unavailable(self): session = self.session() self.target_profiles(other="other-model") found = self.preflight(session, f"vassago:{self.destination}") self.assertFalse(found["available"], found) profile = self.app.profile reason = f"vassago has no {profile} profile: sign in there first" self.assertEqual(found["reason"], reason) [run] = found["runs_there"] self.assertEqual(run["session_id"], session) self.assertFalse(run["ok"]) self.assertEqual(run["profile"], profile) self.assertEqual(run["model"], "fixture-model") self.assertEqual(run["reason"], reason) self.assertEqual(run["alternatives"], []) self.assertIsInstance(run["name"], str) def test_a_relay_slow_to_start_still_reaches_the_target(self): session = self.session() self.target_profiles(other="other-model") self.slow.touch() found = self.preflight(session, f"vassago:{self.destination}") self.assertFalse(found["available"], found) # The target answered: its missing profile, not a target out of reach. self.assertEqual( found["reason"], f"vassago has no {self.app.profile} profile: sign in there first", ) self.assertEqual(found["code"], "profile_unavailable") def test_a_session_moves_onto_another_profile_that_lists_its_model(self): session = self.session() self.target_profiles(other="fixture-model") target = f"vassago:{self.destination}" found = self.preflight(session, target) self.assertTrue(found["available"], found) [run] = found["runs_there"] self.assertFalse(run["ok"]) self.assertEqual(run["alternatives"], ["other"]) transfer = operation_id() with self.app.api( f"/sessions/{session}/move", {"transfer_id": transfer, "target": target, "profiles": {session: "other"}}, ) as response: self.assertEqual(response.status, 202) # Another mapping under the same id is another move. with self.assertRaises(urllib.error.HTTPError) as conflict: self.app.api( f"/sessions/{session}/move", {"transfer_id": transfer, "target": target, "profiles": {}}, ) self.assertEqual(conflict.exception.code, 409) moved = self.settled(transfer) self.assertEqual(moved["state"], "checklist", moved) self.assertEqual(self.target_provider(session), "other") def test_a_mapping_the_target_cannot_run_fails_the_move(self): session = self.session() target = f"vassago:{self.destination}" with self.assertRaises(urllib.error.HTTPError) as outside: self.app.api( f"/sessions/{session}/move", { "transfer_id": operation_id(), "target": target, "profiles": {operation_id(): "other"}, }, ) self.assertEqual(outside.exception.code, 422) self.assertEqual(json.load(outside.exception)["code"], "profile_unavailable") transfer = operation_id() with self.app.api( f"/sessions/{session}/move", {"transfer_id": transfer, "target": target, "profiles": {session: "nope"}}, ) as response: self.assertEqual(response.status, 202) failed = self.settled(transfer) self.assertEqual(failed["state"], "failed", failed) self.assertEqual(failed["error"]["code"], "profile_unavailable") self.assertIn(session, failed["error"]["detail"]) self.assertIn("vassago has no nope profile", failed["error"]["detail"]) # Nothing went live there. with self.assertRaises(urllib.error.HTTPError) as missing: self.target.api(f"/sessions/{session}?tail=0") self.assertEqual(missing.exception.code, 404) if __name__ == "__main__": unittest.main()