test_benchmark_reporting.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import importlib
  2. import importlib.util
  3. import json
  4. import multiprocessing
  5. import threading
  6. from concurrent.futures import ThreadPoolExecutor
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. import pytest
  10. from pydantic import ValidationError
  11. from agent_lab.application.benchmark import (
  12. BenchmarkCaseId,
  13. BenchmarkConfig,
  14. BenchmarkModelCallTiming,
  15. BenchmarkMode,
  16. BenchmarkRunResult,
  17. )
  18. def _reporting_module():
  19. spec = importlib.util.find_spec(
  20. "agent_lab.infrastructure.benchmark_reporting"
  21. )
  22. assert spec is not None, "benchmark_reporting module must be implemented"
  23. return importlib.import_module(
  24. "agent_lab.infrastructure.benchmark_reporting"
  25. )
  26. def _config(**overrides: object) -> BenchmarkConfig:
  27. payload = {
  28. "schema_version": 1,
  29. "base_url": "https://provider.example/v1",
  30. "model": "benchmark-model",
  31. "runs_per_case": 1,
  32. "cases": [BenchmarkCaseId.ORDINARY_CHAT],
  33. "modes": [BenchmarkMode.DUAL_AGENT],
  34. }
  35. payload.update(overrides)
  36. return BenchmarkConfig.model_validate(payload)
  37. def _run(
  38. *,
  39. case_id: BenchmarkCaseId = BenchmarkCaseId.ORDINARY_CHAT,
  40. mode: BenchmarkMode = BenchmarkMode.DUAL_AGENT,
  41. iteration: int = 1,
  42. status: str = "passed",
  43. initial_provider_ttft_ms: int | None = 10,
  44. visible_ttft_ms: int | None = 20,
  45. turn_wall_time_ms: int | None = 30,
  46. prompt_tokens: int | None = 2,
  47. completion_tokens: int | None = 3,
  48. total_tokens: int | None = 5,
  49. cached_tokens: int | None = 1,
  50. model_call_count: int | None = 1,
  51. fallback_count: int | None = 0,
  52. tool_count: int | None = 0,
  53. tool_latencies_ms: list[int | None] | None = None,
  54. semantic_failures: list[str] | None = None,
  55. error: str | None = None,
  56. model_calls: list[BenchmarkModelCallTiming] | None = None,
  57. ) -> BenchmarkRunResult:
  58. return BenchmarkRunResult(
  59. case_id=case_id,
  60. mode=mode,
  61. iteration=iteration,
  62. status=status,
  63. initial_provider_ttft_ms=initial_provider_ttft_ms,
  64. visible_ttft_ms=visible_ttft_ms,
  65. turn_wall_time_ms=turn_wall_time_ms,
  66. prompt_tokens=prompt_tokens,
  67. completion_tokens=completion_tokens,
  68. total_tokens=total_tokens,
  69. cached_tokens=cached_tokens,
  70. model_call_count=model_call_count,
  71. fallback_count=fallback_count,
  72. tool_count=tool_count,
  73. event_names=[],
  74. batch_event_names=[],
  75. tool_event_names=[],
  76. event_sources=[],
  77. tool_statuses=[],
  78. tool_latencies_ms=tool_latencies_ms or [],
  79. semantic_failures=semantic_failures or [],
  80. error=error,
  81. model_calls=model_calls or [],
  82. )
  83. def _model_call(
  84. call_index: int,
  85. elapsed_ms: int | None,
  86. ) -> BenchmarkModelCallTiming:
  87. return BenchmarkModelCallTiming(
  88. call_index=call_index,
  89. call_kind="chat_completion",
  90. first_item_kind="raw_chunk",
  91. provider_ttft_ms=1,
  92. visible_ttft_ms=2,
  93. elapsed_ms=elapsed_ms,
  94. usage=None,
  95. )
  96. def _marker_report(marker: str):
  97. reporting = _reporting_module()
  98. return reporting.build_benchmark_report(
  99. _config(model=marker),
  100. [_run()],
  101. mock=True,
  102. )
  103. def _process_report_writer(
  104. output_dir: str,
  105. marker: str,
  106. timestamp: str,
  107. first_temp_barrier,
  108. result_queue,
  109. ) -> None:
  110. reporting = _reporting_module()
  111. original_write_text = reporting._write_text
  112. first_write = True
  113. def synchronized_write(path: Path, content: str) -> None:
  114. nonlocal first_write
  115. original_write_text(path, content)
  116. if first_write:
  117. first_write = False
  118. first_temp_barrier.wait()
  119. reporting._write_text = synchronized_write
  120. try:
  121. json_path, markdown_path = reporting.write_benchmark_report(
  122. _marker_report(marker),
  123. output_dir,
  124. timestamp=timestamp,
  125. )
  126. except BaseException as exc:
  127. result_queue.put(("error", marker, repr(exc)))
  128. return
  129. result_queue.put(
  130. ("ok", marker, json_path.name, markdown_path.name)
  131. )
  132. def _assert_concurrent_report_pairs(
  133. output_dir: Path,
  134. markers: list[str],
  135. ) -> None:
  136. json_paths = sorted(output_dir.glob("*.json"))
  137. markdown_paths = sorted(output_dir.glob("*.md"))
  138. assert len(json_paths) == len(markers)
  139. assert len(markdown_paths) == len(markers)
  140. assert {path.stem for path in json_paths} == {
  141. path.stem for path in markdown_paths
  142. }
  143. actual_markers = set()
  144. for json_path in json_paths:
  145. marker = json.loads(json_path.read_text())["target"]["model"]
  146. markdown = json_path.with_suffix(".md").read_text()
  147. actual_markers.add(marker)
  148. assert f"- Model: `{marker}`" in markdown
  149. assert actual_markers == set(markers)
  150. assert list(output_dir.glob("*.lock")) == []
  151. assert list(output_dir.glob("*.tmp")) == []
  152. @pytest.mark.parametrize(
  153. ("values", "quantile", "expected"),
  154. [
  155. ([], 0.50, None),
  156. ([7], 0.50, 7.0),
  157. ([7], 0.95, 7.0),
  158. ([1, 3, 5, 7], 0.50, 4.0),
  159. ([1, 3, 5, 7], 0.95, 6.7),
  160. ],
  161. )
  162. def test_percentile_uses_linear_interpolation(
  163. values: list[int], quantile: float, expected: float | None
  164. ):
  165. reporting = _reporting_module()
  166. assert reporting.percentile(values, quantile) == pytest.approx(expected)
  167. def test_report_models_are_strict_and_include_required_summary_fields():
  168. reporting = _reporting_module()
  169. generated_at = datetime(2026, 7, 14, 1, 2, 3, tzinfo=timezone.utc)
  170. report = reporting.build_benchmark_report(
  171. _config(),
  172. [_run()],
  173. mock=True,
  174. generated_at=generated_at,
  175. )
  176. assert isinstance(report, reporting.BenchmarkReport)
  177. assert report.schema_version == 1
  178. assert report.generated_at == generated_at
  179. assert report.target.model_dump() == {
  180. "base_url": "https://provider.example/v1",
  181. "model": "benchmark-model",
  182. "mock": True,
  183. }
  184. assert report.config.model_dump(mode="json") == {
  185. "runs_per_case": 1,
  186. "cases": ["ordinary_chat"],
  187. "modes": ["dual_agent"],
  188. }
  189. assert report.overall.model_dump() == {
  190. "attempted": 1,
  191. "passed": 1,
  192. "failed": 0,
  193. "warnings": report.overall.warnings,
  194. "system_errors": [],
  195. }
  196. with pytest.raises(ValidationError):
  197. reporting.BenchmarkReport.model_validate(
  198. report.model_dump() | {"schema_version": "1"}
  199. )
  200. with pytest.raises(ValidationError):
  201. reporting.BenchmarkAggregate.model_validate(
  202. report.aggregates[0].model_dump() | {"unexpected": True}
  203. )
  204. def test_aggregate_excludes_failed_and_null_samples_from_metrics():
  205. reporting = _reporting_module()
  206. runs = [
  207. _run(
  208. iteration=1,
  209. initial_provider_ttft_ms=10,
  210. visible_ttft_ms=20,
  211. turn_wall_time_ms=30,
  212. prompt_tokens=2,
  213. completion_tokens=3,
  214. total_tokens=5,
  215. cached_tokens=1,
  216. model_call_count=1,
  217. fallback_count=0,
  218. tool_count=2,
  219. ),
  220. _run(
  221. iteration=2,
  222. initial_provider_ttft_ms=None,
  223. visible_ttft_ms=40,
  224. turn_wall_time_ms=None,
  225. prompt_tokens=None,
  226. completion_tokens=7,
  227. total_tokens=7,
  228. cached_tokens=None,
  229. model_call_count=3,
  230. fallback_count=1,
  231. tool_count=None,
  232. ),
  233. _run(
  234. iteration=3,
  235. status="failed",
  236. initial_provider_ttft_ms=999,
  237. visible_ttft_ms=999,
  238. turn_wall_time_ms=999,
  239. prompt_tokens=999,
  240. completion_tokens=999,
  241. total_tokens=999,
  242. cached_tokens=999,
  243. model_call_count=999,
  244. fallback_count=999,
  245. tool_count=999,
  246. error="failed",
  247. ),
  248. ]
  249. aggregate = reporting.build_benchmark_report(
  250. _config(runs_per_case=3), runs, mock=True
  251. ).aggregates[0]
  252. assert (aggregate.attempted, aggregate.passed, aggregate.failed) == (3, 2, 1)
  253. assert aggregate.initial_provider_ttft_ms.model_dump() == {
  254. "count": 1,
  255. "p50": 10.0,
  256. "p95": 10.0,
  257. }
  258. assert aggregate.visible_ttft_ms.model_dump() == {
  259. "count": 2,
  260. "p50": 30.0,
  261. "p95": 39.0,
  262. }
  263. assert aggregate.turn_wall_time_ms.count == 1
  264. assert aggregate.prompt_tokens.model_dump() == {
  265. "count": 1,
  266. "total": 2,
  267. "mean": 2.0,
  268. }
  269. assert aggregate.completion_tokens.model_dump() == {
  270. "count": 2,
  271. "total": 10,
  272. "mean": 5.0,
  273. }
  274. assert aggregate.total_tokens.total == 12
  275. assert aggregate.cached_tokens.total == 1
  276. assert aggregate.model_call_count.model_dump() == {
  277. "count": 2,
  278. "total": 4,
  279. "mean": 2.0,
  280. }
  281. assert aggregate.fallback_count.total == 1
  282. assert aggregate.tool_count.model_dump() == {
  283. "count": 1,
  284. "total": 2,
  285. "mean": 2.0,
  286. }
  287. def test_aggregate_flattens_passed_model_and_tool_latency_samples():
  288. reporting = _reporting_module()
  289. runs = [
  290. _run(
  291. iteration=1,
  292. model_calls=[
  293. _model_call(1, 10),
  294. _model_call(2, None),
  295. _model_call(3, 30),
  296. ],
  297. tool_latencies_ms=[5, None, 15],
  298. ),
  299. _run(
  300. iteration=2,
  301. model_calls=[_model_call(1, 20)],
  302. tool_latencies_ms=[25],
  303. ),
  304. _run(
  305. iteration=3,
  306. status="failed",
  307. model_calls=[_model_call(1, 999)],
  308. tool_latencies_ms=[999],
  309. ),
  310. ]
  311. report = reporting.build_benchmark_report(
  312. _config(runs_per_case=3), runs, mock=True
  313. )
  314. aggregate = report.aggregates[0]
  315. markdown = reporting.render_markdown(report)
  316. assert aggregate.model_elapsed_ms.model_dump() == {
  317. "count": 3,
  318. "p50": 20.0,
  319. "p95": 29.0,
  320. }
  321. assert aggregate.tool_latency_ms.model_dump() == {
  322. "count": 3,
  323. "p50": 15.0,
  324. "p95": 24.0,
  325. }
  326. assert "Model elapsed p50/p95 ms" in markdown
  327. assert "Tool latency p50/p95 ms" in markdown
  328. assert "20.0/29.0" in markdown
  329. assert "15.0/24.0" in markdown
  330. def test_zero_latency_samples_emit_low_confidence_warnings():
  331. reporting = _reporting_module()
  332. aggregate = reporting.build_benchmark_report(
  333. _config(),
  334. [
  335. _run(
  336. initial_provider_ttft_ms=None,
  337. visible_ttft_ms=None,
  338. turn_wall_time_ms=None,
  339. model_calls=[],
  340. tool_latencies_ms=[],
  341. )
  342. ],
  343. mock=True,
  344. ).aggregates[0]
  345. assert {
  346. warning.split(" p95 low confidence:", 1)[0]
  347. for warning in aggregate.warnings
  348. } == {
  349. "ordinary_chat/dual_agent initial_provider_ttft_ms",
  350. "ordinary_chat/dual_agent visible_ttft_ms",
  351. "ordinary_chat/dual_agent turn_wall_time_ms",
  352. "ordinary_chat/dual_agent model_elapsed_ms",
  353. "ordinary_chat/dual_agent tool_latency_ms",
  354. }
  355. assert all("0 samples" in warning for warning in aggregate.warnings)
  356. def test_aggregates_are_stably_sorted_and_warn_for_low_confidence_p95():
  357. reporting = _reporting_module()
  358. runs = [
  359. _run(
  360. case_id=BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS,
  361. mode=BenchmarkMode.DUAL_AGENT,
  362. ),
  363. _run(
  364. case_id=BenchmarkCaseId.ORDINARY_CHAT,
  365. mode=BenchmarkMode.CHAT_AGENT_TOOLS,
  366. ),
  367. _run(
  368. case_id=BenchmarkCaseId.ORDINARY_CHAT,
  369. mode=BenchmarkMode.DUAL_AGENT,
  370. ),
  371. ]
  372. report = reporting.build_benchmark_report(
  373. _config(
  374. cases=[
  375. BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS,
  376. BenchmarkCaseId.ORDINARY_CHAT,
  377. ],
  378. modes=[
  379. BenchmarkMode.CHAT_AGENT_TOOLS,
  380. BenchmarkMode.DUAL_AGENT,
  381. ],
  382. ),
  383. runs,
  384. mock=True,
  385. )
  386. assert [(item.case_id.value, item.mode.value) for item in report.aggregates] == [
  387. ("ordinary_chat", "chat_agent_tools"),
  388. ("ordinary_chat", "dual_agent"),
  389. ("web_search_two_answers", "dual_agent"),
  390. ]
  391. assert all(
  392. any("p95 low confidence" in warning for warning in item.warnings)
  393. for item in report.aggregates
  394. )
  395. assert report.overall.warnings == [
  396. warning
  397. for aggregate in report.aggregates
  398. for warning in aggregate.warnings
  399. ]
  400. def test_errors_are_redacted_before_truncation_in_json_and_markdown():
  401. reporting = _reporting_module()
  402. real_key = "sk-live-secret-value"
  403. leaked_error = (
  404. f"Authorization: Bearer {real_key}; "
  405. f"API-Key={real_key}; "
  406. f"https://example.test/?api_key={real_key}&token={real_key}; "
  407. f'{{"access_token":"{real_key}","key":"{real_key}"}}; '
  408. + "x" * 3000
  409. )
  410. report = reporting.build_benchmark_report(
  411. _config(),
  412. [
  413. _run(
  414. status="failed",
  415. semantic_failures=[f"token={real_key}"],
  416. error=leaked_error,
  417. )
  418. ],
  419. mock=False,
  420. secrets=[real_key],
  421. )
  422. payload = report.model_dump(mode="json")
  423. json_text = reporting.report_to_json(report)
  424. markdown = reporting.render_markdown(report)
  425. assert len(report.runs[0].error) == 2048
  426. assert real_key not in json.dumps(payload)
  427. assert real_key not in json_text
  428. assert real_key not in markdown
  429. assert "[REDACTED]" in json_text
  430. assert "[REDACTED]" in markdown
  431. def test_error_truncation_is_utf8_safe_and_bounded_after_redaction():
  432. reporting = _reporting_module()
  433. real_key = "sk-byte-bound-secret"
  434. error = f"Bearer {real_key} " + "密" * 1000
  435. sanitized = reporting.sanitize_error(error, secrets=[real_key])
  436. redacted = reporting.redact_text(error, secrets=[real_key])
  437. expected = redacted.encode("utf-8")[:2048].decode("utf-8", errors="ignore")
  438. assert sanitized == expected
  439. assert real_key not in sanitized
  440. assert len(sanitized.encode("utf-8")) <= 2048
  441. assert "\ufffd" not in sanitized
  442. def test_configured_secret_is_redacted_from_all_report_string_surfaces():
  443. reporting = _reporting_module()
  444. real_key = "sk-everywhere-secret"
  445. run = _run().model_copy(
  446. update={
  447. "event_names": [real_key],
  448. "event_sources": [f"Bearer {real_key}"],
  449. "tool_statuses": [f"token={real_key}"],
  450. }
  451. )
  452. report = reporting.build_benchmark_report(
  453. _config(
  454. base_url=f"https://provider.example/{real_key}",
  455. model=f"model-{real_key}",
  456. ),
  457. [run],
  458. mock=False,
  459. secrets=[real_key],
  460. )
  461. rendered = reporting.report_to_json(report) + reporting.render_markdown(report)
  462. assert real_key not in rendered
  463. assert "[REDACTED]" in rendered
  464. def test_system_errors_are_typed_redacted_counted_and_rendered():
  465. reporting = _reporting_module()
  466. real_key = "sk-runner-system-secret"
  467. report = reporting.build_benchmark_report(
  468. _config(),
  469. [],
  470. mock=False,
  471. secrets=[real_key],
  472. system_errors=[f"Authorization: Bearer {real_key}"],
  473. )
  474. payload = json.loads(reporting.report_to_json(report))
  475. markdown = reporting.render_markdown(report)
  476. assert report.overall.model_dump() == {
  477. "attempted": 1,
  478. "passed": 0,
  479. "failed": 1,
  480. "warnings": [],
  481. "system_errors": ["Authorization: [REDACTED] [REDACTED]"],
  482. }
  483. assert payload["overall"]["system_errors"] == report.overall.system_errors
  484. assert "## System Errors" in markdown
  485. assert "Authorization: [REDACTED] [REDACTED]" in markdown
  486. assert real_key not in reporting.report_to_json(report)
  487. assert real_key not in markdown
  488. def test_markdown_is_rendered_from_the_same_json_facts():
  489. reporting = _reporting_module()
  490. report = reporting.build_benchmark_report(
  491. _config(runs_per_case=2),
  492. [
  493. _run(iteration=1, visible_ttft_ms=10, total_tokens=5),
  494. _run(iteration=2, visible_ttft_ms=30, total_tokens=9),
  495. ],
  496. mock=True,
  497. generated_at=datetime(2026, 7, 14, tzinfo=timezone.utc),
  498. )
  499. payload = json.loads(reporting.report_to_json(report))
  500. markdown = reporting.render_markdown(report)
  501. aggregate = payload["aggregates"][0]
  502. assert str(aggregate["visible_ttft_ms"]["p50"]) in markdown
  503. assert str(aggregate["visible_ttft_ms"]["p95"]) in markdown
  504. assert str(aggregate["total_tokens"]["total"]) in markdown
  505. assert str(aggregate["total_tokens"]["mean"]) in markdown
  506. assert payload == report.model_dump(mode="json")
  507. def test_atomic_write_creates_matching_unique_json_and_markdown_paths(tmp_path: Path):
  508. reporting = _reporting_module()
  509. report = reporting.build_benchmark_report(
  510. _config(), [_run()], mock=True
  511. )
  512. timestamp = "20260714T010203Z"
  513. (tmp_path / f"{timestamp}.json").write_text("existing")
  514. (tmp_path / f"{timestamp}.md").write_text("existing")
  515. json_path, markdown_path = reporting.write_benchmark_report(
  516. report,
  517. tmp_path,
  518. timestamp=timestamp,
  519. )
  520. assert json_path.name == f"{timestamp}-1.json"
  521. assert markdown_path.name == f"{timestamp}-1.md"
  522. assert json.loads(json_path.read_text()) == report.model_dump(mode="json")
  523. assert markdown_path.read_text() == reporting.render_markdown(report)
  524. assert list(tmp_path.glob("*.tmp")) == []
  525. def test_atomic_write_removes_temps_and_published_half_on_replace_failure(
  526. tmp_path: Path, monkeypatch: pytest.MonkeyPatch
  527. ):
  528. reporting = _reporting_module()
  529. report = reporting.build_benchmark_report(
  530. _config(), [_run()], mock=True
  531. )
  532. real_replace = reporting.os.replace
  533. calls = 0
  534. def fail_second_replace(source: Path, destination: Path) -> None:
  535. nonlocal calls
  536. calls += 1
  537. if calls == 2:
  538. raise OSError("simulated markdown publish failure")
  539. real_replace(source, destination)
  540. monkeypatch.setattr(reporting.os, "replace", fail_second_replace)
  541. with pytest.raises(
  542. reporting.BenchmarkReportWriteError,
  543. match="failed to write benchmark reports",
  544. ):
  545. reporting.write_benchmark_report(
  546. report,
  547. tmp_path,
  548. timestamp="20260714T010203Z",
  549. )
  550. assert list(tmp_path.iterdir()) == []
  551. def test_reservation_failure_after_lock_creation_removes_own_lock(
  552. tmp_path: Path,
  553. monkeypatch: pytest.MonkeyPatch,
  554. ):
  555. reporting = _reporting_module()
  556. original_exists = Path.exists
  557. def failing_exists(path: Path) -> bool:
  558. if path.parent == tmp_path and path.suffix == ".json":
  559. raise OSError("simulated reservation path check failure")
  560. return original_exists(path)
  561. monkeypatch.setattr(Path, "exists", failing_exists)
  562. with pytest.raises(
  563. reporting.BenchmarkReportWriteError,
  564. match="failed to write benchmark reports",
  565. ):
  566. reporting.write_benchmark_report(
  567. _marker_report("reservation-failure"),
  568. tmp_path,
  569. timestamp="20260714T040506Z",
  570. )
  571. assert list(tmp_path.iterdir()) == []
  572. def test_concurrent_thread_writers_reserve_distinct_matching_pairs(
  573. tmp_path: Path,
  574. monkeypatch: pytest.MonkeyPatch,
  575. ):
  576. reporting = _reporting_module()
  577. writer_count = 8
  578. markers = [f"thread-writer-{index}" for index in range(writer_count)]
  579. first_temp_barrier = threading.Barrier(writer_count, timeout=15)
  580. original_write_text = reporting._write_text
  581. thread_state = threading.local()
  582. def synchronized_write(path: Path, content: str) -> None:
  583. original_write_text(path, content)
  584. if not getattr(thread_state, "first_write_done", False):
  585. thread_state.first_write_done = True
  586. first_temp_barrier.wait()
  587. monkeypatch.setattr(reporting, "_write_text", synchronized_write)
  588. with ThreadPoolExecutor(max_workers=writer_count) as executor:
  589. results = list(
  590. executor.map(
  591. lambda marker: reporting.write_benchmark_report(
  592. _marker_report(marker),
  593. tmp_path,
  594. timestamp="20260714T020304Z",
  595. ),
  596. markers,
  597. )
  598. )
  599. assert len({json_path.stem for json_path, _ in results}) == writer_count
  600. _assert_concurrent_report_pairs(tmp_path, markers)
  601. def test_concurrent_process_writers_reserve_distinct_matching_pairs(
  602. tmp_path: Path,
  603. ):
  604. context = multiprocessing.get_context("spawn")
  605. writer_count = 4
  606. markers = [f"process-writer-{index}" for index in range(writer_count)]
  607. first_temp_barrier = context.Barrier(writer_count, timeout=20)
  608. result_queue = context.Queue()
  609. processes = [
  610. context.Process(
  611. target=_process_report_writer,
  612. args=(
  613. str(tmp_path),
  614. marker,
  615. "20260714T030405Z",
  616. first_temp_barrier,
  617. result_queue,
  618. ),
  619. )
  620. for marker in markers
  621. ]
  622. for process in processes:
  623. process.start()
  624. results = [result_queue.get(timeout=30) for _ in processes]
  625. for process in processes:
  626. process.join(timeout=30)
  627. assert all(process.exitcode == 0 for process in processes)
  628. assert all(result[0] == "ok" for result in results), results
  629. assert len({result[2][:-5] for result in results}) == writer_count
  630. _assert_concurrent_report_pairs(tmp_path, markers)