test_benchmark_reporting.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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.parent.name, markdown_path.parent.name)
  131. )
  132. def _assert_concurrent_report_pairs(
  133. output_dir: Path,
  134. markers: list[str],
  135. ) -> None:
  136. published_dirs = sorted(
  137. path
  138. for path in output_dir.iterdir()
  139. if not path.name.startswith(".")
  140. )
  141. assert len(published_dirs) == len(markers)
  142. assert all(path.is_symlink() for path in published_dirs)
  143. actual_markers = set()
  144. targets = set()
  145. for published_dir in published_dirs:
  146. target = published_dir.readlink()
  147. assert not target.is_absolute()
  148. targets.add(target)
  149. json_path = published_dir / "report.json"
  150. markdown_path = published_dir / "report.md"
  151. marker = json.loads(json_path.read_text())["target"]["model"]
  152. markdown = markdown_path.read_text()
  153. actual_markers.add(marker)
  154. assert f"- Model: `{marker}`" in markdown
  155. assert actual_markers == set(markers)
  156. assert len(targets) == len(markers)
  157. _assert_no_publication_artifacts(output_dir)
  158. def _assert_no_publication_artifacts(output_dir: Path) -> None:
  159. entries = list(output_dir.iterdir())
  160. leftovers = [
  161. path.name
  162. for path in entries
  163. if path.name.endswith((".tmp", ".lock"))
  164. or "placeholder" in path.name
  165. or path.suffix in {".json", ".md"}
  166. ]
  167. assert leftovers == []
  168. published_dirs = [
  169. path
  170. for path in entries
  171. if path.is_symlink()
  172. and path.readlink().name.startswith(".")
  173. and path.readlink().name.endswith(".bundle")
  174. ]
  175. published_targets = {path.readlink() for path in published_dirs}
  176. private_bundles = {
  177. Path(path.name)
  178. for path in entries
  179. if path.name.startswith(".") and path.is_dir()
  180. }
  181. assert private_bundles == published_targets
  182. for published_dir in published_dirs:
  183. assert (published_dir / "report.json").stat().st_size > 0
  184. assert (published_dir / "report.md").stat().st_size > 0
  185. @pytest.mark.parametrize(
  186. ("values", "quantile", "expected"),
  187. [
  188. ([], 0.50, None),
  189. ([7], 0.50, 7.0),
  190. ([7], 0.95, 7.0),
  191. ([1, 3, 5, 7], 0.50, 4.0),
  192. ([1, 3, 5, 7], 0.95, 6.7),
  193. ],
  194. )
  195. def test_percentile_uses_linear_interpolation(
  196. values: list[int], quantile: float, expected: float | None
  197. ):
  198. reporting = _reporting_module()
  199. assert reporting.percentile(values, quantile) == pytest.approx(expected)
  200. def test_report_models_are_strict_and_include_required_summary_fields():
  201. reporting = _reporting_module()
  202. generated_at = datetime(2026, 7, 14, 1, 2, 3, tzinfo=timezone.utc)
  203. report = reporting.build_benchmark_report(
  204. _config(),
  205. [_run()],
  206. mock=True,
  207. generated_at=generated_at,
  208. )
  209. assert isinstance(report, reporting.BenchmarkReport)
  210. assert report.schema_version == 1
  211. assert report.generated_at == generated_at
  212. assert report.target.model_dump() == {
  213. "base_url": "https://provider.example/v1",
  214. "model": "benchmark-model",
  215. "mock": True,
  216. }
  217. assert report.config.model_dump(mode="json") == {
  218. "runs_per_case": 1,
  219. "cases": ["ordinary_chat"],
  220. "modes": ["dual_agent"],
  221. }
  222. assert report.overall.model_dump() == {
  223. "attempted": 1,
  224. "passed": 1,
  225. "failed": 0,
  226. "warnings": report.overall.warnings,
  227. "system_errors": [],
  228. }
  229. with pytest.raises(ValidationError):
  230. reporting.BenchmarkReport.model_validate(
  231. report.model_dump() | {"schema_version": "1"}
  232. )
  233. with pytest.raises(ValidationError):
  234. reporting.BenchmarkAggregate.model_validate(
  235. report.aggregates[0].model_dump() | {"unexpected": True}
  236. )
  237. def test_aggregate_excludes_failed_and_null_samples_from_metrics():
  238. reporting = _reporting_module()
  239. runs = [
  240. _run(
  241. iteration=1,
  242. initial_provider_ttft_ms=10,
  243. visible_ttft_ms=20,
  244. turn_wall_time_ms=30,
  245. prompt_tokens=2,
  246. completion_tokens=3,
  247. total_tokens=5,
  248. cached_tokens=1,
  249. model_call_count=1,
  250. fallback_count=0,
  251. tool_count=2,
  252. ),
  253. _run(
  254. iteration=2,
  255. initial_provider_ttft_ms=None,
  256. visible_ttft_ms=40,
  257. turn_wall_time_ms=None,
  258. prompt_tokens=None,
  259. completion_tokens=7,
  260. total_tokens=7,
  261. cached_tokens=None,
  262. model_call_count=3,
  263. fallback_count=1,
  264. tool_count=None,
  265. ),
  266. _run(
  267. iteration=3,
  268. status="failed",
  269. initial_provider_ttft_ms=999,
  270. visible_ttft_ms=999,
  271. turn_wall_time_ms=999,
  272. prompt_tokens=999,
  273. completion_tokens=999,
  274. total_tokens=999,
  275. cached_tokens=999,
  276. model_call_count=999,
  277. fallback_count=999,
  278. tool_count=999,
  279. error="failed",
  280. ),
  281. ]
  282. aggregate = reporting.build_benchmark_report(
  283. _config(runs_per_case=3), runs, mock=True
  284. ).aggregates[0]
  285. assert (aggregate.attempted, aggregate.passed, aggregate.failed) == (3, 2, 1)
  286. assert aggregate.initial_provider_ttft_ms.model_dump() == {
  287. "count": 1,
  288. "p50": 10.0,
  289. "p95": 10.0,
  290. }
  291. assert aggregate.visible_ttft_ms.model_dump() == {
  292. "count": 2,
  293. "p50": 30.0,
  294. "p95": 39.0,
  295. }
  296. assert aggregate.turn_wall_time_ms.count == 1
  297. assert aggregate.prompt_tokens.model_dump() == {
  298. "count": 1,
  299. "total": 2,
  300. "mean": 2.0,
  301. }
  302. assert aggregate.completion_tokens.model_dump() == {
  303. "count": 2,
  304. "total": 10,
  305. "mean": 5.0,
  306. }
  307. assert aggregate.total_tokens.total == 12
  308. assert aggregate.cached_tokens.total == 1
  309. assert aggregate.model_call_count.model_dump() == {
  310. "count": 2,
  311. "total": 4,
  312. "mean": 2.0,
  313. }
  314. assert aggregate.fallback_count.total == 1
  315. assert aggregate.tool_count.model_dump() == {
  316. "count": 1,
  317. "total": 2,
  318. "mean": 2.0,
  319. }
  320. def test_aggregate_flattens_passed_model_and_tool_latency_samples():
  321. reporting = _reporting_module()
  322. runs = [
  323. _run(
  324. iteration=1,
  325. model_calls=[
  326. _model_call(1, 10),
  327. _model_call(2, None),
  328. _model_call(3, 30),
  329. ],
  330. tool_latencies_ms=[5, None, 15],
  331. ),
  332. _run(
  333. iteration=2,
  334. model_calls=[_model_call(1, 20)],
  335. tool_latencies_ms=[25],
  336. ),
  337. _run(
  338. iteration=3,
  339. status="failed",
  340. model_calls=[_model_call(1, 999)],
  341. tool_latencies_ms=[999],
  342. ),
  343. ]
  344. report = reporting.build_benchmark_report(
  345. _config(runs_per_case=3), runs, mock=True
  346. )
  347. aggregate = report.aggregates[0]
  348. markdown = reporting.render_markdown(report)
  349. assert aggregate.model_elapsed_ms.model_dump() == {
  350. "count": 3,
  351. "p50": 20.0,
  352. "p95": 29.0,
  353. }
  354. assert aggregate.tool_latency_ms.model_dump() == {
  355. "count": 3,
  356. "p50": 15.0,
  357. "p95": 24.0,
  358. }
  359. assert "Model elapsed p50/p95 ms" in markdown
  360. assert "Tool latency p50/p95 ms" in markdown
  361. assert "20.0/29.0" in markdown
  362. assert "15.0/24.0" in markdown
  363. def test_zero_latency_samples_emit_low_confidence_warnings():
  364. reporting = _reporting_module()
  365. aggregate = reporting.build_benchmark_report(
  366. _config(),
  367. [
  368. _run(
  369. initial_provider_ttft_ms=None,
  370. visible_ttft_ms=None,
  371. turn_wall_time_ms=None,
  372. model_calls=[],
  373. tool_latencies_ms=[],
  374. )
  375. ],
  376. mock=True,
  377. ).aggregates[0]
  378. assert {
  379. warning.split(" p95 low confidence:", 1)[0]
  380. for warning in aggregate.warnings
  381. } == {
  382. "ordinary_chat/dual_agent initial_provider_ttft_ms",
  383. "ordinary_chat/dual_agent visible_ttft_ms",
  384. "ordinary_chat/dual_agent turn_wall_time_ms",
  385. "ordinary_chat/dual_agent model_elapsed_ms",
  386. "ordinary_chat/dual_agent tool_latency_ms",
  387. }
  388. assert all("0 samples" in warning for warning in aggregate.warnings)
  389. def test_aggregates_are_stably_sorted_and_warn_for_low_confidence_p95():
  390. reporting = _reporting_module()
  391. runs = [
  392. _run(
  393. case_id=BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS,
  394. mode=BenchmarkMode.DUAL_AGENT,
  395. ),
  396. _run(
  397. case_id=BenchmarkCaseId.ORDINARY_CHAT,
  398. mode=BenchmarkMode.CHAT_AGENT_TOOLS,
  399. ),
  400. _run(
  401. case_id=BenchmarkCaseId.ORDINARY_CHAT,
  402. mode=BenchmarkMode.DUAL_AGENT,
  403. ),
  404. ]
  405. report = reporting.build_benchmark_report(
  406. _config(
  407. cases=[
  408. BenchmarkCaseId.WEB_SEARCH_TWO_ANSWERS,
  409. BenchmarkCaseId.ORDINARY_CHAT,
  410. ],
  411. modes=[
  412. BenchmarkMode.CHAT_AGENT_TOOLS,
  413. BenchmarkMode.DUAL_AGENT,
  414. ],
  415. ),
  416. runs,
  417. mock=True,
  418. )
  419. assert [(item.case_id.value, item.mode.value) for item in report.aggregates] == [
  420. ("ordinary_chat", "chat_agent_tools"),
  421. ("ordinary_chat", "dual_agent"),
  422. ("web_search_two_answers", "dual_agent"),
  423. ]
  424. assert all(
  425. any("p95 low confidence" in warning for warning in item.warnings)
  426. for item in report.aggregates
  427. )
  428. assert report.overall.warnings == [
  429. warning
  430. for aggregate in report.aggregates
  431. for warning in aggregate.warnings
  432. ]
  433. def test_errors_are_redacted_before_truncation_in_json_and_markdown():
  434. reporting = _reporting_module()
  435. real_key = "sk-live-secret-value"
  436. leaked_error = (
  437. f"Authorization: Bearer {real_key}; "
  438. f"API-Key={real_key}; "
  439. f"https://example.test/?api_key={real_key}&token={real_key}; "
  440. f'{{"access_token":"{real_key}","key":"{real_key}"}}; '
  441. + "x" * 3000
  442. )
  443. report = reporting.build_benchmark_report(
  444. _config(),
  445. [
  446. _run(
  447. status="failed",
  448. semantic_failures=[f"token={real_key}"],
  449. error=leaked_error,
  450. )
  451. ],
  452. mock=False,
  453. secrets=[real_key],
  454. )
  455. payload = report.model_dump(mode="json")
  456. json_text = reporting.report_to_json(report)
  457. markdown = reporting.render_markdown(report)
  458. assert len(report.runs[0].error) == 2048
  459. assert real_key not in json.dumps(payload)
  460. assert real_key not in json_text
  461. assert real_key not in markdown
  462. assert "[REDACTED]" in json_text
  463. assert "[REDACTED]" in markdown
  464. def test_error_truncation_is_utf8_safe_and_bounded_after_redaction():
  465. reporting = _reporting_module()
  466. real_key = "sk-byte-bound-secret"
  467. error = f"Bearer {real_key} " + "密" * 1000
  468. sanitized = reporting.sanitize_error(error, secrets=[real_key])
  469. redacted = reporting.redact_text(error, secrets=[real_key])
  470. expected = redacted.encode("utf-8")[:2048].decode("utf-8", errors="ignore")
  471. assert sanitized == expected
  472. assert real_key not in sanitized
  473. assert len(sanitized.encode("utf-8")) <= 2048
  474. assert "\ufffd" not in sanitized
  475. def test_configured_secret_is_redacted_from_all_report_string_surfaces():
  476. reporting = _reporting_module()
  477. real_key = "sk-everywhere-secret"
  478. run = _run().model_copy(
  479. update={
  480. "event_names": [real_key],
  481. "event_sources": [f"Bearer {real_key}"],
  482. "tool_statuses": [f"token={real_key}"],
  483. }
  484. )
  485. report = reporting.build_benchmark_report(
  486. _config(
  487. base_url=f"https://provider.example/{real_key}",
  488. model=f"model-{real_key}",
  489. ),
  490. [run],
  491. mock=False,
  492. secrets=[real_key],
  493. )
  494. rendered = reporting.report_to_json(report) + reporting.render_markdown(report)
  495. assert real_key not in rendered
  496. assert "[REDACTED]" in rendered
  497. def test_system_errors_are_typed_redacted_counted_and_rendered():
  498. reporting = _reporting_module()
  499. real_key = "sk-runner-system-secret"
  500. report = reporting.build_benchmark_report(
  501. _config(),
  502. [],
  503. mock=False,
  504. secrets=[real_key],
  505. system_errors=[f"Authorization: Bearer {real_key}"],
  506. )
  507. payload = json.loads(reporting.report_to_json(report))
  508. markdown = reporting.render_markdown(report)
  509. assert report.overall.model_dump() == {
  510. "attempted": 1,
  511. "passed": 0,
  512. "failed": 1,
  513. "warnings": [],
  514. "system_errors": ["Authorization: [REDACTED] [REDACTED]"],
  515. }
  516. assert payload["overall"]["system_errors"] == report.overall.system_errors
  517. assert "## System Errors" in markdown
  518. assert "Authorization: [REDACTED] [REDACTED]" in markdown
  519. assert real_key not in reporting.report_to_json(report)
  520. assert real_key not in markdown
  521. def test_markdown_is_rendered_from_the_same_json_facts():
  522. reporting = _reporting_module()
  523. report = reporting.build_benchmark_report(
  524. _config(runs_per_case=2),
  525. [
  526. _run(iteration=1, visible_ttft_ms=10, total_tokens=5),
  527. _run(iteration=2, visible_ttft_ms=30, total_tokens=9),
  528. ],
  529. mock=True,
  530. generated_at=datetime(2026, 7, 14, tzinfo=timezone.utc),
  531. )
  532. payload = json.loads(reporting.report_to_json(report))
  533. markdown = reporting.render_markdown(report)
  534. aggregate = payload["aggregates"][0]
  535. assert str(aggregate["visible_ttft_ms"]["p50"]) in markdown
  536. assert str(aggregate["visible_ttft_ms"]["p95"]) in markdown
  537. assert str(aggregate["total_tokens"]["total"]) in markdown
  538. assert str(aggregate["total_tokens"]["mean"]) in markdown
  539. assert payload == report.model_dump(mode="json")
  540. def test_markdown_preserves_runtime_error_and_semantic_failures_together():
  541. reporting = _reporting_module()
  542. report = reporting.build_benchmark_report(
  543. _config(),
  544. [
  545. _run(
  546. status="failed",
  547. error="runtime exploded",
  548. semantic_failures=[
  549. "expected web_search event",
  550. "expected two visible answers",
  551. ],
  552. )
  553. ],
  554. mock=True,
  555. )
  556. markdown = reporting.render_markdown(report)
  557. assert "runtime exploded" in markdown
  558. assert "expected web_search event" in markdown
  559. assert "expected two visible answers" in markdown
  560. def test_atomic_write_publishes_complete_bundle_through_relative_symlink(
  561. tmp_path: Path,
  562. ):
  563. reporting = _reporting_module()
  564. report = _marker_report("atomic-bundle")
  565. timestamp = "20260714T010203Z"
  566. competitor = tmp_path / timestamp
  567. competitor.mkdir()
  568. (competitor / "sentinel").write_text("competitor")
  569. json_path, markdown_path = reporting.write_benchmark_report(
  570. report,
  571. tmp_path,
  572. timestamp=timestamp,
  573. )
  574. published_dir = tmp_path / f"{timestamp}-1"
  575. assert json_path == published_dir / "report.json"
  576. assert markdown_path == published_dir / "report.md"
  577. assert published_dir.is_symlink()
  578. bundle_target = published_dir.readlink()
  579. assert not bundle_target.is_absolute()
  580. assert bundle_target.name.startswith(f".{timestamp}.")
  581. assert bundle_target.name.endswith(".bundle")
  582. assert competitor.joinpath("sentinel").read_text() == "competitor"
  583. assert json.loads(json_path.read_text()) == report.model_dump(mode="json")
  584. assert markdown_path.read_text() == reporting.render_markdown(report)
  585. _assert_no_publication_artifacts(tmp_path)
  586. @pytest.mark.parametrize("collision_kind", ["create", "replace"])
  587. def test_symlink_collision_retries_without_removing_or_replacing_competitor(
  588. tmp_path: Path,
  589. monkeypatch: pytest.MonkeyPatch,
  590. collision_kind: str,
  591. ):
  592. reporting = _reporting_module()
  593. timestamp = "20260714T011223Z"
  594. public_path = tmp_path / timestamp
  595. real_symlink = reporting.os.symlink
  596. real_replace = reporting.os.replace
  597. symlink_calls = 0
  598. if collision_kind == "replace":
  599. old_target = tmp_path / "old-competitor"
  600. old_target.mkdir()
  601. real_symlink(old_target.name, public_path)
  602. def collide_before_symlink(source: str, destination: Path) -> None:
  603. nonlocal symlink_calls
  604. symlink_calls += 1
  605. destination = Path(destination)
  606. if symlink_calls == 1:
  607. if collision_kind == "create":
  608. destination.mkdir()
  609. (destination / "sentinel").write_text("competitor")
  610. else:
  611. new_target = tmp_path / "new-competitor"
  612. new_target.mkdir()
  613. replacement = tmp_path / "competitor-replacement"
  614. real_symlink(new_target.name, replacement)
  615. real_replace(replacement, destination)
  616. real_symlink(source, destination)
  617. monkeypatch.setattr(reporting.os, "symlink", collide_before_symlink)
  618. json_path, markdown_path = reporting.write_benchmark_report(
  619. _marker_report(f"symlink-{collision_kind}-collision"),
  620. tmp_path,
  621. timestamp=timestamp,
  622. )
  623. assert symlink_calls == 2
  624. assert json_path.parent == tmp_path / f"{timestamp}-1"
  625. assert markdown_path.parent == json_path.parent
  626. if collision_kind == "create":
  627. assert public_path.joinpath("sentinel").read_text() == "competitor"
  628. else:
  629. assert public_path.readlink() == Path("new-competitor")
  630. assert json.loads(json_path.read_text())["target"]["model"] == (
  631. f"symlink-{collision_kind}-collision"
  632. )
  633. _assert_no_publication_artifacts(tmp_path)
  634. def test_bundle_is_complete_and_matching_before_single_publication(
  635. tmp_path: Path,
  636. monkeypatch: pytest.MonkeyPatch,
  637. ):
  638. reporting = _reporting_module()
  639. real_symlink = reporting.os.symlink
  640. publication_snapshots: list[tuple[str, str]] = []
  641. def inspect_complete_bundle(source: str, destination: Path) -> None:
  642. destination = Path(destination)
  643. bundle = destination.parent / source
  644. json_text = bundle.joinpath("report.json").read_text()
  645. markdown_text = bundle.joinpath("report.md").read_text()
  646. marker = json.loads(json_text)["target"]["model"]
  647. assert f"- Model: `{marker}`" in markdown_text
  648. publication_snapshots.append((json_text, markdown_text))
  649. real_symlink(source, destination)
  650. monkeypatch.setattr(reporting.os, "symlink", inspect_complete_bundle)
  651. json_path, markdown_path = reporting.write_benchmark_report(
  652. _marker_report("complete-before-publish"),
  653. tmp_path,
  654. timestamp="20260714T011224Z",
  655. )
  656. assert len(publication_snapshots) == 1
  657. assert json_path.parent == markdown_path.parent
  658. assert json_path.parent.is_symlink()
  659. assert json_path.read_text() == publication_snapshots[0][0]
  660. assert markdown_path.read_text() == publication_snapshots[0][1]
  661. _assert_no_publication_artifacts(tmp_path)
  662. def test_interrupt_after_symlink_creation_keeps_resolvable_complete_bundle(
  663. tmp_path: Path,
  664. monkeypatch: pytest.MonkeyPatch,
  665. ):
  666. reporting = _reporting_module()
  667. real_symlink = reporting.os.symlink
  668. timestamp = "20260714T011224Z-interrupted"
  669. def publish_then_interrupt(source: str, destination: Path) -> None:
  670. real_symlink(source, destination)
  671. raise KeyboardInterrupt
  672. monkeypatch.setattr(reporting.os, "symlink", publish_then_interrupt)
  673. with pytest.raises(KeyboardInterrupt):
  674. reporting.write_benchmark_report(
  675. _marker_report("interrupt-after-symlink"),
  676. tmp_path,
  677. timestamp=timestamp,
  678. )
  679. published_dir = tmp_path / timestamp
  680. assert published_dir.is_symlink()
  681. assert published_dir.resolve(strict=True).is_dir()
  682. assert (
  683. json.loads(published_dir.joinpath("report.json").read_text())["target"][
  684. "model"
  685. ]
  686. == "interrupt-after-symlink"
  687. )
  688. assert "- Model: `interrupt-after-symlink`" in (
  689. published_dir.joinpath("report.md").read_text()
  690. )
  691. _assert_no_publication_artifacts(tmp_path)
  692. @pytest.mark.parametrize(
  693. "raw_timestamp",
  694. [
  695. pytest.param("<absolute>", id="absolute-path"),
  696. pytest.param("../outside-report", id="parent-traversal"),
  697. pytest.param("segment/report", id="forward-slash"),
  698. pytest.param(r"segment\report", id="backslash"),
  699. pytest.param(".", id="dot-segment"),
  700. pytest.param("..", id="double-dot-segment"),
  701. pytest.param("", id="empty"),
  702. pytest.param(" ", id="space"),
  703. pytest.param("\t", id="tab"),
  704. pytest.param("2026\n0714", id="control-newline"),
  705. pytest.param("2026\x00714", id="control-nul"),
  706. pytest.param("-20260714", id="non-alnum-prefix-hyphen"),
  707. pytest.param("_20260714", id="non-alnum-prefix-underscore"),
  708. pytest.param("2026\u00a00714", id="unicode-whitespace"),
  709. pytest.param("2026\uff0f0714", id="unicode-fullwidth-slash"),
  710. pytest.param("2026\u22150714", id="unicode-division-slash"),
  711. pytest.param("20260714", id="unicode-fullwidth-digits"),
  712. pytest.param("2026\u202ejson", id="unicode-bidi-control"),
  713. pytest.param("a" * 129, id="too-long"),
  714. ],
  715. )
  716. def test_invalid_explicit_timestamp_is_rejected_before_any_filesystem_write(
  717. tmp_path: Path,
  718. raw_timestamp: str,
  719. ):
  720. reporting = _reporting_module()
  721. output_dir = tmp_path / "reports"
  722. timestamp = (
  723. str(tmp_path / "outside-absolute")
  724. if raw_timestamp == "<absolute>"
  725. else raw_timestamp
  726. )
  727. entries_before = sorted(
  728. path.relative_to(tmp_path) for path in tmp_path.rglob("*")
  729. )
  730. with pytest.raises(
  731. reporting.BenchmarkReportWriteError,
  732. match="invalid benchmark report timestamp",
  733. ):
  734. reporting.write_benchmark_report(
  735. _marker_report("invalid-timestamp"),
  736. output_dir,
  737. timestamp=timestamp,
  738. )
  739. entries_after = sorted(
  740. path.relative_to(tmp_path) for path in tmp_path.rglob("*")
  741. )
  742. assert entries_after == entries_before
  743. assert not output_dir.exists()
  744. def test_report_files_and_bundle_directory_are_fsynced_before_publication(
  745. tmp_path: Path,
  746. monkeypatch: pytest.MonkeyPatch,
  747. ):
  748. reporting = _reporting_module()
  749. real_fsync = reporting.os.fsync
  750. real_symlink = reporting.os.symlink
  751. fsynced_objects: list[tuple[int, int]] = []
  752. symlink_calls = 0
  753. def record_fsync(file_descriptor: int) -> None:
  754. file_stat = reporting.os.fstat(file_descriptor)
  755. fsynced_objects.append((file_stat.st_dev, file_stat.st_ino))
  756. real_fsync(file_descriptor)
  757. def inspect_before_symlink(source: str, destination: Path) -> None:
  758. nonlocal symlink_calls
  759. symlink_calls += 1
  760. destination = Path(destination)
  761. bundle_dir = destination.parent / source
  762. expected_before_publication = {
  763. (
  764. bundle_dir.joinpath(name).stat().st_dev,
  765. bundle_dir.joinpath(name).stat().st_ino,
  766. )
  767. for name in ("report.json", "report.md")
  768. }
  769. bundle_stat = bundle_dir.stat()
  770. expected_before_publication.add((bundle_stat.st_dev, bundle_stat.st_ino))
  771. assert set(fsynced_objects) == expected_before_publication
  772. assert len(fsynced_objects) == 3
  773. real_symlink(source, destination)
  774. monkeypatch.setattr(reporting.os, "fsync", record_fsync)
  775. monkeypatch.setattr(reporting.os, "symlink", inspect_before_symlink)
  776. reporting.write_benchmark_report(
  777. _marker_report("fsync-before-publish"),
  778. tmp_path,
  779. timestamp="20260714T011225Z",
  780. )
  781. assert symlink_calls == 1
  782. output_stat = tmp_path.stat()
  783. assert (output_stat.st_dev, output_stat.st_ino) in fsynced_objects
  784. assert len(fsynced_objects) == 4
  785. assert len(set(fsynced_objects)) == 4
  786. _assert_no_publication_artifacts(tmp_path)
  787. def test_file_write_failure_removes_only_unpublished_private_bundle(
  788. tmp_path: Path,
  789. monkeypatch: pytest.MonkeyPatch,
  790. ):
  791. reporting = _reporting_module()
  792. original_write_text = reporting._write_text
  793. write_calls = 0
  794. def fail_second_file(path: Path, content: str) -> None:
  795. nonlocal write_calls
  796. write_calls += 1
  797. if write_calls == 2:
  798. raise OSError("simulated report file failure")
  799. original_write_text(path, content)
  800. monkeypatch.setattr(reporting, "_write_text", fail_second_file)
  801. with pytest.raises(
  802. reporting.BenchmarkReportWriteError,
  803. match="failed to write benchmark reports",
  804. ):
  805. reporting.write_benchmark_report(
  806. _marker_report("file-write-failure"),
  807. tmp_path,
  808. timestamp="20260714T011226Z",
  809. )
  810. assert list(tmp_path.iterdir()) == []
  811. def test_bundle_fsync_failure_removes_unpublished_private_bundle(
  812. tmp_path: Path,
  813. monkeypatch: pytest.MonkeyPatch,
  814. ):
  815. reporting = _reporting_module()
  816. original_fsync_directory = reporting._fsync_directory
  817. def fail_bundle_fsync(path: Path) -> None:
  818. if path.name.endswith(".bundle"):
  819. raise OSError("simulated bundle fsync failure")
  820. original_fsync_directory(path)
  821. monkeypatch.setattr(reporting, "_fsync_directory", fail_bundle_fsync)
  822. with pytest.raises(
  823. reporting.BenchmarkReportWriteError,
  824. match="failed to write benchmark reports",
  825. ):
  826. reporting.write_benchmark_report(
  827. _marker_report("bundle-fsync-failure"),
  828. tmp_path,
  829. timestamp="20260714T011227Z",
  830. )
  831. assert list(tmp_path.iterdir()) == []
  832. def test_symlink_failure_after_publication_start_keeps_complete_private_bundle(
  833. tmp_path: Path,
  834. monkeypatch: pytest.MonkeyPatch,
  835. ):
  836. reporting = _reporting_module()
  837. def fail_symlink(source: str, destination: Path) -> None:
  838. del source, destination
  839. raise OSError("simulated symlink failure")
  840. monkeypatch.setattr(reporting.os, "symlink", fail_symlink)
  841. with pytest.raises(
  842. reporting.BenchmarkReportWriteError,
  843. match="failed to write benchmark reports",
  844. ):
  845. reporting.write_benchmark_report(
  846. _marker_report("symlink-failure"),
  847. tmp_path,
  848. timestamp="20260714T011228Z",
  849. )
  850. entries = list(tmp_path.iterdir())
  851. assert len(entries) == 1
  852. bundle_dir = entries[0]
  853. assert bundle_dir.name.startswith(".20260714T011228Z.")
  854. assert bundle_dir.name.endswith(".bundle")
  855. assert json.loads(bundle_dir.joinpath("report.json").read_text())["target"][
  856. "model"
  857. ] == "symlink-failure"
  858. assert "- Model: `symlink-failure`" in bundle_dir.joinpath(
  859. "report.md"
  860. ).read_text()
  861. def test_symlink_interrupt_after_publication_start_keeps_private_bundle(
  862. tmp_path: Path,
  863. monkeypatch: pytest.MonkeyPatch,
  864. ):
  865. reporting = _reporting_module()
  866. def interrupt_symlink(source: str, destination: Path) -> None:
  867. del source, destination
  868. raise KeyboardInterrupt
  869. monkeypatch.setattr(reporting.os, "symlink", interrupt_symlink)
  870. with pytest.raises(KeyboardInterrupt):
  871. reporting.write_benchmark_report(
  872. _marker_report("symlink-interrupt"),
  873. tmp_path,
  874. timestamp="20260714T011229Z",
  875. )
  876. entries = list(tmp_path.iterdir())
  877. assert len(entries) == 1
  878. bundle_dir = entries[0]
  879. assert bundle_dir.name.startswith(".20260714T011229Z.")
  880. assert bundle_dir.name.endswith(".bundle")
  881. assert json.loads(bundle_dir.joinpath("report.json").read_text())["target"][
  882. "model"
  883. ] == "symlink-interrupt"
  884. assert "- Model: `symlink-interrupt`" in bundle_dir.joinpath(
  885. "report.md"
  886. ).read_text()
  887. def test_post_publication_directory_fsync_failure_keeps_public_bundle(
  888. tmp_path: Path,
  889. monkeypatch: pytest.MonkeyPatch,
  890. ):
  891. reporting = _reporting_module()
  892. original_fsync_directory = reporting._fsync_directory
  893. fsync_calls = 0
  894. def fail_output_directory_fsync(path: Path) -> None:
  895. nonlocal fsync_calls
  896. fsync_calls += 1
  897. if fsync_calls == 2:
  898. raise OSError("simulated output directory fsync failure")
  899. original_fsync_directory(path)
  900. monkeypatch.setattr(
  901. reporting,
  902. "_fsync_directory",
  903. fail_output_directory_fsync,
  904. )
  905. with pytest.raises(
  906. reporting.BenchmarkReportWriteError,
  907. match="failed to write benchmark reports",
  908. ):
  909. reporting.write_benchmark_report(
  910. _marker_report("published-before-fsync-failure"),
  911. tmp_path,
  912. timestamp="20260714T011230Z",
  913. )
  914. published_dir = tmp_path / "20260714T011230Z"
  915. assert published_dir.is_symlink()
  916. assert (
  917. json.loads(published_dir.joinpath("report.json").read_text())["target"]["model"]
  918. == "published-before-fsync-failure"
  919. )
  920. assert "- Model: `published-before-fsync-failure`" in (
  921. published_dir.joinpath("report.md").read_text()
  922. )
  923. _assert_no_publication_artifacts(tmp_path)
  924. @pytest.mark.parametrize("stress_round", range(3))
  925. def test_concurrent_thread_writers_publish_distinct_matching_bundles(
  926. tmp_path: Path,
  927. monkeypatch: pytest.MonkeyPatch,
  928. stress_round: int,
  929. ):
  930. reporting = _reporting_module()
  931. writer_count = 8
  932. markers = [
  933. f"thread-{stress_round}-writer-{index}"
  934. for index in range(writer_count)
  935. ]
  936. first_file_barrier = threading.Barrier(writer_count, timeout=15)
  937. original_write_text = reporting._write_text
  938. thread_state = threading.local()
  939. def synchronized_write(path: Path, content: str) -> None:
  940. original_write_text(path, content)
  941. if not getattr(thread_state, "first_write_done", False):
  942. thread_state.first_write_done = True
  943. first_file_barrier.wait()
  944. monkeypatch.setattr(reporting, "_write_text", synchronized_write)
  945. with ThreadPoolExecutor(max_workers=writer_count) as executor:
  946. results = list(
  947. executor.map(
  948. lambda marker: reporting.write_benchmark_report(
  949. _marker_report(marker),
  950. tmp_path,
  951. timestamp=f"20260714T02030{stress_round}Z",
  952. ),
  953. markers,
  954. )
  955. )
  956. assert len({json_path.parent for json_path, _ in results}) == writer_count
  957. assert all(
  958. json_path.parent == markdown_path.parent
  959. for json_path, markdown_path in results
  960. )
  961. _assert_concurrent_report_pairs(tmp_path, markers)
  962. @pytest.mark.parametrize("stress_round", range(2))
  963. def test_concurrent_process_writers_publish_distinct_matching_bundles(
  964. tmp_path: Path,
  965. stress_round: int,
  966. ):
  967. context = multiprocessing.get_context("spawn")
  968. writer_count = 4
  969. markers = [
  970. f"process-{stress_round}-writer-{index}"
  971. for index in range(writer_count)
  972. ]
  973. first_file_barrier = context.Barrier(writer_count, timeout=20)
  974. result_queue = context.Queue()
  975. processes = [
  976. context.Process(
  977. target=_process_report_writer,
  978. args=(
  979. str(tmp_path),
  980. marker,
  981. f"20260714T03040{stress_round}Z",
  982. first_file_barrier,
  983. result_queue,
  984. ),
  985. )
  986. for marker in markers
  987. ]
  988. for process in processes:
  989. process.start()
  990. results = [result_queue.get(timeout=30) for _ in processes]
  991. for process in processes:
  992. process.join(timeout=30)
  993. assert all(process.exitcode == 0 for process in processes)
  994. assert all(result[0] == "ok" for result in results), results
  995. assert all(result[2] == result[3] for result in results)
  996. assert len({result[2] for result in results}) == writer_count
  997. _assert_concurrent_report_pairs(tmp_path, markers)