"""Starting a daemon on a home another build upgraded. A home records each breaking migration it ran. A build that finds one it does not know refuses the home before it opens storage, and the CLI shows why. An additive difference never blocks a rollback, so an older build still opens a home this checkout upgraded (see robot-docs/migrations.md, "Downgrades"). """ import hashlib import json import shutil import sqlite3 import subprocess import tempfile import time import unittest import urllib.error from contextlib import closing from harness import Provider, alive, operation_id, peer_daemon, text from reference_support import run_current, run_reference PROFILE = "downgrade" FUTURE = "from_a_newer_build" def body(daemon, path, payload=None, *, method=None, headers=None): with daemon.api(path, payload, method=method, headers=headers) as response: return json.load(response) def recorded(database): with closing(sqlite3.connect(database)) as db: return [name for (name,) in db.execute("SELECT name FROM breaking_migrations")] def stop(daemon): """Stops the daemon through its CLI and waits until its process is gone.""" pid = json.loads((daemon.home / "daemon.json").read_text())["pid"] daemon.cli("daemon", "--stop") deadline = time.monotonic() + 15 while alive(pid): if time.monotonic() > deadline: raise AssertionError(f"daemon {pid} outlived daemon --stop") time.sleep(0.05) def published_record(daemon): """The daemon record a ready daemon publishes, if any is there.""" path = daemon.home / "daemon.json" return path.read_text() if path.exists() else None def snapshot(database): """The database file's bytes and logical content, with nothing left in a write-ahead log: what a refused start must leave as it was.""" with closing(sqlite3.connect(database)) as db: dump = list(db.iterdump()) digest = hashlib.sha256(database.read_bytes()).hexdigest() return digest, dump class Downgrades(unittest.TestCase): def setUp(self): self.provider = Provider(lambda _request: text("noted")) self.addCleanup(self.provider.close) def prepare(self, daemon): config = { "providers": { PROFILE: { "extension": "openai", "baseUrl": self.provider.url, "apiKey": "fixture-key", "model": "fixture-model", "protocol": "responses", } }, "active": PROFILE, } (daemon.home / "config.json").write_text(json.dumps(config)) def converse(self, daemon, words): session = operation_id() workspace = tempfile.mkdtemp(prefix="downgrade-workspace-") self.addCleanup(shutil.rmtree, workspace, True) body( daemon, f"/sessions/{session}", {"kind": "new", "workspace": workspace, "provider_profile": PROFILE}, method="PUT", headers={"If-None-Match": "*"}, ) daemon.api( f"/sessions/{session}/inputs/{operation_id()}", {"kind": "message", "text": words}, method="PUT", ).close() deadline = time.monotonic() + 60 while not self.said(daemon, session, "noted"): if time.monotonic() > deadline: raise AssertionError(f"session {session} never answered") time.sleep(0.1) return session def said(self, daemon, session, words): try: items = body(daemon, f"/sessions/{session}/history")["items"] except urllib.error.HTTPError as failure: if failure.code == 503: return False raise return any(words in json.dumps(item) for item in items) def test_an_older_build_opens_a_home_this_build_upgraded(self): daemon = peer_daemon("downgrade-older", self.prepare) session = self.converse(daemon, "kept across the rollback") # This build recorded the breaking migrations it ran; the older one # predates the record, so only the additive part is new to it. self.assertTrue(recorded(daemon.home / "albedo.sqlite")) upgraded_by = body(daemon, "/server")["digest"] daemon.restart(prepare=lambda: run_reference(daemon)) self.assertNotEqual(body(daemon, "/server")["digest"], upgraded_by) self.assertTrue(self.said(daemon, session, "kept across the rollback")) self.assertEqual(body(daemon, f"/sessions/{session}")["id"], session) # The older build writes, and this build opens the home again. written = self.converse(daemon, "written by the older build") daemon.restart(prepare=lambda: run_current(daemon)) self.assertEqual(body(daemon, "/server")["digest"], upgraded_by) self.assertTrue(self.said(daemon, session, "kept across the rollback")) self.assertTrue(self.said(daemon, written, "written by the older build")) def test_a_new_breaking_migration_copies_the_home_first_once(self): daemon = peer_daemon("downgrade-backup", self.prepare) session = self.converse(daemon, "kept in the copy") database = daemon.home / "albedo.sqlite" backups = daemon.home / "backups" backups.mkdir(exist_ok=True) # Copies older builds left, which the oldest go to keep three. for stamp in ("1000000000001", "1000000000002", "1000000000003"): (backups / f"albedo-before-breaking-{stamp}.sqlite").write_bytes(b"") # A copy a crash left unfinished, newest of all: it counts for nothing. unfinished = backups / "albedo-before-breaking-9999999999999.sqlite.partial" unfinished.write_bytes(b"") # As if this build declared a breaking migration the home never ran. pending = sorted(recorded(database))[0] def unrecord(): with closing(sqlite3.connect(database)) as db, db: db.execute("DELETE FROM breaking_migrations WHERE name=?", (pending,)) daemon.restart(prepare=unrecord) copies = sorted(backups.glob("albedo-before-breaking-*.sqlite")) self.assertEqual( [copy.name for copy in copies[:2]], [ "albedo-before-breaking-1000000000002.sqlite", "albedo-before-breaking-1000000000003.sqlite", ], ) self.assertEqual(len(copies), 3) self.assertFalse(unfinished.exists()) self.assertEqual(copies[-1].stat().st_mode & 0o777, 0o600) self.assertEqual(backups.stat().st_mode & 0o777, 0o700) # The copy is the home from before the migration: its session, and # a record without the pending name. with closing(sqlite3.connect(copies[-1])) as copy: self.assertEqual( copy.execute( "SELECT COUNT(*) FROM sessions WHERE id=?", (session,) ).fetchone(), (1,), ) self.assertNotIn( (pending,), copy.execute("SELECT name FROM breaking_migrations") ) self.assertIn(pending, recorded(database)) # Recorded with the copy, so the next start copies nothing. daemon.restart() self.assertEqual(sorted(backups.glob("albedo-before-breaking-*")), copies) def test_a_home_with_an_unknown_breaking_migration_is_refused_unwritten(self): daemon = peer_daemon("downgrade-refused", self.prepare) database = daemon.home / "albedo.sqlite" stop(daemon) with closing(sqlite3.connect(database)) as db, db: db.execute( "INSERT INTO breaking_migrations(name,recorded_at) VALUES(?,0)", (FUTURE,), ) before = snapshot(database) published = published_record(daemon) launch = daemon.start_cli( "daemon", stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) stdout, stderr = launch.communicate(timeout=60) self.assertNotEqual(launch.returncode, 0, stdout + stderr) self.assertIn( f"This home was upgraded by a newer albedo ({FUTURE}); " "update albedo or restore a backup.", stdout + stderr, ) self.assertEqual(snapshot(database), before) # No daemon came up to replace the stopped one's record. self.assertEqual(published_record(daemon), published) if __name__ == "__main__": unittest.main()