Skip to content

The platform for continuously improving AI agents.

26.0 KB
Raw Blame
import json
from datetime import timedelta
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
from uuid import uuid4

import pytest
from asgiref.sync import async_to_sync
from django.test import Client
from django.utils import timezone
from rest_framework.test import APIClient
from test_research_experiments import setup_experiment, start
from test_research_questions import question_run
from test_research_team import assignment

from agent_runtime.research_disposition import TRANSPORT_UNAVAILABLE, execution_exit_code
from agent_runtime.runtime_transport import RuntimeClient, RuntimeUnavailableError
from overbae.core.errors import InputValidationError
from overbae.core.model_registry import openrouter_slug
from overbae.models import BillingTelemetry, ResearchAction, ResearchEvent
from overbae.services import (
    experiment_conversation,
    research,
    research_agent,
    research_orchestration,
    research_questions,
    research_runtime,
    research_sdk,
    research_tools,
)

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


@pytest.fixture
def runtime_api():
    replies, calls = [], []

    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            calls.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
            status, body, *advertised = replies.pop(0)
            self.send_response(status)
            self.send_header("Content-Length", str(advertised[0] if advertised else len(body)))
            self.end_headers()
            self.wfile.write(body)

        def log_message(self, *_):
            pass

    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    thread = Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        yield f"http://127.0.0.1:{server.server_port}", replies, calls
    finally:
        server.shutdown()
        server.server_close()
        thread.join()


@pytest.mark.parametrize(
    "status,errors,reason,failed",
    [
        ("stuck", [], None, True),
        ("error", ["ProviderError"], None, True),
        ("error", ["MaxIterationsReached"], None, False),
        ("error", ["MaxIterationsReached", "ProviderError"], None, True),
        ("error", ["MarketplaceLoadError", "MaxIterationsReached"], None, False),
        ("finished", [], "amendment", False),
        ("finished", [], None, False),
        ("paused", [], "wait", False),
        ("paused", [], "platform_stop", False),
        ("paused", ["PluginLoadError"], "wait", False),
        ("finished", ["PluginLoadError"], None, False),
        ("paused", [], None, True),
    ],
)
def test_sdk_process_disposition_distinguishes_failure_from_execution_slice(
    status, errors, reason, failed
):
    assert bool(execution_exit_code(status, errors=errors, stop_reason=reason)) is failed


def test_sdk_transport_failure_cannot_be_overwritten_by_an_accepted_wait():
    assert (
        execution_exit_code("paused", stop_reason="wait", transport_failed=True)
        == TRANSPORT_UNAVAILABLE
    )


@pytest.mark.parametrize("operation", ["bootstrap", "events", "tools", "messages", "heartbeat"])
@pytest.mark.parametrize("status", [400, 401, 500, 502, 503, 504])
def test_runtime_transport_preserves_request_identity_and_classifies_availability(
    runtime_api, operation, status
):
    endpoint, replies, calls = runtime_api
    replies.append((status, b"{}"))
    client = RuntimeClient(endpoint, "fixture-token")
    body = {"action_id": "retained-action"}
    transient = status in {502, 503, 504}
    with pytest.raises(RuntimeUnavailableError if transient else RuntimeError):
        client.post(operation, body)
    assert client.transport_failed is transient
    assert calls == [body]


def test_runtime_malformed_response_is_not_a_transport_retry(runtime_api):
    endpoint, replies, _ = runtime_api
    replies.append((200, b"invalid JSON"))
    client = RuntimeClient(endpoint, "fixture-token")
    with pytest.raises(ValueError):
        client.post("bootstrap")
    assert client.transport_failed is False


def test_runtime_truncated_response_preserves_unknown_action_without_reposting(runtime_api):
    endpoint, replies, calls = runtime_api
    replies.append((200, b'{"accepted":', 100))
    client = RuntimeClient(endpoint, "fixture-token")
    with pytest.raises(RuntimeUnavailableError):
        client.post("tools", {"action_id": "retained-action"})
    assert client.transport_failed is True
    assert calls == [{"action_id": "retained-action"}]


def test_explicit_resume_fences_the_failed_turn_and_opens_one_recovery_attempt():
    work, lead = assignment()
    lead.checkpoint_manifest = {
        "launch": {"name": "retained-failed-launch"},
        "consecutive_failures": 2,
        "runtime_contract": {"digest": "retained"},
    }
    lead.save(update_fields=["checkpoint_manifest"])
    research_sdk.failed(lead, "Executor failed")
    stale = research_sdk.load(lead.pk)
    research.resume(work, request_key="recover-executor", instructions="The API is available")
    lead.refresh_from_db()
    assert lead.checkpoint_manifest["consecutive_failures"] == 0
    assert lead.checkpoint_manifest["retired_launch"] == "retained-failed-launch"
    assert lead.checkpoint_manifest["runtime_contract"] == {"digest": "retained"}
    assert research_sdk.failed(stale, "Late failure")["state"] == "wait"
    assert (
        research_orchestration.fence(lead.pk, "Late failure", stale.execution_epoch)["state"]
        == "wait"
    )
    research.resume(work, request_key="recover-executor", instructions="The API is available")
    assert work.events.filter(kind="resumed").count() == 1
    with pytest.raises(InputValidationError):
        research.resume(work, request_key="recover-executor", instructions="Different request")
    work.refresh_from_db()
    assert work.state == "running"


def test_bootstrap_retains_contract_and_rejects_corrupted_session_binding():
    client, agent, _, _, _ = session()
    first = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert first.status_code == 200, first.data
    agent.refresh_from_db()
    retained = agent.checkpoint_manifest["runtime_contract"]
    second = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert second.status_code == 200, second.data
    assert second.data["tools"] == first.data["tools"]
    assert second.data["prompt"] == first.data["prompt"]
    retained["conversation"] = str(uuid4())
    agent.save(update_fields=["checkpoint_manifest"])
    refused = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert refused.status_code == 400, refused.data


def test_historical_contract_restore_requires_idle_exact_session_and_preserves_prompt():
    client, agent, _, _, _ = session()
    agent.checkpoint_manifest.pop("runtime_contract")
    agent.save(update_fields=["checkpoint_manifest"])
    missing = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert missing.status_code == 400, missing.data
    publish(client, agent, kind="message", role="user", text="Retained earlier request")
    missing = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert missing.status_code == 400, missing.data
    manifest = {
        "sdk": "1.64.1",
        "prompt": "Earlier conversation instructions",
        "tools": [{"name": "finish"}],
    }
    args = {
        "conversation": agent.sdk_conversation_id,
        "release": agent.sdk_release,
        "epoch": agent.execution_epoch,
        "manifest": manifest,
    }
    with pytest.raises(InputValidationError):
        research_runtime.restore_contract(agent.pk, **args)
    agent.lease_expires_at = timezone.now() - timedelta(seconds=1)
    agent.save(update_fields=["lease_expires_at"])
    with pytest.raises(InputValidationError):
        research_runtime.restore_contract(agent.pk, **{**args, "epoch": agent.execution_epoch + 1})
    research_runtime.restore_contract(agent.pk, **args)
    agent.refresh_from_db()
    agent.lease_expires_at = timezone.now() + timedelta(minutes=4)
    agent.save(update_fields=["lease_expires_at"])
    restored = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert restored.status_code == 200, restored.data
    assert restored.data["prompt"] == manifest["prompt"]
    assert restored.data["tools"] == manifest["tools"]
    assert ResearchEvent.objects.filter(agent=agent, kind="runtime_contract_restored").count() == 1


def test_console_shows_accepted_answer_once_and_preserves_later_messages():
    client, agent, experiment, _, _ = session()
    summary = "Measured candidate accuracy is 0.75 on four examples."
    action = research.claim(agent, "accepted-answer", "finish", {})
    research.complete(
        action, {"summary": summary, "delivery": "answer", "outcome": "completed"}, cost=0
    )
    publish(client, agent, kind="message", role="assistant", text=summary)
    first = experiment_conversation.conversation(experiment)
    assert sum(item["text"] == summary for item in first) == 1
    publish(client, agent, kind="message", role="user", text="Repeat the measured result")
    publish(client, agent, kind="message", role="assistant", text=summary)
    later = experiment_conversation.conversation(experiment)
    assert sum(item["text"] == summary for item in later) == 2


def test_sdk_wait_resumes_on_answer_or_changed_execution_evidence():
    _, _, assignment, agent, action = question_run()
    assert research_sdk.waiting(agent)
    research_questions.answer(
        assignment, question=action.pk, text="Use outcome", request_key="sdk-answer"
    )
    assert not research_sdk.waiting(agent)
    assert any(
        item.get("message") == "Use outcome"
        for item in research_agent.evidence(agent)["inbox"]["messages"]
    )
    agent.wake = {
        "after": (timezone.now() + timedelta(minutes=10)).isoformat(),
        "evidence": research_agent.evidence_identity(research_agent.evidence(agent)),
    }
    assert research_sdk.waiting(agent)
    research.event(
        assignment,
        "agent_message",
        {"sender": "user", "recipient": str(agent.pk), "message": "Amended protocol"},
        agent,
    )
    assert not research_sdk.waiting(agent)


def session(*, experiment=None, user=None, dataset=None):
    if experiment is None:
        experiment, user, dataset = setup_experiment()
    assignment = start(experiment, user)
    agent = research_agent.lease(assignment.agents.get(parent__isnull=True).pk)
    agent.sdk_conversation_id = uuid4()
    agent.execution_epoch = 1
    agent.save(update_fields=["sdk_conversation_id", "execution_epoch"])
    research_runtime.initialize_contract(agent)
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION=f"Bearer {research_runtime.token(agent)}")
    return client, agent, experiment, user, dataset


def publish(client, agent, **payload):
    previous = (
        ResearchEvent.objects.filter(agent=agent, sdk_event_id__isnull=False)
        .order_by("-sdk_sequence")
        .first()
    )
    event = {
        "id": str(uuid4()),
        "parent_id": previous.sdk_event_id if previous else None,
        "timestamp": timezone.now().isoformat(),
        **payload,
    }
    response = client.post(
        "/api/internal/research/events/",
        {"sequence": previous.sdk_sequence + 1 if previous else 0, "event": event},
        format="json",
    )
    assert response.status_code == 200, response.data
    return event


def dispatch(client, event, **changes):
    return client.post(
        "/api/internal/research/tools/",
        {
            "action_id": event["id"],
            "tool": event["tool"],
            "arguments": event["arguments"],
            **changes,
        },
        format="json",
    )


def test_native_dispatch_requires_exact_retained_action_and_replays_its_receipt():
    client, agent, _, _, dataset = session()
    arguments = {"operation": "read", "reference": f"cell:{dataset.active_cell.pk}"}
    invented = {"id": str(uuid4()), "tool": "explore_context", "arguments": arguments}
    assert dispatch(client, invented).status_code == 400
    event = publish(client, agent, kind="action", tool="explore_context", arguments=arguments)
    assert dispatch(client, event, arguments={"operation": "catalog"}).status_code == 400
    assert not ResearchAction.objects.filter(request_key__startswith="sdk:").exists()
    first = dispatch(client, event)
    assert first.status_code == 200, first.data
    assert first.data["status"] == "completed"
    assert dispatch(client, event).data == first.data
    assert ResearchAction.objects.filter(request_key__startswith="sdk:").count() == 1


def test_large_retained_context_replays_losslessly_before_the_next_action():
    client, agent, _, _, dataset = session()
    text = "Current platform context.\n" + "retained evidence\n" * 7000
    event = publish(client, agent, kind="message", role="user", text=text)
    saved = ResearchEvent.objects.get(agent=agent, sdk_event_id=event["id"])
    assert saved.payload["text"] == text
    replay = {"sequence": saved.sdk_sequence, "event": event}
    assert client.post("/api/internal/research/events/", replay, format="json").status_code == 200
    replay["event"] = {**event, "text": text + "changed tail"}
    assert client.post("/api/internal/research/events/", replay, format="json").status_code == 400
    agent.refresh_from_db()
    assert agent.projected_event_sequence == 1
    action = publish(
        client,
        agent,
        kind="action",
        tool="explore_context",
        arguments={"operation": "read", "reference": f"cell:{dataset.active_cell.pk}"},
    )
    first = dispatch(client, action)
    assert first.status_code == 200, first.data
    assert first.data["status"] == "completed"
    assert dispatch(client, action).data == first.data
    assert agent.actions.filter(request_key=f"sdk:{action['id']}").count() == 1


@pytest.mark.parametrize("lost_state", ["running", "unknown"])
def test_sdk_recovers_admitted_operation_without_resubmission(lost_state):
    client, agent, experiment, user, dataset = session()
    arguments = {
        "operation": "prepare",
        "source_cell": str(dataset.active_cell.pk),
        "objective": "Prepare decision training data",
    }
    event = publish(client, agent, kind="action", tool="workshop", arguments=arguments)
    admitted = dispatch(client, event)
    assert admitted.status_code == 200, admitted.data
    assert admitted.data["status"] == "completed", admitted.data
    action = ResearchAction.objects.get(request_key=f"sdk:{event['id']}")
    # Lose only the transport settlement; the owner has already admitted its work.
    action.state = lost_state
    action.result = {}
    action.completed_at = None
    action.save(update_fields=["state", "result", "completed_at"])
    experiment_conversation.send(
        experiment,
        user,
        text="Keep existing work; do not launch another job",
        request_key="recover-amendment",
    )
    original_token = research_runtime.token(agent)
    original_lease = agent.lease
    agent.lease = uuid4()
    agent.save(update_fields=["lease"])
    assert not research_agent.settle_tool(agent, action, {"invented": True}, fence=original_lease)
    client.credentials(HTTP_AUTHORIZATION=f"Bearer {original_token}")
    assert dispatch(client, event).status_code in {401, 403}
    client.credentials(HTTP_AUTHORIZATION=f"Bearer {research_runtime.token(agent)}")
    recovered = dispatch(client, event)
    assert recovered.status_code == 200, recovered.data
    assert recovered.data["status"] == "completed"
    assert recovered.data["receipt"] == admitted.data["receipt"]
    assert agent.assignment.workshop_tasks.count() == 1
    task = agent.assignment.workshop_tasks.get()
    assert recovered.data["data"]["task"] == admitted.data["data"]["task"] == str(task.pk)
    assert recovered.data["data"]["state"] == task.state


@pytest.mark.parametrize("lost_state", ["running", "unknown"])
def test_sdk_does_not_readmit_when_no_native_receipt_exists(lost_state):
    client, agent, _, _, dataset = session()
    arguments = {
        "operation": "prepare",
        "source_cell": str(dataset.active_cell.pk),
        "objective": "Prepare decision data",
    }
    event = publish(client, agent, kind="action", tool="workshop", arguments=arguments)
    action = research.claim(agent, f"sdk:{event['id']}", "workshop", arguments)
    action.state = lost_state
    action.save(update_fields=["state"])
    response = dispatch(client, event)
    assert response.status_code == 200, response.data
    assert response.data["status"] == "unknown"
    assert not agent.assignment.workshop_tasks.exists()


@pytest.mark.parametrize("admitted", [False, True])
def test_sdk_tool_error_is_not_a_native_effect_or_completion_receipt(admitted):
    client, agent, _, _, dataset = session()
    event = publish(
        client,
        agent,
        kind="action",
        tool="explore_context",
        tool_call_id="interrupted-call",
        arguments={"operation": "read", "reference": f"cell:{dataset.active_cell.pk}"},
    )
    if admitted:
        receipt = dispatch(client, event).data
    publish(
        client,
        agent,
        kind="tool_error",
        tool="explore_context",
        tool_call_id="interrupted-call",
        text="Tool interrupted",
        classification={"kind": "unknown", "retryable": False},
    )
    actions = ResearchAction.objects.filter(agent=agent, request_key=f"sdk:{event['id']}")
    assert actions.count() == int(admitted)
    if admitted:
        assert dispatch(client, event).data == receipt
    agent.refresh_from_db()
    agent.assignment.refresh_from_db()
    assert agent.assignment.state == "running"
    assert agent.state not in research.TERMINAL


def test_unread_amendment_stops_new_action_but_preserves_completed_receipt():
    client, agent, experiment, user, dataset = session()
    event = publish(
        client,
        agent,
        kind="action",
        tool="explore_context",
        arguments={"operation": "read", "reference": f"cell:{dataset.active_cell.pk}"},
    )
    first = dispatch(client, event)
    assert first.status_code == 200, first.data
    experiment_conversation.send(
        experiment,
        user,
        text="Only answer my question; do not change the workflow",
        request_key="amend",
    )
    pending = publish(
        client,
        agent,
        kind="action",
        tool="experiment",
        arguments={"operation": "remove", "stages": ["train"]},
    )
    result = dispatch(client, pending)
    assert result.status_code == 200, result.data
    assert result.data["status"] == "denied"
    assert result.data["data"]["reason"] == "unread_user_message"
    (withheld,) = [
        message
        for message in experiment_conversation.conversation(experiment)
        if message["id"] == f"{agent.assignment_id}:{result.data['receipt']}"
    ]
    assert withheld["status"] == "refused"
    assert dispatch(client, event).data == first.data
    experiment.refresh_from_db()
    assert experiment.version == 1


def test_removed_followup_is_never_delivered_and_blocks_no_tool():
    client, agent, experiment, user, dataset = session()
    experiment_conversation.send(experiment, user, text="Translate every row", request_key="queued")
    message = agent.assignment.user_messages.get()
    experiment_conversation.control(
        experiment,
        message=str(message.pk),
        command="remove",
        revision=message.revision,
        request_key="remove",
    )
    heartbeat = client.post("/api/internal/research/heartbeat/", {}, format="json")
    assert heartbeat.status_code == 200, heartbeat.data
    assert heartbeat.data["messages"] == []
    bootstrap = client.post("/api/internal/research/bootstrap/", {}, format="json")
    assert bootstrap.data["messages"] == []
    event = publish(
        client,
        agent,
        kind="action",
        tool="explore_context",
        arguments={"operation": "read", "reference": f"cell:{dataset.active_cell.pk}"},
    )
    assert dispatch(client, event).data["status"] == "completed"


@pytest.mark.parametrize("invalid", ["role", "order", "removed", "text"])
def test_inbox_acknowledgement_requires_ordered_matching_user_event(invalid):
    client, agent, experiment, user, _ = session()
    experiment_conversation.send(experiment, user, text="First amendment", request_key="first")
    experiment_conversation.send(experiment, user, text="Second amendment", request_key="second")
    messages = list(agent.assignment.user_messages.order_by("position", "created_at"))
    message = messages[1] if invalid == "order" else messages[0]
    if invalid == "removed":
        experiment_conversation.control(
            experiment,
            message=str(message.pk),
            command="remove",
            revision=message.revision,
            request_key="remove",
        )
    event = publish(
        client,
        agent,
        kind="message",
        role="assistant" if invalid == "role" else "user",
        sender=str(message.pk),
        text="Changed text" if invalid == "text" else message.text,
    )
    result = client.post(
        "/api/internal/research/messages/",
        {"message_id": str(message.pk), "event_id": event["id"]},
        format="json",
    )
    assert result.status_code == 400, result.data
    message.refresh_from_db()
    assert message.sdk_event_id is None
    assert not ResearchEvent.objects.filter(
        kind="agent_message", payload__user_message=str(message.pk)
    ).exists()


def test_amendment_at_revision_admission_blocks_new_edits_but_not_retained_replay():
    client, agent, experiment, user, dataset = session()
    arguments = {
        "operation": "stage",
        "id": "copy",
        "kind": "data",
        "settings": {"cell": str(dataset.active_cell.pk)},
    }
    admitted = research.claim(agent, f"sdk:{uuid4()}", "experiment", arguments)
    first = research_tools.invoke(admitted)
    experiment.refresh_from_db()
    assert experiment.version == 2
    pending = research.claim(
        agent,
        f"sdk:{uuid4()}",
        "experiment",
        {
            "operation": "stage",
            "id": "replacement",
            "kind": "data",
            "settings": {
                "cell": str(
                    experiment.revisions.get(number=1).document["nodes"][0]["config"]["cell"]
                )
            },
        },
    )
    experiment_conversation.send(
        experiment, user, text="Stop editing; answer only", request_key="racing-amendment"
    )
    with pytest.raises(InputValidationError, match="pending user message"):
        research_tools.invoke(pending)
    replay = research_tools.invoke(admitted)
    assert replay["revision"] == first["revision"]
    assert research_agent.settle_tool(agent, admitted, first, fence=agent.lease)
    experiment.refresh_from_db()
    assert experiment.version == 2


def test_valid_inbox_acknowledgement_replays_without_duplicate_delivery():
    client, agent, experiment, user, _ = session()
    experiment_conversation.send(
        experiment, user, text="Keep the exact attached input", request_key="followup"
    )
    message = agent.assignment.user_messages.get()
    event = publish(
        client, agent, kind="message", role="user", sender=str(message.pk), text=message.text
    )
    body = {"message_id": str(message.pk), "event_id": event["id"]}
    for _ in range(2):
        response = client.post("/api/internal/research/messages/", body, format="json")
        assert response.status_code == 204, response.data
    assert (
        ResearchEvent.objects.filter(
            kind="agent_message", payload__user_message=str(message.pk)
        ).count()
        == 1
    )


async def collect(response):
    return b"".join([chunk async for chunk in response.streaming_content])


def relay(key, **body):
    return Client().post(
        "/api/internal/research/model/chat/completions",
        {"model": "any", "messages": [{"role": "user", "content": "Plan the split"}], **body},
        content_type="application/json",
        HTTP_AUTHORIZATION=f"Bearer {key}",
    )


@pytest.mark.parametrize("stream", [False, True])
def test_the_runner_reaches_the_model_only_through_the_metered_relay(fake_llm, stream):
    client, agent, *_ = session()
    config = client.post("/api/internal/research/bootstrap/", {}, format="json").data
    assert config["base_url"] == "http://api.test/api/internal/research/model"
    assert config["model"] == f"openai/{openrouter_slug(agent.model)}"
    assert "offline-test-key" not in json.dumps(config)
    fake_llm.on(
        lambda request: "Plan the split" in request.text,
        {"content": "Split by customer", "usage": {"cost": 0.02}},
    )

    response = relay(config["api_key"], stream=stream)

    assert response.status_code == 200
    if stream:
        events = async_to_sync(collect)(response).decode().split("\n\n")
        assert events[-2] == "data: [DONE]"
        text = "".join(
            choice["delta"].get("content") or ""
            for event in events[:-2]
            for choice in json.loads(event.removeprefix("data: "))["choices"]
        )
    else:
        text = json.loads(response.content)["choices"][0]["message"]["content"]
    assert text == "Split by customer"
    assert fake_llm.requests[-1].body["model"] == openrouter_slug(agent.model)
    call = agent.actions.get(tool="model")
    assert call.state == "completed" and float(call.cost_usd) == pytest.approx(0.02)
    charged = BillingTelemetry.objects.get(cause_kind="research_action", cause_id=str(call.pk))
    assert float(-charged.amount) == pytest.approx(0.02)


def test_a_relay_call_over_the_run_limit_is_refused_and_exhausts_the_agent(fake_llm):
    client, agent, *_ = session()
    key = client.post("/api/internal/research/bootstrap/", {}, format="json").data["api_key"]
    run = agent.assignment
    run.specification["budget"]["max_model_calls"] = research.model_calls(run)
    run.save(update_fields=["specification"])

    response = relay(key)

    assert response.status_code == 429
    assert not fake_llm.requests
    agent.refresh_from_db()
    assert agent.state == "exhausted"


def test_the_relay_refuses_any_key_but_the_sessions_model_key(fake_llm):
    client, agent, *_ = session()
    assert relay(research_runtime.token(agent)).status_code == 401
    assert relay("offline-test-key").status_code == 401
    assert not fake_llm.requests