Skip to content

The platform for continuously improving AI agents.

33.4 KB
Raw Blame
import uuid
from copy import deepcopy
from datetime import timedelta

import pytest
from django.utils import timezone
from factories import decision_campaign, make_research_campaign
from jsonschema import Draft202012Validator
from pydantic import ValidationError
from test_experiment_engine import flow

from modal_shared.decisions import DECISION_OBJECTIVE
from overbae.core.errors import InputValidationError
from overbae.models import (
    Cell,
    DeployedModel,
    FinetuningJob,
    NativeEvaluationPlan,
    ResearchAssignment,
    TrainingCampaign,
    TrainingTrial,
)
from overbae.services import (
    experiment_checkpoints,
    experiment_engine,
    experiment_execution,
    experiment_interfaces,
    experiment_reuse,
    experiment_settings,
    experiment_training,
    research,
    research_acceptance,
    research_agent,
    research_benchmarks,
    research_evidence,
    research_experiments,
    research_serving,
    research_team,
    research_tools,
    training_campaigns,
)
from overbae.services.research_contract import Benchmark, Campaign, Finish, Serving

pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.covers("state-machines")]


def test_native_benchmark_scores_compare_all_models_and_reuse_exact_completed_evidence():
    experiment, user = flow()
    run = experiment_engine.start(experiment, user, revision=2, request_key="measure", budget={})
    action = research.claim(run.agents.get(parent__isnull=True), "measure", "benchmark", {})
    plan = NativeEvaluationPlan.objects.create(
        project=experiment.project,
        final_cell=Cell.objects.get(dataset__project=experiment.project),
        state="completed",
        request_key=f"research:{action.pk}",
        config={"purpose": "development", "research": {"assignment": str(run.pk)}},
        results={
            "participants": [{"key": name, "model": name} for name in ("base", "better")],
            "comparisons": {
                name: {
                    "raw": {
                        "candidate": {
                            "suite_manifest_sha256": "a" * 64,
                            "benchmarks": {
                                "cases": {
                                    "metrics": {"rougeL": {"mean": value}},
                                    "scored": 16,
                                    "expected": 16,
                                }
                            },
                        }
                    }
                }
                for name, value in (("base", 0.4), ("better", 0.6))
            },
            "completion": {"status": "complete"},
        },
    )
    research.complete(action, {"id": str(plan.pk)}, cost=0)
    action.refresh_from_db()
    binding = experiment_execution.observe(action)["outputs"]["scores"]
    selected = experiment_settings.compare(
        {"scores": [binding]}, {"metric": "/report/metrics/rougeL/mean", "direction": "maximize"}
    )["scores"]["selected"]
    assert selected["input"]["participant"]["key"] == "better"
    assert selected["value"] == 0.6
    assert experiment_reuse.retained(experiment.project, binding)
    altered = deepcopy(binding)
    altered["fingerprint"] = "f" * 64
    assert not experiment_reuse.retained(experiment.project, altered)
    altered = deepcopy(binding)
    altered["report"]["completion"]["status"] = "partial"
    assert not experiment_reuse.retained(experiment.project, altered)
    for report in altered["reports"]:
        report["report"]["completion"]["status"] = "partial"
    incomplete = experiment_settings.compare(
        {"scores": [altered]},
        {"metric": "/report/metrics/rougeL/mean", "direction": "maximize"},
    )
    assert incomplete["scores"]["outcome"] == "insufficient_evidence"
    assert incomplete["scores"]["selected"] is None and "model" not in incomplete
    plan.state = "failed"
    plan.save(update_fields=["state"])
    assert not experiment_reuse.retained(experiment.project, binding)


def test_benchmark_observation_follows_child_flow_without_granting_control():
    experiment, user = flow()
    parent = research.create(
        experiment.project,
        user=user,
        request_key="benchmark-parent",
        context_roots=[f"cell:{Cell.objects.get(dataset__project=experiment.project).pk}"],
        objective="Review benchmark",
        task={"deliverable": "Verified comparison"},
        budget={},
    )
    lead = parent.agents.get(parent__isnull=True)
    controller = research.claim(lead, "flow", "experiment", {"operation": "run"})
    child = experiment_engine.start(
        experiment,
        user,
        revision=2,
        request_key="child",
        budget={},
        controller=controller,
    )
    plan = NativeEvaluationPlan.objects.create(
        project=experiment.project,
        final_cell=Cell.objects.get(dataset__project=experiment.project),
        config={
            "participants": [],
            "baseline": "base",
            "purpose": "development",
            "generation": {"max_tokens": 256, "temperature": 0},
            "research": {"assignment": str(child.pk)},
        },
        results={
            "participants": [{"key": "base", "model": "Qwen/Qwen3-0.6B"}],
            "comparisons": {
                "base": {
                    "raw": {
                        "candidate": {
                            "suite_manifest_sha256": "a" * 64,
                            "benchmarks": {
                                "cases": {
                                    "scored": 16,
                                    "expected": 16,
                                    "metrics": {"rougeL": {"mean": 0.4}},
                                }
                            },
                            "predictions_sha256": "a" * 64,
                        }
                    }
                }
            },
            "completion": {"status": "complete"},
        },
    )
    for agent in [lead, lead.children.get(role="evaluation")]:
        action = research.claim(agent, "inspect-benchmark", "benchmark", {})
        seen = research_benchmarks.invoke(
            action, Benchmark(operation="inspect", evaluation=plan.pk)
        )
        assert seen[0]["results"]["participants"][0]["benchmarks"]["cases"]["scored"] == 16
        assert seen[0]["results"]["participants"][0]["predictions_sha256"] == "a" * 64
        assert research_agent.evidence(agent)["benchmarks"][0]["id"] == str(plan.pk)
        facts = research_acceptance.facts(agent.assignment)
        assert len(facts["benchmarks"]) == 1
        assert facts["benchmarks"][0]["generation"] == {"max_tokens": 256, "temperature": 0}
        assert facts["benchmarks"][0]["id"] == str(plan.pk)
        with pytest.raises(InputValidationError):
            research_benchmarks.invoke(action, Benchmark(operation="stop", evaluation=plan.pk))
    child.specification["task"]["controller_action"] = "unrelated"
    child.save(update_fields=["specification"])
    assert research_acceptance.facts(parent)["benchmarks"] == []
    seen = research_benchmarks.invoke(action, Benchmark(operation="inspect", evaluation=plan.pk))
    assert seen[0]["id"] == str(plan.pk)
    assert research_acceptance.facts(parent)["benchmarks"] == []
    with pytest.raises(InputValidationError):
        research_benchmarks.invoke(action, Benchmark(operation="stop", evaluation=plan.pk))
    foreign, _ = flow()
    plan.project = foreign.project
    plan.save(update_fields=["project"])
    for unavailable in (plan.pk, uuid.uuid4()):
        with pytest.raises(InputValidationError, match="unavailable"):
            research_benchmarks.invoke(
                action, Benchmark(operation="inspect", evaluation=unavailable)
            )


@pytest.fixture(autouse=True)
def checkpoint_schema():
    with experiment_checkpoints.store() as store:
        store.setup()


def retained_training(settings, tmp_path, *, controller=None, with_final=False):
    """A completed flow run whose train stage kept a checkpoint through its campaign."""
    person, arguments = decision_campaign(settings, tmp_path, with_final=with_final)
    cells = [Cell.objects.get(pk=arguments[name]) for name in ("train_cell", "development_cell")]
    experiment = research_experiments.create(
        person.project,
        person.created_by,
        name="Retained training",
        objective="Train and review",
        cells=[cell.pk for cell in cells],
        request_key="retained",
    )
    document = deepcopy(experiment.revisions.get(number=1).document)
    document["nodes"] += [
        {
            "id": "model",
            "kind": "model",
            "title": "Candidate",
            "position": {"x": 0, "y": 200},
            "config": {"model": "Cloudflare/clef-flash"},
        },
        {
            "id": "train",
            "kind": "train",
            "title": "Training",
            "position": {"x": 400, "y": 0},
            "config": {},
            "operation": {
                "tool": "training",
                "arguments": {
                    "operation": "create",
                    "arguments": {
                        "run": {"name": "Candidate", "hyperparameters": {"seed": 713}},
                        "trials": 1,
                    },
                },
            },
        },
    ]
    document["edges"] = [
        {"source": source, "target": "train", "output": output, "input": port}
        for source, output, port in [
            ("data_0", "data", "data"),
            ("data_1", "data", "development"),
            ("model", "model", "model"),
        ]
    ]
    document["outputs"] = {"candidate": {"node": "train", "port": "model"}}
    research_experiments.revise(
        experiment, expected_version=1, document=document, request_key="train"
    )
    run = experiment_engine.start(
        experiment,
        person.created_by,
        revision=2,
        request_key="first",
        budget={},
        controller=controller,
    )
    campaign = make_research_campaign(
        run,
        "retained",
        arguments={
            "base_model": "Cloudflare/clef-flash",
            "dataset": str(cells[0].dataset_id),
            "cell": str(cells[0].pk),
            "validation_cell": str(cells[1].pk),
        },
    )
    job = FinetuningJob.objects.create(
        project=run.project,
        dataset=cells[0].dataset,
        cell=cells[0],
        validation_cell=cells[1],
        base_model="Cloudflare/clef-flash",
        status="succeeded",
        hyperparameters={"seed": 713, "objective": DECISION_OBJECTIVE},
        result={"checkpoint_selection": "1:20", "artifact_identity": "a" * 64},
    )
    job.retained_checkpoints.create(
        key="1:20",
        attempt=1,
        step=20,
        state="available",
        identity="a" * 64,
        selected=True,
        verification={"reload_verified": True},
    )
    job.validation_runs.create(
        key="1:20",
        attempt=1,
        step=20,
        stream="development",
        state="completed",
        metrics={"eval_loss": 0.2},
        coverage={"expected": 4, "scored": 4},
        receipt_fingerprint="b" * 64,
    )
    TrainingTrial.objects.create(campaign=campaign, index=1, job=job, reason="First run")
    training_campaigns.advance(campaign.pk)
    campaign.refresh_from_db()
    binding = experiment_training.model_output(campaign)
    run.execution.nodes.filter(node="train").update(state="completed", outputs={"model": binding})
    experiment_engine.advance(run.pk)
    run.refresh_from_db()
    assert run.state == "completed", run.result
    return experiment, run, campaign


def test_review_follows_owned_flow_campaigns_but_not_unrelated_project_work(settings, tmp_path):
    experiment, run, campaign = retained_training(settings, tmp_path)
    parent = research.create(
        experiment.project,
        user=run.created_by,
        request_key="lead",
        objective="Review exact flow outputs",
        task={"deliverable": "Independent review"},
        budget={},
    )
    lead = parent.agents.get(parent__isnull=True)
    evaluator = lead.children.get(role="evaluation")
    receipt = research.claim(lead, "flow", "experiment", {"operation": "run"})
    request = Finish(
        outcome="unmet",
        summary="Review retained training",
        reviewed_campaigns=[campaign.pk],
        verification_verdict="insufficient",
    )
    review = research.claim(evaluator, "review", "finish", request.model_dump(mode="json"))
    assert not research_agent.evidence(evaluator)["campaigns"]
    with pytest.raises(InputValidationError):
        research_team.prepare_handoff(review, request)
    run.specification["task"].update(
        controller_assignment=str(parent.pk), controller_action=str(receipt.pk)
    )
    run.save(update_fields=["specification"])
    assert research_agent.evidence(evaluator)["campaigns"][0]["id"] == str(campaign.pk)
    observed = research_team.prepare_handoff(review, request)
    assert observed["verification"]["campaigns"][0]["id"] == str(campaign.pk)
    campaign.refresh_from_db()
    assert campaign.request_key.startswith(f"research:{run.pk}:")


def test_reused_checkpoint_is_revalidated_at_consumption(settings, tmp_path):
    experiment, original, campaign = retained_training(settings, tmp_path)
    replay = experiment_engine.start(
        experiment,
        original.created_by,
        revision=2,
        request_key="reuse",
        reuse_run=original.pk,
        budget={},
    )
    binding = replay.execution.nodes.get(node="train").outputs["model"]
    args = {"operation": "inspect", "campaign": str(campaign.pk)}
    experiment_execution.validate_native_bindings(replay, "training", args, {"model": binding})
    campaign.selected.retained_checkpoints.update(state="deleted")
    with pytest.raises(InputValidationError, match="checkpoint"):
        experiment_execution.validate_native_bindings(replay, "training", args, {"model": binding})


def test_a_run_benchmarks_the_trained_model_it_inherited(settings, tmp_path):
    experiment, original, campaign = retained_training(settings, tmp_path)
    replay = experiment_engine.start(
        experiment,
        original.created_by,
        revision=2,
        request_key="reuse",
        reuse_run=original.pk,
        budget={},
    )
    job = campaign.selected
    request = Benchmark(
        operation="run",
        phase="development",
        cell=job.validation_cell_id,
        baseline="candidate",
        participants=[
            {"key": "candidate", "name": "Candidate", "kind": "trained", "job": str(job.pk)}
        ],
        max_seconds=300,
    )
    action = research.claim(replay.agents.get(parent__isnull=True), "benchmark", "benchmark", {})
    # The model came with the run it reuses: it is measured, not refused as another's.
    assert research_benchmarks.invoke(action, request)["id"]


def test_a_checkpoint_being_deployed_is_still_the_trained_model(settings, tmp_path):
    experiment, original, campaign = retained_training(settings, tmp_path)
    binding = original.execution.nodes.get(node="train").outputs["model"]
    FinetuningJob.objects.filter(pk=campaign.selected_id).update(status="deploying")
    # Deployment holds the job in "deploying": a run started meanwhile reuses the model.
    assert research_evidence.verified_model(experiment.project, binding)


def test_reused_campaign_does_not_grant_recipe_mutation(settings, tmp_path):
    experiment, original, campaign = retained_training(settings, tmp_path)
    replay = experiment_engine.start(
        experiment,
        original.created_by,
        revision=2,
        request_key="reuse",
        reuse_run=original.pk,
        budget={},
    )
    action = research.claim(
        replay.agents.get(parent__isnull=True),
        "mutate",
        "training",
        {"operation": "stop", "campaign": str(campaign.pk)},
    )
    # A later run reads the campaign it inherited; only the run that started it may stop it.
    with pytest.raises(InputValidationError):
        research_tools.training(action, Campaign.model_validate(action.arguments))


@pytest.mark.parametrize(("tool", "operation"), [("training", "qualify"), ("serving", "deploy")])
def test_a_later_run_binds_an_earlier_runs_selected_model_without_reusing_its_stages(
    settings, tmp_path, tool, operation
):
    experiment, original, campaign = retained_training(settings, tmp_path, with_final=True)
    later = experiment_engine.start(
        experiment, original.created_by, revision=2, request_key="later", budget={}
    )
    model = research_evidence.published_model(experiment.project, campaign.selected_id)
    experiment_execution.validate_native_bindings(
        later, tool, {"operation": operation, "campaign": str(campaign.pk)}, {"model": model}
    )


@pytest.mark.parametrize("owner_state", ["completed", "unmet"])
def test_a_later_run_takes_over_the_deployment_an_earlier_run_left_serving(
    settings, tmp_path, owner_state
):
    experiment, original, campaign = retained_training(settings, tmp_path)
    TrainingCampaign.objects.filter(pk=campaign.pk).update(state="completed")
    deployed = DeployedModel.objects.create(
        project=experiment.project,
        finetuning_job=campaign.selected,
        model_id="retained-model",
        status="ready",
        serving_runtime={
            "lease": {
                "assignment": str(original.pk),
                "allocation": str(uuid.uuid4()),
                "deadline": (timezone.now() + timedelta(minutes=10)).isoformat(),
            }
        },
    )
    ResearchAssignment.objects.filter(pk=original.pk).update(state=owner_state)
    original.refresh_from_db()
    research_serving.reconcile(original)
    deployed.refresh_from_db()
    assert deployed.status == "ready"
    assert not deployed.serving_runtime["lease"].get("closed_at")
    previous = DeployedModel.objects.get(pk=deployed.pk)
    replay = experiment_engine.start(
        experiment,
        original.created_by,
        revision=2,
        request_key="reuse",
        reuse_run=original.pk,
        budget={},
    )
    request = {"operation": "deploy", "campaign": str(campaign.pk)}
    action = research.claim(replay.agents.get(parent__isnull=True), "deploy", "serving", request)
    serving = research_serving.invoke(action, Serving.model_validate(request))
    assert [item["deployment"] for item in serving] == [str(deployed.pk)]
    deployed.refresh_from_db()
    assert deployed.serving_runtime["lease"]["assignment"] == str(replay.pk)
    research_serving.stop(previous)
    deployed.refresh_from_db()
    assert not deployed.serving_runtime["lease"].get("closed_at")
    # Work outside this experiment has no claim on its deployment.
    other = research.create(
        experiment.project,
        user=original.created_by,
        request_key="elsewhere",
        objective="Unrelated work",
        task={"deliverable": "Report"},
        budget={},
    )
    assert research_serving.describe(other) == []


def test_qualification_requires_declared_development_selection_and_its_exact_model(
    settings, tmp_path
):
    experiment, original, campaign = retained_training(settings, tmp_path)
    document = deepcopy(experiment.revisions.get(number=2).document)
    document["nodes"] += [
        {
            "id": "development",
            "kind": "evaluate",
            "title": "Development",
            "position": {"x": 600, "y": 0},
            "config": {},
            "operation": {"tool": "training", "arguments": {"operation": "inspect"}},
        },
        {
            "id": "select",
            "kind": "compare",
            "title": "Select",
            "position": {"x": 800, "y": 0},
            "config": {"metric": "/report/eval_loss", "direction": "minimize"},
        },
        {
            "id": "final",
            "kind": "qualify",
            "title": "Qualify",
            "position": {"x": 1000, "y": 0},
            "config": {},
            "operation": {"tool": "training", "arguments": {"operation": "qualify"}},
        },
    ]
    document["edges"] += [
        {"source": "train", "target": "development", "output": "model", "input": "model"},
        {"source": "development", "target": "select", "output": "scores", "input": "scores"},
        {"source": "train", "target": "final", "output": "model", "input": "model"},
    ]
    with pytest.raises(InputValidationError, match="qualification must depend"):
        experiment_interfaces.validate(document, executable=True)
    document["edges"][-1]["source"] = "select"
    experiment_interfaces.validate(document, executable=True)
    binding = original.result["outputs"]["candidate"]
    measured = {
        "kind": "scores",
        "phase": "development",
        "data": str(campaign.selected.validation_cell_id),
        "protocol": "verified-protocol",
        "sample_manifest": "verified-samples",
        "report": {"eval_loss": 0.2, "completion": {"status": "complete"}},
        "model": binding,
    }
    selected = experiment_settings.compare({"scores": [measured]}, document["nodes"][-2]["config"])
    assert selected["model"] == binding
    assert selected["scores"]["selected"]["input"] == measured


def test_execution_contract_omits_money_allocations_and_preserves_timeouts(settings, tmp_path):
    experiment, original, _ = retained_training(settings, tmp_path)
    parent = research.create(
        experiment.project,
        user=original.created_by,
        request_key="limits",
        objective="Plan within available resources",
        task={"deliverable": "Comparison"},
        budget={},
    )
    lead = parent.agents.get(parent__isnull=True)
    research.claim(lead, "admitted-work", "workspace", {}, reservation=5)
    schema = next(
        item["function"]["parameters"]
        for item in research_agent.definitions(lead)
        if item["function"]["name"] == "experiment"
    )
    validator = Draft202012Validator(schema)
    assert "max_cost_usd" not in schema["properties"]
    assert not validator.is_valid({"operation": "run", "revision": 1, "max_seconds": 0})
    assert validator.is_valid({"operation": "run", "revision": 1, "max_seconds": 60})
    assert validator.is_valid({"operation": "inspect"})


@pytest.mark.parametrize("key", ["model_1", "Model", "prepare", "valid-model"])
def test_benchmark_participant_constraints_are_available_before_execution(key):
    request = {
        "operation": "run",
        "participants": [{"key": key, "name": "Candidate", "kind": "external", "model": "model"}],
        "baseline": key,
    }
    advertised = Draft202012Validator(Benchmark.model_json_schema())
    if key == "valid-model":
        assert advertised.is_valid(request)
        assert Benchmark.model_validate(request).participants[0].key == key
    else:
        assert not advertised.is_valid(request)
        with pytest.raises(ValidationError):
            Benchmark.model_validate(request)


def test_benchmark_rejects_an_untrained_model_edge_but_accepts_explicit_participants():
    args = {"operation": "run", "participants": [{"kind": "external", "model": "openai/gpt-4o"}]}
    experiment_execution.validate_native_bindings(None, "benchmark", args, {})
    model = {"model": "Qwen/Qwen3.5-0.8B"}
    with pytest.raises(InputValidationError, match="connected trained checkpoint"):
        experiment_execution.validate_native_bindings(None, "benchmark", args, {"model": model})
    with pytest.raises(InputValidationError, match="requires a trained checkpoint"):
        experiment_settings.benchmark_participants(args["participants"], model)


def test_benchmark_catalog_lists_openrouter_models_and_every_one_is_admissible(fake_llm):
    from test_research_experiments import setup_experiment, start

    from overbae.services.decision_providers import qualify_participants

    fake_llm.catalog_payload = [
        {
            "id": slug,
            "name": slug,
            "supported_parameters": ["logprobs", "top_logprobs"],
            "pricing": {"prompt": "0.000001", "completion": "0.000002"},
            "architecture": {"modality": "text->text"},
        }
        for slug in ("openai/gpt-4o", "openai/gpt-4o-mini", "meta-llama/llama-3.3-70b-instruct")
    ]
    experiment, user, _ = setup_experiment()
    work = start(experiment, user)
    lead = work.agents.get(parent__isnull=True)
    schema = next(
        t["function"]["parameters"]
        for t in research_agent.definitions(lead)
        if t["function"]["name"] == "benchmark"
    )
    assert Draft202012Validator(schema).is_valid({"operation": "catalog"})
    assert not Draft202012Validator(schema).is_valid({"operation": "run"})
    action = research.claim(lead, "native-catalog", "benchmark", {"operation": "catalog"})
    options = research_tools.invoke(action)["models"]
    assert {option["model"] for option in options} == {
        item["id"] for item in fake_llm.catalog_payload
    }
    for option in options:
        assert (
            qualify_participants(
                work.project,
                [
                    {
                        "key": "candidate",
                        "name": option["name"],
                        "kind": "external",
                        "model": option["model"],
                    }
                ],
            )[0]["model"]
            == option["model"]
        )
    filtered = research.claim(
        lead, "openai-catalog", "benchmark", {"operation": "catalog", "search": "gpt-4o-mini"}
    )
    assert [m["model"] for m in research_tools.invoke(filtered)["models"]] == ["openai/gpt-4o-mini"]


def test_a_pointer_that_misses_names_the_measurements_the_report_holds():
    scores = {
        "report": {
            "comparisons": {
                "selected": {
                    "raw": {
                        "candidate": {"macro_across_benchmarks": {"accuracy": {"mean": 0.81}}},
                        "baseline": {"macro_across_benchmarks": {"accuracy": {"mean": 0.78}}},
                    }
                }
            }
        }
    }
    rule = {"path": "/report/selected/accuracy/mean", "operator": "gt", "value": 0.75}
    with pytest.raises(InputValidationError) as missed:
        experiment_settings.matches(scores, rule)
    found = "/report/comparisons/selected/raw/candidate/macro_across_benchmarks/accuracy/mean"
    assert found in missed.value.detail
    assert experiment_settings.matches(scores, {**rule, "path": found}) is True


@pytest.mark.parametrize(
    "direction,values,minimum,outcome",
    [
        ("maximize", [0.8, 0.9], None, "candidate_selected"),
        ("minimize", [0.8, 0.9], None, "baseline_best"),
        ("maximize", [0.8, 0.8], None, "tie"),
        ("maximize", [0.8, 0.9], 0.95, "no_qualifier"),
    ],
)
def test_comparison_records_baseline_tie_and_no_qualifier_without_inventing_a_model(
    direction, values, minimum, outcome
):
    reports = [
        {
            "kind": "scores",
            "data": "same-input",
            "phase": "development",
            "protocol": "same-protocol",
            "sample_manifest": "same-samples",
            "model": {"asset": name, "kind": "model"},
            "report": {"accuracy": value, "completion": {"status": "complete"}},
        }
        for name, value in zip(["baseline", "candidate"], values, strict=True)
    ]
    result = experiment_settings.compare(
        {"scores": [reports[1]], "baseline": reports[0]},
        {"metric": "/report/accuracy", "direction": direction, "minimum": minimum},
    )
    assert result["scores"]["outcome"] == outcome
    if outcome in {"tie", "no_qualifier"}:
        assert result["scores"]["selected"] is None and "model" not in result
    else:
        assert result["model"]["asset"] == (
            "baseline" if outcome == "baseline_best" else "candidate"
        )
    assert result["scores"]["baseline"] == 0.8


def measured_comparison(candidate=2.0, baseline=1.0, interval=(0.25, 1.5)):
    reports = [
        {
            "kind": "scores",
            "data": "fixed-data",
            "phase": "development",
            "protocol": "fixed-protocol",
            "sample_manifest": "ordered-sample",
            "candidate_identity": name,
            "evidence": {"predictions": name + "-predictions"},
            "model": {"kind": "model", "asset": name},
            "report": {
                "accuracy": value,
                "scored": 100,
                "expected": 100,
                "interval_95": [0.0, 3.0],
                "completion": {"status": "complete"},
            },
        }
        for name, value in (("baseline", baseline), ("candidate", candidate))
    ]
    reports[1]["paired_comparison"] = {
        "baseline": "baseline",
        "baseline_predictions": "baseline-predictions",
        "candidate_predictions": "candidate-predictions",
        "sample_manifest": "ordered-sample",
        "expected": 100,
        "paired_decisions": 100,
        "metrics": {"/report/accuracy": {"interval_95": list(interval) if interval else None}},
    }
    return {"baseline": reports[0], "scores": [reports[1]]}


@pytest.mark.parametrize(
    ("interval", "threshold", "outcome"),
    [
        ((0.25, 1.5), 0, "candidate_selected"),
        ((-0.1, 1.5), 0, "baseline_best"),
        ((0, 1.5), 0, "baseline_best"),
        ((0.25, 1.5), 1, "baseline_best"),
        (None, 0, "insufficient_evidence"),
    ],
)
def test_paired_difference_policy_uses_strict_bounds_not_marginal_overlap(
    interval, threshold, outcome
):
    inputs = measured_comparison(interval=interval)
    result = experiment_settings.compare(
        inputs,
        {
            "metric": "/report/accuracy",
            "direction": "maximize",
            "minimum_improvement": threshold,
            "require_interval": True,
        },
    )
    assert result["scores"]["outcome"] == outcome
    if outcome == "candidate_selected":
        assert result["model"]["asset"] == "candidate"
    elif outcome == "baseline_best":
        assert result["model"]["asset"] == "baseline"
    else:
        assert "model" not in result


@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")])
def test_comparison_rejects_nonfinite_measurements_even_with_complete_coverage(value):
    with pytest.raises(InputValidationError):
        experiment_settings.compare(
            measured_comparison(candidate=value),
            {
                "metric": "/report/accuracy",
                "direction": "maximize",
            },
        )


def test_better_aggregate_cannot_hide_a_measured_critical_category_regression():
    inputs = measured_comparison(candidate=0.95, baseline=0.9)
    inputs["baseline"]["report"]["critical"] = {"accuracy": 0.9, "scored": 20, "expected": 20}
    inputs["scores"][0]["report"]["critical"] = {"accuracy": 0.5, "scored": 20, "expected": 20}
    result = experiment_settings.compare(
        inputs,
        {
            "metric": "/report/accuracy",
            "direction": "maximize",
            "eligibility": [
                {"path": "/report/critical/accuracy", "operator": "gte", "value": 0.85}
            ],
        },
    )
    assert result["model"]["asset"] == "baseline"
    del inputs["scores"][0]["report"]["critical"]
    missing = experiment_settings.compare(
        inputs,
        {
            "metric": "/report/accuracy",
            "direction": "maximize",
            "eligibility": [
                {"path": "/report/critical/accuracy", "operator": "gte", "value": 0.85}
            ],
        },
    )
    assert missing["scores"]["outcome"] == "insufficient_evidence" and "model" not in missing


@pytest.mark.parametrize("operator", ["gte", "ne", "eq"])
def test_null_eligibility_measurement_remains_insufficient_evidence(operator):
    inputs = measured_comparison(candidate=0.95, baseline=0.9)
    inputs["baseline"]["report"]["critical_accuracy"] = 0.9
    inputs["scores"][0]["report"]["critical_accuracy"] = None
    result = experiment_settings.compare(
        inputs,
        {
            "metric": "/report/accuracy",
            "direction": "maximize",
            "eligibility": [
                {
                    "path": "/report/critical_accuracy",
                    "operator": operator,
                    "value": None if operator == "eq" else 0.85,
                }
            ],
        },
    )
    assert result["scores"]["outcome"] == "insufficient_evidence"
    assert "model" not in result


def test_complete_claim_cannot_rank_a_candidate_with_unscored_hard_rows():
    inputs = measured_comparison()
    inputs["scores"][0]["report"]["scored"] = 60
    result = experiment_settings.compare(
        inputs, {"metric": "/report/accuracy", "direction": "maximize"}
    )
    assert result["scores"]["outcome"] == "insufficient_evidence"
    assert "model" not in result


@pytest.mark.covers("metrics-math")
@pytest.mark.parametrize(
    ("direction", "baseline", "candidate"),
    [
        ("maximize", 0.90, 0.88),
        ("maximize", 0.90, 0.90),
        ("minimize", 0.10, 0.12),
        ("minimize", 0.10, 0.10),
    ],
)
def test_zero_improvement_requirement_still_applies_when_baseline_fails_eligibility(
    direction, baseline, candidate
):
    inputs = measured_comparison(candidate=candidate, baseline=baseline)
    inputs["baseline"]["report"]["critical"] = {
        "accuracy": 0.80,
        "scored": 20,
        "expected": 20,
    }
    inputs["scores"][0]["report"]["critical"] = {
        "accuracy": 0.90,
        "scored": 20,
        "expected": 20,
    }
    result = experiment_settings.compare(
        inputs,
        {
            "metric": "/report/accuracy",
            "direction": direction,
            "minimum_improvement": 0,
            "require_interval": False,
            "eligibility": [
                {"path": "/report/critical/accuracy", "operator": "gte", "value": 0.85}
            ],
        },
    )
    assert result["scores"]["coverage"]["complete"]
    assert result["scores"]["outcome"] == "no_qualifier"
    assert result["scores"]["selected"] is None
    assert "model" not in result