The platform for continuously improving AI agents.
import asyncio
import uuid
import pytest
from temporalio import activity
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from workflows.research import TASK_QUEUE, ResearchAgentWorkflow
pytestmark = pytest.mark.covers("state-machines")
WAIT = {"state": "wait", "seconds": 600}
END = {"state": "end"}
def drive(bursts, *, wake=None):
"""Run the workflow on Temporal's time-skipping server against scripted bursts.
``wake`` signals the workflow: "during" from inside the first burst, "after" once that
burst has returned. Returns the result, the virtual start time of each burst and the
errors passed to the fence.
"""
started, fenced = [], []
async def scenario():
async with await WorkflowEnvironment.start_time_skipping() as env:
identifier = f"research-agent:{uuid.uuid4()}"
first = asyncio.Event()
@activity.defn(name="research_advance")
async def advance(agent: str) -> dict:
started.append(await env.get_current_time())
burst = bursts[min(len(started), len(bursts)) - 1]
if len(started) == 1:
if wake == "during":
await env.client.get_workflow_handle(identifier).signal("wake")
first.set()
if isinstance(burst, Exception):
raise burst
return burst
@activity.defn(name="research_fence")
async def fence(agent: str, error: str, epoch: int | None) -> dict:
fenced.append(error)
return END
async with Worker(
env.client,
task_queue=TASK_QUEUE,
workflows=[ResearchAgentWorkflow],
activities=[advance, fence],
):
handle = await env.client.start_workflow(
ResearchAgentWorkflow.run, "agent", id=identifier, task_queue=TASK_QUEUE
)
if wake == "after":
await first.wait()
await handle.signal(ResearchAgentWorkflow.wake)
return await handle.result()
return asyncio.run(scenario()), started, fenced
def test_a_waiting_agent_resumes_when_its_timer_expires():
result, started, _ = drive([WAIT, END])
assert result == END
assert (started[1] - started[0]).total_seconds() >= 600
@pytest.mark.parametrize("wake", ["during", "after"])
def test_a_wake_resumes_the_agent_without_waiting_out_its_timer(wake):
result, started, _ = drive([WAIT, END], wake=wake)
assert result == END
assert (started[1] - started[0]).total_seconds() < 600
@pytest.mark.covers("recovery")
def test_a_burst_that_keeps_failing_is_fenced_instead_of_retried_forever():
result, started, fenced = drive([RuntimeError("provider client crashed")])
assert result == END
assert len(started) == 4
assert fenced == ["RuntimeError"]