Skip to content

The platform for continuously improving AI agents.

9.1 KB
Raw Blame
from django.db import transaction
from django.utils import timezone

from overbae.core.errors import InputValidationError
from overbae.innermind import runs
from overbae.models import (
    EvalRun,
    ExperimentAsset,
    NativeEvaluationPlan,
    PredictionEvaluation,
    PredictionRow,
    PredictionSet,
    Project,
)
from overbae.services import (
    context_graph,
    experiment_assets,
    experiment_predictions,
    native_evaluation,
)
from overbae.services.datasets import rows


def describe(evaluation):
    run = evaluation.run
    summary = {**(run.summary or {})}
    threshold = evaluation.suite.definition["minimum_score"]
    # The counts runs.aggregate derives its trust flag from; reading the flag by name trips
    # CodeQL's secret-name heuristic.
    reliable = (
        summary.get("errored") == 0 and summary.get("degraded") == 0 and bool(summary.get("scored"))
    )
    summary["completion"] = {
        "status": "complete" if run.status == "completed" and reliable else "incomplete"
    }
    accepted = (
        run.status == "completed"
        and reliable
        and (
            threshold is None or summary.get("score") is not None and summary["score"] >= threshold
        )
    )
    origin = evaluation.prediction_set.candidate.definition.get("native_source")
    return {
        "id": str(run.pk),
        "state": run.status,
        "error": run.error,
        "suite": str(evaluation.suite_id),
        "prediction_set": str(evaluation.prediction_set_id),
        "fingerprint": evaluation.fingerprint,
        "report": summary,
        "accepted": accepted,
        "native_source": origin,
        "phase": origin["phase"] if origin else "development",
    }


@transaction.atomic
def score_native(assignment, evaluation_id, participant, suite_id, request_key):
    Project.objects.select_for_update().get(pk=assignment.project_id)
    assignment.refresh_from_db()
    if not experiment_predictions.authorized(assignment):
        raise InputValidationError("This assignment no longer has scoring authority")
    plan = (
        NativeEvaluationPlan.objects.select_related("final_cell__dataset")
        .filter(pk=evaluation_id, project_id=assignment.project_id)
        .first()
    )
    if plan is None:
        raise InputValidationError("Select a native evaluation in this project")
    suite = experiment_assets.get(assignment.project, suite_id, "suite")
    snapshot = native_evaluation.prediction_snapshot(plan, participant)
    origin = snapshot["origin"]
    identity = context_graph.fingerprint({"native_source": origin, "suite": suite.fingerprint})
    predictions = PredictionSet.objects.filter(
        project_id=assignment.project_id, request_key=request_key
    ).first()
    if predictions is not None:
        if predictions.fingerprint != identity or predictions.assignment_id != assignment.pk:
            raise InputValidationError(
                "This request key identifies different native scoring inputs"
            )
        return create(assignment, predictions.pk, suite.pk, request_key)
    source_rows = list(rows.iter_rows(plan.final_cell))
    if {str(row.index) for row in source_rows} != snapshot["rows"].keys():
        raise InputValidationError("Native evidence does not cover the exact retained source rows")
    candidate = ExperimentAsset.objects.create(
        project_id=assignment.project_id,
        created_by=assignment.created_by,
        kind="candidate",
        name=origin["participant"].get("name") or participant,
        definition={"kind": "native_predictions", "native_source": origin},
        fingerprint=context_graph.fingerprint(origin),
        request_fingerprint=identity,
        request_key=f"native:{request_key}",
    )
    predictions = PredictionSet.objects.create(
        project_id=assignment.project_id,
        candidate=candidate,
        cell=plan.final_cell,
        assignment=assignment,
        fingerprint=identity,
        request_key=request_key,
        state="failed" if any(item["error"] for item in snapshot["rows"].values()) else "completed",
        completed_at=timezone.now(),
    )
    PredictionRow.objects.bulk_create(
        [
            PredictionRow(
                prediction_set=predictions,
                index=row.index,
                input={"value": row.input},
                input_digest=context_graph.fingerprint(row.input),
                state="failed" if snapshot["rows"][str(row.index)]["error"] else "completed",
                output=snapshot["rows"][str(row.index)]["output"],
                error=snapshot["rows"][str(row.index)]["error"],
                trace={
                    "native_evaluation": str(plan.pk),
                    "participant": participant,
                    "source_row": row.index,
                },
            )
            for row in source_rows
        ]
    )
    return create(assignment, predictions.pk, suite.pk, request_key)


def get(project, identifier):
    found = (
        PredictionEvaluation.objects.select_related(
            "run", "suite", "prediction_set__candidate", "prediction_set__cell"
        )
        .filter(run_id=identifier, run__project=project)
        .first()
    )
    if found is None:
        raise InputValidationError("Select an evaluation of retained predictions in this project")
    return found


@transaction.atomic
def create(assignment, prediction_set, suite_id, request_key):
    assignment.refresh_from_db()
    if not experiment_predictions.authorized(assignment):
        raise InputValidationError("This assignment no longer has scoring authority")
    predictions = experiment_predictions.get(assignment.project, prediction_set)
    from overbae.services.research_tools import source_cell  # Native dispatch calls scoring.

    source_cell(assignment, predictions.cell_id)
    suite = experiment_assets.get(assignment.project, suite_id, "suite")
    type(predictions).objects.select_for_update().get(pk=predictions.pk)
    identity = context_graph.fingerprint(
        {"predictions": predictions.fingerprint, "suite": suite.fingerprint}
    )
    existing = (
        PredictionEvaluation.objects.filter(prediction_set=predictions, request_key=request_key)
        .select_related("run", "suite")
        .first()
    )
    if existing:
        if existing.suite_id != suite.pk or existing.assignment_id != assignment.pk:
            raise InputValidationError("This request key identifies another benchmark evaluation")
        return existing
    if predictions.state not in {"completed", "failed"}:
        raise InputValidationError("Wait for prediction attempts to settle before scoring")
    if suite.definition["runtime"] != experiment_assets.scoring_identity():
        raise InputValidationError(
            "The pinned scoring implementation is unavailable; publish a new suite revision"
        )
    rows.verify(predictions.cell)
    for row in predictions.rows.iterator():
        experiment_assets.check_schema(
            suite.definition["input_schema"], row.input["value"], validate=True
        )
        if row.state == "completed":
            experiment_assets.check_schema(
                suite.definition["output_schema"], row.output, validate=True
            )
    run = runs.create_run(
        project=assignment.project,
        cell=predictions.cell,
        mode=EvalRun.Mode.PROVIDED,
        matrix=suite.definition["matrix"],
        name=suite.name,
        judge_model=suite.definition["judge_model"],
        triggered_by=assignment.created_by,
        judges={
            "decision_model": suite.definition["decision_model"],
            "explanation_models": suite.definition["explanation_models"],
        },
        model_name=predictions.candidate.name,
    )
    runs.provide_outputs(
        run,
        {
            row.index: (row.output if row.state == "completed" else None, "")
            for row in predictions.rows.all()
        },
    )
    evaluation = PredictionEvaluation.objects.create(
        assignment=assignment,
        prediction_set=predictions,
        suite=suite,
        run=run,
        request_key=request_key,
        fingerprint=context_graph.fingerprint(
            {
                "protocol": identity,
                "judges": run.judge_context,
                "rows": list(
                    predictions.rows.order_by("index").values(
                        "index", "input_digest", "state", "output", "error"
                    )
                ),
            }
        ),
    )
    runs.launch(run)
    return evaluation


def reconcile(assignment):
    from overbae.tasks.innermind import hand_to_scoring  # Tasks call scoring services.

    for evaluation in PredictionEvaluation.objects.filter(
        assignment=assignment, run__status__in=["pending", "running"]
    ).select_related("run"):
        if not experiment_predictions.authorized(assignment, continuation=True):
            runs.cancel(evaluation.run)
            continue
        if evaluation.run.status == "pending":
            runs.start(evaluation.run_id)
        hand_to_scoring(str(evaluation.run_id))


def observations(assignment):
    return [
        describe(item)
        for item in PredictionEvaluation.objects.filter(assignment=assignment)
        .select_related("run", "suite")
        .order_by("pk")
    ]