Skip to content

The platform for continuously improving AI agents.

7.1 KB
Raw Blame
from datetime import timedelta

from django.db import transaction
from django.db.models import Q
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.models import ComponentExecution
from overbae.services import (
    execution_mandates,
    experiment_assets,
    experiment_components,
    research_context_authorship,
    research_evidence,
    research_team,
)
from overbae.services.experiment_asset_contract import ComponentRequest

ACTIVE = {"queued", "running"}


def authorized(assignment, *, continuation=False):
    try:
        authorize = (
            execution_mandates.require_continuation if continuation else execution_mandates.require
        )
        authorize(assignment, "prepare")
    except InputValidationError:
        return False
    return True


def describe(execution, *, assignment=None):
    result = {
        "execution": str(execution.pk),
        "component": str(execution.component_id),
        "state": execution.state,
        "receipt": execution.receipt,
        "outputs": execution.outputs,
        "error": execution.error,
    }
    if assignment is None:
        return result
    # Native tool dispatch imports the component worker.
    from overbae.services.research_tools import source_boundary

    _, denied, _, _ = source_boundary(assignment)
    sources = research_evidence.input_sources(
        assignment.project, execution.request.get("inputs", {})
    )
    if execution.error:
        sources |= research_context_authorship.asset_use_sources(execution.component)
    if denied and sources & (denied | {"unresolved_evidence"}):
        return {
            **{key: result[key] for key in ("execution", "component", "state")},
            "access": "sealed_data",
            "error": "Details of held-out source rows are unavailable." if execution.error else "",
        }
    return result


@transaction.atomic
def create(action, request):
    agent = research_team.current_turn(action.agent)
    assignment = agent.assignment
    existing = ComponentExecution.objects.filter(action=action).first()
    if existing:
        return existing
    if (
        assignment.state != "running"
        or assignment.deadline <= timezone.now()
        or not authorized(assignment)
    ):
        raise InputValidationError("This assignment no longer has component execution authority")
    component = experiment_assets.get(assignment.project, request.component, "component")
    research_context_authorship.require_asset(assignment, component)
    execution = ComponentExecution.objects.create(
        action=action,
        component=component,
        request=request.model_dump(mode="json", by_alias=True),
        expires_at=min(assignment.deadline, timezone.now() + timedelta(minutes=30)),
    )
    dispatch(execution)
    return execution


def dispatch(execution):
    from overbae.tasks.research import execute_component  # The task invokes this service.

    now = timezone.now()
    claimed = (
        ComponentExecution.objects.filter(pk=execution.pk, state="queued")
        .filter(Q(dispatched_at__isnull=True) | Q(dispatched_at__lt=now - timedelta(seconds=60)))
        .update(dispatched_at=now)
    )
    if claimed:
        transaction.on_commit(lambda: execute_component.delay(str(execution.pk)), robust=True)


def wake(execution):
    from overbae.services.research_wakes import request  # Wakes inspect native component receipts.

    request(execution.action.agent.assignment_id)


def execute(identifier):
    with transaction.atomic():
        execution = (
            ComponentExecution.objects.select_for_update(of=("self",))
            .select_related("action__agent__assignment", "component")
            .get(pk=identifier)
        )
        assignment = execution.action.agent.assignment
        if execution.state != "queued" or execution.expires_at <= timezone.now():
            return
        if not authorized(assignment, continuation=True):
            execution.state = "cancelled"
            execution.completed_at = timezone.now()
            execution.save(update_fields=["state", "completed_at"])
            wake(execution)
            return
        execution.state = "running"
        execution.expires_at = min(assignment.deadline, timezone.now() + timedelta(minutes=23))
        execution.save(update_fields=["state", "expires_at"])
    receipt = {}

    def progress():
        ComponentExecution.objects.filter(pk=identifier).update(receipt=receipt)
        return authorized(assignment, continuation=True) and bool(
            ComponentExecution.objects.filter(
                pk=identifier,
                state="running",
                expires_at__gt=timezone.now(),
                action__agent__assignment__deadline__gt=timezone.now(),
            ).exists()
        )

    try:
        request = ComponentRequest.model_validate(execution.request)
        outputs = experiment_components.execute(
            execution.component,
            experiment_components.values(execution.action, request.inputs),
            request.parameters,
            receipt=receipt,
            progress=progress,
            assignment=assignment,
        )
        experiment_components.publish(
            execution.action, execution.component, request, outputs, receipt, execution=execution
        )
    except Exception as exc:
        state = (
            "unknown"
            if receipt.get("submission_started_at")
            and not receipt.get("submission_rejected")
            and "exit_code" not in receipt
            else "failed"
        )
        ComponentExecution.objects.filter(pk=identifier).update(receipt=receipt)
        ComponentExecution.objects.filter(pk=identifier, state="running").update(
            state=state,
            receipt=receipt,
            error=str(exc),
            completed_at=timezone.now(),
        )
    wake(execution)


def reconcile(assignment):
    for execution in ComponentExecution.objects.filter(
        action__agent__assignment=assignment, state__in=ACTIVE
    ).select_related("action__agent"):
        now = timezone.now()
        if not authorized(assignment, continuation=True):
            state, error = "cancelled", "Execution owner stopped"
        elif execution.expires_at <= now:
            state = "unknown" if execution.state == "running" else "failed"
            error = "Execution deadline expired; uncertain work is not replayed"
        else:
            if execution.state == "queued":
                dispatch(execution)
            continue
        if ComponentExecution.objects.filter(
            pk=execution.pk, state=execution.state, expires_at=execution.expires_at
        ).update(state=state, error=error, completed_at=now):
            wake(execution)


def cancel(assignment):
    ComponentExecution.objects.filter(
        action__agent__assignment=assignment, state__in=ACTIVE
    ).update(state="cancelled", error="Execution owner stopped", completed_at=timezone.now())


def observations(assignment):
    return [
        describe(item, assignment=assignment)
        for item in ComponentExecution.objects.filter(action__agent__assignment=assignment)
        .select_related("component")
        .order_by("pk")
    ]