Skip to content

The platform for continuously improving AI agents.

5.8 KB
Raw Blame
import asyncio
import uuid
from datetime import timedelta

import pytest
from asgiref.sync import sync_to_async
from django.utils import timezone
from temporalio import activity
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from test_workshop_agent import local_sandbox as local_sandbox
from test_workshop_agent import passengers
from test_workshop_session import session as session

from overbae.management.commands.workshop_agent_worker import dispatch
from overbae.models import WorkshopTask
from overbae.services.workshop_agent import agent, lifecycle, sandbox
from workflows.workshop import TASK_QUEUE, WorkshopTaskWorkflow

pytestmark = pytest.mark.covers("recovery")


def drive(outcome):
    """Run the workflow on Temporal's time-skipping server against a scripted loop.

    Returns the result and how often the task was run and fenced.
    """
    supervised, fenced = [], []

    async def scenario():
        async with await WorkflowEnvironment.start_time_skipping() as env:

            @activity.defn(name="supervise_run")
            async def supervise(task: str) -> dict:
                supervised.append(task)
                if isinstance(outcome, Exception):
                    raise outcome
                if isinstance(outcome, list):
                    return outcome[len(supervised) - 1]
                return outcome

            @activity.defn(name="fence_run")
            async def fence(task: str) -> dict:
                fenced.append(task)
                return {"state": "blocked"}

            async with Worker(
                env.client,
                task_queue=TASK_QUEUE,
                workflows=[WorkshopTaskWorkflow],
                activities=[supervise, fence],
            ):
                return await env.client.execute_workflow(
                    WorkshopTaskWorkflow.run,
                    "task",
                    id=f"workshop-task:{uuid.uuid4()}",
                    task_queue=TASK_QUEUE,
                )

    return asyncio.run(asyncio.wait_for(scenario(), 60)), supervised, fenced


def test_a_task_whose_loop_keeps_failing_is_fenced_once_and_its_workflow_ends():
    result, supervised, fenced = drive(ValueError("the loop cannot continue"))
    assert result == {"state": "blocked"}
    assert len(supervised) == 3
    assert fenced == ["task"]


@pytest.mark.parametrize("state", ["completed", "paused", "blocked"])
def test_a_run_that_returns_ends_its_workflow(state):
    result, supervised, fenced = drive({"state": state})
    assert result == {"state": state}
    assert len(supervised) == 1 and not fenced


def test_provider_settlement_retries_through_durable_timers_before_workflow_completion():
    result, supervised, fenced = drive(
        [
            {"state": "running", "settlement_pending": True},
            {"state": "running", "settlement_pending": True},
            {"state": "cancelled"},
        ]
    )
    assert result == {"state": "cancelled"}
    assert len(supervised) == 3 and not fenced


@pytest.mark.django_db(transaction=True)
def test_a_fenced_task_says_so_and_runs_again_when_resumed():
    grant, task = passengers()
    assert agent.fence(str(task.pk)) == {"state": "blocked"}
    task.refresh_from_db()
    assert task.state == "blocked" and task.desired_state == "paused"
    assert task.chat_events.filter(key="fenced").exists()
    assert task.preparation.state == "paused"
    task.dispatched_at = task.created_at
    task.save(update_fields=["dispatched_at"])
    lifecycle.control(grant.project, task.pk, "resume")
    task.refresh_from_db()
    assert task.desired_state == "running" and task.dispatched_at is None


@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("command", ["resume", "cancel"])
def test_control_during_dispatch_is_not_acknowledged_as_older_work(command):
    grant, task = passengers()

    class TemporalClient:
        async def start_workflow(self, *args, **kwargs):
            await sync_to_async(lifecycle.control)(grant.project, task.pk, command)

    asyncio.run(dispatch(TemporalClient()))
    task.refresh_from_db()
    assert task.dispatched_at is None


@pytest.mark.django_db(transaction=True)
def test_progress_during_dispatch_is_acknowledged_without_restarting_a_blocked_task():
    _, task = passengers()

    class TemporalClient:
        async def start_workflow(self, *args, **kwargs):
            current = await sync_to_async(lifecycle.get)(task.pk)
            current.state = "blocked"
            await sync_to_async(current.save)(update_fields=["state", "updated_at"])

    asyncio.run(dispatch(TemporalClient()))
    task.refresh_from_db()
    assert task.dispatched_at is not None
    assert not WorkshopTask.objects.filter(pk=task.pk, dispatched_at=None).exists()


@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("state", ["completed", "cancelled", "blocked", "paused"])
def test_dispatch_recovers_a_settled_task_with_an_unsettled_provider(
    local_sandbox, fake_llm, state
):
    _, task = passengers()
    workspace = sandbox.attach(task)
    task.refresh_from_db()
    task.state = state
    task.desired_state = "paused" if state in {"blocked", "paused"} else "cancelled"
    task.dispatched_at = timezone.now() - timedelta(minutes=6)
    task.save(update_fields=["state", "desired_state", "dispatched_at"])
    calls = []

    class TemporalClient:
        async def start_workflow(self, workflow, identifier, **kwargs):
            calls.append(identifier)
            await sync_to_async(agent.run)(identifier, None)

    asyncio.run(dispatch(TemporalClient()))
    task.refresh_from_db()
    assert calls == [str(task.pk)]
    assert task.state == state
    assert task.workspace["stopped_at"] and workspace.poll() is not None
    asyncio.run(dispatch(TemporalClient()))
    assert calls == [str(task.pk)]
    assert not fake_llm.requests