"""Mail and agent handles between two daemons after a move. The source daemon's PATH holds a loopback ssh, as in move_test, whose host `vassago` runs commands with ALBEDO_HOME set to the peer daemon's home and a login shell that reads no profile. The `down` switch makes every ssh fail as an unreachable host does (a laptop's peer asleep). There is no ssh the other way: the target never reaches the source, as with a laptop. A child of a session moves to vassago; its parent stays here. Letters go to it through the source's pusher, and its letters to "parent" come back through the long-poll the source keeps open. """ import json import os import shlex import shutil import sqlite3 import subprocess import sys import tempfile import time import unittest from contextlib import closing from pathlib import Path from harness import ( Albedo, Provider, exclusive_class, operation_id, peer_daemon, prompt_text, python, text, ) FAKE_SSH = """#!/bin/sh 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 [ -e {down} ]; then echo "ssh: connect to host $target port 22: Network is unreachable" >&2 exit 255 fi exec env -i HOME={home} ALBEDO_HOME="$(cat {hosts}/"$target")" PATH={path} SHELL={login} /bin/sh -c "$*" """ # The host's login shell. It sources no profile: /etc/profile may replace PATH # (NixOS's does), dropping the fake host's python3 for the system's or none. LOGIN_SHELL = """#!/bin/sh [ "$1" = -l ] && shift exec /bin/sh "$@" """ ELSEWHERE = "which this daemon can't reach; ask from there" def wait_for(predicate, timeout=60, message="condition not met"): """`message` may be a function, read when the wait gives up.""" deadline = time.monotonic() + timeout while time.monotonic() < deadline: result = predicate() if result: return result time.sleep(0.05) raise AssertionError(message() if callable(message) else message) def rows(home, sql, *args): with closing(sqlite3.connect(Path(home) / "albedo.sqlite", timeout=10)) as db: return db.execute(sql, args).fetchall() class Forwarding(unittest.TestCase): """A parent here and its child moved to vassago, with what the tests need to drive both daemons. It has no tests of its own.""" remote_home: Path hosts: Path down: Path def setUp(self): self.addCleanup(self.recover) def prepare(app): root = Path(tempfile.mkdtemp(prefix="host-", dir=app.root)) self.remote_home = app.root / "remote-home" self.hosts = root / "hosts" self.down = root / "down" self.hosts.mkdir() local, remote = app.root / "local-bin", root / "remote-bin" for directory in (self.remote_home, local, remote): directory.mkdir(exist_ok=True) os.symlink(shutil.which("python3") or sys.executable, remote / "python3") login = local / "loginsh" login.write_text(LOGIN_SHELL) login.chmod(0o755) path = app.daemon.env["PATH"] ssh = local / "ssh" ssh.write_text( FAKE_SSH.format( down=self.down, hosts=self.hosts, home=self.remote_home, path=shlex.quote(f"{remote}{os.pathsep}{path}"), login=login, ) ) ssh.chmod(0o755) 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) def target_prepare(peer): # The source's profile, with its key: the moved child runs there. for name in ("config.json", "creds.json"): if (self.app.home / name).exists(): shutil.copy(self.app.home / name, peer.home / name) self.target = peer_daemon("forward-target", prepare=target_prepare) (self.hosts / "vassago").write_text(str(self.target.home)) destination = Path(tempfile.mkdtemp(prefix="dest-", dir=self.remote_home)) self.parent = self.app.session() self.app.prompt(self.parent, "hello").close() self.app.idle(self.parent) self.child = operation_id() self.app.api( f"/sessions/{self.child}", { "kind": "child", "parent_id": self.parent, "address": "kid", "name": "kid", "initial_input_id": operation_id(), "task": "wait for letters", }, method="PUT", headers={"If-None-Match": "*"}, ).close() self.app.idle(self.child, timeout=60) self.app.idle(self.parent, timeout=60) transfer = operation_id() self.app.api( f"/sessions/{self.child}/move", {"transfer_id": transfer, "target": f"vassago:{destination}"}, ).close() move = wait_for( lambda: ( (move := self.read(transfer))["state"] in ("checklist", "active", "failed") and move ), 90, lambda: f"the move never reached its checklist: {self.read(transfer)}", ) self.assertEqual(move["state"], "checklist", move) with self.app.api(f"/transfers/{transfer}/finish", {}) as response: self.assertEqual(json.load(response)["state"], "active") def recover(self): self.down.unlink(missing_ok=True) def read(self, transfer): with self.app.api(f"/transfers/{transfer}") as response: return json.load(response) def execute(self, daemon, session, source): """Runs one python cell in `session` on `daemon` (the app or the target) and answers the cell's tool result as text.""" marker = "forward cell " + operation_id() answer = self.provider.script def dispatch(request): messages = request.get("messages", request.get("input", [])) if messages[-1].get("role") == "user" and prompt_text(request) == marker: return python(source) return answer(request) self.provider.script = dispatch try: daemon.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": marker}, method="PUT", ).close() idle(daemon, session) finally: self.provider.script = answer with daemon.api(f"/sessions/{session}/history") as response: items = json.load(response)["items"] [cell] = [item for item in items if item["kind"] == "tool_result"][-1:] return json.dumps(cell) def arrived(self, home, recipient, body): return rows( home, "SELECT id,sender,sender_name,created_at FROM mail WHERE recipient=? AND body=?", recipient, body, ) def idle(daemon, session, timeout=60): deadline = time.monotonic() + timeout while time.monotonic() < deadline: with daemon.api(f"/sessions/{session}?tail=0") as response: snapshot = json.load(response) if snapshot["status"]["phase"] == "idle" and not snapshot["pending_inputs"]: return snapshot time.sleep(0.05) raise AssertionError(f"session did not settle: {snapshot}") # exclusive: the daemon's PATH holds the loopback ssh, and a test kills its # relays @exclusive_class class MoveForwardTests(Forwarding): def test_a_letter_to_a_moved_session_arrives_there_once(self): cell = self.execute( self.app, self.parent, f"r = await mail.submit({self.child!r}, 'hello over there')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(letter, sender, name, _)] = wait_for( lambda: self.arrived(self.target.home, self.child, "hello over there"), 30, "the letter never reached the target", ) # Its sender lives on the source: kept with where it lives. self.assertIsNone(sender) [(remote, host)] = rows( self.target.home, "SELECT sender,host FROM mail_remote WHERE letter=?", letter, ) self.assertEqual(remote, self.parent) self.assertTrue(host) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_outbox WHERE id=? AND delivered_at IS NOT NULL", letter, ), 30, "the source never settled the letter", ) # A resend (an ack the relay dropped) is taken again without a copy. with self.target.api( "/mail/forwarded", { "origin": "source", "host": host, "letters": [ { "id": letter, "recipient": self.child, "sender": self.parent, "sender_name": name, "kind": "message", "body": "hello over there", } ], }, ) as response: [ack] = json.load(response)["acks"] self.assertEqual(ack, {"id": letter, "error": None, "retry": False}) self.assertEqual( len(self.arrived(self.target.home, self.child, "hello over there")), 1 ) # And the moved child reads it there. idle(self.target, self.child) with self.target.api(f"/sessions/{self.child}/history") as response: self.assertIn("hello over there", response.read().decode()) def test_a_letter_waits_while_the_target_is_out_of_reach(self): self.down.touch() self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'while you were away')", ) wait_for( lambda: rows( self.app.home, "SELECT 1 FROM mail_peers WHERE unreachable_since IS NOT NULL", ), 60, "the source never found the target out of reach", ) cell = self.execute( self.app, self.parent, "print('AWAITING', [a['forwarding'] for a in (await mail.open())['awaiting']])", ) self.assertIn("AWAITING ['queued for vassago, unreachable since ", cell) self.assertEqual( self.arrived(self.target.home, self.child, "while you were away"), [] ) self.down.unlink() wait_for( lambda: self.arrived(self.target.home, self.child, "while you were away"), 60, "the letter never arrived once the target was back", ) def test_a_moved_child_writes_to_its_parent_here(self): self.execute( self.app, self.parent, f"await mail.request({self.child!r}, 'report back')" ) wait_for(lambda: self.arrived(self.target.home, self.child, "report back"), 30) idle(self.target, self.child) cell = self.execute( self.target, self.child, "import time\n" "sent = time.time()\n" "r = await mail.submit('parent', 'reporting from vassago')\n" "print('SENT', sent, r.status, r.forwarding)", ) self.assertIn("SENT", cell) sent = float(cell.split("SENT ", 1)[1].split(" ", 1)[0]) [(_, sender, _, created)] = wait_for( lambda: self.arrived(self.app.home, self.parent, "reporting from vassago"), 30, "the parent never got the letter", ) self.assertEqual(sender, self.child) latency = created / 1000 - sent print(f"collect latency {latency:.3f}s", file=sys.stderr) self.assertLess(latency, 5) # The answer closes the request on the side that opened it. idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell) # The long-poll survives its connection dying: the source opens it # again and the next letter still comes. subprocess.run(["pkill", "-f", "albedo_transfer_relay"], check=False) self.execute( self.target, self.child, "await mail.submit('parent', 'after the drop')" ) wait_for( lambda: self.arrived(self.app.home, self.parent, "after the drop"), 60, "the parent never got the letter sent after the connection dropped", ) def test_handles_reach_a_moved_session_and_not_the_other_way(self): cell = self.execute( self.app, self.parent, f"h = await agents.get({self.child!r})\n" "page = await h.messages()\n" "print('READ', 'wait for letters' in str(page))\n" "print('CANCELLED', await h.cancel())", ) self.assertIn("READ True", cell) self.assertIn("CANCELLED", cell) self.assertNotIn("Error", cell) cell = self.execute( self.target, self.child, "p = await agents.get('parent')\n" "try:\n" " await p.messages()\n" "except AgentsError as error:\n" " print('REFUSED', error)\n" "try:\n" " await p.cancel()\n" "except AgentsError as error:\n" " print('REFUSED', error)", ) self.assertEqual(cell.count(ELSEWHERE), 2, cell) # exclusive: restarts the source daemon with its timers 3600 times faster @exclusive_class class MoveForwardBounceTests(Forwarding): def test_a_letter_bounces_after_a_day_out_of_reach(self): self.down.touch() cell = self.execute( self.app, self.parent, f"r = await mail.request({self.child!r}, 'anyone there?')\n" "print('STATUS', r.status, r.forwarding)", ) self.assertIn("STATUS queued queued for vassago", cell) [(sent,)] = rows( self.app.home, "SELECT created_at FROM mail_outbox WHERE body='anyone there?'", ) # A day is 24 s from here; python's kernel does not live at that # speed, so the request went out first. def faster(app): app.daemon.env["ALBEDO_TEST_TIME_SCALE"] = "3600" app.daemon.env["ALBEDO_SCHEDULE_TICK_MS"] = "60000" self.app.restart(prepare=faster) [(sender, body, bounced)] = wait_for( lambda: rows( self.app.home, "SELECT sender,body,created_at FROM mail WHERE recipient=? AND body LIKE 'not delivered:%'", self.parent, ), 90, lambda: ( "the letter never bounced: " + repr(rows(self.app.home, "SELECT * FROM mail_outbox")) ), ) self.assertGreaterEqual(bounced - sent, 24_000) self.assertEqual(sender, self.child) self.assertIn("vassago was out of reach for a day", body) # The bounce answers the request: the sender awaits nothing. self.app.restart( prepare=lambda app: app.daemon.env.pop("ALBEDO_TEST_TIME_SCALE") ) idle(self.app, self.parent) cell = self.execute( self.app, self.parent, "print('AWAITING', (await mail.open())['awaiting'])" ) self.assertIn("AWAITING []", cell) if __name__ == "__main__": unittest.main()