Skip to content

The platform for continuously improving AI agents.

36.0 KB
Raw Blame
import hashlib
import json
from contextlib import suppress
from itertools import zip_longest
from types import SimpleNamespace
from uuid import UUID

import pyarrow as pa
import pyarrow.parquet as pq
from django.db.models import Q

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import (
    Cell,
    DataPartitionMember,
    DataPartitionPlan,
    DatasetPipelineRun,
    ExperimentNodeExecution,
    InferenceRequest,
    PredictionEvaluation,
    ResearchAction,
    ResearchAgent,
    ResearchAssignment,
)
from overbae.services import (
    context_graph,
    experiment_assets,
    experiment_native,
    experiment_scoring,
    experiment_training,
    research,
    research_benchmarks,
    research_effects,
    research_evidence,
    research_experiments,
    research_services,
    research_serving,
    research_team,
    serving_lease,
    training_campaigns,
)
from overbae.services.compute_costs import training_cost
from overbae.services.datasets import pipeline_packages, preparation, rows, store
from overbae.services.research_contract import ServingExample


def cell_record(cell):
    if cell is None:
        return None
    return {
        "id": str(cell.pk),
        "dataset": str(cell.dataset_id),
        "dataset_name": cell.dataset.name,
        "source_brief": cell.dataset.brief,
        "role": cell.dataset.source_spec.get("role"),
        "state": cell.state,
        "rows": cell.rows,
        "fingerprint": cell.fingerprint,
    }


def flow_run_facts(assignment):
    """Every flow run with its outputs. A run that reused a measurement repeats its report byte
    for byte, so each report is kept once, on the newest run that holds it."""
    # Flow dispatch consumes acceptance through the native tools.
    from overbae.services import experiment_dispatch

    runs = experiment_dispatch.observations(assignment, include_reports=True)
    newest = {}
    for run in reversed(runs):
        for binding in run["outputs"].values():
            if "report" not in binding:
                continue
            identity = context_graph.fingerprint(binding["report"])
            if identity in newest:
                del binding["report"]
                binding["report_retained_by_run"] = newest[identity]
            else:
                newest[identity] = run["run"]
    return runs


def execution_failure(assignment, action):
    projected = research_evidence.action_result(assignment, action)
    return {
        "receipt": str(action.pk),
        "at": action.completed_at.isoformat() if action.completed_at else None,
        "tool": action.tool,
        "operation": action.arguments.get("operation") or action.arguments.get("name"),
        "state": action.state,
        "error": projected.get("error"),
        **({"access": projected["access"]} if projected.get("access") == "sealed_data" else {}),
    }


def acceptance_artifacts(assignment):
    owners = research_evidence.owners(assignment)
    references = set()

    def reference(value):
        with suppress(ValueError, TypeError):
            references.add(UUID(str(value)))

    def collect(value):
        if isinstance(value, list):
            for item in value:
                collect(item)
        elif isinstance(value, dict):
            if value.get("kind") in ("artifact", "research_artifact"):
                reference(value.get("id"))
            for key, item in value.items():
                if key == "artifact":
                    reference(item)
                elif key in {"artifacts", "input_artifacts"} and isinstance(item, list):
                    for identifier in item:
                        reference(identifier)
                elif key == "context_roots" and isinstance(item, list):
                    for root in item:
                        if isinstance(root, str) and root.startswith(
                            ("artifact:", "research_artifact:")
                        ):
                            reference(root.split(":", 1)[1])
                collect(item)

    collect(assignment.specification)
    collect({"context_roots": assignment.context.roots})
    collect(assignment.execution_mandate)
    for work_order, result in ResearchAgent.objects.filter(assignment_id__in=owners).values_list(
        "work_order", "result"
    ):
        collect(work_order)
        collect(result)
    for inputs, outputs in ExperimentNodeExecution.objects.filter(
        execution__assignment_id__in=owners,
        execution__assignment__project=assignment.project,
    ).values_list("inputs", "outputs"):
        collect(inputs)
        collect(outputs)
    return (
        research_evidence.artifacts(assignment)
        .filter(Q(assignment_id__in=owners) | Q(pk__in=references))
        .order_by("created_at", "pk")
    )


def score_facts(assignment):
    return [
        {
            **experiment_scoring.describe(evaluation),
            "suite_definition": experiment_assets.describe(evaluation.suite),
            "cell": cell_record(evaluation.prediction_set.cell),
            "candidate": experiment_assets.describe(evaluation.prediction_set.candidate),
        }
        for evaluation in PredictionEvaluation.objects.filter(
            assignment_id__in=research_evidence.owners(assignment),
            assignment__project=assignment.project,
            prediction_set__project=assignment.project,
            suite__project=assignment.project,
        )
        .select_related(
            "run", "suite", "prediction_set__candidate", "prediction_set__cell__dataset"
        )
        .order_by("created_at", "pk")
    ]


def acceptance_partitions(assignment):
    # The renderer is shared with project-wide discovery; only review selects this scope.
    from overbae.services import research_tools

    owners = set(research_evidence.owners(assignment)) | set(
        research_evidence.flows(assignment).values_list("pk", flat=True)
    )
    assignments = ResearchAssignment.objects.filter(pk__in=owners, project=assignment.project)
    pipelines, owned = research_effects.owned_data(assignments)
    plans = set(owned.values_list("pk", flat=True))
    cells = set(pipelines.values_list("source_id", flat=True))

    def identifier(value, destination):
        with suppress(ValueError, TypeError):
            destination.add(UUID(str(value)))

    def collect(value, key=""):
        if isinstance(value, dict):
            if value.get("kind") == "cell":
                identifier(value.get("id"), cells)
            elif value.get("kind") == "partition":
                identifier(value.get("id"), plans)
            for name, child in value.items():
                collect(child, name)
        elif isinstance(value, list):
            for child in value:
                collect(child, key)
        elif isinstance(value, str):
            if key in {
                "cell",
                "source_cell",
                "train_cell",
                "development_cell",
                "final_cell",
                "source_cells",
                "sealed_cells",
            }:
                identifier(value, cells)
            if key in {"partition", "partition_id", "partition_plan"}:
                identifier(value, plans)
            kind, _, reference = value.partition(":")
            if kind == "cell":
                identifier(reference, cells)
            elif kind == "partition":
                identifier(reference, plans)

    for owner in assignments.select_related("context", "experiment_revision"):
        collect(owner.specification)
        collect(owner.execution_mandate)
        collect(owner.context.roots)
        if owner.experiment_revision_id:
            collect(owner.experiment_revision.document)
    if revision := research_experiments.current_revision(assignment):
        collect(revision.document)
    for arguments in ResearchAction.objects.filter(agent__assignment__in=assignments).values_list(
        "arguments", flat=True
    ):
        collect(arguments)
    for inputs, outputs in ExperimentNodeExecution.objects.filter(
        execution_id__in=owners
    ).values_list("inputs", "outputs"):
        collect(inputs)
        collect(outputs)
    for campaign in research_benchmarks.owned_campaigns(assignment):
        collect(campaign.arguments)
    for plan in research_benchmarks.plans(assignment, observe=True):
        cells.add(plan.final_cell_id)
        if plan.calibration_cell_id:
            cells.add(plan.calibration_cell_id)
    cells.update(
        DataPartitionPlan.objects.filter(project=assignment.project, pk__in=plans).values_list(
            "source_cell_id", flat=True
        )
    )
    ancestors = set()
    diagnostics = []
    for cell in Cell.objects.filter(
        pk__in=cells, dataset__project=assignment.project
    ).select_related("dataset"):
        ancestors.add(cell.pk)
        try:
            process = preparation.describe(cell.dataset, cell=cell, include_siblings=False)
        except DatasetError as error:
            if error.code != "preparation_limit":
                raise
            diagnostics.append({"cell": str(cell.pk), "lineage": "incomplete", "error": str(error)})
            continue
        ancestors.update(node["cell"].pk for node in process["nodes"])
    plans.update(
        DataPartitionMember.objects.filter(
            cell_id__in=ancestors, plan__project=assignment.project
        ).values_list("plan_id", flat=True)
    )
    records = research_tools.input_partitions(assignment, plan_ids=plans, include_unavailable=True)
    records.extend(
        {"partition": str(plan.pk), "name": plan.name, "state": plan.state, "error": plan.error}
        for plan in DataPartitionPlan.objects.filter(project=assignment.project, pk__in=plans)
        .exclude(state="completed")
        .order_by("created_at", "pk")
    )
    return records + diagnostics


def facts(assignment):
    observed_at = (
        ResearchAction.objects.filter(agent__assignment=assignment, completed_at__isnull=False)
        .order_by("-completed_at")
        .values_list("completed_at", flat=True)
        .first()
    )
    campaigns = []
    for campaign in (
        research_evidence.campaigns(assignment, observe=True)
        .select_related("selected__cell__dataset", "selected__validation_cell__dataset")
        .order_by("pk")
    ):
        item = {
            "id": str(campaign.pk),
            "state": campaign.state,
            "summary": campaign.summary,
            "max_trials": campaign.max_trials,
            # The versions every run of the campaign trains and checks on.
            "data": {
                role: {"cell": campaign.arguments[key]}
                for role, key in (("train", "cell"), ("development", "validation_cell"))
                if campaign.arguments.get(key)
            },
            "selected": None,
            "trials": [
                {
                    "trial": str(trial.pk),
                    "job": str(trial.job_id),
                    "state": trial.job.status,
                    "base_model": trial.job.base_model,
                    "train": cell_record(trial.job.cell),
                    "development": cell_record(trial.job.validation_cell),
                    "requested_training": trial.job.hyperparameters,
                    "planned_recipe": trial.recipe,
                    "reason": trial.reason,
                    "training_trajectory": experiment_training.development(trial.job),
                    "checkpoint": experiment_training.checkpoint(trial.job),
                    "best_development_loss": training_campaigns.outcome(trial.job),
                    "error": trial.job.error_message,
                    "cost": training_cost(trial.job),
                }
                for trial in campaign.trials.select_related(
                    "job__cell__dataset", "job__validation_cell__dataset"
                ).order_by("created_at")
            ],
        }
        if campaign.selected_id:
            job = campaign.selected
            item["selected"] = {
                "job": str(job.pk),
                "base_model": job.base_model,
                "train": cell_record(job.cell),
                "development": cell_record(job.validation_cell),
                "requested_training": job.hyperparameters,
                "selection": experiment_training.selection(campaign),
                "training_trajectory": experiment_training.development(job),
            }
        campaigns.append(item)
    return research_evidence.project_report(
        assignment,
        {
            "assignment": str(assignment.pk),
            "timing": {
                "started_at": assignment.created_at.isoformat(),
                "through": observed_at.isoformat() if observed_at else None,
                "elapsed_seconds": (observed_at - assignment.created_at).total_seconds()
                if observed_at
                else None,
                "scope": "Assignment creation through last completed action; includes queues and recovery.",
            },
            "costs": research.recorded_costs(assignment),
            "cost_snapshots": [
                {
                    "receipt": str(action["id"]),
                    "recorded_at": action["created_at"].isoformat(),
                    "costs": action["arguments__cost_snapshot"],
                }
                for action in ResearchAction.objects.filter(
                    agent__assignment=assignment,
                    tool="model",
                    arguments__cost_snapshot__as_of__isnull=False,
                )
                .order_by("-created_at")
                .values("id", "created_at", "arguments__cost_snapshot")[:20]
            ]
            + [
                {
                    "receipt": str(action["id"]),
                    "recorded_at": action["completed_at"].isoformat(),
                    "costs": action["result__costs"],
                }
                for action in ResearchAction.objects.filter(
                    agent__assignment=assignment,
                    tool="review",
                    arguments__operation="facts",
                    state="completed",
                    completed_at__isnull=False,
                    result__costs__isnull=False,
                )
                .order_by("-created_at")
                .values("id", "completed_at", "result__costs")[:20]
            ],
            "campaigns": campaigns,
            "scores": score_facts(assignment),
            "discovery": discovery_facts(assignment),
            "input_partitions": acceptance_partitions(assignment),
            "benchmarks": research_benchmarks.observations(assignment),
            # What the trained-on data was made from is part of what a model's result means.
            "transformations": transformation_facts(
                assignment,
                [
                    source["cell"]
                    for campaign in campaigns
                    for source in campaign["data"].values()
                    if isinstance(source, dict) and source.get("cell")
                ],
            ),
            "execution_failures": [
                execution_failure(assignment, action)
                for action in ResearchAction.objects.filter(
                    agent__assignment=assignment,
                    tool__in=[
                        "platform",
                        "training",
                        "experiment",
                        "serving",
                        "benchmark",
                        "retain_pipeline",
                    ],
                    state__in=["failed", "denied", "unknown"],
                ).order_by("created_at")
            ],
            "flow_runs": flow_run_facts(assignment),
            "experiment_outputs": [
                {
                    key: node[key]
                    for key in ("node", "revision", "action", "state", "outputs", "current")
                }
                for node in research_experiments.run_record(assignment)["nodes"]
            ]
            if assignment.experiment_revision_id
            else [],
            "retained_artifacts": [
                research.artifact_record(a) for a in acceptance_artifacts(assignment)
            ],
            "independent_verifications": research_team.accepted_verifications(assignment),
            "inference_reviews": [
                {
                    "receipt": str(action.pk),
                    "created_at": action.created_at.isoformat(),
                    "state": action.state,
                    **{
                        key: action.result[key]
                        for key in ("subject", "accepted", "state")
                        if key in action.result
                    },
                }
                for action in ResearchAction.objects.filter(
                    agent__assignment=assignment,
                    tool="review",
                    arguments__operation="inference",
                ).order_by("created_at")
            ],
            "serving_lifecycle": [
                {
                    "receipt": str(action.pk),
                    "created_at": action.created_at.isoformat(),
                    "state": action.state,
                    "operation": action.arguments.get("operation"),
                    "deployment": action.arguments.get("deployment"),
                    "campaign": action.arguments.get("campaign"),
                }
                for action in ResearchAction.objects.filter(
                    agent__assignment_id__in=research_evidence.owners(assignment),
                    tool="serving",
                    arguments__operation__in=["deploy", "stop"],
                ).order_by("created_at")
            ],
            "serving": [
                {
                    "deployment": str(model.pk),
                    "job": str(model.finetuning_job_id),
                    "model_id": model.model_id,
                    "checkpoint_hash": model.checkpoint_hash,
                    "context_length": model.max_model_len,
                    "state": research_serving.state(model),
                    # How long it was to serve, counted from ready, and when it stopped.
                    "lease": {
                        key: (serving_lease.policy(model) or {}).get(key)
                        for key in ("ttl_seconds", "deadline", "closed_at")
                    },
                    "inferences": [
                        {
                            "id": str(request.pk),
                            "state": request.state,
                            "input": request.payload.get("decisions")
                            or request.payload.get("messages"),
                            "generation": {
                                key: request.payload.get(key)
                                for key in (
                                    "max_tokens",
                                    "temperature",
                                    "chat_template_kwargs",
                                    "deployment_generation",
                                    "checkpoint_hash",
                                )
                            },
                            "result": request.result,
                        }
                        for request in InferenceRequest.objects.filter(
                            deployment=model, payload__source="research"
                        ).order_by("created_at")
                    ],
                }
                for model in research_serving.observed(assignment).order_by("pk")
            ],
        },
    )


def discovery_facts(assignment):
    records, seen = [], set()
    for action in ResearchAction.objects.filter(
        agent__assignment=assignment,
        state="completed",
        tool__in=["platform", "inspect_source"],
    ).order_by("-created_at", "-pk"):
        if action.arguments.get("describe"):
            continue
        if action.tool == "platform":
            if action.arguments.get("name") not in {
                "get_model_catalog",
            }:
                continue
            observed = action.result
        else:
            if not isinstance(action.result, dict) or "dataset" not in action.result:
                continue
            observed = {
                key: action.result.get(key)
                for key in ("cell", "fingerprint", "dataset", "schema", "partition", "role")
            }
            cell = (
                Cell.objects.select_related("dataset")
                .filter(
                    pk=observed["cell"],
                    fingerprint=observed["fingerprint"],
                    dataset__project=assignment.project,
                )
                .first()
            )
            observed["retained_cell"] = cell_record(cell)
        identity = context_graph.canonical([action.tool, action.arguments.get("name"), observed])
        if identity in seen:
            continue
        seen.add(identity)
        records.append(
            {
                "receipt": str(action.pk),
                "at": action.completed_at.isoformat() if action.completed_at else None,
                "tool": action.tool,
                "operation": action.arguments.get("name"),
                "observed": observed,
            }
        )
    return list(reversed(records))


def lineage(project, cells):
    """Completed pipeline runs that produced the cells with these identifiers or the versions
    they were cut from, oldest first. A partition is traced to its source and a published
    version to its run."""
    pending, seen, runs = [UUID(str(cell)) for cell in cells], set(), {}
    while pending and len(seen) < 32:
        identifier = pending.pop()
        if identifier in seen:
            continue
        seen.add(identifier)
        pending += DataPartitionMember.objects.filter(
            cell_id=identifier, plan__project=project, plan__state="completed"
        ).values_list("plan__source_cell_id", flat=True)
        for run in DatasetPipelineRun.objects.filter(
            output_id=identifier, dataset__project=project, state="completed"
        ):
            runs[run.pk] = run.created_at
            pending.append(run.source_id)
    return sorted(runs, key=runs.get)


def transformation_facts(assignment, cells=()):
    """The pipeline runs behind an investigation's data: those its flows ran and those that
    produced the cells with these identifiers, whoever ran them."""
    owners = research_evidence.owners(assignment)
    actions = ResearchAction.objects.filter(
        agent__assignment_id__in=owners,
        tool="platform",
        arguments__name__in=sorted(research_services.PIPELINE_RUNS),
        state="completed",
    ).values_list("pk", flat=True)
    records = []
    for run in (
        DatasetPipelineRun.objects.filter(
            Q(request_key__in=[f"research:{action}" for action in actions])
            | Q(pk__in=lineage(assignment.project, cells)),
            dataset__project=assignment.project,
        )
        .select_related("pipeline__package", "source__dataset", "output__dataset")
        .order_by("created_at")
    ):
        package = run.pipeline.package if run.pipeline_id else None
        record = {
            "run": str(run.pk),
            "state": run.state,
            "source": cell_record(run.source),
            "output": cell_record(run.output),
            "specification": run.specification,
            "package": pipeline_packages.record(package) if package else None,
        }
        if package:
            source = pipeline_packages.files(package)
            record["entrypoints"] = [
                {
                    "path": path,
                    "content": source[path][:16000],
                    "total_characters": len(source[path]),
                    "truncated": len(source[path]) > 16000,
                }
                for path in dict.fromkeys(step["entrypoint"] for step in package.manifest["steps"])
            ]
        records.append(record)
    return records


def example_input(assignment, identifier):
    # Source authority belongs to the tool surface, which invokes acceptance.
    from overbae.services.research_tools import source_cell

    examples = assignment.specification.get("acceptance", {}).get("serving_examples", [])
    example = next((item for item in examples if item["id"] == identifier), None)
    if example is None:
        raise InputValidationError("Select a frozen serving example from the acceptance contract")
    spec = ServingExample.model_validate(example)
    cell = source_cell(assignment, spec.cell)
    if cell.fingerprint != spec.cell_fingerprint:
        raise InputValidationError("The acceptance source fingerprint changed")
    try:
        rows.verify(cell)
    except rows.RowStoreError as exc:
        raise InputValidationError(str(exc)) from exc
    found = list(rows.rows(cell, [spec.row]))
    if len(found) != 1:
        raise InputValidationError("The required source row is unavailable")
    value = found[0].input
    for part in spec.input_path:
        if not isinstance(value, dict) or part not in value:
            raise InputValidationError("The serving example input path is unavailable")
        value = value[part]
    text = value if isinstance(value, str) else context_graph.canonical(value)
    if hashlib.sha256(text.encode()).hexdigest() != spec.input_sha256:
        raise InputValidationError("The acceptance input differs from its frozen bytes")
    return text, {
        **spec.model_dump(mode="json"),
        "cell_fingerprint": cell.fingerprint,
        "input_sha256": hashlib.sha256(text.encode()).hexdigest(),
    }


def review_data(assignment, artifact):
    # Native tool dispatch imports acceptance; use its shared source-access boundary.
    from overbae.services.research_tools import source_cell

    metadata = artifact.metadata
    if artifact.kind != "data" or metadata.get("format") not in {"jsonl", "parquet"}:
        raise InputValidationError("Select a native JSONL or Parquet export with a pinned source")
    if not metadata.get("cell"):
        raise InputValidationError("The retained export has no source identity")
    source = source_cell(assignment, metadata["cell"])
    rows.verify(source)
    if metadata.get("cell") != str(source.pk) or metadata.get("fingerprint") != source.fingerprint:
        raise InputValidationError("The export source identity changed")
    missing = object()
    differences, total = [], 0
    try:
        with research.artifact_stream(artifact) as snapshot:
            exported = (
                (json.loads(line) for line in snapshot)
                if metadata["format"] == "jsonl"
                else (
                    record
                    for batch in pq.ParquetFile(snapshot).iter_batches(batch_size=4096)
                    for record in batch.to_pylist()
                )
            )
            for index, (expected, actual) in enumerate(
                zip_longest(store.iter_rows(rows.frame_path(source)), exported, fillvalue=missing)
            ):
                total += 1
                if (
                    expected is missing
                    or actual is missing
                    or context_graph.canonical(expected) != context_graph.canonical(actual)
                ) and len(differences) < 100:
                    differences.append(index)
    except (ValueError, UnicodeDecodeError, pa.ArrowException) as exc:
        raise InputValidationError(
            "Retained data cannot be decoded in its declared format"
        ) from exc
    return {
        "accepted": not differences,
        "state": "verified" if not differences else "failed",
        "subject": {"artifact": str(artifact.pk), "sha256": artifact.sha256},
        "source": {"cell": str(source.pk), "fingerprint": source.fingerprint},
        "checked_records": total,
        "first_mismatched_indices": differences,
        "scope": "Checksum, full record coverage, order and value fidelity; task semantics and model quality require separate review.",
    }


def verify_report(assignment, artifact):
    """Check a native receipt against the record the platform retained or can recompute."""
    if artifact.action.tool == "flow_receipt":
        expected = context_graph.canonical(artifact.action.arguments).encode()
        if research.artifact_bytes(artifact, limit=len(expected)) != expected:
            raise InputValidationError("The execution receipt differs from its retained record")
        return {
            "state": "verified",
            "accepted": True,
            "subject": {"artifact": str(artifact.pk), "sha256": artifact.sha256},
            "scope": "Execution receipt integrity; task and output verification remain separate",
        }
    if artifact.action.tool == "platform" and artifact.action.arguments.get("name") == "check_data":
        # Tool dispatch imports acceptance; reuse its source-access boundary after initialization.
        from overbae.services.research_tools import source_cell

        source = source_cell(assignment, artifact.metadata.get("cell"))
        if source.fingerprint != artifact.metadata.get("fingerprint"):
            raise InputValidationError(
                "The validation report source identity changed or is unavailable"
            )
        arguments = artifact.action.arguments.get("arguments", {})
        report = experiment_native.check_data(
            source, arguments.get("row_schema", {}), arguments.get("minimum_rows", 1)
        )
        expected = context_graph.canonical(report).encode()
        if research.artifact_bytes(artifact, limit=len(expected)) != expected:
            raise InputValidationError(
                "The validation report differs from its recomputed source check"
            )
        return {
            "state": "verified",
            "accepted": True,
            "subject": {"artifact": str(artifact.pk), "sha256": artifact.sha256},
            "source": {"cell": str(source.pk), "fingerprint": source.fingerprint},
            "report": report,
            "scope": "Recomputed native validation and exact report bytes; task semantics remain separate",
        }
    raise InputValidationError("Select a native execution receipt or data check report")


def verify_inference(assignment, request):
    """Check that a deployment answered in full, and for a serving example that it was sent the
    frozen input. How good the answer is belongs to the model's benchmark."""
    if (
        request.project_id != assignment.project_id
        or not research_serving.observed(assignment).filter(pk=request.deployment_id).exists()
    ):
        raise InputValidationError("Select an inference belonging to this research assignment")
    subject = {
        "inference": str(request.pk),
        "payload_sha256": context_graph.fingerprint(request.payload),
        "response_sha256": context_graph.fingerprint(request.result),
    }
    if request.deployment.inference_contract == "decision" and request.state == "succeeded":
        try:
            serving_lease.completion(
                request.result, request.deployment, request.payload["decisions"]
            )
        except (ValueError, TypeError, KeyError):
            return {
                "subject": subject,
                "accepted": False,
                "state": "insufficient",
                "reason": "Decision response does not match its checkpoint and input contract",
            }
        return {
            "subject": subject,
            "accepted": True,
            "state": "verified",
            "basis": "Checkpoint identity, input-only decisions, ordered options and normalized predictions verified. Task quality remains established only by the separate sealed qualification.",
        }
    if (
        request.state != "succeeded"
        or request.result.get("truncated")
        or not request.result.get("content")
    ):
        return {
            "subject": subject,
            "accepted": False,
            "state": "insufficient",
            "reason": "A complete successful response is required",
        }
    action = ResearchAction.objects.filter(
        agent__assignment=assignment, tool="serving", result__id=str(request.pk)
    ).first()
    example = action.arguments.get("example") if action else None
    if example:
        source, spec = example_input(assignment, example)
        if request.payload.get("research_source") != spec:
            raise InputValidationError("The inference has no matching frozen source receipt")
        if request.payload["messages"][-1].get("content") != source:
            raise InputValidationError(
                "The inference does not contain the exact frozen example input"
            )
    return {
        "subject": subject,
        "accepted": True,
        "state": "verified",
        "basis": "The deployment returned a complete response. Its quality is not judged here.",
    }


def serving_gaps(assignment):
    """What a completed outcome still lacks from the deployments this assignment served: each
    frozen serving example answered under one configuration, or each deployment answered once."""
    examples = assignment.specification.get("acceptance", {}).get("serving_examples", [])
    gaps, configurations = [], set()
    for example in examples:
        action = (
            ResearchAction.objects.filter(
                agent__assignment=assignment,
                tool="serving",
                arguments__operation="infer",
                arguments__example=example["id"],
                state="completed",
            )
            .order_by("-created_at")
            .first()
        )
        request = (
            InferenceRequest.objects.filter(pk=action.result.get("id")).first() if action else None
        )
        if request is None:
            gaps.append(
                f"No completed inference names serving example {example['id']}. Send it with "
                "serving(operation=infer, example=...)."
            )
            continue
        configurations.add(
            context_graph.fingerprint(
                {
                    "instructions": request.payload["messages"][:-1],
                    **{
                        key: request.payload.get(key)
                        for key in (
                            "model_id",
                            "checkpoint_hash",
                            "max_model_len",
                            "max_tokens",
                            "temperature",
                            "chat_template_kwargs",
                        )
                    },
                }
            )
        )
        checked = verify_inference(assignment, request)
        if not checked["accepted"]:
            gaps.append(f"Serving example {example['id']}: {checked['reason']}")
    if len(configurations) > 1:
        gaps.append(
            "All required examples must qualify the same model, instructions and generation settings"
        )
    if examples:
        return gaps
    for model in research_serving.observed(assignment):
        sent = InferenceRequest.objects.filter(
            deployment=model, payload__source="research"
        ).order_by("-created_at")
        request = sent.filter(state="succeeded").first() or sent.first()
        if (request is None or request.state != "succeeded") and research_serving.state(model) in {
            "closed",
            "failed",
            "deleting",
            "deleted",
        }:
            # A deployment that no longer serves and answered nothing delivers nothing.
            continue
        if request is None:
            gaps.append(
                f"Deployment {model.pk} has answered no request, so nothing shows it serves. "
                "Send it one through an inference stage or serving(operation=infer)."
            )
            continue
        checked = verify_inference(assignment, request)
        if not checked["accepted"]:
            gaps.append(f"Deployment {model.pk}: {checked['reason']}")
    return gaps


def retain_manifest(action):
    record = facts(action.agent.assignment)
    data = (json.dumps(record, indent=2, ensure_ascii=False) + "\n").encode()
    return research.retain(
        action,
        SimpleNamespace(
            title="Verified research record",
            kind="report",
            path="platform://research/verified-record",
            metadata={"generated_from": "verified_platform_records"},
        ),
        data,
        source_cells=research_evidence.report_sources(action.agent.assignment, record),
    )