mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 11:08:37 +00:00
Running `pytest --unit` with these changes goes from 3 minutes 44 seconds to just **30 seconds**.
### How does it work
#### Virtual time
Takes advantage of the fact that many of the tests rely on `asyncio.sleep()` to synchronize events in the loop. It unties it from the real time so that `await asyncio.sleep(60)` returns instantly with `loop.time()` reporting 60 seconds passed. `time.time()` is then patched to report loop time. This brings down `test_agent_session.py` test time form 90 seconds to just 1 second without any modifications to the test itself.
- To disable globally `--real-time` option can be used.
- To enable/disable per-module or per-test `pytest.mark.virtual_time`/`.real_time` can be used.
#### Concurrent tests
Tests with real I/O are groupped by their module and executed in a shared event loop. This shrinks wall time of the whole module to wall time of the slowest test + raw compute. `contextvars` are used to preserve input capture and track leaked tasks.
- To disable concurrent execution, `--no-concurrent` option can be used.
- To enable/disable per-module or per-test, `pytest.mark.no_concurrent`/`.no_concurrent` can be used.
### Changes
- Add `pytest-asyncio-concurrent` — gives the speedup for I/O bound tests
- Add `tests/concurrent.py` that extends on `pytest-asyncio-concurrent` and adds crucial features:
- Captures stdout/stderr and reports on failure (same as `pytest`)
- Allows leaked tasks detection in concurrent mode (so that `fail_on_leaked_tasks` continues to work)
- adds `--concurrent`/`--no-concurrent` options
- Adds live progress
- Add `tests/virtual_time.py` that provides instant and deterministic `asyncio` clock for time-bound execution
#### Changes to the tests sources
- https://github.com/livekit/agents/pull/5980/commits/04fe6cbb55c32d1058a01a4c0ddda790b5834770: Add `concurrent`/`virtual_time` markers to tests modules
- https://github.com/livekit/agents/pull/5980/changes/a8f5be0be8b76efefaa55743d8ad0a5d77b15b1b: Tighten timings in `test_audio_decoder.py`, `test_ipc.pt` and `test_room.py`
- https://github.com/livekit/agents/pull/5980/changes/396bce8cbf4618a292ab28a257ea13f58bd3c5a6: Make `test_async_channel` and `test_proc_pool_launch_job_raises_when_all_spawns_fail` in `test_ipc.py` safe to run concurrently
129 lines
4.2 KiB
Python
129 lines
4.2 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
|
|
import pytest
|
|
|
|
from livekit.agents import Agent, AgentSession, AgentTask, RunContext, function_tool
|
|
from livekit.agents.llm import FunctionToolCall
|
|
|
|
from .fake_llm import FakeLLM, FakeLLMResponse
|
|
|
|
pytestmark = [pytest.mark.unit, pytest.mark.virtual_time, pytest.mark.no_concurrent]
|
|
|
|
|
|
class InnerTask(AgentTask):
|
|
"""A task that needs a second user turn to complete (user must trigger 'finish')."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__(instructions="inner task")
|
|
|
|
async def on_enter(self) -> None:
|
|
self.session.generate_reply(instructions="inner_greeting")
|
|
|
|
@function_tool
|
|
async def finish(self, ctx: RunContext) -> str:
|
|
"""Called to complete the inner task."""
|
|
self.complete(None)
|
|
return "done"
|
|
|
|
|
|
class OuterTask(AgentTask):
|
|
"""A task whose on_enter triggers a tool call that awaits InnerTask."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__(instructions="outer task")
|
|
|
|
async def on_enter(self) -> None:
|
|
await self.session.generate_reply(instructions="outer_greeting")
|
|
|
|
@function_tool
|
|
async def start_inner(self, ctx: RunContext) -> str:
|
|
"""Transitions into InnerTask."""
|
|
await InnerTask()
|
|
self.complete(None)
|
|
return "inner completed"
|
|
|
|
|
|
class RootAgent(Agent):
|
|
def __init__(self) -> None:
|
|
super().__init__(instructions="root agent")
|
|
|
|
@function_tool
|
|
async def start_outer(self, ctx: RunContext) -> str:
|
|
"""Transitions into OuterTask."""
|
|
await OuterTask()
|
|
return "outer completed"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_nested_agent_task_no_deadlock():
|
|
"""session.run() must return when an AgentTask hands off to a nested task
|
|
that collects additional user input before completing."""
|
|
llm = _build_fake_llm()
|
|
async with AgentSession(llm=llm) as sess:
|
|
await sess.start(RootAgent())
|
|
|
|
# This must not deadlock — it should return once the on_enter chain
|
|
# has started, even though InnerTask is still waiting for user input.
|
|
first_result = await asyncio.wait_for(sess.run(user_input="go"), timeout=5.0)
|
|
assert first_result is not None
|
|
|
|
# Now complete InnerTask by triggering the finish tool
|
|
second_result = await asyncio.wait_for(sess.run(user_input="done"), timeout=5.0)
|
|
assert second_result is not None
|
|
|
|
|
|
def _build_fake_llm() -> FakeLLM:
|
|
return FakeLLM(
|
|
fake_responses=[
|
|
# user says "go" -> LLM calls start_outer
|
|
FakeLLMResponse(
|
|
input="go",
|
|
content="",
|
|
ttft=0,
|
|
duration=0,
|
|
tool_calls=[FunctionToolCall(name="start_outer", arguments="{}", call_id="call_1")],
|
|
),
|
|
# OuterTask on_enter generate_reply(instructions="outer_greeting")
|
|
# -> LLM calls start_inner
|
|
FakeLLMResponse(
|
|
input="outer_greeting",
|
|
content="",
|
|
ttft=0,
|
|
duration=0,
|
|
tool_calls=[FunctionToolCall(name="start_inner", arguments="{}", call_id="call_2")],
|
|
),
|
|
# InnerTask on_enter generate_reply(instructions="inner_greeting")
|
|
# -> LLM just says hello (no tool call yet — needs user input to finish)
|
|
FakeLLMResponse(
|
|
input="inner_greeting",
|
|
content="hello from inner",
|
|
ttft=0,
|
|
duration=0,
|
|
),
|
|
# user says "done" -> LLM calls finish
|
|
FakeLLMResponse(
|
|
input="done",
|
|
content="",
|
|
ttft=0,
|
|
duration=0,
|
|
tool_calls=[FunctionToolCall(name="finish", arguments="{}", call_id="call_3")],
|
|
),
|
|
# after finish tool output, LLM responds to start_inner tool output
|
|
FakeLLMResponse(
|
|
input="inner completed",
|
|
content="",
|
|
ttft=0,
|
|
duration=0,
|
|
),
|
|
# after start_outer tool output, LLM responds
|
|
FakeLLMResponse(
|
|
input="outer completed",
|
|
content="all done",
|
|
ttft=0,
|
|
duration=0,
|
|
),
|
|
]
|
|
)
|