Skip to content

The platform for continuously improving AI agents.

11.5 KB
Raw Blame
import json
from datetime import timedelta
from http.server import BaseHTTPRequestHandler
from socketserver import ThreadingUnixStreamServer
from tempfile import TemporaryDirectory
from threading import Thread
from urllib.parse import parse_qs, urlsplit

import pytest
from django.utils import timezone
from temporalio.exceptions import ApplicationError
from test_experiment_engine import flow
from test_experiment_operator import supervised
from test_research_team import assignment

from overbae.core.errors import InputValidationError
from overbae.services import (
    experiment_checkpoints,
    research,
    research_agent,
    research_orchestration,
    research_runtime,
    research_sdk,
)

pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]


@pytest.fixture
def engine(settings):
    state = {
        "containers": {},
        "images": {},
        "create_status": 201,
        "stop_status": 204,
        "stopped": [],
    }
    for suffix in ("a", "b"):
        release = "sha256:" + suffix * 64
        state["images"][release] = {
            "json": {
                "Id": release,
                "Architecture": "arm64",
                "Os": "linux",
                "RootFS": {"Layers": ["dependencies", suffix]},
                "Config": {"User": "10001:10001", "Entrypoint": ["python"]},
            },
            "history": [
                {"CreatedBy": 'ENTRYPOINT ["python"]', "Size": 0},
                {
                    "CreatedBy": "COPY agent_runtime /opt/runtime/agent_runtime # buildkit",
                    "Size": 10,
                },
                {"CreatedBy": "RUN pip install --require-hashes", "Size": 100},
            ],
        }

    class Handler(BaseHTTPRequestHandler):
        def reply(self, status, body=None):
            data = json.dumps(body).encode() if body is not None else b""
            self.send_response(status)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def do_GET(self):
            if self.path.startswith("/images/"):
                _, _, release, operation = self.path.split("/")
                return self.reply(200, state["images"][release][operation])
            name = self.path.split("/")[2]
            item = state["containers"].get(name)
            self.reply(200 if item else 404, item)

        def do_POST(self):
            parsed = urlsplit(self.path)
            body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
            if parsed.path == "/containers/create":
                if state["create_status"] != 201:
                    return self.reply(state["create_status"])
                name = parse_qs(parsed.query)["name"][0]
                state["containers"][name] = {
                    "Image": body["Image"],
                    "Config": {"Labels": body["Labels"], "User": body["User"]},
                    "HostConfig": body["HostConfig"],
                    "Mounts": [
                        {"Type": "volume", "Name": mount["Source"], "Destination": mount["Target"]}
                        for mount in body["HostConfig"]["Mounts"]
                    ],
                    "State": {"Running": False, "Status": "created", "ExitCode": 0},
                }
                return self.reply(201, {"Id": name})
            name, operation = parsed.path.split("/")[2:4]
            if operation == "stop":
                if state["stop_status"] != 204:
                    return self.reply(state["stop_status"])
                state["stopped"].append(name)
            state["containers"][name]["State"] = {
                "Running": operation == "start",
                "Status": "running" if operation == "start" else "exited",
                "ExitCode": 0,
            }
            self.reply(204)

        def log_message(self, *_):
            pass

    with TemporaryDirectory(prefix="engine-", dir="/tmp") as directory:
        socket = directory + "/api.sock"
        server = ThreadingUnixStreamServer(socket, Handler)
        thread = Thread(target=server.serve_forever, daemon=True)
        thread.start()
        settings.RESEARCH_EXECUTOR = "docker"
        settings.RESEARCH_DOCKER_SOCKET = socket
        settings.RESEARCH_DOCKER_IMAGE = "sha256:" + "a" * 64
        settings.RESEARCH_DOCKER_NETWORK = "isolated-test"
        settings.RESEARCH_CALLBACK_URL = "http://api.test/api/internal/research"
        try:
            yield state
        finally:
            server.shutdown()
            server.server_close()
            thread.join()


@pytest.mark.parametrize("blocked_by", [None, "running", "epoch", "dependencies", "late_install"])
def test_runtime_upgrade_preserves_conversation_and_requires_idle_compatible_executor(
    engine, blocked_by
):
    work, agent = assignment()
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    launch = agent.checkpoint_manifest["launch"]
    old = engine["containers"][launch["name"]]
    old["State"] = {"Running": False, "Status": "exited", "ExitCode": 1}
    research_sdk.failed(agent, "Projection rejected the retained context")
    work.refresh_from_db()
    research_agent.reconcile(work)
    agent.refresh_from_db()
    contract = research_runtime.conversation_contract(agent)
    conversation, epoch, sequence = (
        agent.sdk_conversation_id,
        agent.execution_epoch,
        agent.projected_event_sequence,
    )
    replacement = "sha256:" + "b" * 64
    arguments = {
        "conversation": conversation,
        "release": agent.sdk_release,
        "replacement": replacement,
        "epoch": epoch,
        "reason": "Accept full retained event text",
    }
    if blocked_by == "running":
        old["State"]["Running"] = True
    elif blocked_by == "epoch":
        arguments["epoch"] -= 1
    elif blocked_by == "dependencies":
        engine["images"][replacement]["json"]["RootFS"]["Layers"][0] = "different-sdk"
    elif blocked_by == "late_install":
        engine["images"][replacement]["json"]["RootFS"]["Layers"].append("changed-sdk")
        engine["images"][replacement]["history"].insert(
            0, {"CreatedBy": "RUN pip install different-sdk", "Size": 10}
        )
    if blocked_by:
        with pytest.raises(InputValidationError):
            research_sdk.upgrade_runtime(agent.pk, **arguments)
        agent.refresh_from_db()
        assert agent.sdk_release == arguments["release"]
        assert agent.execution_epoch == epoch
        assert not work.events.filter(kind="runtime_upgraded").exists()
        return
    research_sdk.upgrade_runtime(agent.pk, **arguments)
    research_sdk.upgrade_runtime(agent.pk, **arguments)
    agent.refresh_from_db()
    assert agent.sdk_conversation_id == conversation
    assert agent.projected_event_sequence == sequence
    assert agent.execution_epoch == epoch + 1
    assert research_runtime.conversation_contract(agent) == contract
    assert agent.checkpoint_manifest["launch"] == launch
    assert work.events.filter(kind="runtime_upgraded").count() == 1
    assert len(engine["containers"]) == 1
    research.resume(
        work, request_key="resume-upgrade", instructions="Continue the retained request"
    )
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    resumed = agent.checkpoint_manifest["launch"]
    assert resumed["release"] == replacement
    # The volumes are named by the conversation, so the upgrade keeps the agent's state.
    assert resumed["conversation"] == launch["conversation"]
    assert len(engine["containers"]) == 2


@pytest.mark.parametrize("old_running", [False, True])
def test_explicit_resume_stops_the_retired_writer_before_one_new_launch(engine, old_running):
    work, agent = assignment()
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    old = agent.checkpoint_manifest["launch"]["name"]
    engine["containers"][old]["State"] = {"Running": old_running, "Status": "exited", "ExitCode": 1}
    agent.checkpoint_manifest["consecutive_failures"] = 2
    agent.save(update_fields=["checkpoint_manifest"])
    research_sdk.failed(agent, "Three permanent process failures")
    conversation = agent.sdk_conversation_id
    research.resume(work, request_key="recover", instructions="Resolved the launch failure")
    research_sdk.advance(agent.pk)
    research.resume(work, request_key="recover", instructions="Resolved the launch failure")
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    assert len(engine["containers"]) == 2
    assert engine["containers"][old]["State"]["Running"] is False
    assert engine["stopped"] == ([old] if old_running else [])
    assert agent.sdk_conversation_id == conversation
    assert agent.checkpoint_manifest["consecutive_failures"] == 0


def test_transport_exits_do_not_exhaust_permanent_failure_recovery(engine):
    work, agent = assignment()
    for _ in range(5):
        research_sdk.advance(agent.pk)
        agent.refresh_from_db()
        name = agent.checkpoint_manifest["launch"]["name"]
        engine["containers"][name]["State"] = {"Running": False, "Status": "exited", "ExitCode": 75}
        assert research_sdk.advance(agent.pk)["state"] == "wait"
    agent.refresh_from_db()
    work.refresh_from_db()
    assert work.state == "running"
    assert agent.checkpoint_manifest["consecutive_failures"] == 0


@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("interruption", ["resume", "lease_expired"])
def test_interrupted_operator_restarts_without_waiting_for_changed_evidence(engine, interruption):
    with experiment_checkpoints.store() as store:
        store.setup()
    experiment, user = flow()
    _, agent = supervised(experiment, user)
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    launch = agent.checkpoint_manifest["launch"]
    assert launch["evidence"]
    conversation = agent.sdk_conversation_id
    if interruption == "resume":
        research_sdk.failed(agent, "Interrupted operator")
        research.resume(agent.assignment, request_key="retry-operator", instructions="Resume")
    else:
        agent.lease_expires_at = timezone.now() - timedelta(seconds=1)
        agent.save(update_fields=["lease_expires_at"])
    research_sdk.advance(agent.pk)
    agent.refresh_from_db()
    assert engine["stopped"] == [launch["name"]]
    assert len(engine["containers"]) == 2
    assert agent.checkpoint_manifest["launch"]["name"] != launch["name"]
    assert agent.sdk_conversation_id == conversation
    assert not research_sdk.waiting(agent)


def test_permanent_launch_failure_fences_its_actual_admitted_epoch(engine):
    work, agent = assignment()
    engine["create_status"] = 404
    for _ in range(4):
        with pytest.raises(ApplicationError) as failure:
            research_orchestration.advance(agent.pk)
    agent.refresh_from_db()
    assert failure.value.details[0] == agent.execution_epoch
    assert research_orchestration.fence(agent.pk, failure.value.type, failure.value.details[0]) == {
        "state": "end"
    }
    work.refresh_from_db()
    assert work.state == "blocked"


def test_expired_run_retries_unavailable_shutdown_without_starting_another_executor(engine):
    work, agent = assignment()
    research_sdk.advance(agent.pk)
    work.deadline = timezone.now() - timedelta(seconds=1)
    work.save(update_fields=["deadline"])
    engine["stop_status"] = 503
    assert research_orchestration.advance(agent.pk)["state"] == "wait"
    work.refresh_from_db()
    assert work.state == "stopping"
    engine["stop_status"] = 204
    assert research_orchestration.advance(agent.pk)["state"] == "end"
    assert len(engine["containers"]) == 1 and len(engine["stopped"]) == 1