Skip to content

The platform for continuously improving AI agents.

9.8 KB
Raw Blame
from copy import deepcopy

import pytest
from factories import make_project, make_user
from test_experiment_preparation import experiment_on, passengers
from test_research_experiments import invoke, save, setup_experiment, start
from test_transform_spec import SPEC

from overbae.core.errors import InputValidationError
from overbae.models import Dataset, FinetuningJob, NativeEvaluationPlan
from overbae.services import (
    experiment_execution,
    experiment_preflight,
    experiment_training,
    research_experiments,
)
from overbae.services.datasets import land
from overbae.services.decision_providers import qualify_participants

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


@pytest.fixture(autouse=True)
def openrouter(fake_llm):
    fake_llm.catalog_payload = [
        {
            "id": "openai/gpt-4o",
            "name": "GPT-4o",
            "supported_parameters": ["logprobs", "top_logprobs"],
            "pricing": {"prompt": "0.000001", "completion": "0.000002"},
            "architecture": {"modality": "text->text"},
        }
    ]
    return fake_llm


def training_document(experiment):
    document = deepcopy(experiment.revisions.get(number=1).document)
    document["nodes"].extend(
        [
            {
                "id": "train",
                "kind": "train",
                "title": "Train Qwen",
                "position": {"x": 300, "y": 0},
                "config": {"model": {"model": "Qwen/Qwen3.5-0.8B"}},
                "operation": {
                    "tool": "training",
                    "arguments": {
                        "operation": "create",
                        "arguments": {
                            "run": {"name": "Candidate", "hyperparameters": {}},
                            "trials": 1,
                        },
                    },
                },
            },
            {
                "id": "benchmark",
                "kind": "evaluate",
                "title": "Compare Qwen",
                "config": {},
                "position": {"x": 600, "y": 0},
                "operation": {
                    "tool": "benchmark",
                    "arguments": {
                        "operation": "run",
                        "baseline": "base",
                        "participants": [
                            {
                                "key": "base",
                                "name": "GPT-4o",
                                "kind": "external",
                                "model": "openai/gpt-4o",
                            },
                        ],
                    },
                },
            },
        ]
    )
    document["edges"] = [
        {"source": "data_0", "output": "data", "target": "train", "input": "data"},
        {"source": "data_0", "output": "data", "target": "train", "input": "development"},
        {"source": "data_0", "output": "data", "target": "benchmark", "input": "data"},
        {"source": "train", "output": "model", "target": "benchmark", "input": "model"},
    ]
    document["outputs"] = {"comparison": {"node": "benchmark", "port": "scores"}}
    return document


def test_drafting_reports_configuration_and_input_errors_together_before_execution():
    experiment, user, dataset = setup_experiment()
    run = start(experiment, user)
    document = training_document(experiment)
    run_settings = document["nodes"][-2]["operation"]["arguments"]["arguments"]["run"]
    run_settings["hyperparameters"]["learning_rate"] = -1
    revision = save(run, document)
    result = invoke(run, "inspect")
    assert not result["ready"] and result["revision"] == revision
    errors = "\n".join(result["issues"])
    assert "learning_rate must be a finite number" in errors
    assert "benchmark:" in errors and str(dataset.active_cell.pk) in errors
    assert not experiment_training.campaigns([run]).exists()
    assert not NativeEvaluationPlan.objects.exists()


@pytest.mark.parametrize("named", [False, True])
def test_future_checkpoint_binds_once_with_the_baseline_preserved(named):
    experiment, _, dataset = setup_experiment()
    land.land_rows(
        dataset,
        [
            {
                "input": {
                    "decision": {
                        "state": "observed",
                        "question": "Choose",
                        "kind": "choice",
                        "options": ["yes", "no"],
                    }
                },
                "expected_output": {"probabilities": [1, 0]},
                # The same version feeds the train stage, which reads conversations.
                "messages": [
                    {"role": "user", "content": "Choose"},
                    {"role": "assistant", "content": "yes"},
                ],
            }
        ],
    )
    dataset.refresh_from_db()
    document = training_document(experiment)
    document["nodes"][0]["config"] = {
        "cell": str(dataset.active_cell.pk),
        "fingerprint": dataset.active_cell.fingerprint,
    }
    benchmark = document["nodes"][-1]
    if named:
        benchmark["operation"]["arguments"]["participants"].append(
            {"key": "tuned", "name": "Tuned Qwen", "kind": "trained"}
        )

    document = research_experiments.validate_document(experiment.project, document)
    assert experiment_preflight.readiness(experiment.project, document) == {
        "ready": True,
        "errors": [],
    }
    job = FinetuningJob.objects.create(
        project=experiment.project,
        dataset=dataset,
        base_model="Qwen/Qwen3.5-0.8B",
        hyperparameters={"objective": "decision_cross_entropy"},
    )
    inputs = {
        "data": {"cell": str(dataset.active_cell.pk)},
        "model": {"model": job.base_model, "job": str(job.pk)},
    }
    args = experiment_execution.arguments(benchmark, inputs)
    selected = qualify_participants(experiment.project, args["participants"])
    assert args["baseline"] == "base"
    assert len(selected) == 2
    assert selected[1]["job"] == str(job.pk)
    assert selected[1]["key"] == ("tuned" if named else "candidate")
    repeated = experiment_execution.arguments(
        {**benchmark, "operation": {"tool": "benchmark", "arguments": args}}, inputs
    )
    assert repeated == args
    with pytest.raises(InputValidationError, match="connected model output"):
        experiment_preflight.validate(
            experiment.project,
            {
                **document,
                "edges": [e for e in document["edges"] if e["input"] != "model"],
                "nodes": [
                    *document["nodes"][:-1],
                    {
                        **benchmark,
                        "operation": {
                            "tool": "benchmark",
                            "arguments": {
                                **benchmark["operation"]["arguments"],
                                "participants": [
                                    {"key": "tuned", "kind": "trained", "name": "Unbound"}
                                ],
                                "baseline": "tuned",
                            },
                        },
                    },
                ],
            },
        )


def decision_data():
    """A project with decision-format train and development versions."""
    user = make_user()
    project = make_project(member=user)
    cells = {}
    for role in ("train", "development"):
        dataset = Dataset.objects.create(project=project, name=f"Decisions {role}", intent="train")
        land.land_rows(
            dataset,
            [
                {
                    "input": {
                        "decision": {
                            "state": f"case {index}",
                            "question": "Approve?",
                            "kind": "choice",
                            "options": ["yes", "no"],
                        }
                    },
                    "expected_output": {"probabilities": [index % 2, 1 - index % 2]},
                    "messages": [
                        {"role": "user", "content": f"case {index}"},
                        {"role": "assistant", "content": "yes" if index % 2 else "no"},
                    ],
                }
                for index in range(12)
            ],
        )
        dataset.refresh_from_db()
        cells[role] = dataset.active_cell
    return project, user, cells


def generation_monitoring(node):
    node["operation"]["arguments"]["arguments"]["run"]["monitoring"] = {
        "generation": {"kind": "classification", "labels": ["yes", "no"]}
    }


@pytest.mark.parametrize(
    ("recipe", "ready"),
    [
        ({"monitoring": {"initial": False}, "pre_training_baseline": True}, False),
        ({"pre_training_baseline": False}, True),
    ],
)
def test_fresh_decision_preparation_validates_training_recipe_before_execution(recipe, ready):
    dataset, user = passengers()
    experiment = experiment_on(dataset, user)
    run = start(experiment, user)
    assert invoke(
        run,
        "stage",
        id="prepare",
        kind="transform",
        inputs={"data": "data_0"},
        settings={"spec": SPEC},
    )["ready"]
    assert invoke(run, "stage", id="split", kind="split", inputs={"data": "prepare"})["ready"]
    result = invoke(
        run,
        "stage",
        id="train",
        kind="train",
        inputs={"data": "split.train", "development": "split.development"},
        settings={
            "model": "OvermindLab/qwen-3.5-0.8B-decision",
            "use_case": "Predict survival from passenger features",
            "hyperparameters": recipe,
        },
    )
    assert result["ready"] is ready, result["issues"]
    if not ready:
        assert any("pre_training_baseline" in issue for issue in result["issues"])
    assert not experiment_training.campaigns([run]).exists()
    assert not FinetuningJob.objects.filter(project=run.project).exists()