-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevolve.py
More file actions
4799 lines (4115 loc) · 202 KB
/
Copy pathevolve.py
File metadata and controls
4799 lines (4115 loc) · 202 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
#!/usr/bin/env python3
"""
Agentic Harness Engineering: Automated Evolution Evaluation System
Main loop: evaluate -> collect logs -> NexAU analyze & improve -> next iteration
Supports multiple config modes:
1. Single file: --config agentic_harness_engineering_config.yaml
2. Inherited overlay: --config configs/experiments/exp-001-gpt54.yaml (with _base field)
3. Batch parallel: --batch configs/experiments/
"""
import argparse
import collections
import concurrent.futures
import copy
import json
import math
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.request
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
import yaml
from dotenv import load_dotenv
ROOT_DIR = Path(__file__).resolve().parent.parent
PROJECT_DIR = Path(__file__).resolve().parent
EVOLVE_AGENT_DIR = PROJECT_DIR / "agents" / "evolve_agent"
EXPERIMENTS_DIR = PROJECT_DIR / "experiments"
load_dotenv(PROJECT_DIR / ".env", override=True)
_ENV_KEYS = [
"GITHUB_TOKEN", "E2B_API_KEY", "E2B_API_URL", "E2B_DOMAIN",
"LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL",
"LANGFUSE_SECRET_KEY", "LANGFUSE_PUBLIC_KEY", "LANGFUSE_HOST",
"SERPER_API_KEY",
]
print("[env] Loaded .env, current environment variables:")
for k in _ENV_KEYS:
v = os.environ.get(k, "")
if v:
masked = v[:4] + "***" + v[-4:] if len(v) > 10 else "***"
print(f" {k}={masked}")
else:
print(f" {k}=(not set)")
def validate_env_for_config(config: dict) -> None:
"""Validate required environment variables for the configured execution mode.
The LLM keys are always required — the agent cannot run without an LLM.
E2B / GitHub credentials are only relevant in the cloud-sandbox ("e2b")
execution mode; when ``harbor.env`` is "docker" the loop runs entirely on
the local Docker daemon and needs neither. This keeps a fully-local run from
hard-failing on a missing E2B account.
"""
env_mode = config.get("harbor", {}).get("env", "docker")
# LLM keys are mandatory in every mode.
missing_llm = [k for k in ("LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL")
if not os.environ.get(k)]
if missing_llm:
print(f"[env] ERROR: missing required LLM environment variables: "
f"{', '.join(missing_llm)}")
print("[env] the code agent needs a reachable LLM "
"(set LLM_API_KEY / LLM_BASE_URL / LLM_MODEL in .env)")
sys.exit(1)
if env_mode == "e2b":
# Cloud-sandbox mode genuinely needs an E2B account.
if not os.environ.get("E2B_API_KEY"):
print("[env] ERROR: harbor.env == 'e2b' but E2B_API_KEY is not set")
print("[env] set E2B_API_KEY in .env, or switch harbor.env to "
"'docker' for fully-local execution")
sys.exit(1)
if not os.environ.get("GITHUB_TOKEN"):
print("[env] WARNING: GITHUB_TOKEN not set — some nexau install "
"steps may be rate-limited")
else:
print(f"[env] harbor.env == '{env_mode}': running locally, "
"E2B / GitHub credentials not required")
# ---------------------------------------------------------------------------
# Feishu Webhook Notification
# ---------------------------------------------------------------------------
def send_feishu_notification(config: dict, title: str, content: str) -> None:
"""Send notification via Feishu custom bot Webhook.
Config requires:
notify:
feishu_webhook: "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxx"
enabled: true (default true)
"""
notify_cfg = config.get("notify", {})
if not notify_cfg.get("enabled", True):
return
webhook_url = notify_cfg.get("feishu_webhook", "")
if not webhook_url:
return
meta_name = config.get("_meta", {}).get("_name", "unknown")
body = {
"msg_type": "interactive",
"card": {
"header": {
"title": {"tag": "plain_text", "content": f"[Agentic Harness Engineering] {title}"},
"template": "blue",
},
"elements": [
{
"tag": "markdown",
"content": f"**Experiment**: {meta_name}\n\n{content}",
},
],
},
}
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(
webhook_url,
data=data,
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
result = json.loads(resp.read().decode())
if result.get("code") != 0:
print(f"[notify] Feishu send failed: {result}")
else:
print(f"[notify] Feishu notification sent: {title}")
except Exception as exc:
print(f"[notify] Feishu notification error (does not affect experiment): {exc}")
# ---------------------------------------------------------------------------
# Config Loading: _base Inheritance + Deep Merge
# ---------------------------------------------------------------------------
def resolve_env_vars(obj):
"""Recursively resolve ${VAR_NAME} in config values with environment variables. Unmatched ones are kept as-is."""
if isinstance(obj, str):
return re.sub(r'\$\{([^}]+)\}', lambda m: os.environ.get(m.group(1), m.group(0)), obj)
if isinstance(obj, dict):
return {k: resolve_env_vars(v) for k, v in obj.items()}
if isinstance(obj, list):
return [resolve_env_vars(item) for item in obj]
return obj
def deep_merge(base: dict, overlay: dict) -> dict:
"""Deep merge two dicts, overlay overrides base."""
result = copy.deepcopy(base)
for key, value in overlay.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = copy.deepcopy(value)
return result
def load_config(config_path: str) -> dict:
"""Load config file with _base inheritance chain support."""
config_path = Path(config_path).resolve()
with open(config_path, encoding="utf-8") as f:
raw = yaml.safe_load(f) or {}
if "_base" not in raw:
return resolve_env_vars(raw)
base_ref = raw.pop("_base")
base_path = (config_path.parent / base_ref).resolve()
base = load_config(str(base_path))
meta = {}
for key in list(raw.keys()):
if key.startswith("_"):
meta[key] = raw.pop(key)
config = deep_merge(base, raw)
# Mutually-exclusive data-source keys: if the overlay explicitly sets one,
# drop the other inherited from base so downstream readers see a single source.
if 'path' in raw and 'dataset' in config and 'dataset' not in raw:
config.pop('dataset', None)
elif 'dataset' in raw and 'path' in config and 'path' not in raw:
config.pop('path', None)
config["_meta"] = meta
return resolve_env_vars(config)
def resolve_source_dir(config: dict) -> Path:
"""Resolve source_config_dir, supporting absolute and relative paths (relative to PROJECT_DIR)."""
raw = config["source_config_dir"]
p = Path(raw)
if p.is_absolute():
return p
return (PROJECT_DIR / raw).resolve()
def apply_agent_yaml_patch(yaml_path: Path, patch: dict, label: str = "patch") -> None:
"""Deep merge a patch dict into the specified agent yaml file."""
if not patch:
return
if not yaml_path.exists():
print(f"[{label}] Warning: {yaml_path} does not exist, skipping patch")
return
with open(yaml_path, encoding="utf-8") as f:
agent_config = yaml.safe_load(f)
patched = deep_merge(agent_config, patch)
with open(yaml_path, "w", encoding="utf-8") as f:
yaml.dump(patched, f, default_flow_style=False, allow_unicode=True)
print(f"[{label}] Applied patch to {yaml_path.name}: {list(patch.keys())}")
def apply_code_agent_patch(workspace_dir: Path, agent_config_filename: str, patch: dict) -> None:
"""Apply code_agent_patch to the agent config in workspace.
The patch is a YAML deep-merge, so it only applies when the agent config is
YAML. Adapters whose evolve target is a free-form file (e.g. the wizard
adapter's markdown system_prompt.md) must not be YAML-merged — doing so
parses and rewrites the prompt as YAML and corrupts it. Skip them.
"""
if not agent_config_filename.lower().endswith((".yaml", ".yml")):
if patch:
print(
f"[code_agent_patch] skipped: {agent_config_filename} is not a YAML "
"agent config (free-form evolve target)"
)
return
apply_agent_yaml_patch(workspace_dir / agent_config_filename, patch, label="code_agent_patch")
def build_evolve_agent_patch(evolve_agent_cfg: dict) -> dict:
"""Extract fields from evolve_agent config to patch into evolve_agent.yaml.
Same format as code_agent_patch, passed through directly as target yaml structure."""
return dict(evolve_agent_cfg)
def build_explore_agent_patch(config: dict) -> dict:
"""Extract patch from explore_agent_patch. If not explicitly specified, inherits api_type/reasoning/tool_call_mode from evolve_agent."""
ml_patch = dict(config.get("explore_agent_patch", {}))
if ml_patch:
return ml_patch
evolve_cfg = config.get("evolve_agent", {})
if not evolve_cfg:
return {}
derived: dict = {}
if "tool_call_mode" in evolve_cfg:
derived["tool_call_mode"] = evolve_cfg["tool_call_mode"]
evolve_llm = evolve_cfg.get("llm_config", {})
llm_keys: dict = {}
for key in ("api_type", "reasoning"):
if key in evolve_llm:
llm_keys[key] = evolve_llm[key]
if llm_keys:
derived["llm_config"] = llm_keys
return derived
def get_llm_config(config: dict, role: str = "agent") -> dict:
"""Get LLM config for the specified role.
role='agent': read from config.llm
role='evolve': fields in evolve_agent.llm_config take priority, fallback to config.llm"""
base_llm = config["llm"]
if role == "evolve":
evolve_llm = config.get("evolve_agent", {}).get("llm_config", {})
return {
"api_key": evolve_llm.get("api_key", base_llm["api_key"]),
"base_url": evolve_llm.get("base_url", base_llm["base_url"]),
"model": evolve_llm.get("model", base_llm["model"]),
}
return {
"api_key": base_llm["api_key"],
"base_url": base_llm["base_url"],
"model": base_llm["model"],
}
def set_llm_env(llm_cfg: dict) -> None:
"""Write LLM config to environment variables for ${env.LLM_*} references."""
for cfg_key, env_key in [("api_key", "LLM_API_KEY"), ("base_url", "LLM_BASE_URL"), ("model", "LLM_MODEL")]:
val = llm_cfg.get(cfg_key, "")
if val:
os.environ[env_key] = val
# ---------------------------------------------------------------------------
# Phase 0: Create Experiment Directory + Initialize Workspace
# ---------------------------------------------------------------------------
def create_experiment_dir(config: dict, config_path: str, experiment_name: str | None = None) -> Path:
"""Create a new experiment directory, save config snapshot and evolve agent config, return experiment dir path."""
if experiment_name:
exp_dir = EXPERIMENTS_DIR / experiment_name
else:
timestamp = datetime.now().strftime("%Y-%m-%d__%H-%M-%S")
meta_name = config.get("_meta", {}).get("_name", "")
dir_name = f"{timestamp}__{meta_name}" if meta_name else timestamp
exp_dir = EXPERIMENTS_DIR / dir_name
exp_dir.mkdir(parents=True, exist_ok=True)
# Save the merged complete config snapshot (not raw file copy)
snapshot_path = exp_dir / "config_snapshot.yaml"
if not snapshot_path.exists():
snapshot = {k: v for k, v in config.items() if k != "_meta"}
with open(snapshot_path, "w", encoding="utf-8") as f:
yaml.dump(snapshot, f, default_flow_style=False, allow_unicode=True)
print(f"[exp] Config snapshot saved")
# If overlay config, also save the original overlay file
if config.get("_meta"):
overlay_dst = exp_dir / "experiment_overlay.yaml"
if not overlay_dst.exists() and Path(config_path).exists():
shutil.copy2(config_path, overlay_dst)
# Copy evolve agent directory into exp_dir/evolve_agent/
evolve_dst = exp_dir / "evolve_agent"
if EVOLVE_AGENT_DIR.is_dir():
if not evolve_dst.exists():
shutil.copytree(EVOLVE_AGENT_DIR, evolve_dst)
else:
for item in EVOLVE_AGENT_DIR.iterdir():
dst = evolve_dst / item.name
if dst.exists():
continue
if item.is_file():
shutil.copy2(item, dst)
elif item.is_dir():
shutil.copytree(item, dst)
(exp_dir / "runs").mkdir(exist_ok=True)
print(f"[exp] Experiment directory: {exp_dir}")
return exp_dir
def init_workspace(source_dir: Path, workspace_dir: Path) -> bool:
"""Copy from source config directory to workspace and git init. Returns whether a new initialization was performed."""
if workspace_dir.exists() and (workspace_dir / ".git").exists():
print(f"[init] Workspace already exists with git history, skipping initialization")
return False
print(f"[init] Initializing workspace from {source_dir} to {workspace_dir}")
if workspace_dir.exists():
shutil.rmtree(workspace_dir)
shutil.copytree(source_dir, workspace_dir)
subprocess.run(["git", "init"], cwd=workspace_dir, check=True, capture_output=True)
subprocess.run(["git", "add", "-A"], cwd=workspace_dir, check=True, capture_output=True)
subprocess.run(
["git", "commit", "-m", "v0: baseline from " + source_dir.name],
cwd=workspace_dir, check=True, capture_output=True,
)
print(f"[init] Workspace initialization complete, baseline committed")
return True
# ---------------------------------------------------------------------------
# Phase 1: Run Evaluation
# ---------------------------------------------------------------------------
def find_latest_job_dir(jobs_root: Path) -> Path | None:
"""Find the latest job directory."""
if not jobs_root.exists():
return None
job_dirs = [
d for d in jobs_root.iterdir()
if d.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}__\d{2}-\d{2}-\d{2}", d.name)
]
if not job_dirs:
return None
return max(job_dirs, key=lambda d: d.name)
class HarborJobTimeoutError(Exception):
"""Single harbor evaluation timeout."""
pass
class ExperimentTimeoutError(Exception):
"""Total experiment duration timeout."""
pass
def wait_for_job(jobs_root: Path, started_after: str | None,
poll_interval: int = 30, timeout_minutes: int = 0) -> Path:
"""Poll and wait for harbor job to complete, return job_dir. timeout_minutes <= 0 means no limit."""
timeout_sec = timeout_minutes * 60 if timeout_minutes > 0 else 0
t0 = time.monotonic()
timeout_msg = f", timeout {timeout_minutes} min" if timeout_sec else ""
print(f"[eval] Waiting for evaluation to complete, checking every {poll_interval}s{timeout_msg}...")
while True:
if timeout_sec and (time.monotonic() - t0) > timeout_sec:
elapsed_min = (time.monotonic() - t0) / 60
raise HarborJobTimeoutError(
f"Harbor evaluation timeout: waited {elapsed_min:.1f} min, exceeded limit of {timeout_minutes} min"
)
job_dir = find_latest_job_dir(jobs_root)
if job_dir is None:
time.sleep(poll_interval)
continue
if started_after and job_dir.name <= started_after:
time.sleep(poll_interval)
continue
result_path = job_dir / "result.json"
if not result_path.exists():
time.sleep(poll_interval)
continue
try:
result = json.loads(result_path.read_text(encoding="utf-8"))
if result.get("finished_at") is not None:
print(f"[eval] Evaluation complete: {job_dir.name}")
return job_dir
except (json.JSONDecodeError, KeyError):
pass
time.sleep(poll_interval)
def _build_harbor_cmd(config: dict, workspace_dir: Path, agent_config_filename: str,
iteration_dir: Path, n_concurrent_override: int | None = None) -> list[str]:
"""Build the harbor CLI command list."""
harbor_cfg = config["harbor"]
dataset = config.get("dataset")
task_path = config.get("path")
llm_cfg = get_llm_config(config, role="agent")
model = llm_cfg["model"]
config_path = (workspace_dir / agent_config_filename).resolve()
k = int(harbor_cfg.get("k", 1))
n_concurrent = n_concurrent_override or harbor_cfg["n_concurrent"]
# Select the agent by registered name, or by import path for custom adapters
# (e.g. the wizard adapter) that aren't in harbor's AgentName enum.
import_path = harbor_cfg.get("agent_import_path")
agent_selector = (
["--agent-import-path", import_path]
if import_path
else ["--agent", harbor_cfg["agent"]]
)
# Resolve the harbor CLI next to the running interpreter and invoke it THROUGH
# that interpreter, so it works regardless of PATH propagation under `uv run`
# and even if the venv console-script shebang is stale (e.g. the project dir
# was relocated after the venv was created).
harbor_script = Path(sys.executable).parent / "harbor"
harbor_argv = [sys.executable, str(harbor_script)] if harbor_script.exists() else ["harbor"]
cmd = [
*harbor_argv, "run",
*agent_selector,
"--env", harbor_cfg["env"],
"--model", model,
"--n-concurrent", str(n_concurrent),
"--ak", f"config_path={config_path}",
"--jobs-dir", str(iteration_dir),
]
if k > 1:
cmd.extend(["-k", str(k)])
if task_path:
resolved = Path(task_path)
if not resolved.is_absolute():
resolved = (PROJECT_DIR / resolved).resolve()
cmd.extend(["-p", str(resolved)])
elif dataset:
cmd.extend(["--dataset", dataset])
else:
raise ValueError("Config must specify either 'dataset' or 'path'")
for tn in config.get("task_names", []):
cmd.extend(["-t", tn])
for xn in config.get("exclude_task_names", []):
cmd.extend(["-x", xn])
if harbor_cfg.get("force_build"):
cmd.append("--force-build")
# Harbor's default teardown is `compose down --rmi all`, which deletes the
# task image after EVERY trial. For registry tasks with prebuilt images
# (multi-GB ghcr pulls) that means re-downloading the image per trial and
# eval exceptions whenever the network hiccups. `no_delete: true` keeps
# images cached across trials (containers are still removed).
if harbor_cfg.get("no_delete"):
cmd.append("--no-delete")
return cmd
def launch_harbor(config: dict, workspace_dir: Path, agent_config_filename: str,
iteration_dir: Path, label: str = "",
n_concurrent_override: int | None = None) -> tuple[subprocess.Popen, str]:
"""Launch harbor evaluation process without waiting. Returns (proc, started_after).
Use wait_for_harbor() to wait for completion and get the job_dir.
Thread-safe: uses env= to pass LLM vars to the subprocess without
modifying the process-global environment.
"""
llm_cfg = get_llm_config(config, role="agent")
sub_env = os.environ.copy()
# Harbor imports the agent adapter by dotted path (e.g.
# agents.wizard_agent.adapter). Installed console scripts don't put the
# repo on sys.path and cwd is ROOT_DIR (one level up), so pass the repo
# dir via PYTHONPATH instead of relying on packaging side effects.
repo_dir = str(Path(__file__).resolve().parent)
existing_pythonpath = sub_env.get("PYTHONPATH", "")
sub_env["PYTHONPATH"] = (
f"{repo_dir}{os.pathsep}{existing_pythonpath}" if existing_pythonpath else repo_dir
)
for cfg_key, env_key in [("api_key", "LLM_API_KEY"),
("base_url", "LLM_BASE_URL"),
("model", "LLM_MODEL")]:
val = llm_cfg.get(cfg_key, "")
if val:
sub_env[env_key] = val
e2b_sandbox_timeout = config["harbor"].get("e2b_sandbox_timeout")
if e2b_sandbox_timeout is not None:
sub_env["E2B_SANDBOX_TIMEOUT"] = str(int(e2b_sandbox_timeout))
prev_latest = find_latest_job_dir(iteration_dir)
started_after = prev_latest.name if prev_latest else ""
cmd = _build_harbor_cmd(config, workspace_dir, agent_config_filename,
iteration_dir, n_concurrent_override=n_concurrent_override)
tag = f" [{label}]" if label else ""
print(f"[eval{tag}] Starting evaluation: {' '.join(cmd)}", flush=True)
proc = subprocess.Popen(
cmd,
cwd=ROOT_DIR,
stdout=sys.stdout,
stderr=sys.stderr,
env=sub_env,
)
return proc, started_after
def wait_for_harbor(proc: subprocess.Popen, iteration_dir: Path,
started_after: str, timeout_minutes: int = 0,
label: str = "") -> Path:
"""Wait for a previously launched harbor process to finish and return its job_dir."""
tag = f" [{label}]" if label else ""
try:
job_dir = wait_for_job(iteration_dir, started_after or None, timeout_minutes=timeout_minutes)
except HarborJobTimeoutError:
print(f"[eval{tag}] Harbor evaluation timeout ({timeout_minutes} min), terminating...")
proc.terminate()
try:
proc.wait(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
job_dir = find_latest_job_dir(iteration_dir)
if job_dir is None:
raise HarborJobTimeoutError(f"Harbor evaluation timeout with no completed job directory{tag}")
print(f"[eval{tag}] Using existing results after timeout: {job_dir.name}")
return job_dir
if proc.poll() is None:
print(f"[eval{tag}] Harbor process still running, waiting for exit...")
proc.wait()
return job_dir
def run_harbor(config: dict, workspace_dir: Path, agent_config_filename: str,
iteration_dir: Path) -> Path:
"""Start harbor evaluation and wait for completion. Results are written directly to iteration_dir."""
job_timeout = int(config.get("harbor_job_timeout_minutes") or 0)
proc, started_after = launch_harbor(config, workspace_dir, agent_config_filename, iteration_dir)
return wait_for_harbor(proc, iteration_dir, started_after, timeout_minutes=job_timeout)
# ---------------------------------------------------------------------------
# Phase 2: Compute Evaluation Results
# ---------------------------------------------------------------------------
_EXCEPTION_LINE_RE = re.compile(
r"^([a-zA-Z_][\w.]*(?:Error|Exception|Timeout|Fault))\b"
)
def _extract_exception_type(exc_text: str) -> str:
"""Extract Python exception class name from exception.txt content.
Strategy:
1. Prefer regex matching standard exception names (ending with Error/Exception/Timeout/Fault)
2. Fallback to "module.ClassName: message" format, requiring class name >= 4 chars (to exclude apt 'E:' etc.)
Both passes scan from the last line upward.
"""
lines = exc_text.strip().splitlines()
# First pass: exact match for standard exception naming
for line in reversed(lines):
stripped = line.strip()
m = _EXCEPTION_LINE_RE.match(stripped)
if m:
full_name = m.group(1)
return full_name.rsplit(".", 1)[-1]
# Second pass: loose match for "ClassName: message" format
for line in reversed(lines):
stripped = line.strip()
if ":" in stripped and not stripped.startswith(" "):
candidate = stripped.split(":")[0].strip()
parts = candidate.rsplit(".", 1)
short = parts[-1] if len(parts) > 1 else parts[0]
if short and len(short) >= 4 and short[0].isupper() and short.isidentifier():
return short
return "Unknown"
def pass_at_k_est(n: int, c: int, k: int) -> float:
"""Chen et al. unbiased estimator for single-task pass@k.
n = total samples, c = number of correct samples."""
if k > n or k < 0 or n == 0:
return float("nan")
num_wrong = n - c
if num_wrong >= k:
return 1.0 - math.comb(num_wrong, k) / math.comb(n, k)
return 1.0 if c > 0 else 0.0
def compute_pass_at_k_metrics(per_task_rollouts: dict, k: int) -> dict:
"""Compute pass@1, pass@2, ..., pass@k aggregate metrics using Chen et al. estimator.
Returns dict:
pass_at: {1: rate, 2: rate, ..., k: rate} - macro-averaged over eligible tasks (n>=i)
per_task_pass_at: {task_name: {1: est, 2: est, ...}} - per-task estimates
eligible_counts: {1: n_tasks, 2: n_tasks, ...} - tasks with n>=i for each i
"""
pass_at: dict[int, float] = {}
per_task_pass_at: dict[str, dict[int, float]] = {}
eligible_counts: dict[int, int] = {}
for i in range(1, k + 1):
estimates = []
for task_name, ro in sorted(per_task_rollouts.items()):
n = ro["n_pass"] + ro["n_fail"] + ro.get("n_exception", 0)
c = ro["n_pass"]
if n >= i:
est = pass_at_k_est(n, c, i)
estimates.append(est)
per_task_pass_at.setdefault(task_name, {})[i] = est
eligible_counts[i] = len(estimates)
pass_at[i] = sum(estimates) / len(estimates) if estimates else 0.0
return {
"pass_at": pass_at,
"per_task_pass_at": per_task_pass_at,
"eligible_counts": eligible_counts,
}
def compute_stats(job_dir: Path, k: int = 1) -> dict:
"""Compute detailed evaluation statistics from harbor raw job_dir.
When k>1, groups trials by task name: a task passes only if ALL k rollouts pass.
Returns dict:
pass_rate: Pass rate over all tasks; when k>1, this is pass@1 (Chen et al.)
n_pass: Number of tasks that pass (all rollouts pass when k>1)
n_fail: Number of tasks that fail
n_exception: Number of tasks with all-exception results
n_total: Number of unique tasks
k: Rollout count per task
exception_types: dict[str, int] - Exception type distribution
task_results: dict[task_name, "pass"|"fail"|"exception"] - Per-task results
per_task_rollouts: dict[task_name, {n_pass, n_fail, n_exception, total}] - Per-task rollout detail (when k>1)
trial_stats: dict with raw per-trial counts (when k>1)
"""
trial_dirs = [
d for d in job_dir.iterdir()
if d.is_dir() and (d / "result.json").exists()
]
# Collect per-trial results grouped by task name
task_trials: dict[str, list[str]] = {}
exception_types: dict[str, int] = {}
timeout_trial_counts: dict[str, int] = {}
for trial_dir in sorted(trial_dirs):
task_name = re.sub(r"__[A-Za-z0-9]{6,}$", "", trial_dir.name)
reward_src = trial_dir / "verifier" / "reward.txt"
exception_src = trial_dir / "exception.txt"
if reward_src.exists():
try:
reward_val = float(reward_src.read_text().strip())
result = "pass" if reward_val >= 1.0 else "fail"
except ValueError:
result = "fail"
else:
result = "exception"
if exception_src.exists():
exc_text = exception_src.read_text(errors="replace").strip()
exc_type = _extract_exception_type(exc_text)
exception_types[exc_type] = exception_types.get(exc_type, 0) + 1
if "Timeout" in exc_type:
timeout_trial_counts[task_name] = timeout_trial_counts.get(task_name, 0) + 1
else:
exception_types["Unknown"] = exception_types.get("Unknown", 0) + 1
task_trials.setdefault(task_name, []).append(result)
# Aggregate per-task results (all rollouts must pass when k>1)
task_results: dict[str, str] = {}
per_task_rollouts: dict[str, dict] = {}
trial_n_pass = 0
trial_n_fail = 0
trial_n_exception = 0
for task_name, trials in sorted(task_trials.items()):
tp = trials.count("pass")
tf = trials.count("fail")
te = trials.count("exception")
trial_n_pass += tp
trial_n_fail += tf
trial_n_exception += te
if tp == len(trials):
task_results[task_name] = "pass"
elif te == len(trials):
task_results[task_name] = "exception"
else:
task_results[task_name] = "fail"
if k > 1:
per_task_rollouts[task_name] = {
"n_pass": tp,
"n_fail": tf,
"n_exception": te,
"total": len(trials),
}
n_pass = sum(1 for r in task_results.values() if r == "pass")
n_fail = sum(1 for r in task_results.values() if r == "fail")
n_exception = sum(1 for r in task_results.values() if r == "exception")
n_total = len(task_results)
pass_rate = n_pass / n_total if n_total > 0 else 0.0
n_trials_total = trial_n_pass + trial_n_fail + trial_n_exception
# Compute pass@k metrics (Chen et al. estimator)
pass_at_k_metrics: dict | None = None
if k > 1:
pass_at_k_metrics = compute_pass_at_k_metrics(per_task_rollouts, k)
# Use pass@1 as primary metric
pass_rate = pass_at_k_metrics['pass_at'].get(1, 0.0)
trial_pass_rate = trial_n_pass / n_trials_total if n_trials_total > 0 else 0.0
pass_at_parts = " | ".join(f"pass@{i}={pass_at_k_metrics['pass_at'][i]:.1%}" for i in range(1, k + 1))
print(f"[stats] {n_trials_total} trials across {n_total} tasks (k={k})")
print(f"[stats] Per-trial: {trial_n_pass} pass, {trial_n_fail} fail, {trial_n_exception} exception (trial pass rate: {trial_pass_rate:.1%})")
print(f"[stats] {pass_at_parts}")
else:
print(f"[stats] {n_total} tasks: {n_pass} pass, {n_fail} fail, {n_exception} exception")
print(f"[stats] Pass rate: {pass_rate:.1%}")
if exception_types:
print(f"[stats] Exception types: {exception_types}")
timeout_tasks = set(timeout_trial_counts.keys())
if timeout_tasks:
print(f"[stats] Timeout tasks ({len(timeout_tasks)}): {', '.join(sorted(timeout_tasks))}")
result = {
"pass_rate": pass_rate,
"n_pass": n_pass,
"n_fail": n_fail,
"n_exception": n_exception,
"n_total": n_total,
"k": k,
"exception_types": exception_types,
"task_results": task_results,
"timeout_tasks": timeout_tasks,
}
if k > 1:
result["per_task_rollouts"] = per_task_rollouts
result["pass_at_k"] = pass_at_k_metrics
result["trial_stats"] = {
"n_pass": trial_n_pass,
"n_fail": trial_n_fail,
"n_exception": trial_n_exception,
"n_total": n_trials_total,
"trial_pass_rate": trial_n_pass / n_trials_total if n_trials_total > 0 else 0.0,
}
return result
# ---------------------------------------------------------------------------
# Phase 2.4: Task Stability Tracking (Cross-Iteration)
# ---------------------------------------------------------------------------
def load_task_history(exp_dir: Path) -> dict:
"""Load cross-iteration task result history.
Returns dict:
task_name -> list[(iteration, "pass"|"fail"|"exception")]
"""
history_path = exp_dir / "task_history.json"
if history_path.exists():
return json.loads(history_path.read_text(encoding="utf-8"))
return {}
def save_task_history(exp_dir: Path, history: dict) -> None:
"""Persist task result history."""
history_path = exp_dir / "task_history.json"
with open(history_path, "w", encoding="utf-8") as f:
json.dump(history, f, ensure_ascii=False, indent=2)
def update_task_history(exp_dir: Path, iteration: int, task_results: dict,
per_task_rollouts: dict | None = None) -> dict:
"""Update task history with current iteration results, return updated full history.
Each entry is [iteration, result] or [iteration, result, rollout_info] when k>1.
rollout_info = {n_pass, n_fail, n_exception, total}.
"""
history = load_task_history(exp_dir)
for task_name, result in task_results.items():
if task_name not in history:
history[task_name] = []
existing_iters = {entry[0] for entry in history[task_name]}
if iteration not in existing_iters:
if per_task_rollouts and task_name in per_task_rollouts:
history[task_name].append([iteration, result, per_task_rollouts[task_name]])
else:
history[task_name].append([iteration, result])
save_task_history(exp_dir, history)
return history
def compute_task_stability(task_history: dict, min_iterations: int = 3) -> dict:
"""Compute stability classification for each task based on historical data.
Returns dict:
stable_pass: list[task_name] - Passed in all iterations that reached verifier
stable_fail: list[task_name] - Failed in all iterations that reached verifier
unstable: list[task_name] - Flipped between pass and fail (>=min_iterations data points)
possibly_unstable: list[task_name] - Has both pass and fail but insufficient data (<min_iterations)
infra_only: list[task_name] - All exceptions, never reached verifier
"""
stable_pass = []
stable_fail = []
unstable = []
possibly_unstable = []
infra_only = []
for task_name, entries in task_history.items():
verdicts = [e[1] for e in entries if e[1] in ("pass", "fail")]
exceptions = [e[1] for e in entries if e[1] == "exception"]
if not verdicts:
if exceptions:
infra_only.append(task_name)
continue
has_pass = "pass" in verdicts
has_fail = "fail" in verdicts
if has_pass and has_fail:
if len(verdicts) >= min_iterations:
unstable.append(task_name)
else:
possibly_unstable.append(task_name)
elif has_pass and not has_fail:
stable_pass.append(task_name)
elif has_fail and not has_pass:
stable_fail.append(task_name)
return {
"stable_pass": sorted(stable_pass),
"stable_fail": sorted(stable_fail),
"unstable": sorted(unstable),
"possibly_unstable": sorted(possibly_unstable),
"infra_only": sorted(infra_only),
}
def compute_iteration_diff(current_results: dict, prev_results: dict | None,
current_rollouts: dict | None = None,
prev_rollouts: dict | None = None) -> dict | None:
"""Compare current and previous iteration task results, compute the full 9-state transition matrix.
When rollout data is available (k>1), also subdivides stable_fail into
rollout_improved / rollout_regressed / rollout_unchanged, and annotates
each task with (prev_pass_count, cur_pass_count, k) in rollout_details.
"""
if prev_results is None:
return None
flipped = [] # fail -> pass (real capability improvement)
regressed = [] # pass -> fail (real capability regression)
infra_recovered = [] # exception -> pass (infra recovery)
infra_lost = [] # pass -> exception (infra failure)
stable_pass = [] # pass -> pass (consistently passing)
stable_fail = [] # fail -> fail (consistently failing)
exception_to_fail = [] # exception -> fail (infra recovered but task still fails, new optimization target)
fail_to_exception = [] # fail -> exception (infra failure coverage)
exception_stable = [] # exception -> exception (persistent infra error)
rollout_improved = [] # fail -> fail but more rollouts passing
rollout_regressed = [] # fail -> fail but fewer rollouts passing
rollout_unchanged = [] # fail -> fail with same rollout pass count
rollout_details = {} # task -> (prev_n_pass, cur_n_pass, total)
has_rollouts = bool(current_rollouts and prev_rollouts)
all_tasks = set(current_results) | set(prev_results)
for task in sorted(all_tasks):
cur = current_results.get(task, "exception")
prev = prev_results.get(task, "exception")
if has_rollouts and (task in current_rollouts or task in prev_rollouts):
cur_ro = current_rollouts.get(task, {})
prev_ro = prev_rollouts.get(task, {})
cur_np = cur_ro.get("n_pass", 0)
prev_np = prev_ro.get("n_pass", 0)
total = cur_ro.get("total", prev_ro.get("total", 0))
rollout_details[task] = (prev_np, cur_np, total)
if prev == cur == "pass":
stable_pass.append(task)
elif prev == cur == "fail":
if has_rollouts and task in rollout_details:
prev_np, cur_np, _ = rollout_details[task]
if cur_np > prev_np:
rollout_improved.append(task)
elif cur_np < prev_np:
rollout_regressed.append(task)
else:
rollout_unchanged.append(task)
stable_fail.append(task)
elif prev == cur == "exception":
exception_stable.append(task)
elif prev == "fail" and cur == "pass":
flipped.append(task)
elif prev == "pass" and cur == "fail":
regressed.append(task)
elif prev == "exception" and cur == "pass":
infra_recovered.append(task)
elif prev == "pass" and cur == "exception":
infra_lost.append(task)
elif prev == "exception" and cur == "fail":
exception_to_fail.append(task)
elif prev == "fail" and cur == "exception":
fail_to_exception.append(task)
return {
"flipped": flipped,
"regressed": regressed,
"net": len(flipped) - len(regressed),
"infra_recovered": infra_recovered,
"infra_lost": infra_lost,
"stable_pass": stable_pass,
"stable_fail": stable_fail,
"exception_to_fail": exception_to_fail,
"fail_to_exception": fail_to_exception,
"exception_stable": exception_stable,
"rollout_improved": rollout_improved,
"rollout_regressed": rollout_regressed,
"rollout_unchanged": rollout_unchanged,
"rollout_details": rollout_details,
}
# ---------------------------------------------------------------------------
# Phase 2.3.5: Trajectory Info Pre-extraction (reduce evolve agent redundant file reads)