Skip to content

The platform for continuously improving AI agents.

12.5 KB
Raw Blame
"""One research agent's epochs on its executor: start a launch while the agent holds its lease,
read it back, and settle the epoch when the runner ends. Where the executor runs is the
executor's concern (services/research_executor)."""

import uuid
from datetime import datetime, timedelta

from django.conf import settings
from django.db import transaction
from django.utils import timezone
from temporalio.exceptions import ApplicationError

from agent_runtime.research_disposition import TRANSPORT_UNAVAILABLE
from overbae.core.errors import InputValidationError
from overbae.models import ResearchAgent, ResearchAssignment, ResearchEvent
from overbae.services import (
    experiment_operator,
    research,
    research_agent,
    research_runtime,
    research_science,
    research_team,
)
from overbae.services.research_executor import ExecutorUnavailableError, Launch, executor


def load(identifier):
    return ResearchAgent.objects.select_related(
        "assignment__project", "assignment__created_by", "assignment__context"
    ).get(pk=identifier)


def locked_current(agent):
    research_science.experiment_for(agent.assignment, lock=True)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    current.assignment = assignment
    return current


def owns(current, previous):
    return (
        current.execution_epoch == previous.execution_epoch
        and current.lease == previous.lease
        and current.checkpoint_manifest.get("launch") == previous.checkpoint_manifest.get("launch")
    )


def admitted(agent):
    return (
        agent.assignment.state == "running"
        and agent.state not in research.TERMINAL
        and agent.lease_expires_at
        and agent.lease_expires_at > timezone.now()
        and agent.assignment.deadline > timezone.now()
        and research.authorized(agent.assignment)
    )


def waiting(agent):
    if agent.state != "waiting" or research_runtime.pending_messages(agent):
        return False
    question = agent.wake.get("question")
    if question:
        return not agent.assignment.events.filter(
            kind="question_answered", payload__question=question
        ).exists()
    after = agent.wake.get("after")
    return bool(
        after
        and datetime.fromisoformat(after) > timezone.now()
        and agent.wake.get("evidence")
        == research_agent.evidence_identity(research_agent.evidence(agent))
    )


def launch_of(agent):
    manifest = agent.checkpoint_manifest.get("launch")
    return Launch.from_manifest(manifest) if manifest else None


def upgrade_runtime(agent_id, *, conversation, release, replacement, epoch, reason):
    """Move a blocked, idle lead to another release of the research image. Its conversation
    continues only when the new release keeps the same dependencies."""
    if not reason.strip() or len(reason) > 2000 or release == replacement:
        raise InputValidationError("Supply a different runtime and a bounded recovery reason")
    runtime = executor()
    dependencies = runtime.dependencies(release)
    if dependencies is None or dependencies != runtime.dependencies(replacement):
        raise InputValidationError("Runtime recovery requires identical SDK dependency layers")
    with transaction.atomic():
        agent = locked_current(load(agent_id))
        payload = {
            "conversation": str(conversation),
            "from_release": release,
            "to_release": replacement,
            "from_epoch": epoch,
            "to_epoch": epoch + 1,
            "reason": reason,
            "dependencies": dependencies,
        }
        if (
            agent.sdk_release == replacement
            and agent.execution_epoch == epoch + 1
            and agent.assignment.state == "blocked"
            and agent.assignment.events.filter(
                agent=agent, kind="runtime_upgraded", payload=payload
            ).exists()
        ):
            return
        if (
            agent.parent_id is not None
            or agent.assignment.state != "blocked"
            or agent.state not in research.TERMINAL
            or str(agent.sdk_conversation_id) != str(conversation)
            or agent.sdk_release != release
            or agent.execution_epoch != epoch
            or (agent.lease_expires_at and agent.lease_expires_at > timezone.now())
        ):
            raise InputValidationError("Recovery requires the exact blocked idle lead and epoch")
        research_runtime.conversation_contract(agent)
        launch = launch_of(agent)
        if (
            launch is None
            or launch.release != release
            or launch.conversation != str(agent.sdk_conversation_id)
        ):
            raise InputValidationError("The retained executor does not own this conversation")
        status = runtime.status(launch)
        if status is None or status.state != "exited":
            raise InputValidationError("Confirm the previous executor has exited before recovery")
        agent.sdk_release = replacement
        agent.checkpoint_manifest["runtime_contract"]["release"] = replacement
        agent.execution_epoch += 1
        agent.lease = agent.lease_expires_at = None
        agent.save(
            update_fields=[
                "sdk_release",
                "checkpoint_manifest",
                "execution_epoch",
                "lease",
                "lease_expires_at",
            ]
        )
        ResearchEvent.objects.create(
            assignment=agent.assignment, agent=agent, kind="runtime_upgraded", payload=payload
        )


@transaction.atomic
def start_launch(agent, runtime):
    current = locked_current(agent)
    if (
        not owns(current, agent)
        or not admitted(current)
        or not research_team.lease_matches(current, agent.lease)
    ):
        return {"state": "wait", "seconds": 5}
    runtime.launch(
        launch_of(current),
        {
            "RESEARCH_API_URL": settings.RESEARCH_CALLBACK_URL,
            "RESEARCH_RUNTIME_TOKEN": research_runtime.token(current),
            "RESEARCH_RESUME": str(int(current.projected_event_sequence > 0)),
        },
    )
    return {"state": "wait", "seconds": 5}


def advance(identifier):
    runtime = executor()
    agent = load(identifier)
    launch = launch_of(agent)
    if launch:
        status = runtime.status(launch)
        active = status is not None and status.running
        if active:
            with transaction.atomic():
                current = locked_current(agent)
                if not owns(current, agent) or admitted(current):
                    return {"state": "wait", "seconds": 5}
                runtime.stop(launch)
                agent = current
        valid = admitted(agent)
        retired = agent.checkpoint_manifest.get("retired_launch") == launch.name
        if status is not None and status.state == "created" and valid and not retired:
            return start_launch(agent, runtime)
        interrupted = active or retired
        exit_code = status.exit_code or 0 if status is not None and not interrupted else 0
        unavailable = exit_code == TRANSPORT_UNAVAILABLE
        failed_exit = bool(exit_code)
        failures = (
            agent.checkpoint_manifest.get("consecutive_failures", 0) + (not unavailable)
            if failed_exit
            else 0
        )
        if (
            failures >= 3
            and agent.assignment.state == "running"
            and agent.state not in research.TERMINAL
        ):
            return failed(agent, "The OpenHands executor failed after three recovery attempts")
        with transaction.atomic():
            current = locked_current(agent)
            if not owns(current, agent):
                return {"state": "wait", "seconds": 5}
            retained = runtime.status(launch)
            if retained is not None and retained.running:
                return {"state": "wait", "seconds": 5}
            current.lease = None
            current.lease_expires_at = None
            current.checkpoint_manifest = {
                **current.checkpoint_manifest,
                "launch": None,
                "retired_launch": None,
                "consecutive_failures": failures,
            }
            current.save(update_fields=["lease", "lease_expires_at", "checkpoint_manifest"])
            # An operator takes one turn per wake. One that ended its turn without calling
            # wait stands by against what the turn was shown, instead of starting another.
            evidence = agent.checkpoint_manifest["launch"].get("evidence")
            if not interrupted and not failed_exit and evidence:
                experiment_operator.stand_by(current, evidence)
        if unavailable:
            return {"state": "wait", "seconds": 15}
        agent = load(identifier)
    if agent.assignment.state != "running" or agent.state in research.TERMINAL:
        return {"state": "end"}
    if not research.authorized(agent.assignment) or agent.assignment.deadline <= timezone.now():
        research_agent.reconcile(research.stop(agent.assignment))
        return {"state": "end"}
    if agent.sdk_conversation_id is None and agent.actions.filter(tool="model").exists():
        return failed(agent, "This previous-runtime conversation requires explicit migration")
    if waiting(agent):
        return {"state": "wait", "seconds": 15}
    if not settings.RESEARCH_CALLBACK_URL:
        raise InputValidationError("Configure RESEARCH_CALLBACK_URL, the internal research API")
    release = agent.sdk_release or runtime.release()
    with transaction.atomic():
        research_science.experiment_for(agent.assignment, lock=True)
        current = research_agent.lease(identifier)
        if current is None:
            return {"state": "wait", "seconds": 5}
        new_conversation = current.sdk_conversation_id is None
        current.sdk_conversation_id = current.sdk_conversation_id or uuid.uuid4()
        if current.sdk_release and current.sdk_release != release:
            raise InputValidationError("The retained SDK image requires an explicit migration")
        current.sdk_release = release
        if new_conversation:
            research_runtime.initialize_contract(current)
        current.execution_epoch += 1
        current.state = "ready"
        current.lease_expires_at = timezone.now() + timedelta(seconds=240)
        launch = Launch(
            name=f"overmind-research-{current.pk.hex}-{current.execution_epoch}",
            release=release,
            conversation=str(current.sdk_conversation_id),
            labels={
                "overmind.agent": str(current.pk),
                "overmind.epoch": str(current.execution_epoch),
            },
        )
        current.checkpoint_manifest = {
            **current.checkpoint_manifest,
            "launch": {
                **launch.manifest(),
                **(
                    {"evidence": research_agent.evidence_identity(research_agent.evidence(current))}
                    if experiment_operator.is_operator(current.assignment)
                    else {}
                ),
            },
        }
        current.save(
            update_fields=[
                "sdk_conversation_id",
                "sdk_release",
                "execution_epoch",
                "state",
                "lease_expires_at",
                "checkpoint_manifest",
            ]
        )
    try:
        with research_team.turn(current):
            research_agent.observe(current)
        return start_launch(current, runtime)
    except Exception as error:
        if isinstance(error, ExecutorUnavailableError):
            raise
        raise ApplicationError(
            "Research launch failed", current.execution_epoch, type=type(error).__name__
        ) from error


@transaction.atomic
def failed(agent, message):
    research_science.experiment_for(agent.assignment, lock=True)
    assignment = ResearchAssignment.objects.select_for_update().get(pk=agent.assignment_id)
    current = ResearchAgent.objects.select_for_update().get(pk=agent.pk)
    if not owns(current, agent):
        return {"state": "wait", "seconds": 5}
    if assignment.state == "running":
        assignment.state = "blocked"
        assignment.result = {**assignment.result, "reason": "sdk_runtime_failed", "error": message}
        assignment.save(update_fields=["state", "result"])
        current.lease = None
        current.lease_expires_at = None
        current.save(update_fields=["lease", "lease_expires_at"])
        research.event(assignment, "blocked", assignment.result, current)
    return {"state": "end"}