-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathrunner.py
More file actions
2910 lines (2729 loc) · 112 KB
/
runner.py
File metadata and controls
2910 lines (2729 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import json
import math
import os
import shlex
import subprocess
import sys
import time
from dataclasses import asdict
from datetime import UTC, datetime
from itertools import product
from pathlib import Path
from typing import Any
from uuid import uuid4
from .adapters import (
HERMES_SANDBOX_UNAVAILABLE_REASON,
HYPERLIQUID_LIVE_UNAVAILABLE_REASON,
OSWORLD_DOCKER_UNAVAILABLE_REASON,
SWE_BENCH_DOCKER_UNAVAILABLE_REASON,
TERMINAL_BENCH_DOCKER_UNAVAILABLE_REASON,
VISION_LANGUAGE_FIXED_RUNTIME_REASON,
VISION_LANGUAGE_HARNESS_RUNTIME_UNAVAILABLE_REASON,
VISION_LANGUAGE_REAL_INPUTS_UNAVAILABLE_REASON,
discover_adapters,
)
from .db import (
connect_database,
create_run_group,
finish_run_group,
get_latest_run_for_signature,
get_latest_succeeded_run_for_signature,
initialize_database,
insert_run_start,
list_runs,
next_attempt_for_signature,
recover_stale_running_runs,
repair_nonzero_returncode_statuses,
repair_nonpublishable_success_statuses,
replace_run_trajectories,
update_run_result,
)
from .env_utils import git_head, load_env_file, merged_environment, safe_version_from_package_json
from .leaderboard import delta_to_high_score
from .analyze_trajectory import summarize as summarize_trajectory
from .random_baseline_runner import (
CALIBRATION_HARNESSES,
CALIBRATION_SPEC_VERSION,
SYNTHETIC_HARNESSES,
is_synthetic_harness,
run_synthetic_baseline,
)
from .trajectory_normalize_hook import normalize_outcome_trajectories
from .types import (
BenchmarkAdapter,
BenchmarkRunOutcome,
ExecutionContext,
LeaderboardComparison,
RunRequest,
)
PROVIDER_KEY_ENV: dict[str, str] = {
"openai": "OPENAI_API_KEY",
"groq": "GROQ_API_KEY",
"openrouter": "OPENROUTER_API_KEY",
"anthropic": "ANTHROPIC_API_KEY",
"google": "GOOGLE_API_KEY",
"vllm": "VLLM_API_KEY",
"cerebras": "CEREBRAS_API_KEY",
}
OPENAI_COMPAT_BASE_URL: dict[str, str] = {
"groq": "https://api.groq.com/openai/v1",
"openrouter": "https://openrouter.ai/api/v1",
"vllm": "http://127.0.0.1:8001/v1",
"cerebras": "https://api.cerebras.ai/v1",
}
# Providers whose API key has no real secret value (self-hosted endpoints).
PROVIDER_DUMMY_KEY: dict[str, str] = {
"vllm": "dummy",
}
DEFAULT_STALE_RECOVERY_SECONDS = 6 * 60 * 60
LATEST_COMPARABLE_SCORE_TOLERANCE = 0.15
CANONICAL_REAL_HARNESSES: tuple[str, ...] = ("eliza", "hermes", "openclaw")
LATEST_SNAPSHOT_AGENTS: set[str] = {
*CANONICAL_REAL_HARNESSES,
*SYNTHETIC_HARNESSES,
"compare",
}
def _utc_now() -> str:
return datetime.now(UTC).isoformat()
def _sanitize_name(value: str) -> str:
cleaned = "".join(ch if ch.isalnum() or ch in {"-", "_", "."} else "-" for ch in value.strip().lower())
cleaned = cleaned.strip("-")
return cleaned or "item"
def _signature_for(adapter: BenchmarkAdapter, request: RunRequest) -> str:
extra_config = dict(request.extra_config)
if request.agent.strip().lower() in CALIBRATION_HARNESSES:
extra_config["calibration_spec_version"] = CALIBRATION_SPEC_VERSION
payload = {
"benchmark_id": adapter.id,
"benchmark_directory": adapter.directory,
"agent": request.agent,
"provider": request.provider,
"model": request.model,
"extra_config": extra_config,
}
return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")).hexdigest()
def _comparison_signature_for(adapter: BenchmarkAdapter, request: RunRequest) -> str:
"""Hash the benchmark/model/config shape without the harness label.
``signature`` intentionally includes ``request.agent`` so resume/idempotency
stays per-harness. For apples-to-apples reporting we also need a stable
grouping key that lets the latest index line up Eliza, Hermes, and OpenClaw
runs using the same benchmark configuration.
"""
return _comparison_signature_from_parts(
benchmark_id=adapter.id,
benchmark_directory=adapter.directory,
agent=request.agent,
provider=request.provider,
model=request.model,
extra_config=request.extra_config,
)
def _comparison_signature_from_parts(
*,
benchmark_id: str,
benchmark_directory: str,
agent: str,
provider: str,
model: str,
extra_config: dict[str, Any] | None,
) -> str:
normalized_extra = _comparison_extra_config(extra_config, agent=agent)
payload = {
"benchmark_id": benchmark_id,
"benchmark_directory": benchmark_directory,
"provider": provider,
"model": model,
"extra_config": normalized_extra,
}
return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8")).hexdigest()
def _comparison_extra_config(
extra_config: dict[str, Any] | None,
*,
agent: str,
) -> dict[str, Any]:
normalized_extra = dict(extra_config or {})
injected_agent = str(normalized_extra.get("agent") or "").strip().lower()
injected_harness = str(normalized_extra.get("harness") or "").strip().lower()
comparable_agents = set(LATEST_SNAPSHOT_AGENTS) | set(SYNTHETIC_HARNESSES)
if injected_agent in comparable_agents:
normalized_extra.pop("agent", None)
if injected_harness in comparable_agents:
normalized_extra.pop("harness", None)
for runtime_key in (
"eliza_bench_http_timeout_s",
"openclaw_timeout_s",
"timeout_s",
):
normalized_extra.pop(runtime_key, None)
if str(normalized_extra.get("reasoning_effort") or "").strip().lower() == "low":
normalized_extra.pop("reasoning_effort", None)
dataset = str(normalized_extra.get("dataset") or "").strip()
suite = str(normalized_extra.get("suite") or "").strip()
if dataset and suite and dataset == suite:
normalized_extra.pop("dataset", None)
if agent.strip().lower() in CALIBRATION_HARNESSES:
normalized_extra["calibration_spec_version"] = CALIBRATION_SPEC_VERSION
return normalized_extra
def _comparison_signature_for_row(
row: dict[str, Any],
*,
benchmark_id: str,
agent: str,
) -> str:
existing = row.get("comparison_signature")
if isinstance(existing, str) and existing.strip():
return existing.strip()
return _comparison_signature_from_parts(
benchmark_id=benchmark_id,
benchmark_directory=str(row.get("benchmark_directory") or benchmark_id),
agent=agent,
provider=str(row.get("provider") or ""),
model=str(row.get("model") or ""),
extra_config=row.get("extra_config")
if isinstance(row.get("extra_config"), dict)
else {},
)
def _effective_request(adapter: BenchmarkAdapter, request: RunRequest) -> RunRequest:
request_extra = dict(request.extra_config)
per_benchmark = request_extra.pop("per_benchmark", None)
per_benchmark_extra: dict[str, Any] = {}
if isinstance(per_benchmark, dict):
adapter_specific = per_benchmark.get(adapter.id)
if isinstance(adapter_specific, dict):
per_benchmark_extra = dict(adapter_specific)
merged_extra = dict(adapter.default_extra_config)
merged_extra.update(per_benchmark_extra)
merged_extra.update(request_extra)
explicit_agent = "agent" in per_benchmark_extra or "agent" in request_extra
agent_label = request.agent.strip()
if agent_label and not explicit_agent and agent_label != "compare":
merged_extra["agent"] = agent_label
if (
adapter.id == "trust"
and agent_label.lower() in {"eliza", "hermes", "openclaw"}
and "handler" not in per_benchmark_extra
and "handler" not in request_extra
):
merged_extra["handler"] = "eliza"
if agent_label:
merged_extra.setdefault("harness", agent_label)
return RunRequest(
benchmarks=request.benchmarks,
agent=request.agent,
provider=request.provider,
model=request.model,
extra_config=merged_extra,
resume=request.resume,
rerun_failed=request.rerun_failed,
force=request.force,
)
def _is_harness_compatible(adapter: BenchmarkAdapter, harness_label: str) -> bool:
if not harness_label or is_synthetic_harness(harness_label):
return True
if harness_label == "compare":
# Model/provider compare is valid for normal multi-harness adapters,
# but not for adapters that run a single concrete implementation under
# the hood.
return len(adapter.agent_compatibility) > 1
return harness_label in adapter.agent_compatibility
def _result_subdir(run_root: Path, adapter: BenchmarkAdapter, run_id: str) -> Path:
return run_root / f"{_sanitize_name(adapter.directory)}__{_sanitize_name(adapter.id)}" / run_id
def _provider_model_name(provider: str, model: str) -> str:
provider = provider.strip().lower()
model = model.strip()
if provider == "cerebras" and model.startswith("openai/"):
return model.split("/", 1)[1]
return model
def _default_env(workspace_root: Path, request: RunRequest) -> dict[str, str]:
env = dict(os.environ)
load_env_file(workspace_root / "eliza" / ".env")
load_env_file(workspace_root / ".env")
load_env_file(workspace_root.parent / ".env")
load_env_file(workspace_root.parent.parent / ".env")
env = dict(os.environ)
python_bin = str(Path(sys.executable).parent)
path_entries = [python_bin]
for candidate in (
Path.home() / ".bun" / "bin",
Path("/opt/homebrew/bin"),
Path("/usr/local/bin"),
):
if candidate.exists():
path_entries.append(str(candidate))
existing_path = env.get("PATH", "")
if existing_path:
path_entries.append(existing_path)
env["PATH"] = os.pathsep.join(path_entries)
env["PYTHONUNBUFFERED"] = "1"
env["PIP_DISABLE_PIP_VERSION_CHECK"] = "1"
plugin_python_paths: list[str] = []
plugins_root = workspace_root / "plugins"
if plugins_root.exists():
for candidate in sorted(plugins_root.glob("*/python")):
if candidate.is_dir():
plugin_python_paths.append(str(candidate))
benchmarks_root = workspace_root / "benchmarks"
adapter_python_paths = [
str((benchmarks_root / "eliza-adapter").resolve()),
str((benchmarks_root / "hermes-adapter").resolve()),
str((benchmarks_root / "openclaw-adapter").resolve()),
]
workspace_python = [
str(workspace_root),
str(workspace_root / "eliza" / "packages" / "python"),
*adapter_python_paths,
*plugin_python_paths,
]
existing_pythonpath = env.get("PYTHONPATH", "")
env["PYTHONPATH"] = (
os.pathsep.join(workspace_python + [existing_pythonpath])
if existing_pythonpath
else os.pathsep.join(workspace_python)
)
provider = request.provider.strip().lower()
model_name = _provider_model_name(provider, request.model)
harness = request.agent.strip().lower() or "eliza"
env["BENCHMARK_MODEL_PROVIDER"] = provider or request.provider
env["BENCHMARK_MODEL_NAME"] = model_name
env["BENCHMARK_HARNESS"] = harness
env["ELIZA_BENCH_HARNESS"] = harness
env["BENCHMARK_AGENT"] = harness
env["ELIZA_PROVIDER"] = provider or request.provider
env["MODEL_NAME"] = model_name
env["OPENAI_MODEL"] = model_name
env["ANTHROPIC_MODEL"] = model_name
env["OPENAI_LARGE_MODEL"] = model_name
env["OPENAI_SMALL_MODEL"] = model_name
env["GROQ_LARGE_MODEL"] = model_name
env["GROQ_SMALL_MODEL"] = model_name
env["OPENROUTER_LARGE_MODEL"] = model_name
env["OPENROUTER_SMALL_MODEL"] = model_name
env["CEREBRAS_MODEL"] = model_name
env["CEREBRAS_LARGE_MODEL"] = model_name
env["CEREBRAS_SMALL_MODEL"] = model_name
reasoning_effort = request.extra_config.get("reasoning_effort")
if isinstance(reasoning_effort, str) and reasoning_effort.strip():
# Model profiles carry provider-neutral extra config. Mirror the
# reasoning knob into the env names consumed by the TS OpenAI-compatible
# provider and Cerebras-specific benchmark clients.
env["OPENAI_REASONING_EFFORT"] = reasoning_effort.strip()
env["CEREBRAS_REASONING_EFFORT"] = reasoning_effort.strip()
env.setdefault("ELIZA_CONVERSATION_COMPACTOR", "structured-state")
env.setdefault("MAX_CONVERSATION_TOKENS", "120000")
env.setdefault("BENCHMARK_CAPTURE_TRAJECTORIES", "1")
if harness == "eliza" and request.extra_config.get("allow_stub_embedding") is True:
# Diagnostic-only opt-in. Release-evidence runs use the real embedding
# handler from plugin-local-inference and must not silently publish
# zero-vector memory behavior.
env.setdefault("ELIZA_BENCH_ALLOW_STUB_EMBEDDING", "1")
if provider in PROVIDER_DUMMY_KEY:
provider_key = PROVIDER_KEY_ENV.get(provider)
if provider_key and not env.get(provider_key):
env[provider_key] = PROVIDER_DUMMY_KEY[provider]
if provider in OPENAI_COMPAT_BASE_URL:
provider_key = PROVIDER_KEY_ENV.get(provider)
if provider_key and env.get(provider_key):
env["OPENAI_API_KEY"] = env[provider_key]
base_url_override = (
request.extra_config.get("vllm_base_url")
if provider == "vllm"
else None
)
if isinstance(base_url_override, str) and base_url_override.strip():
env["OPENAI_BASE_URL"] = base_url_override.strip()
env["VLLM_BASE_URL"] = base_url_override.strip()
elif provider == "vllm" and env.get("VLLM_BASE_URL"):
env["OPENAI_BASE_URL"] = env["VLLM_BASE_URL"]
else:
env["OPENAI_BASE_URL"] = OPENAI_COMPAT_BASE_URL[provider]
if provider == "cerebras":
env["CEREBRAS_BASE_URL"] = env["OPENAI_BASE_URL"]
return env
def _repo_meta(workspace_root: Path) -> dict[str, str | None]:
benchmarks_root = workspace_root / "benchmarks"
eliza_root = workspace_root / "eliza"
return {
"benchmarks_commit": git_head(benchmarks_root),
"eliza_commit": git_head(eliza_root),
"eliza_version": safe_version_from_package_json(eliza_root / "package.json"),
"benchmarks_version": safe_version_from_package_json(benchmarks_root / "package.json"),
}
def _adapter_version_from_pyproject(adapter_root: Path) -> str | None:
try:
pyproject = (adapter_root / "pyproject.toml").read_text(encoding="utf-8")
except OSError:
return None
for line in pyproject.splitlines():
stripped = line.strip()
if stripped.startswith("version") and "=" in stripped:
_, _, raw = stripped.partition("=")
return raw.strip().strip('"').strip("'")
return None
def _build_reproducibility_metadata(
*,
workspace_root: Path,
request: RunRequest,
repo_meta: dict[str, str | None],
) -> dict[str, Any]:
"""Persist enough metadata that an old result can be re-run.
Fields:
``cli_argv`` — process argv at orchestrator start.
``extra_config`` — request.extra_config dict (preserved verbatim).
``harness_commit_sha`` — ``git rev-parse HEAD`` of the workspace.
``dataset_revision`` — adapter-specific (TODO; ``None`` for now).
``adapter_versions`` — version strings of each in-repo adapter.
``seed`` / ``temperature`` — from extra_config or env.
``provider`` / ``model`` — already required.
"""
benchmarks_root = workspace_root / "benchmarks"
try:
harness_commit = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=str(workspace_root),
capture_output=True,
text=True,
timeout=5,
check=False,
).stdout.strip() or None
except (OSError, subprocess.SubprocessError):
harness_commit = None
extra_config = dict(request.extra_config) if request.extra_config else {}
seed = extra_config.get("seed")
temperature = extra_config.get("temperature")
if temperature is None:
try:
temperature = float(os.environ.get("BENCHMARK_TEMPERATURE", "")) if os.environ.get("BENCHMARK_TEMPERATURE") else None
except ValueError:
temperature = None
return {
"cli_argv": list(sys.argv),
"extra_config": extra_config,
"harness_commit_sha": harness_commit,
"benchmarks_commit_sha": repo_meta.get("benchmarks_commit"),
"eliza_commit_sha": repo_meta.get("eliza_commit"),
# TODO: each adapter should expose its own dataset revision (e.g.
# SWE-bench dataset version, hermes-tblite checkpoint). For now we
# record ``None`` rather than fabricate.
"dataset_revision": None,
"adapter_versions": {
"eliza": _adapter_version_from_pyproject(benchmarks_root / "eliza-adapter"),
"hermes": _adapter_version_from_pyproject(benchmarks_root / "hermes-adapter"),
"openclaw": _adapter_version_from_pyproject(benchmarks_root / "openclaw-adapter"),
},
"seed": seed,
"temperature": temperature,
"provider": request.provider,
"model": request.model,
}
def _status_after_returncode(returncode: int) -> str:
return "succeeded" if returncode == 0 else "failed"
def _required_env_for_request(adapter: BenchmarkAdapter, request: RunRequest) -> tuple[str, ...]:
if adapter.id == "lifeops_bench":
extra = request.extra_config
agent = str(
extra.get("agent")
or extra.get("harness")
or request.model
or ""
).strip().lower()
mode = str(extra.get("mode") or "").strip().lower()
if agent in {"perfect", "wrong"} and mode != "live":
return ()
if mode == "live":
return ("CEREBRAS_API_KEY", "ANTHROPIC_API_KEY")
provider_key = PROVIDER_KEY_ENV.get(request.provider.strip().lower())
if agent in {"eliza", "hermes", "openclaw", "cerebras-direct"}:
return (provider_key or "CEREBRAS_API_KEY",)
return ()
if adapter.id == "voicebench_quality":
stt_provider = str(
request.extra_config.get("stt_provider")
or os.environ.get("VOICEBENCH_QUALITY_STT_PROVIDER")
or os.environ.get("VOICEBENCH_STT_PROVIDER")
or "groq"
).strip().lower()
required = ["CEREBRAS_API_KEY"]
if stt_provider == "groq":
required.append("GROQ_API_KEY")
elif stt_provider == "eliza-runtime":
required.append("ELIZA_BENCH_URL" if os.environ.get("ELIZA_BENCH_URL") else "ELIZA_API_BASE")
return tuple(required)
if adapter.id == "hyperliquid_bench":
required = list(adapter.required_env)
if "HL_PRIVATE_KEY" not in required:
required.append("HL_PRIVATE_KEY")
provider_key = PROVIDER_KEY_ENV.get(request.provider.strip().lower())
if provider_key:
required = [key for key in required if key not in PROVIDER_KEY_ENV.values()]
required.append(provider_key)
seen: set[str] = set()
deduped: list[str] = []
for key in required:
if key in seen:
continue
seen.add(key)
deduped.append(key)
return tuple(deduped)
provider = request.provider.strip().lower()
required = list(adapter.required_env)
provider_key = PROVIDER_KEY_ENV.get(provider)
if provider_key:
required = [key for key in required if key not in PROVIDER_KEY_ENV.values()]
required.append(provider_key)
seen: set[str] = set()
deduped: list[str] = []
for key in required:
if key in seen:
continue
seen.add(key)
deduped.append(key)
return tuple(deduped)
def _ensure_viewer_snapshot(
conn,
*,
workspace_root: Path,
benchmark_ids: set[str] | None = None,
) -> Path:
from .viewer_data import build_viewer_dataset
data = build_viewer_dataset(conn, benchmark_ids=benchmark_ids)
out = workspace_root / "benchmarks" / "benchmark_results" / "viewer_data.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(data, indent=2, ensure_ascii=True), encoding="utf-8")
return out
def _collect_run_trajectory_metrics(run_root: Path, *, duration_seconds: float) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any], dict[str, Any], list[dict[str, Any]]]:
summary, records = summarize_trajectory(run_root)
has_real_prompt = summary.prompt_tokens > 0
has_real_completion = summary.completion_tokens > 0
has_real_total = summary.total_tokens > 0
prompt_tokens: int | None = summary.prompt_tokens if has_real_prompt else None
completion_tokens: int | None = summary.completion_tokens if has_real_completion else None
if has_real_total:
total_tokens: int | None = summary.total_tokens
elif has_real_prompt or has_real_completion:
total_tokens = (prompt_tokens or 0) + (completion_tokens or 0)
else:
total_tokens = None
llm_call_count: int | None = summary.turns if summary.turns else None
telemetry_missing = total_tokens in (None, 0) or llm_call_count in (None, 0)
trajectory_summary = {
"files": summary.files,
"turns": summary.turns,
"prompt_chars": summary.prompt_chars,
"repeated_prefixes": [
{"snippet": snippet, "count": count}
for snippet, count in summary.repeated_prefixes
],
}
token_metrics: dict[str, Any] = {
"llm_call_count": llm_call_count,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
"cached_tokens": summary.cached_tokens,
"avg_prompt_tokens": (prompt_tokens / summary.turns) if (prompt_tokens and summary.turns) else None,
"avg_completion_tokens": (completion_tokens / summary.turns) if (completion_tokens and summary.turns) else None,
"telemetry_missing": telemetry_missing,
}
cache_metrics = {
"cache_read_input_tokens": summary.cached_tokens,
"cache_creation_input_tokens": summary.cache_creation_tokens,
"turns_with_cached_field": summary.turns_with_cached_field,
"cache_hit_ratio": summary.cache_hit_ratio,
}
throughput = (summary.turns / duration_seconds) if duration_seconds > 0 else None
performance_metrics = {
"duration_seconds": duration_seconds,
"mean_latency_ms": summary.mean_latency_ms,
"p95_latency_ms": summary.p95_latency_ms,
"throughput_per_second": throughput,
}
trajectory_rows = [
{
"trajectory_file": record.file,
"turn_index": record.index,
"prompt_tokens": record.tokens.prompt,
"completion_tokens": record.tokens.completion,
"total_tokens": record.tokens.total or (record.tokens.prompt + record.tokens.completion),
"cached_tokens": record.tokens.cached,
"cache_creation_tokens": record.tokens.cache_creation,
"latency_ms": record.latency_ms,
"prompt_chars": len(record.prompt_text),
}
for record in records
]
token_metrics = _complete_token_metrics(
token_metrics,
trajectory_summary=trajectory_summary,
result_json_path=None,
)
return trajectory_summary, token_metrics, cache_metrics, performance_metrics, trajectory_rows
def _estimated_tokens_from_chars(chars: Any) -> int:
if isinstance(chars, bool) or not isinstance(chars, (int, float)) or chars <= 0:
return 0
return int(math.ceil(float(chars) / 4.0))
def _sum_result_generated_tokens(value: Any) -> int:
if isinstance(value, dict):
total = 0
for key, item in value.items():
if key in {"tokens_generated", "generated_tokens"} and isinstance(item, (int, float)) and not isinstance(item, bool):
total += int(item)
else:
total += _sum_result_generated_tokens(item)
return total
if isinstance(value, list):
return sum(_sum_result_generated_tokens(item) for item in value)
return 0
def _result_generated_token_estimate(result_json_path: Any) -> int:
if not result_json_path:
return 0
path = Path(str(result_json_path))
try:
payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return 0
return _sum_result_generated_tokens(payload)
def _complete_token_metrics(
token_metrics: dict[str, Any] | None,
*,
trajectory_summary: dict[str, Any] | None,
result_json_path: Any,
) -> dict[str, Any]:
"""Return numeric token metrics, using explicit estimates when telemetry is absent."""
tokens = dict(token_metrics or {})
summary = trajectory_summary or {}
prompt = tokens.get("prompt_tokens")
completion = tokens.get("completion_tokens")
total = tokens.get("total_tokens")
calls = tokens.get("llm_call_count")
cached = tokens.get("cached_tokens", tokens.get("cache_read_input_tokens"))
turns = summary.get("turns")
prompt_chars = summary.get("prompt_chars")
source: str | None = tokens.get("token_estimate_source")
if not isinstance(calls, (int, float)) or isinstance(calls, bool):
calls = turns if isinstance(turns, (int, float)) and not isinstance(turns, bool) else 0
calls = int(calls)
if not isinstance(prompt, (int, float)) or isinstance(prompt, bool):
prompt = _estimated_tokens_from_chars(prompt_chars)
if prompt:
source = source or "prompt_chars_div_4"
tokens["estimated_prompt_tokens"] = prompt
else:
prompt = 0
if not isinstance(completion, (int, float)) or isinstance(completion, bool):
generated = _result_generated_token_estimate(result_json_path)
if generated:
completion = generated
source = source or "result_tokens_generated"
tokens["estimated_completion_tokens"] = completion
elif isinstance(total, (int, float)) and not isinstance(total, bool):
completion = max(0, int(total) - int(prompt))
else:
completion = 0
if not isinstance(total, (int, float)) or isinstance(total, bool) or int(total) < int(prompt) + int(completion):
total = int(prompt) + int(completion)
if source is not None:
tokens["estimated_total_tokens"] = total
if not isinstance(cached, (int, float)) or isinstance(cached, bool):
cached = 0
tokens["llm_call_count"] = calls
tokens["call_count"] = calls
tokens["prompt_tokens"] = int(prompt)
tokens["input_tokens"] = int(prompt)
tokens["completion_tokens"] = int(completion)
tokens["output_tokens"] = int(completion)
tokens["total_tokens"] = int(total)
tokens["cached_tokens"] = int(cached)
tokens["avg_prompt_tokens"] = (int(prompt) / calls) if calls else 0
tokens["avg_completion_tokens"] = (int(completion) / calls) if calls else 0
tokens["telemetry_missing"] = source is not None or int(total) <= 0 or calls <= 0
if source is not None:
tokens["token_estimate_source"] = source
return tokens
SYNTHETIC_AGENT_SUFFIX = "_v1"
SYNTHETIC_AGENT_SET: set[str] = set(SYNTHETIC_HARNESSES)
def _is_synthetic_agent(agent: str) -> bool:
agent_lc = agent.strip().lower()
if agent_lc in SYNTHETIC_AGENT_SET:
return True
return agent_lc.endswith(SYNTHETIC_AGENT_SUFFIX)
def _is_numeric_score(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool)
def _publication_quarantine_reason(
*,
status: str,
agent: str,
score: Any,
token_metrics: dict[str, Any] | None,
metrics: dict[str, Any],
) -> str | None:
"""Return ``None`` if the result is publishable; otherwise a reason string.
``latest/`` is the source of truth for the most recent successful real
benchmark result. Telemetry and sample-size weaknesses are recorded as
publication warnings, not quarantine reasons, because hiding successful
rows makes the matrix look missing and breaks idempotent tracking. Explicit
sample/mock datasets are not publishable real-agent results.
"""
del token_metrics
if _is_synthetic_agent(agent):
return None
if status == "incompatible":
return "incompatible_harness"
if status != "succeeded":
return "unsucceeded_run"
if not _is_numeric_score(score):
return "missing_score"
dataset_source = metrics.get("dataset_source")
if metrics.get("sample") is True or (
isinstance(dataset_source, str) and dataset_source.strip().lower() == "sample"
):
return "sample_task_set"
if metrics.get("use_sample_tasks") is True:
return "sample_task_set"
if metrics.get("demo_mode") is True or metrics.get("demoMode") is True:
return "demo_mode"
failed_scenarios = metrics.get("failed_scenarios")
if isinstance(failed_scenarios, (int, float)) and not isinstance(failed_scenarios, bool):
if failed_scenarios > 0:
return "failed_scenarios"
successful_runs = metrics.get("successful_runs")
total_runs = metrics.get("total_runs")
if (
isinstance(total_runs, (int, float))
and not isinstance(total_runs, bool)
and total_runs > 0
and isinstance(successful_runs, (int, float))
and not isinstance(successful_runs, bool)
and successful_runs <= 0
):
return "zero_successful_runs"
if (
score == 0
and metrics.get("avg_net_worth") == 0
and metrics.get("avg_items_sold") == 0
and metrics.get("avg_orders_placed") == 0
and metrics.get("total_revenue") == 0
):
return "no_activity_zero_score"
if metrics.get("interrupted") is True:
return "interrupted_run"
return None
def _publication_warnings(
*,
benchmark_id: str,
status: str,
token_metrics: dict[str, Any] | None,
metrics: dict[str, Any],
) -> list[str]:
if status != "succeeded":
return []
warnings: list[str] = []
tokens = token_metrics or {}
token_telemetry_optional = benchmark_id in {
"configbench",
"eliza_replay",
"evm",
"framework",
"hermes_yc_bench",
"personality_bench",
"social_alpha",
"solana",
"vision_language",
"voiceagentbench",
}
estimate_source = tokens.get("token_estimate_source")
if estimate_source is not None or any(str(key).startswith("estimated_") for key in tokens):
source = str(estimate_source or "unknown")
warnings.append(f"estimated_token_metrics:{source}")
total_tokens = tokens.get("total_tokens")
llm_calls = tokens.get("llm_call_count")
if not token_telemetry_optional and total_tokens in (None, 0):
warnings.append("telemetry_missing_total_tokens")
if not token_telemetry_optional and llm_calls in (None, 0):
warnings.append(f"telemetry_missing_llm_calls:{llm_calls!r}")
elif not token_telemetry_optional and llm_calls == 1:
warnings.append("single_llm_call")
total_instances = metrics.get("total_instances")
if isinstance(total_instances, (int, float)) and total_instances <= 1:
warnings.append(f"insufficient_total_instances:{total_instances!r}")
total_samples = metrics.get("total_samples")
if isinstance(total_samples, (int, float)) and total_samples <= 2:
warnings.append(f"insufficient_total_samples:{total_samples!r}")
total_tasks = metrics.get("total_tasks")
if isinstance(total_tasks, (int, float)) and total_tasks <= 1:
warnings.append(f"insufficient_total_tasks:{total_tasks!r}")
total_questions = metrics.get("total_questions")
if isinstance(total_questions, (int, float)) and total_questions <= 2:
warnings.append(f"insufficient_total_questions:{total_questions!r}")
scenario_count = metrics.get("scenario_count")
if isinstance(scenario_count, (int, float)) and scenario_count <= 1:
warnings.append(f"insufficient_scenario_count:{scenario_count!r}")
n_value = metrics.get("n")
if isinstance(n_value, (int, float)) and n_value <= 2:
warnings.append(f"insufficient_n:{n_value!r}")
dataset_source = metrics.get("dataset_source")
if metrics.get("sample") is True or (
isinstance(dataset_source, str) and dataset_source.strip().lower() == "sample"
):
warnings.append("sample_task_set")
if metrics.get("use_sample_tasks") is True:
warnings.append("sample_task_set")
if metrics.get("demo_mode") is True or metrics.get("demoMode") is True:
warnings.append("demo_mode")
if metrics.get("interrupted") is True:
warnings.append("interrupted_run")
return warnings
_QUARANTINE_TRACKER: dict[Path, list[tuple[str, str, str]]] = {}
def _record_quarantine(output_root: Path, agent: str, benchmark_id: str, reason: str) -> None:
_QUARANTINE_TRACKER.setdefault(output_root, []).append((benchmark_id, agent, reason))
def _pop_quarantine_records(output_root: Path) -> list[tuple[str, str, str]]:
return _QUARANTINE_TRACKER.pop(output_root, [])
def _annotate_latest_index_comparability(index: dict[str, Any]) -> None:
"""Add per-benchmark comparability metadata for latest rows."""
groups: dict[str, dict[str, str | None]] = {}
latest = index.get("latest")
if not isinstance(latest, dict):
index["benchmark_comparability"] = {}
return
for key, entry in latest.items():
if not isinstance(key, str) or "::" not in key or not isinstance(entry, dict):
continue
benchmark_id, agent = key.split("::", 1)
groups.setdefault(benchmark_id, {})[agent] = entry.get("comparison_signature")
index["benchmark_comparability"] = {
benchmark_id: {
"comparable": len({sig for sig in signatures.values() if sig}) <= 1,
"comparison_signatures": signatures,
"agents": sorted(signatures),
}
for benchmark_id, signatures in sorted(groups.items())
}
def _stable_latest_index_updated_at(entries: list[dict[str, Any]]) -> str:
timestamps = [
str(value)
for entry in entries
for value in (
entry.get("updated_at"),
entry.get("ended_at"),
entry.get("started_at"),
)
if value
]
return max(timestamps) if timestamps else _utc_now()
def _write_latest_result_snapshot(
output_root: Path,
*,
adapter: BenchmarkAdapter,
request: RunRequest,
run_group_id: str,
run_id: str,
status: str,
score: float | None,
unit: str | None,
higher_is_better: bool | None,
metrics: dict[str, Any],
trajectory_summary: dict[str, Any] | None = None,
token_metrics: dict[str, Any] | None = None,
cache_metrics: dict[str, Any] | None = None,
performance_metrics: dict[str, Any] | None = None,
result_json_path: str | None = None,
artifacts: list[str] | None = None,
error: str | None = None,
reproducibility: dict[str, Any] | None = None,
signature: str | None = None,
comparison_signature: str | None = None,
adapters: dict[str, BenchmarkAdapter] | None = None,
) -> Path:
"""Route a snapshot to ``latest/`` or ``baselines/``.
Real-agent rows publish to ``latest/`` unless they are structurally
incompatible with the selected harness. Synthetic baselines
(``perfect_v1`` etc.) are always written to ``baselines/`` and never
intermingle with ``latest/``.
"""
agent = request.agent
is_synthetic = _is_synthetic_agent(agent)
quarantine_reason = (
None if is_synthetic
else _publication_quarantine_reason(
status=status,
agent=agent,
score=score,
token_metrics=token_metrics,
metrics=metrics,
)
)
if is_synthetic:
target_dir = output_root / "baselines"
elif quarantine_reason is not None:
target_dir = output_root / "quarantine"
else:
target_dir = output_root / "latest"
publication_warnings = [] if is_synthetic else _publication_warnings(
benchmark_id=adapter.id,
status=status,
token_metrics=token_metrics,
metrics=metrics,
)
target_dir.mkdir(parents=True, exist_ok=True)
snapshot_path = target_dir / f"{_sanitize_name(adapter.id)}__{_sanitize_name(agent)}.json"
payload: dict[str, Any] = {
"updated_at": _utc_now(),
"benchmark_id": adapter.id,
"benchmark_directory": adapter.directory,
"run_group_id": run_group_id,
"run_id": run_id,
"signature": signature,
"comparison_signature": comparison_signature
or _comparison_signature_for(adapter, request),
"status": status,
"agent": agent,
"provider": request.provider,
"model": request.model,
"score": score,
"unit": unit,
"higher_is_better": higher_is_better,
"metrics": metrics,
"trajectory_summary": trajectory_summary or {},
"token_metrics": token_metrics or {},
"cache_metrics": cache_metrics or {},
"performance_metrics": performance_metrics or {},
"result_json_path": result_json_path,
"artifacts": artifacts or [],
"error": error,
"reproducibility": reproducibility or {},
}
if quarantine_reason is not None:
payload["quarantine_reason"] = quarantine_reason
_record_quarantine(output_root, agent, adapter.id, quarantine_reason)
if publication_warnings:
payload["publication_warnings"] = publication_warnings
if is_synthetic:
payload["synthetic"] = True
snapshot_tmp = snapshot_path.with_name(
f"{snapshot_path.name}.{os.getpid()}.{uuid4().hex}.tmp"
)
snapshot_tmp.write_text(
json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=True),
encoding="utf-8",
)
snapshot_tmp.replace(snapshot_path)
# Also prune stale entries from alternate directories. Failed/quarantined