Skip to content

The platform for continuously improving AI agents.

10.4 KB
Raw Blame
from django.db import transaction

from overbae.core.errors import InputValidationError
from overbae.models import DatasetPipelineRun, ExperimentExecution, ResearchAction
from overbae.services import (
    context_graph,
    experiment_engine,
    experiment_operator,
    experiment_training,
    research,
    research_benchmarks,
    research_evidence,
    research_science,
    research_team,
)
from overbae.services.research_contract import Artifact


def owned(assignment):
    return research_evidence.flows(assignment).select_related("execution", "execution__revision")


def data_checks(run):
    """What the platform found in the data each transform spec of this run prepared, by
    stage: only stages with a finding are listed."""
    stages = {
        f"research:{action}": node
        for node, action in run.execution.nodes.exclude(action=None).values_list(
            "node", "action_id"
        )
    }
    found = {}
    for preparation in DatasetPipelineRun.objects.filter(
        dataset__project_id=run.project_id, request_key__in=stages
    ).select_related("source__dataset__project"):
        steps = preparation.result.get("steps") or []
        checks = steps[-1].get("preparation") if steps else None
        if checks and (checks["flagged"] or checks["failed"]):
            found[stages[preparation.request_key]] = {
                "flagged": checks["flagged"],
                "failed": checks["failed"],
            }
    return found


def observations(assignment, *, include_reports=False):
    return research_evidence.project_report(
        assignment,
        [
            {
                "run": str(run.pk),
                "state": run.state,
                "revision": run.execution.revision.number,
                "receipt": next(
                    (
                        str(value)
                        for value in assignment.artifacts.filter(
                            metadata__flow_run=str(run.pk), action__tool="flow_receipt"
                        ).values_list("pk", flat=True)
                    ),
                    None,
                ),
                "outputs": {
                    port: {
                        key: value
                        for key, value in binding.items()
                        if include_reports or key != "report"
                    }
                    for port, binding in run.result.get("outputs", {}).items()
                },
                "failed_nodes": run.result.get("failed_nodes", []),
                "nodes": list(run.execution.nodes.values("node", "state", "error")),
                **({"data_checks": checks} if (checks := data_checks(run)) else {}),
            }
            for run in owned(assignment).order_by("created_at", "pk")
        ],
    )


@transaction.atomic
def launch(action, request, revision):
    # The task imports the executor at delivery, after this transaction commits.
    from overbae.tasks.research import advance_flow

    agent = action.agent
    if agent.parent_id:
        raise InputValidationError("Only the research lead admits flow execution")
    allocation = research.claim(
        agent,
        f"flow-allocation:{action.pk}",
        "flow_allocation",
        action.arguments,
    )
    if allocation.state == "denied":
        raise InputValidationError(allocation.result["error"])
    previous = (
        owned(agent.assignment)
        .filter(specification__task__controller_action=str(action.pk))
        .first()
    )
    if previous:
        return {"run": str(previous.pk), "state": previous.state}
    research_team.admit_mutation(agent)
    allowance = research.allowance(agent.assignment)
    seconds = min(request.max_seconds, allowance["remaining_seconds"])
    if seconds < 60:
        raise InputValidationError("There is insufficient time remaining to execute the flow")

    def start(reuse):
        return experiment_engine.start(
            revision.experiment,
            agent.assignment.created_by,
            revision=revision.number,
            request_key=str(action.pk),
            parameters=request.parameters,
            budget={"max_seconds": seconds},
            controller=action,
            reuse_run=reuse,
            rerun_from=request.rerun_from if reuse else [],
            plan_fingerprint=request.plan_fingerprint,
            admission=request.admission.model_dump(mode="json") if request.admission else None,
            # A run an operator starts stays under the autonomy it was given.
            operator=experiment_operator.autonomy(agent.assignment)
            if experiment_operator.is_operator(agent.assignment)
            else "suggest",
        )

    # Unless another run is named, results come from this assignment's latest settled run:
    # what a later stage takes further is what was measured, not a second execution of it.
    latest = (
        owned(agent.assignment)
        .filter(state__in=["completed", "unmet"])
        .order_by("-created_at")
        .first()
    )
    if request.plan_fingerprint or request.reuse_run or latest is None:
        run = start(request.reuse_run)
    else:
        try:
            with transaction.atomic():
                run = start(latest.pk)
        except InputValidationError:
            # That run cannot be reused as it stands; execute the flow in full.
            run = start(None)
    allocation.result = {"run": str(run.pk)}
    allocation.state = "running"
    allocation.save(update_fields=["result", "state"])
    transaction.on_commit(lambda: advance_flow.delay(str(run.pk)))
    return {
        "run": str(run.pk),
        "state": run.state,
        "revision": revision.number,
    }


@transaction.atomic
def reopen_allocation(run):
    controller = run.specification["task"].get("controller_action")
    if not controller:
        return
    owner = ResearchAction.objects.select_related("agent__assignment").get(pk=controller)
    assignment = type(run).objects.select_for_update().get(pk=owner.agent.assignment_id)
    if assignment.state != "running" or not research.authorized(assignment):
        raise InputValidationError("The controlling research assignment is no longer active")
    allocation = owner.agent.actions.select_for_update().get(
        request_key=f"flow-allocation:{controller}"
    )
    allocation.state, allocation.cost_usd = "running", None
    allocation.save(update_fields=["state", "cost_usd"])


def reconcile(assignment, *, stopping=False):
    settled = True
    for run in owned(assignment):
        if not reconcile_run(assignment, run, stopping=stopping):
            settled = False
    return settled


def receipt_record(run):
    return {
        "run": str(run.pk),
        "state": run.state,
        "definition": run.execution.fingerprint,
        "revision": run.execution.revision.number,
        "parameters": run.execution.parameters,
        "result": run.result,
        "nodes": list(
            run.execution.nodes.order_by("scope_id", "node", "attempt").values(
                "node", "scope_id", "attempt", "state", "inputs", "outputs", "error"
            )
        ),
    }


@transaction.atomic
def reconcile_run(assignment, run, *, stopping=False):
    research_science.experiment_for(assignment, lock=True)
    ExperimentExecution.objects.select_for_update().get(pk=run.pk)
    run.refresh_from_db()
    controller = ResearchAction.objects.get(pk=run.specification["task"]["controller_action"])
    if controller.state == "unknown":
        research.complete(
            controller,
            {"run": str(run.pk), "state": run.state, "revision": run.execution.revision.number},
            cost=0,
        )
    if stopping and run.state not in research.TERMINAL:
        research.stop(run)
    if run.state not in research.TERMINAL:
        return False
    allocation = assignment.agents.get(parent__isnull=True).actions.get(
        request_key=f"flow-allocation:{run.specification['task']['controller_action']}"
    )
    if allocation.cost_usd is None and unsubmitted(run):
        allocation.cost_usd = 0
        allocation.save(update_fields=["cost_usd"])
    # Provider settlements can arrive after the execution receipt is complete.
    committed = research.number(research.allowance(run)["committed_usd"])
    if allocation.reservation_usd != committed:
        allocation.reservation_usd = committed
        allocation.save(update_fields=["reservation_usd"])
    if allocation.state != "completed":
        costs = research.recorded_costs(run)
        record = receipt_record(run)
        receipt = research.claim(
            allocation.agent,
            f"flow-receipt:{run.pk}:{context_graph.fingerprint(record)}",
            "flow_receipt",
            record,
            effect=run.execution,
        )
        if receipt.state == "denied":
            raise InputValidationError("The retained flow receipt could not be recorded")
        artifact = research.retain(
            receipt,
            Artifact(
                path=f"flow/{run.pk}/receipt.json",
                title=f"Flow r{run.execution.revision.number} execution",
                kind="report",
                metadata={
                    "flow_run": str(run.pk),
                    "definition": run.execution.fingerprint,
                    "phase": "final" if run.result.get("selection_locked") else "development",
                },
            ),
            context_graph.canonical(record).encode(),
            source_cells=research_evidence.report_sources(assignment, record),
        )
        research.complete(receipt, research.artifact_record(artifact), cost=0)
        research.complete(
            allocation,
            {
                "run": str(run.pk),
                "state": run.state,
                "costs": costs,
                "artifact": str(artifact.pk),
            },
            cost=costs["all_in_actual_usd"],
        )
    return True


def unsubmitted(run):
    # Native launchers and the document dispatcher share the tool registry.
    from overbae.services import research_tools

    actions = ResearchAction.objects.filter(agent__assignment=run)
    if any(
        action.tool not in {"benchmark", "training", "platform"}
        or action.state not in {"failed", "denied"}
        or action.cost_usd != 0
        or action.reservation_usd != 0
        for action in actions
    ):
        return False
    pipelines, partitions = research_tools.owned_work(run)
    return not (
        experiment_training.campaigns([run.pk]).exists()
        or research_benchmarks.plans(run).exists()
        or pipelines.exists()
        or partitions.exists()
    )