Skip to content

The platform for continuously improving AI agents.

19.7 KB
Raw Blame
import math
import operator
from decimal import Decimal
from typing import Any, Literal
from uuid import UUID

from pydantic import Field, model_validator

from agent_runtime.contracts import Contract
from overbae.core.errors import InputValidationError
from overbae.services import context_graph


class Predicate(Contract):
    path: str = Field(
        min_length=1,
        description="JSON Pointer in the connected score binding. A qualification's sealed accuracy: "
        "/report/comparisons/selected/raw/candidate/macro_across_benchmarks/accuracy/mean. "
        "Per-class metrics: .../raw/candidate/benchmarks/<benchmark>/labels/<option index>/precision "
        "or recall; label identifies that option. These use scored hard targets only: also require "
        ".../benchmarks/<benchmark>/coverage = 1. Undefined denominators are null. Calibration: "
        ".../benchmarks/<benchmark>/expected_top1_ece (range 0 to 1) or metrics/brier/mean "
        "(unnormalized squared-error sum, range 0 to 2). The unchanged base "
        "is under .../raw/baseline/.... The benchmark key comes from each row's benchmark field, "
        "then source field, then the exact dataset name; a final split does not imply key 'final'. "
        "Escape ~ as ~0 and / as ~1 in JSON Pointer keys. A training check: /report/eval_loss.",
    )
    operator: Literal["gt", "gte", "lt", "lte", "eq", "ne"]
    value: Any

    @model_validator(mode="after")
    def finite_operand(self):
        if isinstance(self.value, float) and not math.isfinite(self.value):
            raise ValueError("Predicates require finite numeric operands")
        return self


class Condition(Contract):
    predicate: Predicate


class Comparison(Contract):
    metric: str = Field(
        min_length=1,
        description="JSON Pointer in each measured score binding: /report/eval_loss for training checks. Benchmark collections expand to one report per participant and benchmark. Compare only complete measurements with the same dataset, phase and protocol.",
    )
    direction: Literal["minimize", "maximize"]
    minimum: float | None = Field(default=None, allow_inf_nan=False)
    maximum: float | None = Field(default=None, allow_inf_nan=False)
    minimum_improvement: float = Field(default=0, ge=0, allow_inf_nan=False)
    require_interval: bool = False
    eligibility: list[Predicate] = Field(default_factory=list, max_length=20)


class Investigation(Contract):
    objective: str = Field(min_length=1, max_length=12000)
    acceptance: dict = Field(default_factory=dict)
    outputs: list[Literal["data", "model", "scores"]] = Field(min_length=1, max_length=4)
    max_seconds: int = Field(default=3600, ge=60, le=86400)
    max_model_calls: int = Field(default=40, ge=1, le=200)


class ServingCheck(Contract):
    messages: list[dict] = Field(default_factory=list, max_length=20)
    decisions: list[dict] = Field(default_factory=list, max_length=16)
    max_tokens: int = Field(default=256, ge=1, le=4096)
    response_schema: dict = Field(
        min_length=1,
        description="JSON Schema for the retained inference result. Decision responses have "
        "predictions: [{kind, options, probabilities, model_identity}] and top-level model_identity; "
        "probabilities is not a top-level field. The runtime already verifies exact checkpoint, "
        "request count/order/options, finite probabilities in [0,1] and sum 1. Chat responses "
        "have content, usage, finish_reason, latency_ms and truncated.",
    )


class Publication(Contract):
    checks: list[ServingCheck] = Field(default_factory=list, max_length=10)


class Subflow(Contract):
    experiment: UUID
    revision: int = Field(ge=1)
    parameters: dict = Field(default_factory=dict)
    inputs: dict[str, str] = Field(default_factory=dict)
    model: dict | None = None
    outputs: dict[str, str] = Field(min_length=1)
    definition: dict | None = Field(default=None, alias="_definition")


class Mapping(Subflow):
    experiment: UUID | None = None
    revision: int | None = Field(default=None, ge=1)
    recipe: dict | None = None
    outputs: dict[str, str] = Field(default_factory=dict)
    bindings: list[dict] = Field(min_length=1, max_length=32)
    keys: list[str] = Field(default_factory=list, max_length=32)
    labels: dict[str, str] = Field(default_factory=dict, max_length=32)
    concurrency: int = Field(default=2, ge=1, le=4)

    @model_validator(mode="after")
    def candidates(self):
        if any(set(binding) & self.inputs.keys() for binding in self.bindings):
            raise ValueError("Candidate parameters cannot replace a shared input binding")
        if bool(self.recipe) == bool(self.experiment):
            raise ValueError("Choose an inline recipe or a pinned reusable experiment")
        if self.experiment and self.revision is None:
            raise ValueError("Pin the reusable recipe revision")
        if not self.keys:
            counts = {}
            for binding in self.bindings:
                identity = context_graph.fingerprint(binding)[:24]
                counts[identity] = counts.get(identity, 0) + 1
                self.keys.append(f"variant_{identity}_{counts[identity]}")
        if len(self.keys) != len(self.bindings) or len(set(self.keys)) != len(self.keys):
            raise ValueError("Each variant requires a distinct stable key")
        if any(not key or len(key) > 100 for key in self.keys):
            raise ValueError("Variant keys must contain 1–100 characters")
        if set(self.labels) - set(self.keys) or any(
            len(label) > 200 for label in self.labels.values()
        ):
            raise ValueError("Labels name existing variants and contain at most 200 characters")
        return self


class Iteration(Subflow):
    max_iterations: int = Field(ge=1, le=16)
    until: Predicate
    feedback: dict[str, str] = Field(default_factory=dict)


CONTROL_SETTINGS = {"subflow": Subflow, "map": Mapping, "iterate": Iteration}


def benchmark_participants(selected, model=None, *, connected=False):
    participants = [dict(item) for item in selected]
    job = model.get("job") if model else None
    if model and not job:
        raise InputValidationError(
            "A benchmark model input requires a trained checkpoint. Select OpenRouter models "
            "as explicit participants."
        )
    pending = [p for p in participants if p.get("kind") == "trained" and not p.get("job")]
    if len(pending) > 1 or pending and not (connected or job):
        raise InputValidationError(
            "A benchmark may bind one unnamed training job from its connected model output"
        )
    if pending and job:
        pending[0]["job"] = job
    elif (
        (connected or job)
        and not pending
        and not any(
            p.get("kind") == "trained" and str(p.get("job")) == str(job) for p in participants
        )
    ):
        candidate = {"key": "candidate", "name": "Connected checkpoint", "kind": "trained"}
        if job:
            candidate.update(
                job=job, name=str(model.get("name") or model.get("model") or job)[:255]
            )
            if model.get("instructions"):
                candidate["instructions"] = model["instructions"]
        participants.append(candidate)
    keys = [p["key"] for p in participants]
    if len(set(keys)) != len(keys):
        raise InputValidationError(
            "Benchmark participant keys must be distinct, including candidate"
        )
    return participants


def pointers(value, prefix="", limit=4000):
    """Every pointer into a binding, shallowest first, up to ``limit``."""
    pending, found = [(prefix, value)], []
    while pending and len(found) < limit:
        path, item = pending.pop(0)
        found.append(path)
        if isinstance(item, dict):
            pending.extend((f"{path}/{key}", child) for key, child in item.items())
    return found


def lookup(value, path):
    keys = path[1:].split("/") if path.startswith("/") else path.split(".")
    binding = value
    try:
        for key in keys:
            key = key.replace("~1", "/").replace("~0", "~")
            value = value[int(key)] if isinstance(value, list) and key.isdecimal() else value[key]
    except (KeyError, TypeError, IndexError) as exc:
        # A report is deep and its shape is not known until it exists: name what it holds
        # under the same final keys, so the pointer is corrected in one step.
        available = pointers(binding)
        alike = next(
            (
                matched
                for size in (2, 1)
                if (
                    matched := [
                        item for item in available if item.split("/")[-size:] == keys[-size:]
                    ]
                )
            ),
            [],
        )
        held = f" It holds: {', '.join(alike[:6])}." if alike else ""
        raise InputValidationError(
            f"The required measurement {path} is unavailable.{held}"
        ) from exc
    return value


def matches(value, predicate):
    rule = Predicate.model_validate(predicate)
    operations = {
        "gt": operator.gt,
        "gte": operator.ge,
        "lt": operator.lt,
        "lte": operator.le,
        "eq": operator.eq,
        "ne": operator.ne,
    }
    try:
        return operations[rule.operator](lookup(value, rule.path), rule.value)
    except TypeError as exc:
        raise InputValidationError("The measurement and predicate have incompatible types") from exc


def compare(inputs, settings):
    policy = Comparison.model_validate(settings)
    reports, incomplete = [], False

    def unwrap_scores(value):
        while value and value.get("selected"):
            value = value["selected"]["input"]
        return value

    baseline = unwrap_scores(inputs.get("baseline"))
    if baseline is None and (policy.minimum_improvement or policy.require_interval):
        raise InputValidationError("An improvement policy requires an explicit baseline")
    pending = list(inputs["scores"]) + ([baseline] if baseline else [])
    while pending:
        report = pending.pop(0)
        if report.get("coverage", {}).get("complete") is False:
            incomplete = True
        if "reports" in report and "selected" not in report:
            pending[0:0] = report["reports"]
        elif "selected" in report and report["selected"] is None:
            incomplete = True
            pending[0:0] = [item["input"] for item in report["reports"]]
        else:
            reports.append(report)
    datasets = {report.get("data") for report in reports}
    phases = {report.get("phase") for report in reports}
    protocols = {report.get("protocol") for report in reports}
    manifests = {report["sample_manifest"] for report in reports if report.get("sample_manifest")}
    if len(manifests) > 1:
        raise InputValidationError("Compare the same retained sample and group manifest")
    if any(not report.get("sample_manifest") for report in reports):
        incomplete = True
    if reports and (len(datasets) != 1 or None in datasets or len(phases) != 1 or None in phases):
        raise InputValidationError(
            "Compare measurements from the same dataset and evaluation phase"
        )
    if reports and (len(protocols) != 1 or None in protocols):
        raise InputValidationError("Compare measurements produced by the same evaluation protocol")
    if baseline and "reports" in baseline and "selected" not in baseline:
        raise InputValidationError("Choose one measured report as the explicit baseline")
    values = []
    expected_counts = {}

    def complete_coverage(value, path=""):
        nonlocal incomplete
        if not isinstance(value, dict):
            return True
        result = True
        if "expected" in value:
            expected = value["expected"]
            if path in expected_counts and expected_counts[path] != expected:
                incomplete = True
            expected_counts[path] = expected
            result = expected is not None and value.get("scored") == expected
        return all(
            [
                result,
                *(
                    complete_coverage(child, f"{path}/{key}")
                    for key, child in value.items()
                    if isinstance(child, dict)
                ),
            ]
        )

    for report in reports:
        complete = report.get("report", {}).get("completion", {}).get("status") == "complete"
        complete &= complete_coverage(report.get("report", {}))
        incomplete |= not complete
        try:
            value = lookup(report, policy.metric)
        except InputValidationError:
            if complete:
                raise
            value = None
        incomplete |= value is None
        if value is not None and (
            isinstance(value, bool)
            or not isinstance(value, (float, int))
            or not math.isfinite(value)
        ):
            raise InputValidationError("Comparison requires finite measured values")
        eligible = (
            complete
            and value is not None
            and (policy.minimum is None or value >= policy.minimum)
            and (policy.maximum is None or value <= policy.maximum)
        )
        missing = False
        for predicate in policy.eligibility:
            try:
                measurement = lookup(report, predicate.path)
            except InputValidationError:
                missing = True
                eligible = False
                continue
            if measurement is None:
                missing = True
                eligible = False
                continue
            if isinstance(measurement, float) and not math.isfinite(measurement):
                raise InputValidationError("Eligibility requires finite measurements")
            eligible &= matches(report, predicate)
        incomplete |= missing
        meets_criteria = eligible
        is_baseline = baseline is not None and unwrap_scores(report) == baseline
        if baseline and not is_baseline:
            try:
                base_value = lookup(baseline, policy.metric)
            except InputValidationError:
                base_value = None
            if value is None or base_value is None:
                incomplete = True
                eligible = False
            else:
                improvement = (
                    Decimal(str(value)) - Decimal(str(base_value))
                    if policy.direction == "maximize"
                    else Decimal(str(base_value)) - Decimal(str(value))
                )
                eligible &= improvement > Decimal(str(policy.minimum_improvement))
            if policy.require_interval:
                paired = report.get("paired_comparison", {})
                measured = paired.get("metrics", {}).get(policy.metric, {})
                interval = measured.get("interval_95")
                same_baseline = (
                    bool(baseline.get("candidate_identity"))
                    and paired.get("baseline") == baseline["candidate_identity"]
                    and bool(baseline.get("evidence", {}).get("predictions"))
                    and paired.get("baseline_predictions") == baseline["evidence"]["predictions"]
                    and paired.get("candidate_predictions")
                    == report.get("evidence", {}).get("predictions")
                    and bool(paired.get("candidate_predictions"))
                    and paired.get("sample_manifest") == report.get("sample_manifest")
                )
                expected = measured.get("expected", paired.get("expected"))
                complete_pairs = (
                    measured.get("paired_decisions", paired.get("paired_decisions")) == expected
                    and expected is not None
                )
                if not interval or not same_baseline or not complete_pairs:
                    incomplete = True
                    eligible = False
                else:
                    if not isinstance(interval, list) or len(interval) != 2:
                        raise InputValidationError("A paired interval requires two measured bounds")
                    low, high = interval
                    if (
                        any(
                            type(bound) not in {int, float} or not math.isfinite(bound)
                            for bound in interval
                        )
                        or low > high
                    ):
                        raise InputValidationError(
                            "A paired interval must have finite ordered bounds"
                        )
                    eligible &= (
                        Decimal(str(low)) > Decimal(str(policy.minimum_improvement))
                        if policy.direction == "maximize"
                        else Decimal(str(high)) < -Decimal(str(policy.minimum_improvement))
                    )
        item = {
            "input": report,
            "value": value,
            "eligible": eligible,
            "meets_criteria": meets_criteria,
            "baseline": is_baseline,
            "reason": ""
            if eligible
            else "Incomplete coverage"
            if not complete
            else "Outside the declared criteria",
        }
        if not any(
            unwrap_scores(existing["input"]) == unwrap_scores(report) for existing in values
        ):
            values.append(item)
        elif is_baseline:
            next(
                existing
                for existing in values
                if unwrap_scores(existing["input"]) == unwrap_scores(report)
            )["baseline"] = True
    eligible = [item for item in values if item["eligible"]]
    choose = min if policy.direction == "minimize" else max
    best = choose(eligible, key=lambda item: item["value"]) if eligible else None
    ties = [
        item
        for item in values
        if best
        and item["value"] == best["value"]
        and (item["eligible"] or best["baseline"] and item["meets_criteria"])
    ]
    selected = best if not incomplete and len(ties) == 1 else None
    outcome = (
        "insufficient_evidence"
        if incomplete or not values
        else "no_qualifier"
        if not eligible
        else "tie"
        if len(ties) > 1
        else "baseline_best"
        if selected["baseline"]
        else "candidate_selected"
    )
    baseline_value = next((item["value"] for item in values if item["baseline"]), None)
    result = {
        "kind": "scores",
        "data": next(iter(datasets), None),
        "phase": next(iter(phases), None),
        "protocol": next(iter(protocols), None),
        "report": selected["input"]["report"] if selected else {},
        **(
            {
                key: selected["input"].get(key)
                for key in (
                    "sample_manifest",
                    "candidate_identity",
                    "evidence",
                    "paired_comparison",
                )
            }
            if selected
            else {}
        ),
        "metric": policy.metric,
        "direction": policy.direction,
        "policy": policy.model_dump(),
        "selected": selected,
        "outcome": outcome,
        "reports": values,
        "baseline": baseline_value,
        "delta": float(Decimal(str(best["value"])) - Decimal(str(baseline_value)))
        if best and baseline_value is not None
        else None,
        "coverage": {
            "complete": not incomplete and bool(values),
            "measured": sum(item["value"] is not None for item in values),
            "candidates": len(values),
        },
    }
    outputs = {"scores": {**result, "fingerprint": context_graph.fingerprint(result)}}
    if selected:
        candidate = selected["input"]
        while candidate.get("selected"):
            candidate = candidate["selected"]["input"]
        if candidate.get("model", {}).get("job") or candidate.get("model", {}).get("asset"):
            outputs["model"] = candidate["model"]
    return outputs