test_benchmark_runner.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. import asyncio
  2. from collections.abc import AsyncIterator
  3. from typing import Any
  4. import pytest
  5. from pydantic import ValidationError
  6. from agent_lab.application import benchmark
  7. from agent_lab.application.contracts import AgentParams
  8. from agent_lab.application.events import ResultPolicy
  9. from agent_lab.application.tools import ToolDefinition, ToolRegistry
  10. from agent_lab.domain.events import ToolCallEvent
  11. from agent_lab.domain.messages import ChatMessage, StreamItem
  12. from agent_lab.domain.messages import TokenUsage
  13. from agent_lab.infrastructure.sqlite_store import SQLiteSessionStore
  14. class ManualClock:
  15. def __init__(self) -> None:
  16. self.now = 0.0
  17. def __call__(self) -> float:
  18. return self.now
  19. class ScriptedTimingClient:
  20. def __init__(self, clock: ManualClock, *, fail: bool = False) -> None:
  21. self.clock = clock
  22. self.fail = fail
  23. self.closed = False
  24. async def stream_chat(
  25. self,
  26. messages: list[ChatMessage],
  27. tools: list[dict[str, Any]],
  28. params: AgentParams,
  29. tool_choice: dict[str, Any] | None = None,
  30. ) -> AsyncIterator[StreamItem]:
  31. del messages, tools, params, tool_choice
  32. self.clock.now = 0.011
  33. yield StreamItem.raw_response_chunk({"provider": "first"})
  34. if self.fail:
  35. self.clock.now = 0.023
  36. raise RuntimeError("stream failed")
  37. self.clock.now = 0.037
  38. yield StreamItem.message_delta("visible")
  39. self.clock.now = 0.041
  40. yield StreamItem.usage_item(TokenUsage(total_tokens=3))
  41. self.clock.now = 0.059
  42. yield StreamItem.usage_item(TokenUsage(total_tokens=5))
  43. self.clock.now = 0.071
  44. async def aclose(self) -> None:
  45. self.closed = True
  46. class WhitespaceTimingClient:
  47. def __init__(self, clock: ManualClock) -> None:
  48. self.clock = clock
  49. async def stream_chat(
  50. self,
  51. messages: list[ChatMessage],
  52. tools: list[dict[str, Any]],
  53. params: AgentParams,
  54. tool_choice: dict[str, Any] | None = None,
  55. ) -> AsyncIterator[StreamItem]:
  56. del messages, tools, params, tool_choice
  57. self.clock.now = 0.011
  58. yield StreamItem.raw_response_chunk({"provider": "first"})
  59. self.clock.now = 0.019
  60. yield StreamItem.message_delta("")
  61. self.clock.now = 0.023
  62. yield StreamItem.message_delta(" \n")
  63. self.clock.now = 0.037
  64. yield StreamItem.message_delta("visible")
  65. self.clock.now = 0.050
  66. yield StreamItem.usage_item(TokenUsage(total_tokens=5))
  67. async def aclose(self) -> None:
  68. return None
  69. class FallbackBenchmarkClient:
  70. def __init__(self) -> None:
  71. self.calls = 0
  72. self.closed = False
  73. async def stream_chat(
  74. self,
  75. messages: list[ChatMessage],
  76. tools: list[dict[str, Any]],
  77. params: AgentParams,
  78. tool_choice: dict[str, Any] | None = None,
  79. ) -> AsyncIterator[StreamItem]:
  80. del messages, tools, params
  81. self.calls += 1
  82. if self.calls == 1:
  83. assert tool_choice is None
  84. yield StreamItem.raw_response_chunk({"chat": 1})
  85. yield StreamItem.message_delta("I will set the volume to 30.")
  86. yield StreamItem.text_event(
  87. ToolCallEvent(
  88. id="volume-1",
  89. name="device.volume.adjust",
  90. arguments={"mode": "absolute"},
  91. raw_arguments='{"mode":"absolute"}',
  92. )
  93. )
  94. yield StreamItem.usage_item(TokenUsage(total_tokens=5))
  95. return
  96. if self.calls == 2:
  97. assert tool_choice is not None
  98. yield StreamItem.raw_response_chunk({"fallback": 1})
  99. yield StreamItem.provider_tool_call(
  100. ToolCallEvent(
  101. id="fallback-volume",
  102. name="device.volume.adjust",
  103. arguments={"mode": "absolute", "value": 30},
  104. raw_arguments='{"mode":"absolute","value":30}',
  105. )
  106. )
  107. yield StreamItem.usage_item(TokenUsage(total_tokens=7))
  108. return
  109. raise RuntimeError("unexpected fallback client call")
  110. async def aclose(self) -> None:
  111. self.closed = True
  112. class RecordingSQLiteSessionStore(SQLiteSessionStore):
  113. instances: list["RecordingSQLiteSessionStore"] = []
  114. def __init__(self, database_path: str) -> None:
  115. super().__init__(database_path)
  116. self.instances.append(self)
  117. class BlockingTimingClient:
  118. def __init__(self, clock: ManualClock) -> None:
  119. self.clock = clock
  120. self.blocked = asyncio.Event()
  121. self.closed = False
  122. async def stream_chat(
  123. self,
  124. messages: list[ChatMessage],
  125. tools: list[dict[str, Any]],
  126. params: AgentParams,
  127. tool_choice: dict[str, Any] | None = None,
  128. ) -> AsyncIterator[StreamItem]:
  129. del messages, tools, params, tool_choice
  130. self.clock.now = 0.010
  131. yield StreamItem.raw_response_chunk({"first": True})
  132. self.blocked.set()
  133. await asyncio.Event().wait()
  134. async def aclose(self) -> None:
  135. self.closed = True
  136. class NoAnswerClient:
  137. def __init__(self) -> None:
  138. self.closed = False
  139. async def stream_chat(
  140. self,
  141. messages: list[ChatMessage],
  142. tools: list[dict[str, Any]],
  143. params: AgentParams,
  144. tool_choice: dict[str, Any] | None = None,
  145. ) -> AsyncIterator[StreamItem]:
  146. del messages, tools, params, tool_choice
  147. yield StreamItem.raw_response_chunk({"no_answer": True})
  148. yield StreamItem.usage_item(TokenUsage(total_tokens=1))
  149. async def aclose(self) -> None:
  150. self.closed = True
  151. class ConcurrentTimingClient:
  152. def __init__(self) -> None:
  153. self.calls = 0
  154. self.first_started = asyncio.Event()
  155. self.release_first = asyncio.Event()
  156. async def stream_chat(
  157. self,
  158. messages: list[ChatMessage],
  159. tools: list[dict[str, Any]],
  160. params: AgentParams,
  161. tool_choice: dict[str, Any] | None = None,
  162. ) -> AsyncIterator[StreamItem]:
  163. del messages, tools, params, tool_choice
  164. self.calls += 1
  165. call_number = self.calls
  166. yield StreamItem.raw_response_chunk({"call": call_number})
  167. if call_number == 1:
  168. self.first_started.set()
  169. await self.release_first.wait()
  170. yield StreamItem.usage_item(TokenUsage(total_tokens=call_number))
  171. async def aclose(self) -> None:
  172. return None
  173. def test_benchmark_result_models_are_strict_and_allow_nullable_metrics():
  174. timing_type = getattr(benchmark, "BenchmarkModelCallTiming")
  175. result_type = getattr(benchmark, "BenchmarkRunResult")
  176. timing = timing_type(
  177. call_index=1,
  178. call_kind="chat_completion",
  179. first_item_kind="raw_chunk",
  180. provider_ttft_ms=11,
  181. visible_ttft_ms=37,
  182. elapsed_ms=59,
  183. usage=TokenUsage(
  184. prompt_tokens=2,
  185. completion_tokens=3,
  186. total_tokens=5,
  187. cached_tokens=1,
  188. ),
  189. )
  190. result = result_type(
  191. case_id=benchmark.BenchmarkCaseId.ORDINARY_CHAT,
  192. mode=benchmark.BenchmarkMode.DUAL_AGENT,
  193. iteration=1,
  194. status="failed",
  195. initial_provider_ttft_ms=None,
  196. visible_ttft_ms=None,
  197. turn_wall_time_ms=None,
  198. prompt_tokens=None,
  199. completion_tokens=None,
  200. total_tokens=None,
  201. cached_tokens=None,
  202. model_call_count=None,
  203. fallback_count=None,
  204. tool_count=None,
  205. event_names=[],
  206. event_sources=[],
  207. tool_statuses=[],
  208. tool_latencies_ms=[],
  209. semantic_failures=["missing visible answer"],
  210. error=None,
  211. model_calls=[timing],
  212. )
  213. assert result.model_calls == [timing]
  214. assert result.initial_provider_ttft_ms is None
  215. with pytest.raises(ValidationError):
  216. timing_type(
  217. call_index="1",
  218. call_kind="chat_completion",
  219. first_item_kind=None,
  220. provider_ttft_ms=None,
  221. visible_ttft_ms=None,
  222. elapsed_ms=None,
  223. usage=None,
  224. )
  225. with pytest.raises(ValidationError):
  226. result_type.model_validate(result.model_dump() | {"unexpected": True})
  227. @pytest.mark.asyncio
  228. async def test_timing_client_keeps_provider_visible_and_elapsed_timings_separate():
  229. clock = ManualClock()
  230. inner = ScriptedTimingClient(clock)
  231. client = benchmark.TimingChatClient(inner, clock=clock)
  232. items = [
  233. item
  234. async for item in client.stream_chat(
  235. messages=[],
  236. tools=[],
  237. params=AgentParams(model="benchmark-model"),
  238. )
  239. ]
  240. assert [item.kind for item in items] == [
  241. "raw_chunk",
  242. "message_delta",
  243. "usage",
  244. "usage",
  245. ]
  246. assert client.timings == [
  247. benchmark.BenchmarkModelCallTiming(
  248. call_index=1,
  249. call_kind="chat_completion",
  250. first_item_kind="raw_chunk",
  251. provider_ttft_ms=11,
  252. visible_ttft_ms=37,
  253. elapsed_ms=71,
  254. usage=TokenUsage(total_tokens=5),
  255. )
  256. ]
  257. @pytest.mark.asyncio
  258. async def test_timing_client_ignores_blank_deltas_for_visible_ttft():
  259. clock = ManualClock()
  260. client = benchmark.TimingChatClient(
  261. WhitespaceTimingClient(clock),
  262. clock=clock,
  263. )
  264. async for _ in client.stream_chat(
  265. messages=[],
  266. tools=[],
  267. params=AgentParams(model="benchmark-model"),
  268. ):
  269. pass
  270. assert client.timings[0].provider_ttft_ms == 11
  271. assert client.timings[0].visible_ttft_ms == 37
  272. @pytest.mark.asyncio
  273. async def test_benchmark_output_queue_ignores_blank_deltas_for_visible_ttft():
  274. clock = ManualClock()
  275. queue = benchmark._BenchmarkOutputQueue(clock)
  276. clock.now = 0.019
  277. await queue.put({"type": "message_delta", "content": ""})
  278. clock.now = 0.023
  279. await queue.put({"type": "message_delta", "content": " \n\t "})
  280. assert queue.first_message_delta_at is None
  281. clock.now = 0.037
  282. await queue.put({"type": "message_delta", "content": "visible"})
  283. assert queue.first_message_delta_at == 0.037
  284. @pytest.mark.asyncio
  285. async def test_timing_client_records_failed_fallback_and_closes_inner_client():
  286. clock = ManualClock()
  287. inner = ScriptedTimingClient(clock, fail=True)
  288. client = benchmark.TimingChatClient(inner, clock=clock)
  289. with pytest.raises(RuntimeError, match="stream failed"):
  290. async for _ in client.stream_chat(
  291. messages=[],
  292. tools=[{"type": "function", "function": {"name": "mock"}}],
  293. params=AgentParams(model="benchmark-model"),
  294. tool_choice={"type": "function", "function": {"name": "mock"}},
  295. ):
  296. pass
  297. await client.aclose()
  298. assert inner.closed is True
  299. assert client.timings == [
  300. benchmark.BenchmarkModelCallTiming(
  301. call_index=1,
  302. call_kind="argument_fallback",
  303. first_item_kind="raw_chunk",
  304. provider_ttft_ms=11,
  305. visible_ttft_ms=None,
  306. elapsed_ms=23,
  307. usage=None,
  308. )
  309. ]
  310. @pytest.mark.asyncio
  311. async def test_timing_client_finishes_timing_when_stream_is_cancelled():
  312. clock = ManualClock()
  313. inner = BlockingTimingClient(clock)
  314. client = benchmark.TimingChatClient(inner, clock=clock)
  315. async def consume() -> None:
  316. async for _ in client.stream_chat(
  317. messages=[],
  318. tools=[],
  319. params=AgentParams(model="benchmark-model"),
  320. ):
  321. pass
  322. task = asyncio.create_task(consume())
  323. await inner.blocked.wait()
  324. clock.now = 0.025
  325. task.cancel()
  326. await asyncio.gather(task, return_exceptions=True)
  327. await client.aclose()
  328. assert client.timings[0].first_item_kind == "raw_chunk"
  329. assert client.timings[0].provider_ttft_ms == 10
  330. assert client.timings[0].visible_ttft_ms is None
  331. assert client.timings[0].elapsed_ms == 25
  332. assert inner.closed is True
  333. @pytest.mark.asyncio
  334. async def test_timing_client_indexes_concurrent_calls_by_start_order():
  335. inner = ConcurrentTimingClient()
  336. client = benchmark.TimingChatClient(inner)
  337. async def collect() -> None:
  338. async for _ in client.stream_chat(
  339. messages=[],
  340. tools=[],
  341. params=AgentParams(model="benchmark-model"),
  342. ):
  343. pass
  344. first = asyncio.create_task(collect())
  345. await inner.first_started.wait()
  346. await collect()
  347. inner.release_first.set()
  348. await first
  349. assert [timing.call_index for timing in client.timings] == [1, 2]
  350. assert [timing.usage.total_tokens for timing in client.timings] == [1, 2]
  351. @pytest.mark.asyncio
  352. @pytest.mark.parametrize("mode", benchmark.BENCHMARK_MODES)
  353. @pytest.mark.parametrize("case_id", benchmark.BENCHMARK_CASE_IDS)
  354. async def test_mock_benchmark_client_emits_raw_semantics_and_fixed_usage(
  355. case_id: benchmark.BenchmarkCaseId,
  356. mode: benchmark.BenchmarkMode,
  357. ):
  358. case = benchmark.BENCHMARK_CASE_CATALOG[case_id]
  359. client = benchmark.MockBenchmarkChatClient(case, mode)
  360. expected_rounds = benchmark.build_mock_rounds(case, mode)
  361. emitted_rounds = []
  362. for _ in expected_rounds:
  363. emitted_rounds.append(
  364. [
  365. item
  366. async for item in client.stream_chat(
  367. messages=[],
  368. tools=[],
  369. params=AgentParams(model="benchmark-model"),
  370. )
  371. ]
  372. )
  373. await client.aclose()
  374. assert [items[0].kind for items in emitted_rounds] == [
  375. "raw_chunk"
  376. ] * len(expected_rounds)
  377. assert [items[1:-1] for items in emitted_rounds] == expected_rounds
  378. assert [items[-1].usage for items in emitted_rounds] == [
  379. TokenUsage(
  380. prompt_tokens=10,
  381. completion_tokens=5,
  382. total_tokens=15,
  383. cached_tokens=2,
  384. )
  385. ] * len(expected_rounds)
  386. with pytest.raises(RuntimeError, match=f"mock benchmark stream exhausted: {case_id}"):
  387. async for _ in client.stream_chat(
  388. messages=[],
  389. tools=[],
  390. params=AgentParams(model="benchmark-model"),
  391. ):
  392. pass
  393. @pytest.mark.asyncio
  394. async def test_mock_runner_is_ordered_ignores_factory_and_reports_event_ledgers():
  395. config = benchmark.BenchmarkConfig(
  396. schema_version=1,
  397. base_url="https://provider.example/v1",
  398. model="benchmark-model",
  399. runs_per_case=2,
  400. cases=[
  401. benchmark.BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS,
  402. benchmark.BenchmarkCaseId.ORDINARY_CHAT,
  403. ],
  404. modes=[
  405. benchmark.BenchmarkMode.CHAT_AGENT_TOOLS,
  406. benchmark.BenchmarkMode.DUAL_AGENT,
  407. ],
  408. )
  409. factory_calls = 0
  410. def forbidden_factory(config: benchmark.BenchmarkConfig, api_key: str):
  411. del config, api_key
  412. nonlocal factory_calls
  413. factory_calls += 1
  414. raise AssertionError("mock mode must not call client_factory")
  415. results = await benchmark.BenchmarkRunner(
  416. config,
  417. api_key=None,
  418. mock=True,
  419. client_factory=forbidden_factory,
  420. ).run()
  421. assert factory_calls == 0
  422. assert [(item.case_id, item.mode, item.iteration) for item in results] == [
  423. (case_id, mode, iteration)
  424. for case_id in config.cases
  425. for mode in config.modes
  426. for iteration in range(1, 3)
  427. ]
  428. assert {item.status for item in results} == {"passed"}
  429. search_results = [
  430. item
  431. for item in results
  432. if item.case_id is benchmark.BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS
  433. ]
  434. assert {item.model_call_count for item in search_results} == {2}
  435. assert {item.fallback_count for item in search_results} == {0}
  436. assert {item.tool_count for item in search_results} == {1}
  437. assert {tuple(item.event_names) for item in search_results} == {
  438. ("knowledge.web.search",)
  439. }
  440. assert {tuple(item.tool_statuses) for item in search_results} == {("success",)}
  441. assert {
  442. tuple(item.event_sources) for item in search_results
  443. } == {("provider_resolved",), ("text_event",)}
  444. assert all(len(item.tool_latencies_ms) == 1 for item in search_results)
  445. assert all(
  446. latency is not None and latency >= 0
  447. for item in search_results
  448. for latency in item.tool_latencies_ms
  449. )
  450. ordinary_results = [
  451. item
  452. for item in results
  453. if item.case_id is benchmark.BenchmarkCaseId.ORDINARY_CHAT
  454. ]
  455. assert all(item.event_names == [] for item in ordinary_results)
  456. assert all(item.tool_count == 0 for item in ordinary_results)
  457. @pytest.mark.asyncio
  458. async def test_mock_runner_passes_all_catalog_cases_in_both_modes():
  459. config = benchmark.BenchmarkConfig(
  460. schema_version=1,
  461. base_url="https://provider.example/v1",
  462. model="benchmark-model",
  463. )
  464. results = await benchmark.BenchmarkRunner(config, api_key=None, mock=True).run()
  465. assert len(results) == 12
  466. assert all(result.status == "passed" for result in results)
  467. assert all(result.semantic_failures == [] for result in results)
  468. @pytest.mark.asyncio
  469. async def test_runner_uses_a_fresh_in_memory_store_and_unique_session_per_run(monkeypatch):
  470. RecordingSQLiteSessionStore.instances = []
  471. monkeypatch.setattr(benchmark, "SQLiteSessionStore", RecordingSQLiteSessionStore)
  472. config = benchmark.BenchmarkConfig(
  473. schema_version=1,
  474. base_url="https://provider.example/v1",
  475. model="benchmark-model",
  476. runs_per_case=2,
  477. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  478. modes=[benchmark.BenchmarkMode.DUAL_AGENT],
  479. )
  480. results = await benchmark.BenchmarkRunner(config, api_key=None, mock=True).run()
  481. assert len(results) == 2
  482. assert len(RecordingSQLiteSessionStore.instances) == 2
  483. sessions = [store.list_sessions() for store in RecordingSQLiteSessionStore.instances]
  484. assert all(store.database_path == ":memory:" for store in RecordingSQLiteSessionStore.instances)
  485. assert [len(records) for records in sessions] == [1, 1]
  486. assert len({records[0]["id"] for records in sessions}) == 2
  487. @pytest.mark.asyncio
  488. async def test_runner_keeps_provider_visible_and_turn_wall_time_distinct():
  489. clock = ManualClock()
  490. client = ScriptedTimingClient(clock)
  491. config = benchmark.BenchmarkConfig(
  492. schema_version=1,
  493. base_url="https://provider.example/v1",
  494. model="benchmark-model",
  495. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  496. modes=[benchmark.BenchmarkMode.DUAL_AGENT],
  497. )
  498. result = (
  499. await benchmark.BenchmarkRunner(
  500. config,
  501. api_key="test-key",
  502. client_factory=lambda config, api_key: client,
  503. clock=clock,
  504. ).run()
  505. )[0]
  506. assert result.status == "passed"
  507. assert result.initial_provider_ttft_ms == 11
  508. assert result.visible_ttft_ms == 37
  509. assert result.turn_wall_time_ms == 71
  510. assert result.model_calls[0].elapsed_ms == 71
  511. assert client.closed is True
  512. @pytest.mark.asyncio
  513. async def test_runner_continues_after_one_factory_failure():
  514. config = benchmark.BenchmarkConfig(
  515. schema_version=1,
  516. base_url="https://provider.example/v1",
  517. model="benchmark-model",
  518. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  519. modes=[
  520. benchmark.BenchmarkMode.DUAL_AGENT,
  521. benchmark.BenchmarkMode.CHAT_AGENT_TOOLS,
  522. ],
  523. )
  524. clients: list[ScriptedTimingClient] = []
  525. calls = 0
  526. def factory(config: benchmark.BenchmarkConfig, api_key: str):
  527. del config, api_key
  528. nonlocal calls
  529. calls += 1
  530. if calls == 1:
  531. raise RuntimeError("first factory failed")
  532. clock = ManualClock()
  533. client = ScriptedTimingClient(clock)
  534. clients.append(client)
  535. return client
  536. results = await benchmark.BenchmarkRunner(
  537. config,
  538. api_key="test-key",
  539. client_factory=factory,
  540. ).run()
  541. assert [result.status for result in results] == ["failed", "passed"]
  542. assert results[0].error == "first factory failed"
  543. assert results[1].error is None
  544. assert clients[0].closed is True
  545. @pytest.mark.asyncio
  546. async def test_runner_marks_semantic_mismatch_failed_and_continues():
  547. config = benchmark.BenchmarkConfig(
  548. schema_version=1,
  549. base_url="https://provider.example/v1",
  550. model="benchmark-model",
  551. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  552. modes=[
  553. benchmark.BenchmarkMode.DUAL_AGENT,
  554. benchmark.BenchmarkMode.CHAT_AGENT_TOOLS,
  555. ],
  556. )
  557. failed_client = NoAnswerClient()
  558. calls = 0
  559. def factory(config: benchmark.BenchmarkConfig, api_key: str):
  560. del config, api_key
  561. nonlocal calls
  562. calls += 1
  563. if calls == 1:
  564. return failed_client
  565. return benchmark.MockBenchmarkChatClient(
  566. benchmark.BENCHMARK_CASE_CATALOG[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  567. benchmark.BenchmarkMode.CHAT_AGENT_TOOLS,
  568. )
  569. results = await benchmark.BenchmarkRunner(
  570. config,
  571. api_key="test-key",
  572. client_factory=factory,
  573. ).run()
  574. assert [result.status for result in results] == ["failed", "passed"]
  575. assert results[0].error is None
  576. assert results[0].semantic_failures == ["answer_count expected 1, got 0"]
  577. assert failed_client.closed is True
  578. @pytest.mark.asyncio
  579. async def test_runner_reports_argument_fallback_model_and_tool_ledgers(monkeypatch):
  580. client = FallbackBenchmarkClient()
  581. registry = ToolRegistry(
  582. [
  583. ToolDefinition(
  584. name="device.volume.adjust",
  585. description="Force fallback for benchmark ledger coverage.",
  586. parameters={
  587. "type": "object",
  588. "properties": {
  589. "mode": {"type": "string"},
  590. "value": {"type": "integer"},
  591. },
  592. "required": ["mode", "value"],
  593. },
  594. handler=lambda event: {
  595. "tool": event.name,
  596. "status": "payload-status-is-not-kernel-status",
  597. },
  598. argument_resolver=lambda event, context: {},
  599. result_policy=ResultPolicy.SILENT_SUCCESS,
  600. )
  601. ]
  602. )
  603. monkeypatch.setattr(benchmark, "build_default_tool_registry", lambda: registry)
  604. config = benchmark.BenchmarkConfig(
  605. schema_version=1,
  606. base_url="https://provider.example/v1",
  607. model="benchmark-model",
  608. cases=[benchmark.BenchmarkCaseId.DEVICE_VOLUME_SILENT],
  609. modes=[benchmark.BenchmarkMode.DUAL_AGENT],
  610. )
  611. result = (
  612. await benchmark.BenchmarkRunner(
  613. config,
  614. api_key="test-key",
  615. client_factory=lambda config, api_key: client,
  616. ).run()
  617. )[0]
  618. assert result.status == "failed"
  619. assert result.model_call_count == 1
  620. assert result.fallback_count == 1
  621. assert result.tool_count == 1
  622. assert result.total_tokens == 12
  623. assert [timing.call_kind for timing in result.model_calls] == [
  624. "chat_completion",
  625. "argument_fallback",
  626. ]
  627. assert result.event_names == ["device.volume.adjust"]
  628. assert result.event_sources == ["text_event"]
  629. assert result.tool_statuses == ["success"]
  630. assert result.semantic_failures == [
  631. "fallback_count expected 0, ledger got 1",
  632. "fallback_count expected 0, timing got 1",
  633. ]
  634. assert client.calls == 2
  635. assert client.closed is True
  636. def test_live_runner_requires_an_api_key():
  637. config = benchmark.BenchmarkConfig(
  638. schema_version=1,
  639. base_url="https://provider.example/v1",
  640. model="benchmark-model",
  641. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  642. modes=[benchmark.BenchmarkMode.DUAL_AGENT],
  643. )
  644. with pytest.raises(ValueError, match="api_key"):
  645. benchmark.BenchmarkRunner(config, api_key=None)
  646. def test_visible_answer_order_ignores_empty_deltas_before_a_tool_result():
  647. answers, first_answer_index, first_tool_index = (
  648. benchmark.BenchmarkRunner._visible_answers(
  649. [
  650. {"type": "message_delta", "content": " "},
  651. {"type": "tool_result", "message": {}},
  652. {"type": "message_delta", "content": "late answer"},
  653. ]
  654. )
  655. )
  656. assert answers == ["late answer"]
  657. assert first_answer_index == 2
  658. assert first_tool_index == 1
  659. def _semantic_failures_for_counts(
  660. *,
  661. ledger_model_count: int,
  662. timing_model_count: int,
  663. ledger_fallback_count: int = 0,
  664. timing_fallback_count: int = 0,
  665. ) -> list[str]:
  666. config = benchmark.BenchmarkConfig(
  667. schema_version=1,
  668. base_url="https://provider.example/v1",
  669. model="benchmark-model",
  670. cases=[benchmark.BenchmarkCaseId.ORDINARY_CHAT],
  671. modes=[benchmark.BenchmarkMode.DUAL_AGENT],
  672. )
  673. runner = benchmark.BenchmarkRunner(config, api_key=None, mock=True)
  674. timings = [
  675. benchmark.BenchmarkModelCallTiming(
  676. call_index=index,
  677. call_kind=call_kind,
  678. first_item_kind="raw_chunk",
  679. provider_ttft_ms=0,
  680. visible_ttft_ms=0 if call_kind == "chat_completion" else None,
  681. elapsed_ms=0,
  682. usage=TokenUsage(),
  683. )
  684. for index, call_kind in enumerate(
  685. ["chat_completion"] * timing_model_count
  686. + ["argument_fallback"] * timing_fallback_count,
  687. start=1,
  688. )
  689. ]
  690. return runner._semantic_failures(
  691. case=benchmark.BENCHMARK_CASE_CATALOG[
  692. benchmark.BenchmarkCaseId.ORDINARY_CHAT
  693. ],
  694. mode=benchmark.BenchmarkMode.DUAL_AGENT,
  695. outputs=[{"type": "message_delta", "content": "Ordinary answer."}],
  696. audits=[],
  697. event_names=[],
  698. event_sources=[],
  699. tool_statuses=[],
  700. model_call_count=ledger_model_count,
  701. fallback_count=ledger_fallback_count,
  702. tool_count=0,
  703. timings=timings,
  704. check_mock_text=True,
  705. )
  706. @pytest.mark.parametrize("actual_count", [0, 2])
  707. def test_semantics_reject_missing_or_extra_model_calls_even_when_ledgers_agree(
  708. actual_count: int,
  709. ):
  710. failures = _semantic_failures_for_counts(
  711. ledger_model_count=actual_count,
  712. timing_model_count=actual_count,
  713. )
  714. assert failures == [
  715. f"model_call_count expected 1, ledger got {actual_count}",
  716. f"model_call_count expected 1, timing got {actual_count}",
  717. ]
  718. def test_semantics_reject_extra_fallback_calls_even_when_ledgers_agree():
  719. failures = _semantic_failures_for_counts(
  720. ledger_model_count=1,
  721. timing_model_count=1,
  722. ledger_fallback_count=1,
  723. timing_fallback_count=1,
  724. )
  725. assert failures == [
  726. "fallback_count expected 0, ledger got 1",
  727. "fallback_count expected 0, timing got 1",
  728. ]
  729. def test_semantics_keep_timing_vs_ledger_consistency_failure():
  730. failures = _semantic_failures_for_counts(
  731. ledger_model_count=1,
  732. timing_model_count=2,
  733. )
  734. assert failures == [
  735. "model_call_count expected 1, timing got 2",
  736. "model_call_count ledger=1, timing=2",
  737. ]