Skip to content

The platform for continuously improving AI agents.

20.3 KB
Raw Blame
import json
from uuid import uuid4

import pytest
from factories import make_project, make_user
from jsonschema import Draft202012Validator
from pydantic import ValidationError
from test_research_experiments import setup_experiment, start
from test_research_team import assignment, invoke, specialist

from agent_runtime.tool_contract import ToolArgumentsError
from modal_shared.decisions import DECISION_OBJECTIVE, TEXT_OBJECTIVE
from overbae.models import Dataset
from overbae.services import (
    experiment_checkpoints,
    experiment_conversation,
    experiment_training,
    research,
    research_agent,
    research_continuity,
    research_team,
    research_tools,
    training_monitoring,
)
from overbae.services.datasets import land, rows, store
from overbae.services.research_contract import TOOLS

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


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


def test_wait_returns_at_once_when_nothing_can_progress_without_the_lead():
    experiment, user, _ = setup_experiment()
    run = experiment_conversation.send(
        experiment, user, text="Explore this data", request_key="explore"
    )
    lead = run.agents.get(parent__isnull=True)
    waited = invoke(lead, "wait", {"seconds": 60, "reason": "Awaiting the evaluator"})
    assert waited.result["running"] is False
    lead.refresh_from_db()
    assert lead.state != "waiting"


def test_acknowledged_user_instruction_survives_long_history_and_reload():
    experiment, user, _ = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    lead.messages = research_agent.messages(lead)
    instruction = "Keep the temporal holdout sealed and compare both requested candidate models."
    experiment_conversation.send(experiment, user, text=instruction, request_key="constraint")
    experiment_conversation.deliver(lead)
    page = research_team.inbox(lead)
    action = research.claim(
        lead,
        "acknowledge",
        "inbox",
        {"operation": "acknowledge", "events": [entry["event"] for entry in page["messages"]]},
    )
    research.complete(action, research_tools.invoke(action), cost=0)
    lead.refresh_from_db()
    lead.messages = research_agent.messages(lead) + [
        {"role": "assistant", "content": "Inspected retained measurement."} for _ in range(24)
    ]
    lead.save(update_fields=["messages"])
    lead.refresh_from_db()
    history = research_agent.messages(lead)
    assert instruction in json.dumps(history)
    assert run.specification["objective"] in json.dumps(history)
    assert not research_team.inbox(lead)["messages"]
    lead.messages = []
    assert instruction in json.dumps(research_agent.messages(lead))


@pytest.mark.parametrize("nested", [False, True])
def test_history_search_recovers_old_failure_without_an_action_id(nested):
    experiment, user, _ = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    failed = research.claim(
        lead, "old-failure", "workspace", {"operation": "python", "code": "inspect_schema()"}
    )
    result = (
        {
            "error": "Invalid tool arguments",
            "details": [{"field": "participants.0.model", "message": "Required"}],
        }
        if nested
        else {"error": "Target schema excludes temporal identifiers"}
    )
    research.complete(failed, result, state="failed", cost=0)
    for index in range(25):
        action = research.claim(
            lead, f"later-{index}", "remember", {"text": f"Later observation {index}"}
        )
        research.complete(action, {"saved": True}, cost=0)
    search = research.claim(
        lead,
        "recall",
        "history",
        {"query": "participants.0.model" if nested else "temporal", "state": "failed"},
    )
    result = research_tools.invoke(search)
    assert [item["receipt"] for item in result["actions"]] == [str(failed.pk)]
    assert result["actions"][0]["result"]["error"] == failed.result["error"]


def tool_turns(count, *, size=300):
    history = [
        {"role": "system", "content": "Engineer"},
        {"role": "user", "content": "Qualify both candidates"},
    ]
    for index in range(count):
        history += [
            {
                "role": "assistant",
                "tool_calls": [
                    {
                        "id": str(index),
                        "function": {
                            "name": "workspace",
                            "arguments": json.dumps({"operation": "python", "code": "run()"}),
                        },
                    }
                ],
            },
            {
                "role": "tool",
                "tool_call_id": str(index),
                "content": json.dumps(
                    {
                        "tool": "workspace",
                        "operation": "python",
                        "status": "failed" if index == 1 else "completed",
                        "receipt": f"receipt-{index}",
                        "error": {"message": "Column Age is text"} if index == 1 else None,
                        "data": {"output": "retained old output " * size},
                    }
                ),
            },
        ]
    return history


def test_transcript_is_unchanged_until_it_reaches_the_limit():
    history = tool_turns(5)
    assert research_continuity.fit(history, [], limit=20000, target=2000) is history


def test_compaction_archives_whole_turns_into_a_ledger_in_one_step():
    history = tool_turns(8)
    original = json.dumps(history)
    compacted = research_continuity.fit(history, [], limit=4000, target=2500)
    assert research_continuity.token_count(compacted, []) <= 2500
    assert compacted[:2] == history[:2]
    assert compacted[-2:] == history[-2:]
    calls = {call["id"] for message in compacted for call in message.get("tool_calls", [])}
    assert calls == {message["tool_call_id"] for message in compacted if message["role"] == "tool"}
    archive = json.loads(compacted[2]["content"])["archive"]
    assert archive["turns"] == 8 - len(calls)
    assert archive["actions"][1] == {
        "tool": "workspace",
        "operation": "python",
        "status": "failed",
        "receipt": "receipt-1",
        "error": "Column Age is text",
    }
    assert json.dumps(history) == original
    # A later compaction extends the same ledger instead of nesting archives.
    grown = compacted + tool_turns(6)[2:]
    again = research_continuity.fit(grown, [], limit=4000, target=2500)
    merged = json.loads(again[2]["content"])["archive"]
    assert merged["turns"] > archive["turns"]
    assert merged["actions"][: len(archive["actions"])] == archive["actions"]
    assert sum(research_continuity.archived(message) is not None for message in again) == 1


def test_first_plan_has_available_capabilities_and_downstream_contracts():
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    packet = json.loads(research_agent.messages(lead)[1]["content"])
    assert packet["tool_catalogue"] == {"operation": "contracts", "kind": "tools"}
    assert "tool_capabilities" not in packet
    assert "platform_operations" not in packet
    assert (
        research_continuity.token_count(
            research_agent.messages(lead), research_agent.definitions(lead)
        )
        < 120000
    )


def test_tool_schemas_stay_identical_across_turns_of_one_phase():
    _, lead = assignment()
    before = research_agent.definitions(lead)
    child = specialist(lead)
    invoke(lead, "platform", {"name": "create_data_partition", "describe": True})
    invoke(
        lead,
        "manage_agent",
        {"agent": str(child.pk), "operation": "stop", "reason": "No longer needed"},
    )
    lead.refresh_from_db()
    assert research_agent.definitions(lead) == before


def test_model_discovery_returns_decision_models_and_preserves_requested_pages():
    _, lead = assignment()
    result = invoke(lead, "platform", {"name": "get_model_catalog", "arguments": {"query": "clef"}})
    models = {entry["model"]: entry for entry in result.result["models"]}
    assert models["Cloudflare/clef"]["training"]["available"] is True
    assert models["Cloudflare/clef-flash"]["family"] == "decision"
    assert models["Cloudflare/clef"]["decision"]["limits"]["options"] > 1
    page = invoke(lead, "platform", {"name": "get_model_catalog", "arguments": {"limit": 20}})
    assert len(page.result["models"]) == 20
    action = lead.actions.filter(tool="platform").latest("created_at")
    visible = research_agent.tool_observation(action)["data"]
    assert visible["models"] == page.result["models"]
    assert visible["next_offset"] == 20
    next_page = invoke(
        lead, "platform", {"name": "get_model_catalog", "arguments": {"offset": 20, "limit": 20}}
    )
    assert not {m["model"] for m in page.result["models"]} & {
        m["model"] for m in next_page.result["models"]
    }


@pytest.mark.parametrize(
    "family,objective", [("decision", DECISION_OBJECTIVE), ("chat", TEXT_OBJECTIVE)]
)
def test_model_catalogue_monitoring_matches_native_admission(settings, family, objective):
    settings.FINETUNING_BACKEND = "modal"
    _, lead = assignment()
    result = invoke(
        lead, "platform", {"name": "get_model_catalog", "arguments": {"family": family}}
    )
    models = result.result["models"]
    assert models
    for model in models:
        monitoring = model["training"]["monitoring"]
        recipe = {"objective": objective, "monitoring": {"generation": {"kind": "exact_match"}}}
        if "exact_match" in monitoring["generation_checks"]:
            training_monitoring.resolve(recipe, has_development=True, provider="modal")
        else:
            with pytest.raises(ValueError, match="probability metrics"):
                training_monitoring.resolve(recipe, has_development=True, provider="modal")
            assert monitoring["measurement"] == "native_probabilities"


def test_platform_tool_schema_rejects_unknown_operations_and_invalid_native_arguments():
    _, lead = assignment()
    schema = next(
        t["function"]["parameters"]
        for t in research_agent.definitions(lead)
        if t["function"]["name"] == "platform"
    )
    validator = Draft202012Validator(schema)
    validator.validate({"name": "get_model_catalog", "arguments": {"query": "clef"}})
    validator.validate({"name": "get_job", "describe": True})
    assert list(validator.iter_errors({"name": "not_a_tool"}))
    assert list(validator.iter_errors({"name": "get_job", "arguments": {}}))
    assert list(validator.iter_errors({"name": "get_model_catalog", "arguments": {"limit": 999}}))


def test_history_search_excludes_model_calls_that_only_repeat_the_search_terms():
    _, lead = assignment()
    for index in range(6):
        action = research.claim(lead, f"query-{index}", "model", {"messages": "Find Clef"})
        research.complete(action, {"calls": [{"name": "history", "query": "Clef"}]}, cost=0)
    invoke(lead, "platform", {"name": "get_model_catalog", "arguments": {"query": "clef"}})
    search = invoke(lead, "history", {"query": "Clef", "limit": 5})
    assert search.result["actions"]
    assert all(action["tool"] != "model" for action in search.result["actions"])


def test_source_page_keeps_every_requested_row_visible():
    experiment, user, dataset = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    run.experiment_revision = None
    run.save(update_fields=["experiment_revision"])
    lead.refresh_from_db()
    action = invoke(lead, "inspect_source", {"cell": str(dataset.active_cell.pk), "limit": 20})
    visible = research_agent.tool_observation(action)["data"]
    assert len(visible["rows"]) == 20
    assert visible["rows"] == action.result["rows"]
    assert visible["next_offset"] == 20


def test_large_source_pages_preserve_whole_rows_and_exact_continuation():
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Long records", intent="explore")
    land.land_rows(dataset, [{"index": i, "value": "unaltered " * 900} for i in range(7)])
    dataset.refresh_from_db()
    cell = dataset.active_cell
    work, lead = assignment(
        project=project, user=user, context_roots=[f"cell:{cell.pk}"], sealed_cells=()
    )
    expected = list(store.iter_rows(rows.frame_path(cell)))
    offset, collected = 0, []
    while offset is not None:
        result = invoke(
            lead, "inspect_source", {"cell": str(cell.pk), "offset": offset, "limit": 100}
        ).result
        assert 0 < len(result["rows"]) < len(expected)
        collected.extend(result["rows"])
        offset = result["next_offset"]
        assert offset is None or offset == len(collected)
    assert collected == expected


@pytest.mark.parametrize(
    "record",
    [
        {"value": 1},
        {"value": 1, "input": None, "expected_output": None},
        {"messages": [{"role": "user", "content": "Hello"}]},
    ],
)
def test_source_inspection_preserves_stored_columns_without_consumer_defaults(record):
    user = make_user()
    project = make_project(member=user)
    dataset = Dataset.objects.create(project=project, name="Raw source", intent="explore")
    land.land_rows(dataset, [record])
    dataset.refresh_from_db()
    cell = dataset.active_cell
    work, lead = assignment(
        project=project, user=user, context_roots=[f"cell:{cell.pk}"], sealed_cells=()
    )
    result = invoke(lead, "inspect_source", {"cell": str(cell.pk)}).result
    assert result["rows"] == list(store.iter_rows(rows.frame_path(cell)))
    assert set(result["rows"][0]) == {column["name"] for column in result["schema"]}


@pytest.mark.parametrize(
    ("tool", "arguments"),
    [
        ("asset", {"operation": "inspect"}),
        (
            "asset",
            {
                "operation": "publish",
                "kind": "candidate",
                "name": "Candidate",
                "definition": {"kind": "catalogue"},
            },
        ),
        ("component", {"operation": "run"}),
        ("prediction", {"operation": "run", "candidate": str(uuid4())}),
        ("prediction", {"operation": "resume"}),
        ("score", {"operation": "run", "prediction_set": str(uuid4())}),
        ("benchmark", {"operation": "run"}),
        ("serving", {"operation": "deploy"}),
        ("review", {"operation": "report"}),
        ("workspace", {"operation": "status"}),
        ("workspace", {"operation": "interrupt"}),
        ("training", {"operation": "create", "arguments": {"model": "wrong field"}}),
        ("platform", {"name": "get_job", "arguments": {}}),
    ],
)
def test_advertised_requirements_reject_invalid_execution_before_side_effects(tool, arguments):
    _, lead = assignment()
    definition = next(
        t["function"] for t in research_agent.definitions(lead) if t["function"]["name"] == tool
    )
    assert not Draft202012Validator(definition["parameters"]).is_valid(arguments)
    action = research.claim(lead, "invalid-contract", tool, arguments)
    with pytest.raises(ToolArgumentsError) as caught:
        research_tools.invoke(action)
    assert caught.value.details
    assert lead.actions.count() == 1
    assert not experiment_training.campaigns([lead.assignment]).exists()


def test_argument_errors_name_a_scalar_written_where_a_structure_belongs():
    with pytest.raises(ValidationError) as caught:
        TOOLS["experiment"].parse({"operation": "stage", "kind": "train", "settings": "notes"})
    details = research_tools.argument_failure(caught.value)["details"]
    assert any(item["field"] == "settings" and "'notes'" in item["message"] for item in details)


def test_tool_schemas_are_resolvable_and_description_reads_need_no_execution_arguments():
    _, lead = assignment()
    for item in research_agent.definitions(lead):
        schema = item["function"]["parameters"]
        Draft202012Validator.check_schema(schema)
    described = invoke(lead, "training", {"operation": "create", "describe": True})
    assert "base_model" in described.result["properties"]["run"]["description"]
    assert "request_key" not in described.result["properties"]
    assert not experiment_training.campaigns([lead.assignment]).exists()
    described = invoke(lead, "platform", {"name": "create_data_partition", "describe": True})
    assert "request_key" not in described.result["input_schema"]["properties"]


def test_published_assets_are_discoverable_without_losing_entries_between_pages():
    _, lead = assignment()
    identities = set()
    for index in range(21):
        action = invoke(
            lead,
            "asset",
            {
                "operation": "publish",
                "kind": "candidate",
                "name": f"Candidate {index}",
                "definition": {"kind": "catalogue", "model": "openai/gpt-5-mini"},
            },
        )
        identities.add(action.result["id"])
    page = invoke(lead, "asset", {"operation": "list", "kind": "candidate", "limit": 20})
    visible = research_agent.tool_observation(page)["data"]
    assert len(visible["assets"]) == 20
    assert visible["next_offset"] == 20
    remainder = invoke(
        lead, "asset", {"operation": "list", "kind": "candidate", "offset": 20, "limit": 20}
    )
    assert len(remainder.result["assets"]) == 1
    assert remainder.result["next_offset"] is None
    assert {entry["id"] for entry in visible["assets"] + remainder.result["assets"]} == identities


@pytest.mark.parametrize("state", ["failed", "unknown"])
def test_all_tools_keep_call_outcome_separate_from_native_status_and_original_receipt(state):
    _, lead = assignment()
    for name in TOOLS:
        raw = {"state": "running", "id": str(uuid4()), "measured_score": None}
        if state != "completed":
            raw["error"] = "Admission could not be confirmed"
        action = research.claim(lead, f"receipt-{name}", name, {})
        research.complete(action, raw, state=state, cost=0)
        result = research_agent.tool_observation(action)
        assert result["status"] == state
        assert result["data"]["state"] == "running"
        assert result["data"]["id"] == raw["id"]
        assert result["data"]["measured_score"] is None
        receipt = invoke(lead, "inspect_action", {"action": result["receipt"]}).result
        assert json.loads(receipt["text"])["result"] == raw
        if state == "unknown":
            assert result["error"]["code"] == "outcome_unknown"
        action.refresh_from_db()
        assert action.result == raw


def test_identifiers_damaged_in_copying_are_restored_before_a_call_is_judged():
    _, lead = assignment()
    lead = research_agent.lease(lead.pk)
    teammate = str(lead.children.get(role="evaluation").pk)
    damaged = {
        "dropped-quote": ("inspect_agent", {"agent": teammate + '}}],{"'}),
        "truncated": ("message_agent", {"agent": teammate[:-5], "message": "Checked"}),
        "gapped": ("inspect_agent", {"agent": teammate[:18] + teammate[23:]}),
        "unseen": ("inspect_action", {"action": "9b1293a5-116d-495d-9988-004529e4f"}),
    }
    turn = research_agent.admit_model(
        lead,
        lead.lease,
        "turn",
        {},
        0,
        source_scope=research_agent.model_source_scope(lead.assignment),
    )
    research_agent.accept_model_response(
        turn,
        lead.lease,
        [],
        "",
        [
            {
                "id": key,
                "type": "function",
                "function": {"name": tool, "arguments": json.dumps(args)},
            }
            for key, (tool, args) in damaged.items()
        ],
        {"response_cost": 0},
        sent=[{"role": "user", "content": f"Your evaluator is {teammate}."}],
    )
    calls = {action.request_key: action for action in lead.actions.exclude(tool="model")}
    assert calls["dropped-quote"].arguments == {"agent": teammate}
    assert calls["truncated"].arguments["agent"] == teammate
    assert calls["gapped"].arguments["agent"] == teammate
    assert {calls[key].state for key in ("dropped-quote", "truncated", "gapped")} == {"pending"}
    # An identifier the agent was never shown is not guessed at.
    assert calls["unseen"].state == "failed"


def test_a_tokenizer_control_string_in_data_is_counted_as_text():
    history = [{"role": "tool", "content": "USER: hi <|endoftext|> ASSISTANT: hello"}]
    assert research_continuity.token_count(history, []) > research_continuity.token_count(
        [{"role": "tool", "content": "USER: hi  ASSISTANT: hello"}], []
    )