Skip to content

The platform for continuously improving AI agents.

42.7 KB
Raw Blame
import json

from django.db import transaction
from django.db.models import CharField, Exists, OuterRef
from django.db.models.fields.json import KT
from django.db.models.functions import Cast
from django.utils import timezone
from pydantic import ValidationError
from rest_framework.exceptions import ValidationError as ServiceValidationError

from overbae.core.errors import InputValidationError
from overbae.models import (
    ComponentExecution,
    DataPartitionPlan,
    DatasetPipelineRun,
    ExperimentNodeExecution,
    PredictionAttempt,
    ResearchAction,
    TrainingCampaign,
)
from overbae.services import (
    benchmark_evaluations,
    context_graph,
    execution_mandates,
    experiment_artifacts,
    experiment_native,
    experiment_native_contract,
    experiment_training,
    research,
    research_benchmarks,
    research_effects,
    research_evidence,
    research_services,
    research_serving,
    research_workspace,
    serving_lease,
)
from overbae.services.datasets.rows import RowStoreError
from overbae.services.experiment_catalog import resolved
from overbae.services.experiment_interfaces import bound_arguments
from overbae.services.experiment_settings import benchmark_participants


def submit(agent, revision, node, inputs, *, key, node_receipt=None):
    # The domain dispatcher imports experiment services for agent-authored operations.
    from overbae.services import experiment_preflight, research_tools

    payload = arguments(node, inputs)
    if node["operation"]["tool"] == "workspace":
        payload["code"] = experiment_artifacts.execution_code(payload["code"], key)
    previous = agent.actions.filter(request_key=key).exclude(state="pending").first()
    if previous is not None:
        receipt = research.claim(agent, key, node["operation"]["tool"], payload)
        if (
            receipt.experiment_revision_id != revision.pk
            or receipt.experiment_node != node["id"]
            or receipt.experiment_inputs != inputs
        ):
            raise InputValidationError("This request key already binds a different node execution")
        return receipt
    experiment_preflight.validate_resolved(agent.assignment.project, node, inputs)
    validate_native_bindings(agent.assignment, node["operation"]["tool"], payload, inputs)
    receipt = research.claim(agent, key, node["operation"]["tool"], payload)
    with transaction.atomic():
        receipt = (
            ResearchAction.objects.select_for_update()
            .select_related("agent__assignment")
            .get(pk=receipt.pk)
        )
        if receipt.state != "pending":
            return receipt
        receipt.experiment_revision = revision
        receipt.experiment_node = node["id"]
        receipt.experiment_inputs = inputs
        receipt.state = "running"
        receipt.started_at = timezone.now()
        receipt.save(
            update_fields=[
                "experiment_revision",
                "experiment_node",
                "experiment_inputs",
                "state",
                "started_at",
            ]
        )
        if node_receipt is not None:
            if (
                node_receipt.execution_id != agent.assignment_id
                or node_receipt.node != node["id"]
                or key != f"flow:{node_receipt.pk}"
            ):
                raise InputValidationError("The operation must retain its exact flow receipt")
            ExperimentNodeExecution.objects.filter(pk=node_receipt.pk).update(action=receipt)
    try:
        result = invoke_native(receipt)
    except (InputValidationError, ValidationError, ValueError, RowStoreError) as exc:
        research.complete(receipt, research_tools.argument_failure(exc), state="failed", cost=0)
        raise
    except Exception:
        research.complete(
            receipt, {"error": "Node operation outcome requires reconciliation"}, state="unknown"
        )
        raise
    else:
        research.complete(receipt, result, cost=0)
    return receipt


def retained_node(action):
    # Stored node identity is defined by the immutable flow compiler.
    from overbae.services import research_experiments

    action.refresh_from_db()
    receipt = (
        ExperimentNodeExecution.objects.select_related(
            "execution__assignment", "execution__revision", "scope"
        )
        .filter(action=action, execution_id=action.agent.assignment_id)
        .first()
    )
    if receipt is None:
        raise InputValidationError("Continuation requires the admitted flow node receipt")
    execution, scope = receipt.execution, receipt.scope
    node = next((item for item in scope.document["nodes"] if item["id"] == receipt.node), None)
    operation = node.get("operation") if node else None
    if (
        scope.execution_id != execution.pk
        or action.agent.parent_id is not None
        or action.experiment_revision_id != execution.revision_id
        or action.experiment_node != receipt.node
        or action.experiment_inputs != receipt.inputs
        or action.request_key != f"flow:{receipt.pk}"
        or execution.fingerprint
        != context_graph.fingerprint(
            {"document": execution.document, "parameters": execution.parameters}
        )
        or not operation
        or operation["tool"]
        not in {
            "platform",
            "training",
            "benchmark",
            "serving",
            "component",
            "prediction",
            "score",
            "workspace",
        }
        or operation["tool"] == "training"
        and operation["arguments"].get("operation") not in {"create", "qualify", "inspect"}
        or node["kind"] == "research"
        or receipt.identity != research_experiments.node_identity(scope.document, receipt.node)
    ):
        raise InputValidationError("The operation is not its admitted deterministic flow node")
    expected = arguments(node, receipt.inputs)
    if operation["tool"] == "workspace":
        expected["code"] = experiment_artifacts.execution_code(expected["code"], action.request_key)
    if (
        action.tool != operation["tool"]
        or action.arguments != expected
        or action.fingerprint
        != context_graph.fingerprint({"tool": action.tool, "arguments": expected})
    ):
        raise InputValidationError("The operation differs from its pinned node arguments")
    return receipt, node


def admitted_node(action):
    receipt, node = retained_node(action)
    if (
        receipt.execution.assignment.state != "running"
        or receipt.scope.state != "running"
        or receipt.state not in {"pending", "waiting"}
        or action.state not in {"pending", "running", "unknown", "completed"}
    ):
        raise InputValidationError("The operation is not its admitted deterministic flow node")
    return node


def owns_action(action):
    owned = (
        bool(action.experiment_node)
        or bool(action.experiment_inputs)
        or action.request_key.startswith("flow:")
        or ExperimentNodeExecution.objects.filter(action=action).exists()
    )
    if owned:
        admitted_node(action)
    return owned


def invoke_native(action, *, workspace=None):
    # The native dispatcher imports graph execution for experiment tools.
    from overbae.services import research_tools

    with execution_mandates.continuing_node(action):
        if action.tool == "workspace":
            for value in action.experiment_inputs.values():
                for binding in value if isinstance(value, list) else [value]:
                    if binding.get("artifact"):
                        research_workspace.stage_artifact(
                            action.agent,
                            binding["artifact"],
                            fingerprint=binding["fingerprint"],
                            sandbox=workspace,
                        )
        return research_tools.invoke(action, workspace=workspace)


def cell_output(cell, *, sealed=False):
    return {
        "kind": "data",
        "cell": str(cell.pk),
        "dataset": str(cell.dataset_id),
        "fingerprint": cell.fingerprint,
        "sealed": sealed
        or cell.partition_memberships.filter(
            role="final", plan__project_id=cell.dataset.project_id
        ).exists(),
    }


def execution_result(action):
    if action.tool == "workspace":
        if action.result.get("state") == "completed" or action.result.get("timed_out"):
            return action.result
        status = (
            action.agent.actions.filter(
                tool="workspace",
                arguments__execution=str(action.pk),
                arguments__operation__in=["status", "interrupt"],
                state="completed",
            )
            .order_by("-created_at")
            .first()
        )
        if status:
            return status.result
    return action.result


def poll(action):
    if action.tool != "workspace" or action.arguments.get("operation") != "python":
        return
    if action.result.get("state") in {"completed", "failed"}:
        return
    sandbox = research_workspace.existing(action.agent)
    if sandbox is None:
        return
    result = research_workspace.checked_rpc(
        action.agent, sandbox, {"operation": "status", "execution": str(action.pk)}
    )
    action.result = result
    action.save(update_fields=["result"])
    if result.get("state") == "completed":
        research_workspace.checkpoint(action.agent, sandbox, covered=str(action.pk))
    if result.get("state") in {"accepted", "running", "completed"} and action.state in {
        "unknown",
        "running",
    }:
        research.complete(action, result, cost=0)


def reconcile(action):
    # Domain admission persists its idempotent request before queuing provider work.
    from overbae.services import research_tools

    if action.state not in {"running", "unknown"}:
        return
    key = f"research:{action.pk}"
    project = action.agent.assignment.project
    record = None
    result = None
    replayable_admission = False
    workspace = None
    if action.tool == "component" and action.arguments.get("operation") == "run":
        from overbae.models import ComponentExecution
        from overbae.services import component_execution

        replayable_admission = True
        record = ComponentExecution.objects.filter(action=action).first()
        if record:
            result = component_execution.describe(record)
    if action.tool in {"prediction", "score"}:
        from overbae.models import PredictionEvaluation, PredictionSet
        from overbae.services import experiment_predictions, experiment_scoring

        replayable_admission = action.arguments.get("operation") == "run"
        if action.tool == "prediction":
            record = PredictionSet.objects.filter(project=project, request_key=key).first()
            if record:
                result = experiment_predictions.describe(record)
        else:
            record = (
                PredictionEvaluation.objects.filter(run__project=project, request_key=key)
                .select_related("run", "suite")
                .first()
            )
            if record:
                result = experiment_scoring.describe(record)
    if action.tool == "platform" and action.arguments.get("name") == "create_data_partition":
        replayable_admission = True
        record = DataPartitionPlan.objects.filter(project=project, request_key=key).first()
        if record:
            result = {"workflow": {"id": str(record.pk)}}
    elif (
        action.tool == "platform"
        and action.arguments.get("name") in research_services.PIPELINE_RUNS
    ):
        replayable_admission = True
        record = DatasetPipelineRun.objects.filter(
            dataset__project=project, request_key=key
        ).first()
        if record:
            result = {"run": {"id": str(record.pk)}}
    elif action.tool == "benchmark":
        replayable_admission = action.arguments.get("operation") == "run"
        if action.arguments.get("eval_set") or action.arguments.get("suite"):
            cohort = list(
                benchmark_evaluations.records(action.agent.assignment).filter(group=action.pk)
            )
            if cohort:
                result = benchmark_evaluations.describe(cohort)
        else:
            record = (
                research_benchmarks.plans(action.agent.assignment).filter(request_key=key).first()
            )
            if record:
                result = research_benchmarks.describe(record)
    elif action.tool == "training" and action.arguments.get("operation") == "create":
        replayable_admission = True
        record = TrainingCampaign.objects.filter(
            project=action.agent.assignment.project,
            request_key=experiment_training.request_key(action.agent.assignment, action),
        ).first()
        if record:
            result = {"campaign": experiment_training.describe(record)}
    elif action.tool == "workspace" and action.arguments.get("operation") == "python":
        action.agent.refresh_from_db()
        # Submit deduplicates in the original kernel. A lost sandbox must not replay
        # an uncertain execution against an older filesystem snapshot.
        workspace = research_workspace.existing(action.agent)
        replayable_admission = not action.agent.workspace.get("sandbox") or workspace is not None
    if (
        action.tool == "platform"
        and action.arguments.get("name") in experiment_native_contract.WRITES
    ):
        replayable_admission = True
    if action.tool == "serving" and action.arguments.get("operation") == "infer":
        from overbae.models import InferenceRequest
        from overbae.services import inference_requests

        inference = InferenceRequest.objects.filter(project=project, request_key=key).first()
        if inference:
            result = inference_requests.describe(inference)
        else:
            replayable_admission = True
    if result is None and replayable_admission:
        ResearchAction.objects.filter(pk=action.pk, state="unknown").update(state="running")
        try:
            result = invoke_native(action, workspace=workspace)
        except (
            InputValidationError,
            ValidationError,
            ServiceValidationError,
            ValueError,
            RowStoreError,
        ) as exc:
            research.complete(action, research_tools.argument_failure(exc), state="failed", cost=0)
            return
    if result is not None:
        research.complete(action, result, cost=0)
    poll(action)


def observe(action):
    if action.state != "completed":
        return {"state": action.state, "outputs": {}}
    assignment = action.agent.assignment
    outputs = action.experiment_outputs
    result = execution_result(action)
    if action.tool == "workspace":
        if result.get("timed_out") or result.get("exit_code") not in {None, 0}:
            return {"state": "failed", "outputs": {}}
        state = result.get("state", "unknown")
        if state != "completed":
            return {"state": state, "outputs": {}}
        if result.get("exit_code") != 0:
            return {"state": "unverified", "outputs": {}}
        return {"state": "completed" if outputs else "awaiting_output", "outputs": outputs}
    if action.tool == "component":
        if action.arguments.get("operation") == "run":
            from overbae.models import ComponentExecution
            from overbae.services import component_execution

            result = component_execution.describe(ComponentExecution.objects.get(action=action))
            if result["state"] == "unknown":
                result["state"] = "failed"
        return {
            "state": result.get("state", "unknown"),
            "outputs": result.get("outputs", {}),
            "error": result.get("error", ""),
        }
    if action.tool == "prediction":
        from overbae.services import (
            experiment_predictions,  # Prediction services use shared admission.
        )

        predictions = experiment_predictions.get(assignment.project, result.get("id"))
        return {
            "state": predictions.state,
            "outputs": {
                "predictions": {
                    "kind": "predictions",
                    "prediction_set": str(predictions.pk),
                    "candidate": str(predictions.candidate_id),
                    "cell": str(predictions.cell_id),
                    "fingerprint": predictions.fingerprint,
                }
            }
            if predictions.state == "completed"
            else {},
        }
    if action.tool == "score":
        from overbae.services import experiment_scoring  # Scoring uses the shared native services.

        evaluation = experiment_scoring.get(assignment.project, result.get("id"))
        report = experiment_scoring.describe(evaluation)
        return {
            "state": report["state"],
            "outputs": {
                "scores": {
                    "kind": "scores",
                    "evaluation": report["id"],
                    "report": {
                        **report["report"],
                        "expected": evaluation.prediction_set.rows.count(),
                    },
                    "accepted": report["accepted"],
                    "fingerprint": report["fingerprint"],
                    "phase": report["phase"],
                    "protocol": evaluation.suite.fingerprint,
                    "sample_manifest": context_graph.fingerprint(
                        list(
                            evaluation.prediction_set.rows.order_by("index").values(
                                "index", "input_digest"
                            )
                        )
                    ),
                    "candidate_identity": evaluation.prediction_set.candidate.fingerprint,
                    "evidence": {
                        "evaluation": report["id"],
                        "predictions": evaluation.prediction_set.fingerprint,
                    },
                    "data": str(evaluation.prediction_set.cell_id),
                    "candidate": str(evaluation.prediction_set.candidate_id),
                    "model": {
                        "kind": "model",
                        "asset": str(evaluation.prediction_set.candidate_id),
                        "fingerprint": evaluation.prediction_set.candidate.fingerprint,
                    },
                }
            }
            if report["state"] == "completed"
            else {},
        }
    if action.tool == "platform":
        name = action.arguments.get("name")
        if name in experiment_native_contract.WRITES:
            return experiment_native.observe(action) or {"state": "unverified", "outputs": {}}
        if name in research_services.PIPELINE_RUNS:
            run = (
                DatasetPipelineRun.objects.filter(
                    pk=result.get("run", {}).get("id"),
                    dataset__project=assignment.project,
                    request_key=f"research:{action.pk}",
                )
                .select_related("output")
                .first()
            )
            if run:
                outputs = (
                    {
                        "data": cell_output(
                            run.output,
                            # What is written from sealed rows holds them.
                            sealed=bool(action.experiment_inputs.get("data", {}).get("sealed")),
                        )
                    }
                    if run.state == "completed" and run.output_id and run.mode == "publish"
                    else {}
                )
                return {
                    "state": run.state,
                    "outputs": outputs,
                    "error": run.error,
                }
        if name == "create_data_partition":
            plan = (
                DataPartitionPlan.objects.filter(
                    pk=result.get("workflow", {}).get("id"),
                    project=assignment.project,
                    request_key=f"research:{action.pk}",
                )
                .prefetch_related("members__cell")
                .first()
            )
            if plan:
                outputs = (
                    {
                        m.role: {
                            **cell_output(m.cell, sealed=m.role == "final"),
                            "partition": str(plan.pk),
                        }
                        for m in plan.members.all()
                    }
                    if plan.state == "completed"
                    else {}
                )
                return {
                    "state": plan.state,
                    "outputs": outputs,
                    "error": plan.error,
                }
    if action.tool == "benchmark":
        if action.arguments.get("eval_set") or action.arguments.get("suite"):
            return benchmark_evaluations.observe(assignment, action.pk)
        plan = (
            research_benchmarks.plans(assignment)
            .filter(pk=result.get("id"), request_key=f"research:{action.pk}")
            .first()
        )
        if plan:
            binding = {
                "kind": "scores",
                "evaluation": str(plan.pk),
                "data": str(plan.final_cell_id),
                "phase": plan.config.get("purpose"),
                "protocol": context_graph.fingerprint(
                    {
                        key: plan.config.get(key)
                        for key in (
                            "runtime",
                            "inference",
                            "scorer",
                            "calibration_method",
                            "temperatures",
                            "bootstrap_samples",
                            "seed",
                            "logarithm_floor",
                        )
                    }
                ),
            }
            return {
                "state": plan.state,
                "outputs": {
                    "scores": {
                        **binding,
                        "report": plan.results,
                        "reports": research_benchmarks.score_reports(plan, binding),
                        "fingerprint": context_graph.fingerprint(
                            {"config": plan.config, "results": plan.results}
                        ),
                    }
                }
                if plan.state == "completed"
                else {},
            }
    if action.tool == "training":
        identifier = action.arguments.get("campaign") or (result.get("campaign") or {}).get("id")
        campaign = (
            experiment_training.campaigns(research_evidence.owners(assignment))
            .filter(pk=identifier)
            .first()
            if identifier
            else None
        )
        if campaign:
            if action.arguments.get("operation") == "inspect":
                job_id = action.experiment_inputs.get("model", {}).get("job")
                trial = (
                    campaign.trials.filter(
                        job_id=job_id, job__status__in=experiment_training.TRAINED
                    )
                    .select_related("job")
                    .first()
                )
                checks = (
                    list(
                        trial.job.validation_runs.filter(state="completed", stream="development")
                        .order_by("attempt", "step")
                        .values(
                            "id",
                            "attempt",
                            "step",
                            "metrics",
                            "coverage",
                            "receipt_fingerprint",
                            "policy_fingerprint",
                            "sample_fingerprint",
                        )
                    )
                    if trial
                    else []
                )
                if checks:
                    return {
                        "state": "completed",
                        "outputs": {
                            "scores": {
                                "kind": "scores",
                                "job": str(job_id),
                                "campaign": str(campaign.pk),
                                "checks": json.loads(context_graph.canonical(checks)),
                                "reports": [
                                    {
                                        "kind": "scores",
                                        "data": str(trial.job.validation_cell_id),
                                        "phase": "development",
                                        "sample_manifest": check["sample_fingerprint"],
                                        "candidate_identity": context_graph.fingerprint(
                                            [str(job_id), check["attempt"], check["step"]]
                                        ),
                                        "evidence": {
                                            "validation": str(check["id"]),
                                            "receipt": check["receipt_fingerprint"],
                                        },
                                        "job": str(job_id),
                                        "checkpoint": {
                                            "attempt": check["attempt"],
                                            "step": check["step"],
                                        },
                                        **(
                                            {"model": action.experiment_inputs["model"]}
                                            if all(
                                                action.experiment_inputs["model"]
                                                .get("checkpoint", {})
                                                .get(key)
                                                == check[key]
                                                for key in ("attempt", "step")
                                            )
                                            else {}
                                        ),
                                        "protocol": context_graph.fingerprint(
                                            {
                                                "policy": check["policy_fingerprint"],
                                                "sample": check["sample_fingerprint"],
                                            }
                                        )
                                        if check["policy_fingerprint"]
                                        and check["sample_fingerprint"]
                                        else None,
                                        "report": {
                                            **check["metrics"],
                                            **check["coverage"],
                                            "completion": {
                                                "status": "complete"
                                                if (
                                                    check["coverage"].get("expected", 0) > 0
                                                    and check["coverage"].get("scored")
                                                    == check["coverage"]["expected"]
                                                )
                                                else "incomplete"
                                            },
                                        },
                                        "fingerprint": check["receipt_fingerprint"],
                                    }
                                    for check in checks
                                ],
                                "fingerprint": context_graph.fingerprint(
                                    {"receipt": result, "inputs": action.experiment_inputs}
                                ),
                            }
                        },
                    }
                return {"state": "awaiting_output", "outputs": {}}
            if campaign.state == "running":
                return {"state": "running", "outputs": {}}
            model = experiment_training.model_output(campaign)
            if model is not None:
                return {"state": "completed", "outputs": {"model": model}}
            return {
                "state": "cancelled" if campaign.state == "cancelled" else "failed",
                "outputs": {},
                "error": experiment_training.selection(campaign).get("reason")
                or campaign.summary
                or f"The campaign is {campaign.state}",
            }
    if action.tool == "serving":
        if action.arguments.get("operation") in {"infer", "stop"}:
            return experiment_native.observe_serving(action)
        campaign = (
            research_evidence.experiment_campaigns(assignment)
            .filter(pk=action.arguments.get("campaign"))
            .first()
        )
        submitted = (
            next(
                (
                    item
                    for item in result
                    if isinstance(item, dict)
                    and (
                        campaign
                        and campaign.selected_id
                        and item.get("job") == str(campaign.selected_id)
                        or item.get("deployment") == action.arguments.get("deployment")
                    )
                ),
                None,
            )
            if isinstance(result, list)
            else None
        )
        model = (
            research_serving.observed(assignment).filter(pk=submitted["deployment"]).first()
            if submitted and submitted.get("deployment")
            else None
        )
        if model:
            lease = model.serving_runtime.get("lease", {})
            if submitted.get("generation") != str(model.deployment_generation) or (
                submitted.get("lease") or {}
            ).get("allocation") != lease.get("allocation"):
                return {"state": "superseded", "outputs": {}}
            if model.status == "ready" and not serving_lease.closed(model):
                return {
                    "state": "completed",
                    "outputs": {
                        "deployment": {
                            "kind": "deployment",
                            "deployment": str(model.pk),
                            "job": str(model.finetuning_job_id),
                            "generation": str(model.deployment_generation),
                            "allocation": lease.get("allocation"),
                        }
                    },
                }
            return {
                "state": "expired" if serving_lease.closed(model) else model.status,
                "outputs": {},
                "error": model.error_message,
            }
    return {"state": "recorded", "outputs": {}}


def arguments(node, inputs):
    operation = node["operation"]
    args = json.loads(json.dumps(operation["arguments"]))
    if operation["tool"] in {"prediction", "score", "component"}:
        if operation["tool"] in {"prediction", "score"}:
            bound = {}
            for key, source in bound_arguments(operation["tool"], args["operation"]).items():
                value = inputs
                for part in source.split("."):
                    if not isinstance(value, dict) or part not in value:
                        raise InputValidationError(f"Connect a retained input providing {source}")
                    value = value[part]
                bound[key] = value
        else:
            bound = {"inputs": inputs}
            if node["kind"] == "component":
                bound["component"] = node["config"]["asset"]
        for key, value in bound.items():
            if key in args and args[key] != value:
                raise InputValidationError(f"{key} must match its connected retained input")
            args[key] = value
        return args
    if operation["tool"] == "workspace":
        prefix = (
            "import json as _experiment_json\n"
            + f"inputs = _experiment_json.loads({context_graph.canonical(inputs)!r})\nparameters = _experiment_json.loads({context_graph.canonical(node['config'])!r})\n"
        )
        args["code"] = prefix + args["code"]
    elif operation["tool"] == "platform":
        for path, source in bound_arguments("platform", args["name"]).items():
            value = inputs
            for part in source.split("."):
                if not isinstance(value, dict) or part not in value:
                    raise InputValidationError(f"Connect a retained input providing {source}")
                value = value[part]
            native = args
            parts = path.split(".")
            for part in parts[:-1]:
                native = native.setdefault(part, {})
            key = parts[-1]
            if key in native and native[key] != value:
                raise InputValidationError(
                    f"Remove {path}; its value is bound by the connected input"
                )
            native[key] = value
    elif operation["tool"] == "training":
        native = args.setdefault("arguments", {})
        if args["operation"] == "create":
            run = native.setdefault("run", {})
            model = inputs["model"]["model"]
            if run.get("base_model", model) != model:
                raise InputValidationError("Training must use the connected model")
            run["base_model"] = model
            data = inputs.get("data") or {}
            if "cell" not in data:
                raise InputValidationError("Training requires a published train input")
            for port, key in (("data", "cell"), ("development", "validation_cell")):
                bound = inputs.get(port) or {}
                if "cell" not in bound:
                    continue
                if bound.get("sealed"):
                    raise InputValidationError("A sealed final version cannot train or validate")
                if key in run and run[key] != bound["cell"]:
                    raise InputValidationError("Training data differs from the connected dataset")
                run[key] = bound["cell"]
            run.setdefault("dataset", data["dataset"])
        elif args["operation"] == "inspect":
            campaign = inputs.get("model", {}).get("campaign")
            if not campaign or args.get("campaign") not in {None, campaign}:
                raise InputValidationError("Inspection must use the connected trained model")
            args["campaign"] = campaign
    elif operation["tool"] == "benchmark":
        cell = inputs.get("data", {}).get("cell")
        if not cell or args.get("cell") not in {None, cell}:
            raise InputValidationError("Benchmark data must match the connected dataset")
        args["cell"] = cell
        suite = inputs.get("suite", {}).get("asset")
        if suite:
            if args.get("suite") not in {None, suite}:
                raise InputValidationError("The benchmark suite must match its connected eval set")
            args["suite"] = suite
        model = inputs.get("model", {})
        if model:
            if not args.get("participants"):
                args["baseline"] = "candidate"
            args["participants"] = benchmark_participants(args.get("participants", []), model)
    elif operation["tool"] == "serving":
        port, field = (
            ("deployment", "deployment")
            if args["operation"] in {"infer", "stop"}
            else ("model", "campaign")
        )
        value = inputs.get(port, {}).get(field)
        if not value or args.get(field) not in {None, value}:
            raise InputValidationError(f"Serving requires the connected {field}")
        args[field] = value
    return args


@transaction.atomic
def retain_outputs(action, bindings):
    action = (
        ResearchAction.objects.select_for_update(of=("self",))
        .select_related("agent__assignment", "experiment_revision")
        .get(pk=action.pk)
    )
    result = execution_result(action)
    if action.tool != "workspace":
        raise InputValidationError(
            "Native operations retain their outputs automatically. Inspect or execute the saved node "
            "to observe its current result; outputs is only for authored Python artifacts."
        )
    if (
        action.state != "completed"
        or result.get("state") != "completed"
        or result.get("exit_code") != 0
        or result.get("timed_out")
    ):
        raise InputValidationError(
            "Only a successful authored execution can bind retained artifacts"
        )
    execution = (
        ExperimentNodeExecution.objects.select_related("scope").filter(action=action).first()
    )
    document = execution.scope.document if execution else action.experiment_revision.document
    node = next(n for n in document["nodes"] if n["id"] == action.experiment_node)
    outputs = {}
    for port, identifier in bindings.items():
        kind = resolved(node).outputs.get(port)
        artifact = research.accessible_artifact(action.agent.assignment, identifier)
        accepted = {
            "data": {"data"},
            "model": {"model"},
            "predictions": {"data", "benchmark"},
            "scores": {"evaluation", "benchmark"},
        }
        if kind not in accepted or artifact.kind not in accepted[kind]:
            raise InputValidationError("The retained artifact type does not match the output port")
        if (
            artifact.agent_id != action.agent_id
            or action.started_at is None
            or artifact.created_at < action.started_at
        ):
            raise InputValidationError("Retain the output from this node's execution workspace")
        if artifact.metadata.get("producer_action") != str(action.pk) or artifact.metadata.get(
            "inputs_fingerprint"
        ) != context_graph.fingerprint(action.experiment_inputs):
            raise InputValidationError(
                "Output metadata must bind producer_action and inputs_fingerprint from execute"
            )
        outputs[port] = {
            "kind": kind,
            "artifact": str(artifact.pk),
            "fingerprint": artifact.sha256,
            "path": f"{research_workspace.ROOT}/inputs/artifacts/{artifact.pk}.bin",
            "verification": "retained_bytes",
        }
    if not outputs:
        raise InputValidationError("Bind at least one retained output")
    if action.experiment_outputs and action.experiment_outputs != outputs:
        raise InputValidationError("This execution already retained different outputs")
    action.experiment_outputs = outputs
    action.save(update_fields=["experiment_outputs"])
    return observe(action)


def validate_native_bindings(assignment, tool, args, inputs, *, project=None):
    if tool == "serving" and args.get("operation") in {"infer", "stop"}:
        binding = inputs.get("deployment", {})
        deployed = research_serving.observed(assignment).filter(pk=args.get("deployment")).first()
        if (
            not deployed
            or binding.get("generation") != str(deployed.deployment_generation)
            or binding.get("allocation")
            != deployed.serving_runtime.get("lease", {}).get("allocation")
        ):
            raise InputValidationError("The connected deployment generation or allocation changed")
    model = inputs.get("model", {})
    if model.get("job") and not research_evidence.verified_model(
        project or assignment.project, model
    ):
        raise InputValidationError(
            "The connected checkpoint no longer matches its verified publication"
        )
    if (
        tool == "serving"
        and args.get("operation") == "deploy"
        and not (
            research_evidence.experiment_campaigns(assignment)
            .filter(pk=args.get("campaign"), selected_id=model.get("job"))
            .exists()
        )
    ):
        raise InputValidationError(
            "The connected checkpoint must be the campaign's selected candidate"
        )
    if (
        tool == "benchmark"
        and model
        and (
            not model.get("job")
            or not any(
                str(p.get("job")) == str(model["job"]) and p.get("kind") == "trained"
                for p in args.get("participants", [])
            )
        )
    ):
        raise InputValidationError("The benchmark must include the connected trained checkpoint")
    if tool == "training" and args.get("operation") == "inspect":
        campaign = (
            research_evidence.campaigns(assignment, observe=True)
            .filter(pk=args.get("campaign"))
            .first()
        )
        trial = (
            campaign.trials.select_related("job")
            .filter(job_id=inputs.get("model", {}).get("job"))
            .first()
            if campaign
            else None
        )
        if trial is None or (
            inputs.get("data") and inputs["data"].get("cell") != str(trial.job.validation_cell_id)
        ):
            raise InputValidationError(
                "Development measurement requires this run's retained trial and its exact development data"
            )
        selected = experiment_training.handoff(trial.job)
        if (
            selected["state"] != "ready"
            or inputs["model"].get("fingerprint") != selected["checkpoint"]["identity"]
        ):
            raise InputValidationError(
                "Development measurement requires the connected verified checkpoint"
            )
    if (
        tool == "serving"
        and args.get("deployment")
        and (
            not research_serving.observed(assignment)
            .filter(
                pk=args["deployment"],
                finetuning_job_id=(inputs.get("model") or inputs.get("deployment", {})).get("job"),
            )
            .exists()
        )
    ):
        raise InputValidationError("Deployment differs from the connected model")


def has_unconfirmed_work(assignment):
    return pending_work([assignment.pk])


def pending_work(assignments):
    components = ComponentExecution.objects.filter(action__agent__assignment_id__in=assignments)
    attempts = PredictionAttempt.objects.filter(row__prediction_set__assignment_id__in=assignments)
    calls = (
        ResearchAction.objects.filter(
            agent__assignment_id__in=assignments,
            tool="prediction_model",
            state__in=["pending", "running", "unknown"],
        )
        .alias(prediction_attempt=KT("arguments__attempt"))
        .filter(prediction_attempt=OuterRef("attempt_identity"))
    )
    return (
        experiment_native.pending_work(assignments)
        or components.filter(state__in=["queued", "running"]).exists()
        or research_effects.unconfirmed_unknown(components).exists()
        or research_effects.unsettled_scripts(components).exists()
        or attempts.filter(state__in=["queued", "running"]).exists()
        or research_effects.unconfirmed_unknown(attempts)
        .exclude(receipt__model_actions__0__isnull=False)
        .exists()
        or research_effects.unsettled_scripts(attempts).exists()
        or attempts.alias(attempt_identity=Cast("pk", CharField())).filter(Exists(calls)).exists()
    )