Skip to content

The platform for continuously improving AI agents.

19.7 KB
Raw Blame
import json
import uuid

import pytest
from jsonschema import Draft202012Validator
from test_context_graph import lineage
from test_experiment_engine import flow
from test_research_experiments import setup_experiment, start

from overbae.core.errors import InputValidationError
from overbae.models import Cell, DataPartitionPlan, FinetuningJob, ResearchAction
from overbae.services import (
    context_graph,
    context_query,
    experiment_checkpoints,
    experiment_engine,
    experiment_execution,
    experiment_interfaces,
    experiment_stages,
    experiment_training,
    research,
    research_agent,
    research_tools,
)
from overbae.services.datasets import partition_plans
from overbae.services.experiment_compiler import compile_document
from overbae.services.experiment_contract import Document
from overbae.services.research_contract import TOOLS, Explore

pytestmark = [pytest.mark.django_db, pytest.mark.covers("lineage")]


def query(lead, **arguments):
    action = research.claim(lead, str(uuid.uuid4()), "explore_context", arguments)
    result = research_tools.invoke(action)
    research.complete(action, result, cost=0)
    return result


def read_all(lead, **arguments):
    page = query(lead, **arguments)
    content = page["content"]
    while page["next_offset"] is not None:
        page = query(lead, **page["continuation"])
        content += page["content"]
    return json.loads(content)


def test_context_is_retrieved_before_planning_instead_of_preloaded_into_messages():
    experiment, user, dataset = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    packet = research_agent.packet(lead)
    assert "context" not in packet
    assert "components" not in packet["experiment"]
    assert "data_consumers" not in packet
    assert "explore_context" in {
        entry["function"]["name"] for entry in research_agent.definitions(lead)
    }
    details = query(lead, operation="contracts", kind="train")
    assert details["operation"] == "training.create"
    assert details["inputs"]["development"] == {"type": "data", "required": False}
    found = query(lead, operation="search", kind="cell", query=dataset.active_cell.title)
    assert f"cell:{dataset.active_cell.pk}" in {node["reference"] for node in found["nodes"]}
    assert all("facts" not in node for node in found["nodes"])


@pytest.mark.parametrize("kind", ["check_data", "export_data"])
def test_small_operation_contract_is_executable_without_followup_schema_reads(kind):
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    contract = query(lead, operation="contracts", kind=kind)
    Draft202012Validator.check_schema(contract["settings"])
    assert contract["settings"]["properties"] and contract["outputs"]
    # Its connection supplies the source, so the source is not a setting.
    assert "source_cell" not in contract["settings"]["properties"]
    assert contract["example"]["arguments"]["kind"] == kind


@pytest.mark.parametrize(
    "asked",
    [
        "component:train",
        "tool:check_data",
        "check_data",
        "experiment",
        "tool:experiment",
        "made-up",
    ],
)
def test_a_contract_lookup_resolves_however_it_is_named(asked):
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    found = query(lead, operation="contracts", kind=asked)
    if asked == "made-up":
        # A miss answers with what can be looked up.
        assert found["found"] is False and "train" in found["stage_kinds"]
    elif asked == "tool:check_data":
        assert found["tool"] == "platform" and "row_schema" in found["input_schema"]["properties"]
    elif "experiment" in asked:
        assert read_all(lead, operation="contracts", kind=asked)["name"] == "experiment"
    else:
        assert found["kind"] == asked.removeprefix("component:")


def test_a_continuation_handed_back_as_a_cursor_still_continues():
    experiment, user, dataset = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    Cell.objects.filter(pk=dataset.active_cell.pk).update(stats={"profile": "long detail " * 200})
    reference = f"cell:{dataset.active_cell.pk}"
    first = query(lead, operation="read", reference=reference, length=800)
    following = query(
        lead, operation="read", reference=reference, cursor=json.dumps(first["continuation"])
    )
    assert following["offset"] == 800 and following["fingerprint"] == first["fingerprint"]
    missing = query(lead, operation="read", reference=reference, path="/stats/absent")
    assert missing["missing"] == "absent" and missing["fields"] == ["profile"]


def test_agent_follows_fresh_action_relationships_without_losing_edges_between_pages():
    experiment, user, _ = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    actions = []
    for index in range(5):
        action = research.claim(lead, f"retained-{index}", "remember", {"text": f"Finding {index}"})
        research.complete(action, {"saved": True}, cost=0)
        actions.append(action)
    edges, cursor = [], None
    while True:
        page = query(
            lead,
            operation="traverse",
            reference=f"research_agent:{lead.pk}",
            direction="incoming",
            relationship="agent",
            kind="research_action",
            limit=2,
            cursor=cursor,
        )
        edges.extend(page["edges"])
        references = {node["reference"] for node in page["nodes"]}
        assert all({edge["source"], edge["target"]} <= references for edge in page["edges"])
        cursor = page["next_cursor"]
        if not cursor:
            break
    assert {f"research_action:{action.pk}" for action in actions} <= {e["source"] for e in edges}
    assert len({e["id"] for e in edges}) == len(edges)
    lead.refresh_from_db()
    action = actions[0]
    ResearchAction.objects.filter(pk=action.pk).update(state="failed")
    read = query(lead, operation="read", reference=f"research_action:{action.pk}")
    assert json.loads(read["content"])["state"] == "failed"


def test_large_graph_record_can_be_read_completely_and_restarts_when_it_changes():
    experiment, user, dataset = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    Cell.objects.filter(pk=dataset.active_cell.pk).update(stats={"profile": "long detail " * 1000})
    reference = f"cell:{dataset.active_cell.pk}"
    first = query(lead, operation="read", reference=reference, length=800)
    content = first["content"]
    continuation = first["continuation"]
    while continuation is not None:
        page = query(lead, **continuation)
        content += page["content"]
        continuation = page["continuation"]
    assert json.loads(content)["stats"]["profile"] == "long detail " * 1000
    Cell.objects.filter(pk=dataset.active_cell.pk).update(stats={"profile": "revised"})
    # A record that changed between pages is read again from its start, never spliced.
    again = query(
        lead, operation="read", reference=reference, offset=800, fingerprint=first["fingerprint"]
    )
    assert again["restarted"] is True and again["offset"] == 0
    assert json.loads(again["content"])["stats"]["profile"] == "revised"


@pytest.mark.covers("tenancy")
def test_graph_cursor_and_exact_reads_cannot_cross_projects():
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    other, other_user, foreign_data = setup_experiment()
    foreign = start(other, other_user).agents.get(parent__isnull=True)
    cursor = query(lead, operation="search", limit=1)["next_cursor"]
    with pytest.raises(InputValidationError, match="cursor"):
        query(foreign, operation="search", limit=1, cursor=cursor)
    with pytest.raises(InputValidationError, match="unavailable"):
        query(lead, operation="read", reference=f"cell:{foreign_data.active_cell.pk}")


@pytest.mark.covers("privacy")
def test_graph_read_refuses_a_version_the_run_seals():
    experiment, user, dataset = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    Cell.objects.filter(pk=dataset.active_cell.pk).update(stats={"private_target": "sealed-value"})
    run.specification["sealed_cells"] = [str(dataset.active_cell.pk)]
    run.save(update_fields=["specification"])
    lead.refresh_from_db()
    with pytest.raises(partition_plans.SealedHoldoutError):
        query(lead, operation="read", reference=f"cell:{dataset.active_cell.pk}")


def test_executed_partition_is_linked_to_its_node_flow_revision_and_exact_output():
    with experiment_checkpoints.store() as store:
        store.setup()
    experiment, user = flow()
    run = experiment_engine.start(
        experiment, user, revision=2, request_key="native-graph", budget={}
    )
    experiment_engine.advance(run.pk)
    partition_plans.build(DataPartitionPlan.objects.get().pk)
    experiment_engine.advance(run.pk)
    node = run.execution.nodes.get(node="partition")
    output = node.outputs["train"]["cell"]
    page = research_tools.visible_context(
        run,
        Explore(
            operation="traverse",
            reference=f"cell:{output}",
            relationship="produces",
            direction="incoming",
        ),
    )
    assert [edge["source"] for edge in page["edges"]] == [f"node_execution:{node.pk}"]
    page = research_tools.visible_context(
        run,
        Explore(
            operation="traverse",
            reference=f"node_execution:{node.pk}",
            relationship="execution",
            direction="outgoing",
        ),
    )
    assert [edge["target"] for edge in page["edges"]] == [f"flow_execution:{run.pk}"]
    page = research_tools.visible_context(
        run,
        Explore(
            operation="traverse",
            reference=f"flow_execution:{run.pk}",
            relationship="revision",
            direction="outgoing",
        ),
    )
    assert [edge["target"] for edge in page["edges"]] == [
        f"experiment_revision:{run.experiment_revision_id}"
    ]


def test_targeted_refresh_retires_removed_relationships_without_deleting_unrelated_nodes():
    project, _, _, cell, job, _ = lineage()
    context_graph.refresh(project)
    replacement = Cell.objects.create(
        dataset=cell.dataset, position=1, title="Replacement", state="ok", fingerprint="b" * 64
    )
    FinetuningJob.objects.filter(pk=job.pk).update(cell=replacement)
    old = context_query.execute(
        project,
        Explore(
            operation="traverse",
            reference=f"cell:{cell.pk}",
            direction="incoming",
            relationship="cell",
            kind="training_run",
        ),
    )
    assert old["edges"] == []
    current = context_query.execute(
        project,
        Explore(
            operation="traverse",
            reference=f"cell:{replacement.pk}",
            direction="incoming",
            relationship="cell",
            kind="training_run",
        ),
    )
    assert current["edges"][0]["source"] == f"training_run:{job.pk}"
    assert context_graph.inspect(project, kind="cell")["total"] == 2


def test_native_catalogue_discovers_all_tools_and_runs_the_selected_model_lookup():
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    root = read_all(lead, operation="contracts")
    tools = read_all(lead, **root["native_tools"])["tools"]
    assert {item["name"] for item in tools} == set(TOOLS)
    found = read_all(lead, operation="contracts", kind="tools", query="get_model_catalog")
    entry = read_all(lead, **found["tools"][0]["read"])
    schema = read_all(lead, **entry["operations"]["get_model_catalog"]["input_schema"]["read"])
    arguments = {"name": "get_model_catalog", "arguments": {"query": "clef"}}
    Draft202012Validator(schema).validate(arguments)
    action = research.claim(lead, "discovered-models", "platform", arguments)
    result = research_tools.invoke(action)
    research.complete(action, result, cost=0)
    assert {item["model"] for item in result["models"]} == {
        "Cloudflare/clef",
        "Cloudflare/clef-flash",
    }
    response_schema = read_all(lead, **entry["response_schema"])
    Draft202012Validator(response_schema).validate(research_agent.tool_observation(action))
    assert not experiment_training.campaigns([lead.assignment]).exists()


def test_catalogue_distinguishes_discovery_from_permission_to_execute():
    experiment, user, _ = setup_experiment()
    run = start(experiment, user)
    lead = run.agents.get(parent__isnull=True)
    training = read_all(lead, operation="contracts", kind="tool:training")
    available = read_all(lead, **training["available_input_schema"]["read"])
    validator = Draft202012Validator(available)
    assert validator.is_valid({"operation": "create", "describe": True})
    assert not validator.is_valid({"operation": "create", "describe": False, "arguments": {}})
    serving = read_all(lead, operation="contracts", kind="tool:serving")
    available = read_all(lead, **serving["available_input_schema"]["read"])
    assert set(available["properties"]["operation"]["enum"]) == {
        "deploy",
        "infer",
        "inspect",
        "stop",
    }
    # A specialist of an adaptive investigation reads the platform and changes nothing.
    investigation = research.create(
        run.project,
        user=user,
        request_key="investigation",
        objective="Investigate the data",
        task={"deliverable": "Findings"},
        budget={},
    )
    evaluator = investigation.agents.get(role="evaluation")
    platform = read_all(evaluator, operation="contracts", kind="tool:platform")
    available = read_all(evaluator, **platform["available_input_schema"]["read"])
    validator = Draft202012Validator(available)
    assert validator.is_valid({"name": "get_model_catalog", "arguments": {}})
    assert not validator.is_valid({"name": "create_data_partition", "arguments": {}})


@pytest.mark.parametrize(
    "query_text", ["dataset pipeline check export data", "check_data export_data"]
)
def test_catalogue_search_finds_operations_from_multiword_tasks(query_text):
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    found = read_all(lead, operation="contracts", kind="tools", query=query_text)
    platform = next(item for item in found["tools"] if item["name"] == "platform")
    operations = {item["name"]: item for item in platform["matching_operations"]}
    for name in ("check_data", "export_data"):
        contract = read_all(lead, **operations[name]["read"])
        schema = contract["input_schema"]
        arguments = {
            "source_cell": str(experiment.revisions.first().document["nodes"][0]["config"]["cell"])
        }
        if name == "check_data":
            arguments["row_schema"] = {"type": "object"}
        Draft202012Validator(schema).validate({"name": name, "arguments": arguments})
    assert (
        read_all(lead, operation="contracts", kind="tools", query="nonexistent_operation_xyz")[
            "tools"
        ]
        == []
    )


def test_operation_discovery_supplies_compilable_flow_connections():
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    document = experiment.revisions.first().document
    previous = document["nodes"][0]["id"]
    previous_output = "data"
    for name in ("check_data", "export_data"):
        action = research.claim(lead, name, "platform", {"name": name, "describe": True})
        contract = research_tools.invoke(action)
        flow = next(item for item in contract["flow"] if item["kind"] == name)
        source_input = next(iter(flow["interface"]["consumes"]))
        arguments = (
            {"row_schema": {"type": "object"}} if name == "check_data" else {"format": "jsonl"}
        )
        document["nodes"].append(
            {
                "id": name,
                "kind": flow["kind"],
                "title": name,
                "position": {"x": 300 * len(document["nodes"]), "y": 0},
                "operation": {
                    "tool": "platform",
                    "arguments": {"name": name, "arguments": arguments},
                },
            }
        )
        document["edges"].append(
            {
                "source": previous,
                "output": previous_output,
                "target": name,
                "input": source_input,
            }
        )
        previous = name
        previous_output = (
            next(
                port
                for port, formats in flow["interface"]["produces"].items()
                if formats == ["dataset.cell"]
            )
            if name == "check_data"
            else "artifact"
        )
    document["outputs"] = {"export": {"node": previous, "port": previous_output}}
    compiled, _ = compile_document(Document.model_validate(document), {})
    assert compiled["nodes"][-1]["kind"] == "export_data"


@pytest.mark.parametrize(
    "kind,tool,operation,authored,inputs",
    [
        (
            "predict",
            "prediction",
            "run",
            {},
            {
                "model": {"asset": str(uuid.UUID(int=1))},
                "data": {"cell": str(uuid.UUID(int=2))},
            },
        ),
        (
            "evaluate",
            "score",
            "run",
            {},
            {
                "predictions": {"prediction_set": str(uuid.UUID(int=3))},
                "suite": {"asset": str(uuid.UUID(int=4))},
            },
        ),
        ("evaluate", "training", "inspect", {}, {"model": {"campaign": str(uuid.UUID(int=5))}}),
        ("validate", "component", "validate", {"schema": {"type": "object"}}, {"artifact": {}}),
        ("publish", "serving", "deploy", {}, {"model": {"campaign": str(uuid.UUID(int=5))}}),
        ("evaluate", "benchmark", "run", {}, {"data": {"cell": str(uuid.UUID(int=2))}}),
        (
            "split",
            "platform",
            "create_data_partition",
            {
                "name": "Development split",
                "recipe": {"seed": 37, "fractions": {"train": 0.8, "development": 0.2}},
            },
            {"data": {"cell": str(uuid.UUID(int=2))}},
        ),
    ],
)
def test_stage_settings_compile_to_an_operation_that_its_connections_complete(
    kind,
    tool,
    operation,
    authored,
    inputs,
):
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    selected = f"{tool}.{operation}"
    contract = query(lead, operation="contracts", kind=kind, query=selected)
    assert contract["operation"] == selected
    Draft202012Validator(contract["settings"]).validate(authored)
    # What a connection supplies is never asked of the author.
    supplied = experiment_interfaces.bound_arguments(tool, operation)
    assert supplied
    assert not {path.rsplit(".", 1)[-1] for path in supplied} & set(
        contract["settings"]["properties"]
    )
    config, saved = experiment_stages.build(
        kind, "Stage", {**authored, "operation": selected}, inputs, "", created=True
    )
    resolved = experiment_execution.arguments(
        {"kind": kind, "config": config, "operation": saved}, inputs
    )
    TOOLS[tool].parse(resolved)


def test_named_tool_operation_requires_its_selector_instead_of_defaulting_to_another_operation():
    experiment, user, _ = setup_experiment()
    lead = start(experiment, user).agents.get(parent__isnull=True)
    entry = read_all(lead, operation="contracts", kind="tool:inbox")
    schema = read_all(lead, **entry["operations"]["acknowledge"]["input_schema"]["read"])
    validator = Draft202012Validator(schema)
    arguments = {"operation": "acknowledge", "events": [1]}
    assert validator.is_valid(arguments)
    assert not validator.is_valid({"events": arguments["events"]})