From 54f591507c823998dcc3e0287c7666359aab034c Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sun, 15 Nov 2026 21:33:46 -0500 Subject: [PATCH] test(e2e): move sessions both ways between this daemon and a pinned older build Two recent changes nearly broke moves between daemons of different builds, and only review caught them: the tests compared column sets of one build. move_versions_test.py now runs a real older daemon beside this checkout's and moves populated sessions (transcript, cells, memory, work, a vent, a delivered webhook letter, a schedule, a workspace link) both ways through the real ssh relay, finishes the checklist and runs a cell and a turn on the target. A third scenario adds a column only this daemon has and checks the reference refuses it at staging while the source keeps the session. test/reference-daemon.sh pins the reference commit (5016e980, the last commit of 2026-11-14; there are no release tags), extracts it with git archive, builds it with its own snapshot script and CLI, and caches it per commit under ALBEDO_REFERENCE_CACHE. A cold build takes about 37 s; CI keeps it in an albedo-reference cache keyed by the script. areas.toml selects the test for transfer, adapter, migration and core table changes. The move to the reference is marked expectedFailure: 4de2d000 added the carried columns sessions.pending_switch_{caller,provider,model} and mail.held_until and the carried table session_side_questions, so the reference refuses the manifest with "core/sessions here lacks pending_switch_caller, pending_switch_provider, pending_switch_model". --- .tangled/workflows/test.yml | 9 + test/e2e/areas.toml | 62 ++++- test/e2e/move_versions_test.py | 428 +++++++++++++++++++++++++++++++++ test/reference-daemon.sh | 49 ++++ 4 files changed, 545 insertions(+), 3 deletions(-) create mode 100644 test/e2e/move_versions_test.py create mode 100755 test/reference-daemon.sh diff --git a/.tangled/workflows/test.yml b/.tangled/workflows/test.yml index cadced75f..7166c45f4 100644 --- a/.tangled/workflows/test.yml +++ b/.tangled/workflows/test.yml @@ -25,6 +25,9 @@ environment: GOMODCACHE: '/workspace/.cache/go-mod' # A restored GOCACHE would replay passing `go test` results; CI runs them all. GOFLAGS: '-count=1' + # The older daemon move_versions_test.py moves sessions to and from, built by + # test/reference-daemon.sh once per pinned commit. + ALBEDO_REFERENCE_CACHE: '/workspace/.cache/albedo-reference' # Spindle restores these before the clone and saves them after every run, red # or timed out too: a failed test leaves the compiled artefacts valid. Go and @@ -44,6 +47,12 @@ cache: fallback: true when: always paths: [/workspace/.cache/go-build, /workspace/.cache/go-mod] + # Keyed by the script that pins the reference commit. Its launcher names + # this path, so the cache must come back to the same place. + - key: albedo-reference + hash: [test/reference-daemon.sh, flake.lock] + when: always + paths: [/workspace/.cache/albedo-reference] - key: cargo hash: [native/render/Cargo.lock, flake.lock] fallback: true diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index d7d213dae..30d24a5e6 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -5,7 +5,21 @@ "src/albedo/harness/sdk/network*.gleam" = ["network_test.py", "discord_test.py"] "src/albedo/openai_api/proxy.gleam" = ["network_test.py"] "priv/python/albedo_plugins/proxy.py" = ["discord_test.py", "browser_test.py"] -"src/albedo/transfer/**" = ["transfer_test.py", "transfer_activation_test.py"] +"src/albedo/transfer/**" = [ + "transfer_test.py", + "transfer_activation_test.py", + "move_versions_test.py", +] +# What a transfer carries, and the reference build moves are checked against. +"src/albedo/harness/extensions/*/transfer.gleam" = [ + "transfer_test.py", + "transfer_activation_test.py", + "move_test.py", + "move_forward_test.py", + "move_checklist_test.py", + "move_versions_test.py", +] +"test/reference-daemon.sh" = ["move_versions_test.py"] "src/albedo/harness/sdk/subscriptions.gleam" = ["artifacts_test.py"] "src/albedo/harness/extensions/artifacts/**" = ["artifacts_test.py"] "src/albedo/harness/extensions/skills/**" = ["skills_test.py"] @@ -130,13 +144,17 @@ "cell_limits_test.py", "prompt_test.py", ] -"src/albedo/harness/kernel/migrations/**" = ["migrations_test.py"] +"src/albedo/harness/kernel/migrations/**" = [ + "migrations_test.py", + "move_versions_test.py", +] "src/albedo/harness/kernel/transfer.gleam" = [ "transfer_test.py", "transfer_activation_test.py", "move_test.py", "move_forward_test.py", "move_checklist_test.py", + "move_versions_test.py", ] "src/albedo/harness/kernel/base.gleam" = [ "extensions_test.py", @@ -194,7 +212,11 @@ "compaction_progress_test.py", "lifecycle_test.py", ] -"src/albedo/daemon/mail.gleam" = ["agents_test.py", "queue_test.py"] +"src/albedo/daemon/mail.gleam" = [ + "agents_test.py", + "queue_test.py", + "move_versions_test.py", +] "src/albedo/daemon/active_output*" = ["active_output_test.py"] "src/albedo/daemon/session_naming.gleam" = ["session_name_test.py"] "src/albedo/daemon/migrations/session_titles.gleam" = [ @@ -222,6 +244,40 @@ "src/albedo/daemon/usage_hours.gleam" = ["usage_test.py"] "src/albedo/daemon/migrations/usage_hours.gleam" = ["usage_test.py"] "src/albedo/daemon/*side_question*" = ["side_questions_test.py"] +# Moves, and the core tables and migrations a transfer carries. +"src/albedo/daemon/transfer*.gleam" = [ + "transfer_test.py", + "transfer_activation_test.py", + "move_test.py", + "move_forward_test.py", + "move_checklist_test.py", + "move_versions_test.py", +] +"src/albedo/daemon/*moves*" = [ + "transfer_test.py", + "transfer_activation_test.py", + "move_test.py", + "move_forward_test.py", + "move_checklist_test.py", + "move_versions_test.py", +] +"src/albedo/daemon/relays.gleam" = [ + "transfer_test.py", + "transfer_activation_test.py", + "move_test.py", + "move_forward_test.py", + "move_checklist_test.py", + "move_versions_test.py", +] +"src/albedo/daemon/conversation.gleam" = [ + "daemon_test.py", + "integration_test.py", + "move_versions_test.py", +] +"src/albedo/daemon/migrations*" = [ + "migrations_test.py", + "move_versions_test.py", +] "src/albedo/daemon/**" = [ "daemon_test.py", "integration_test.py", diff --git a/test/e2e/move_versions_test.py b/test/e2e/move_versions_test.py new file mode 100644 index 000000000..38dd7cba6 --- /dev/null +++ b/test/e2e/move_versions_test.py @@ -0,0 +1,428 @@ +"""Moving sessions between this checkout's daemon and an older one. + +The older daemon is the reference build that test/reference-daemon.sh pins, +built once outside the checkout and cached. Both daemons are peers of the +running test, each with its own home, and the reference boots with its own +CLI. A move here is the real one: the source's driver reaches the target over +a loopback ssh, as in move_test, stages its bundle there and pumps segments +through its own relay into the target daemon. Host `current` runs commands +against this checkout's daemon and host `reference` against the older one. + +Moves must work in both directions while the transfer protocol matches (see +robot-docs/workspaces.md, "Moving a session"). A segment the target cannot +read, here a column the source has and the target lacks, is refused at +staging, and the source keeps its session. +""" + +import functools +import hashlib +import hmac +import json +import os +import shlex +import shutil +import sqlite3 +import subprocess +import sys +import tempfile +import time +import unittest +import urllib.error +import urllib.parse +import urllib.request +from contextlib import closing +from pathlib import Path + +from harness import ( + OFFLINE, + ROOT, + Provider, + fresh_prompt, + operation_id, + peer_daemon, + 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 +mkdir -p {root}/remote-"$target" +exec env -i HOME={root}/remote-"$target" 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 "$@" +""" + +PROFILE = "versions" +NOTE = "the cache key is the prefix hash" +WORK = "ship the picker" +VENT = "the relay stalled" +SCHEDULED = "summarise the deploys" +HOOK = "deploys" +DELIVERY = b'{"status":"deployed"}' + + +@functools.cache +def reference(): + """The reference build's directory, built on first use.""" + built = subprocess.run( + [str(ROOT / "test/reference-daemon.sh")], text=True, capture_output=True + ) + if built.returncode: + raise RuntimeError("building the reference daemon failed:\n" + built.stderr) + return Path(built.stdout.strip().splitlines()[-1]) + + +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.1) + raise AssertionError(message() if callable(message) else message) + + +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 idle(daemon, session, timeout=60): + def settled(): + try: + snapshot = body(daemon, f"/sessions/{session}?tail=0") + except urllib.error.HTTPError as failure: + if failure.code == 503: + return None + raise + if snapshot["status"]["phase"] == "idle" and not snapshot["pending_inputs"]: + return snapshot + return None + + return wait_for(settled, timeout, f"session {session} did not settle") + + +class MixedVersionMoves(unittest.TestCase): + def setUp(self): + self.cells = {} + + def reply(request): + prompt = fresh_prompt(request) + for marker, source in self.cells.items(): + if marker in prompt: + return python(source) + return text("done") + + self.provider = Provider(reply) + self.addCleanup(self.provider.close) + self.root = Path(tempfile.mkdtemp(prefix="versions-")) + self.addCleanup(shutil.rmtree, self.root, True) + self.hosts = self.root / "hosts" + self.hosts.mkdir() + build = reference() + + def prepare(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)) + (daemon.home / "extensions.json").write_text( + json.dumps({**OFFLINE, "enabled": {"webhooks": True}}) + ) + daemon.env["PATH"] = self.ssh_path(daemon.env["PATH"]) + + def prepare_reference(daemon): + prepare(daemon) + daemon.env["ALBEDO_DAEMON"] = str(build / "daemon" / "albedo-daemon") + daemon.env["ALBEDO_TEST_CLI"] = str(build / "albedo") + daemon.env["ALBEDO_ROOT"] = str(build / "src") + + self.current = peer_daemon("versions-current", prepare) + self.reference = peer_daemon("versions-reference", prepare_reference) + (self.hosts / "current").write_text(str(self.current.home)) + (self.hosts / "reference").write_text(str(self.reference.home)) + # Two builds, not one daemon twice. + self.assertNotEqual( + body(self.current, "/server")["digest"], + body(self.reference, "/server")["digest"], + ) + + def ssh_path(self, path): + """The PATH with the loopback ssh ahead of `path`, written once.""" + local, remote = self.root / "local-bin", self.root / "remote-bin" + if not local.exists(): + local.mkdir() + remote.mkdir() + os.symlink(shutil.which("python3") or sys.executable, remote / "python3") + login = local / "loginsh" + login.write_text(LOGIN_SHELL) + login.chmod(0o755) + ssh = local / "ssh" + ssh.write_text( + FAKE_SSH.format( + root=self.root, + hosts=self.hosts, + path=shlex.quote(f"{remote}{os.pathsep}{path}"), + login=login, + ) + ) + ssh.chmod(0o755) + return f"{local}{os.pathsep}{path}" + + # -- driving a daemon ---------------------------------------------- + + def session(self, daemon, workspace): + session = operation_id() + created = body( + daemon, + f"/sessions/{session}", + {"kind": "new", "workspace": str(workspace), "provider_profile": PROFILE}, + method="PUT", + headers={"If-None-Match": "*"}, + ) + self.assertEqual(created["id"], session) + return session + + def say(self, daemon, session, words): + daemon.api( + f"/sessions/{session}/inputs/{operation_id()}", + {"kind": "message", "text": words}, + method="PUT", + ).close() + idle(daemon, session) + + def cell(self, daemon, session, source): + """Runs `source` as the model's next cell and answers its result.""" + marker = "versions cell " + operation_id() + self.cells[marker] = source + self.say(daemon, session, marker) + results = [ + json.loads(part["value"]) + for entry in self.history(daemon, session) + if entry["kind"] == "tool_result" and entry["tool"]["name"] == "python" + for part in entry["content"] + if part["kind"] == "json" and part["field"] == "result" + ] + self.assertTrue(results, f"no cell ran on {daemon.root.name}") + self.assertEqual(results[-1]["status"], "ok", results[-1]) + return results[-1]["output"] + + def history(self, daemon, session): + return body(daemon, f"/sessions/{session}/history")["items"] + + def deliver(self, daemon, hook, secret, event): + signature = ( + "sha256=" + hmac.new(secret.encode(), DELIVERY, hashlib.sha256).hexdigest() + ) + request = urllib.request.Request( + f"{daemon.base}/extensions/webhooks/hooks/{hook}/deliveries", + data=DELIVERY, + headers={"X-Albedo-Signature": signature, "X-Albedo-Event-Id": event}, + ) + with urllib.request.urlopen(request, timeout=25) as response: + self.assertLess(response.status, 300) + + def receipts(self, daemon, hook): + return body( + daemon, f"/extensions/webhooks/hooks/{hook}/deliveries?state=delivered" + )["items"] + + def populated(self, daemon): + """A session on `daemon` with a transcript, cells, a memory note, a + work item, a vent, a delivered webhook letter, a schedule and a + linked workspace: (session, workspace, hook).""" + workspace = Path(tempfile.mkdtemp(prefix="workspace-", dir=self.root)) + other = Path(tempfile.mkdtemp(prefix="linked-", dir=self.root)) + session = self.session(daemon, workspace) + self.say(daemon, session, "hello from the source") + self.cell( + daemon, + session, + f"memory.append({NOTE!r})\n" + f"await work.create({WORK!r})\n" + f"await vent('harness', 'moved mid-copy', title={VENT!r})\n" + "print('cell ran on the source')", + ) + job = { + "session_id": session, + "kind": "recurring", + "prompt": SCHEDULED, + "delay_seconds": 3600, + "every_seconds": 3600, + } + with daemon.api("/extensions/schedule/jobs", job) as response: + self.assertEqual(response.status, 201) + created = body( + daemon, "/extensions/webhooks/hooks", {"name": HOOK, "session_id": session} + ) + hook, secret = created["resource"]["value"]["id"], created["secret"] + self.deliver(daemon, hook, secret, "deploy-1") + wait_for( + lambda: self.receipts(daemon, hook), + 30, + "the webhook letter was never delivered", + ) + idle(daemon, session) + self.link(daemon, workspace, other) + return session, workspace, hook + + def link(self, daemon, workspace, other): + def group(path): + query = urllib.parse.urlencode({"workspace": str(path)}) + return body(daemon, f"/extensions/links/groups?{query}")[ + "configuration_resource" + ] + + mine, theirs = group(workspace), group(other) + body( + daemon, + mine["url"], + {"other_workspace": str(other), "other_etag": theirs["etag"]}, + headers={"If-Match": mine["etag"]}, + ) + + def move(self, source, session, target): + transfer = operation_id() + with source.api( + f"/sessions/{session}/move", {"transfer_id": transfer, "target": target} + ) as response: + self.assertEqual(response.status, 202) + return transfer, wait_for( + lambda: ( + (move := self.read(source, transfer))["state"] + in ("checklist", "active", "failed") + and move + ), + 120, + lambda: f"the move never settled: {self.read(source, transfer)}", + ) + + def read(self, daemon, transfer): + return body(daemon, f"/transfers/{transfer}") + + def preflight(self, source, session, target): + query = urllib.parse.urlencode({"session_id": session, "target": target}) + return body(source, "/transfers/preflight?" + query) + + # -- scenarios ------------------------------------------------------ + + def moves_and_works(self, source, target, host): + session, _workspace, hook = self.populated(source) + destination = Path(tempfile.mkdtemp(prefix="moved-", dir=self.root)) + where = f"{host}:{destination}" + found = self.preflight(source, session, where) + self.assertTrue(found["available"], found) + + transfer, move = self.move(source, session, where) + self.assertEqual(move["state"], "checklist", move) + kinds = {binding["kind"] for binding in move["bindings"]} + self.assertEqual(kinds, {"schedule", "webhook"}, move["bindings"]) + finished = body(source, f"/transfers/{transfer}/finish", {}) + self.assertEqual(finished["state"], "active", finished) + self.assertIsNone(finished["error"]) + + # The source copy refuses input and says where it went. + with self.assertRaises(urllib.error.HTTPError) as refused: + source.api( + f"/sessions/{session}/inputs/{operation_id()}", + {"kind": "message", "text": "still here?"}, + method="PUT", + ) + self.assertEqual(refused.exception.code, 409) + self.assertEqual(json.load(refused.exception)["code"], "session_moved") + + # The target runs the session with everything it carried. + arrived = body(target, f"/sessions/{session}?tail=0") + self.assertEqual(arrived["workspace"], str(destination)) + self.assertIsNone(arrived["moved"]) + said = json.dumps(self.history(target, session)) + self.assertIn("hello from the source", said) + self.assertIn("cell ran on the source", said) + self.assertIn(f"webhook {HOOK} #", said) + [receipt] = self.receipts(target, hook) + self.assertIsNotNone(receipt["delivered_at"]) + self.assertEqual(receipt["session_id"], session) + jobs = body(target, f"/extensions/schedule/jobs?session_id={session}") + self.assertEqual([job["value"]["prompt"] for job in jobs["items"]], [SCHEDULED]) + output = self.cell( + target, + session, + "print('cell ran on the target')\n" + f"print(memory.grep({NOTE!r}))\n" + "print(sorted(i.title for i in await work.list()))\n" + "print([v['title'] for v in await vents()])", + ) + self.assertIn("cell ran on the target", output) + self.assertIn(NOTE, output) + self.assertIn(repr([WORK]), output) + self.assertIn(VENT, output) + self.say(target, session, "and a turn on the target") + + # Broken since 4de2d000 ("improve crash tolerance"), which added the + # transferred core columns sessions.pending_switch_{caller,provider,model} + # and mail.held_until and the transferred core table + # session_side_questions. The reference refuses the manifest at staging: + # "core/sessions here lacks pending_switch_caller, pending_switch_provider, + # pending_switch_model". Remove this mark with the fix. + @unittest.expectedFailure + def test_a_session_moves_from_this_daemon_to_the_reference(self): + self.moves_and_works(self.current, self.reference, "reference") + + def test_a_session_moves_from_the_reference_to_this_daemon(self): + self.moves_and_works(self.reference, self.current, "current") + + def test_a_column_the_reference_lacks_is_refused_and_the_source_keeps_it(self): + # A transfer exports every column of a carried table, so a column only + # this daemon has is refused by the reference before anything goes + # live, as the mail column filing letters once was. + session = self.session( + self.current, tempfile.mkdtemp(prefix="workspace-", dir=self.root) + ) + self.say(self.current, session, "hello from the source") + with closing(sqlite3.connect(self.current.home / "albedo.sqlite")) as db: + db.execute("ALTER TABLE sessions ADD COLUMN versions_probe TEXT") + db.commit() + destination = Path(tempfile.mkdtemp(prefix="moved-", dir=self.root)) + _transfer, move = self.move(self.current, session, f"reference:{destination}") + self.assertEqual(move["state"], "failed", move) + self.assertEqual(move["error"]["code"], "transfer_version") + table, _, missing = move["error"]["detail"].partition(" here lacks ") + self.assertEqual(table, "core/sessions") + self.assertIn("versions_probe", missing.split(", ")) + # Nothing went live on the reference, and the source still runs it. + with self.assertRaises(urllib.error.HTTPError) as absent: + self.reference.api(f"/sessions/{session}?tail=0") + self.assertEqual(absent.exception.code, 404) + self.assertIsNone(body(self.current, f"/sessions/{session}?tail=0")["moved"]) + self.say(self.current, session, "still here") + self.assertIn("still here", json.dumps(self.history(self.current, session))) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/reference-daemon.sh b/test/reference-daemon.sh new file mode 100755 index 000000000..812ccb6fd --- /dev/null +++ b/test/reference-daemon.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Build the reference daemon and CLI that mixed-version scenarios run beside +# this checkout's (test/e2e/move_versions_test.py), then print the directory +# holding them: `daemon/albedo-daemon` (a launcher for ALBEDO_DAEMON) and +# `albedo` (the CLI for ALBEDO_TEST_CLI). +# +# REFERENCE is the commit those scenarios treat as the older daemon. Albedo has +# no release tags yet, so it is pinned here, the only place it is recorded. +# robot-docs/testing.md ("Mixed-version moves") says when and how to bump it. +# +# The build is cached under $ALBEDO_REFERENCE_CACHE (default +# ~/.cache/albedo-reference), one directory per commit, so a repeat run only +# prints the path. The sources come from `git archive`, outside the checkout, +# and build with their own snapshot script and the current dev shell's tools. +set -euo pipefail + +REFERENCE=5016e9802369aa430c182a3cdcae1cb61062aef2 + +root="$(cd "$(dirname "$0")/.." && pwd)" +cache="${ALBEDO_REFERENCE_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/albedo-reference}" +out="$cache/$REFERENCE" +if [[ -e "$out/built" ]]; then + echo "$out" + exit 0 +fi +mkdir -p "$cache" +# One build per commit, however many suites ask for it at once. +exec 9>"$cache/$REFERENCE.lock" +flock 9 +if [[ -e "$out/built" ]]; then + echo "$out" + exit 0 +fi +# The launcher names its absolute paths, so the build happens in place and +# `built` marks it complete; a half-finished one is started over. +rm -rf "$out" +mkdir -p "$out/src" +if ! git -C "$root" cat-file -e "$REFERENCE^{commit}" 2>/dev/null; then + # A shallow clone, as CI's may be, lacks the commit until it is fetched. + git -C "$root" fetch --quiet --depth=1 origin "$REFERENCE" >&2 +fi +git -C "$root" archive "$REFERENCE" | tar -x -C "$out/src" +"$out/src/test/snapshot-daemon.sh" "$out/daemon" >/dev/null +go -C "$out/src/cli" build -o "$out/albedo" ./cmd/albedo >&2 +# The sources stay: the launcher runs their priv/bin/albedo-daemon. Their +# build tree is only an intermediate. +rm -rf "$out/src/build" +touch "$out/built" +echo "$out" -- knotmirror 0.0.1