#!/usr/bin/env python3 """Evaluate the BrowseComp orchestrator architecture on DeepResearch-9K. The coordinator has no search tools and delegates to full local-search worker episodes. Output rows intentionally match ``aggregate_eval.py`` so solo and orchestration runs can be compared on exactly the same qids and strata. """ from __future__ import annotations import argparse import asyncio import hashlib import json import os import sys import time from collections import Counter from pathlib import Path from typing import Any REPO_ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(REPO_ROOT / "examples" / "browsecomp")) sys.path.insert(0, str(REPO_ROOT / "examples" / "browsecomp" / "orgpatterns")) import browsecomp_env # noqa: E402 import browsecomp_rm # noqa: E402 import orchestrator_pipeline as op # noqa: E402 def read_jsonl(path: Path) -> list[dict[str, Any]]: with path.open(encoding="utf-8") as handle: return [json.loads(line) for line in handle if line.strip()] def endpoint_list(values: list[str]) -> list[str]: result = [item.strip().rstrip("/") for value in values for item in value.split(",") if item.strip()] if not result: raise ValueError("at least one endpoint is required") return result def record_index(record: dict[str, Any], fallback: int) -> int: metadata = record.get("metadata") or {} benchmark = metadata.get("benchmark") or {} return int(benchmark.get("index", fallback)) def choose_endpoint(endpoints: list[str], *, index: int, role: str) -> str: digest = hashlib.sha256(f"{role}:{index}".encode()).digest() return endpoints[int.from_bytes(digest[:8], "big") % len(endpoints)] def initial_stats(*, coordinator_seed: int) -> dict[str, Any]: return { "workers_spawned": 0, "followups": 0, "worker_turns": 0, "worker_prompt_tokens": 0, "worker_completion_tokens": 0, "worker_total_tokens": 0, "worker_usage_calls": 0, "worker_usage_missing": 0, "worker_usage_inconsistent": 0, "worker_http_errors": 0, "worker_http_status_counts": {}, "worker_tool_stats": {}, "worker_call_sequence": 0, "report_chars": 0, "coord_turns": 0, "coord_prompt_tokens": 0, "coord_completion_tokens": 0, "coord_total_tokens": 0, "coord_last_total_tokens": 0, "coord_usage_calls": 0, "coord_usage_missing": 0, "coord_usage_inconsistent": 0, "coord_request_kwargs": {"seed": coordinator_seed}, "gate_calls": 0, "gate_stop_safe": 0, "gate_continue": 0, "gate_fallback": 0, "gate_parse_failures": 0, "gate_http_attempts": 0, "gate_prompt_tokens": 0, "gate_completion_tokens": 0, "gate_total_tokens": 0, "gate_cached_prompt_tokens": 0, "gate_uncached_prompt_tokens": 0, "gate_reasoning_other_tokens": 0, "gate_cache_detail_calls": 0, "gate_usage_calls": 0, "gate_usage_missing": 0, "gate_usage_inconsistent": 0, "gate_opportunities": 0, "gate_schedule_skips": 0, "gate_events": [], } async def evaluate_one( semaphore: asyncio.Semaphore, *, record: dict[str, Any], fallback_index: int, coordinator_urls: list[str], worker_urls: list[str], seed_base: int, remote_judge: bool, judge_semaphore: asyncio.Semaphore, model_label: str, coordinator_label: str, ) -> dict[str, Any]: metadata = dict(record.get("metadata") or {}) benchmark = dict(metadata.get("benchmark") or {}) index = record_index(record, fallback_index) qid = str(metadata.get("qid") or metadata.get("manifest_qid") or "") if not qid: raise ValueError(f"record index={index} has no qid") episode_seed = seed_base + index coordinator_url = choose_endpoint(coordinator_urls, index=index, role="coordinator") worker_url = choose_endpoint(worker_urls, index=index, role="worker") worker_kwargs = dict(op._sampling_kw("ORCH_WORKER_TEMP"), seed=episode_seed) stats = initial_stats(coordinator_seed=episode_seed) label = str(metadata.get("answer") or record.get("label") or "") question = str(metadata.get("question") or "") started = time.perf_counter() predicted: str | None = None explanation = "" error: str | None = None async with semaphore: try: answer, explanation = await op.coordinate( coordinator_url, worker_url, record, worker_kwargs, stats, ) predicted = (answer or "").strip() or None except Exception as exc: # noqa: BLE001 error = f"{type(exc).__name__}: {exc}"[:1000] elapsed = time.perf_counter() - started stop_reason = stats.get("coordinate_stop_reason") or ( "agent_error" if error else "finish" if predicted else "coord_max_turns" ) local_em = int(browsecomp_env.em_score(label, predicted or "")) judge_score: int | None = None judge_remote_called = False judge_error: str | None = None if remote_judge: try: async with judge_semaphore: judge_score, judge_remote_called = await browsecomp_rm.judge( question, label, predicted or "", with_remote_flag=True, ) judge_score = int(judge_score) except Exception as exc: # noqa: BLE001 judge_error = f"{type(exc).__name__}: {exc}"[:1000] public_stats = {key: value for key, value in stats.items() if key != "coord_request_kwargs"} tool_stats = dict(public_stats.get("worker_tool_stats") or {}) row: dict[str, Any] = { "index": index, "qid": qid, "manifest_qid": metadata.get("manifest_qid"), "difficulty": metadata.get("difficulty"), "teacher_correct": metadata.get("teacher_correct"), "benchmark": benchmark, "question": question, "label": label, "sampling_seed": episode_seed, "coordinator_sampling_seed": episode_seed, "model_label": model_label, "coordinator_model_label": coordinator_label, "predicted": predicted or "", "explanation": explanation or "", "num_turns": int(stats.get("coord_turns", 0)), "stop_reason": stop_reason, "tool_stats": tool_stats, "local_em": local_em, "active_seconds": elapsed, "wall_seconds": elapsed, "judge_score": judge_score, "judge_remote_called": bool(judge_remote_called), "orch": public_stats, } if error: row["error"] = error if judge_error: row["judge_error"] = judge_error return row async def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--coord-url", action="append", required=True) parser.add_argument("--worker-url", action="append", required=True) parser.add_argument("--data", type=Path, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--offset", type=int, default=0) parser.add_argument("--limit", type=int, default=0) parser.add_argument("--concurrency", type=int, default=8) parser.add_argument("--judge-concurrency", type=int, default=8) parser.add_argument("--seed-base", type=int, default=20260811) parser.add_argument("--model-label", required=True) parser.add_argument("--coordinator-label", required=True) parser.add_argument("--remote-judge", action="store_true") args = parser.parse_args() if args.out.exists(): parser.error(f"refusing to overwrite existing output: {args.out}") if args.offset < 0 or args.limit < 0 or args.concurrency < 1 or args.judge_concurrency < 1: parser.error("offset/limit must be non-negative and concurrency values must be positive") coordinator_urls = endpoint_list(args.coord_url) worker_urls = endpoint_list(args.worker_url) records = read_jsonl(args.data) selected = list(enumerate(records))[args.offset :] if args.limit: selected = selected[: args.limit] if not selected: parser.error("selected evaluation slice is empty") op.WORKER_PROMPT_TEMPLATE = json.loads(json.dumps(records[0]["prompt"])) semaphore = asyncio.Semaphore(args.concurrency) judge_semaphore = asyncio.Semaphore(args.judge_concurrency) args.out.parent.mkdir(parents=True, exist_ok=True) tasks = [ asyncio.create_task( evaluate_one( semaphore, record=record, fallback_index=fallback_index, coordinator_urls=coordinator_urls, worker_urls=worker_urls, seed_base=args.seed_base, remote_judge=args.remote_judge, judge_semaphore=judge_semaphore, model_label=args.model_label, coordinator_label=args.coordinator_label, ) ) for fallback_index, record in selected ] completed: list[dict[str, Any]] = [] with args.out.open("w", encoding="utf-8") as handle: for task in asyncio.as_completed(tasks): row = await task completed.append(row) handle.write(json.dumps(row, ensure_ascii=False) + "\n") handle.flush() correct = sum(int(item.get("judge_score") or 0) for item in completed) errors = sum(bool(item.get("error")) for item in completed) judge_errors = sum(bool(item.get("judge_error")) for item in completed) print( f"completed={len(completed)}/{len(tasks)} index={row['index']} " f"correct={correct} errors={errors} judge_errors={judge_errors}", flush=True, ) completed.sort(key=lambda row: int(row["index"])) expected_indexes = [record_index(record, fallback) for fallback, record in selected] actual_indexes = [int(row["index"]) for row in completed] if actual_indexes != expected_indexes: raise RuntimeError(f"output coverage mismatch: actual={actual_indexes} expected={expected_indexes}") errors = sum(bool(row.get("error")) for row in completed) judge_errors = sum(bool(row.get("judge_error")) for row in completed) stop_reasons = Counter(str(row.get("stop_reason") or "unknown") for row in completed) summary = { "questions": len(completed), "correct": sum(int(row.get("judge_score") or 0) for row in completed), "local_em_correct": sum(int(row["local_em"]) for row in completed), "agent_errors": errors, "judge_errors": judge_errors, "stop_reasons": dict(sorted(stop_reasons.items())), "workers_spawned": sum(int(row["orch"].get("workers_spawned", 0)) for row in completed), "worker_search_calls": sum(int(row["tool_stats"].get("search", 0)) for row in completed), "worker_open_calls": sum(int(row["tool_stats"].get("open_page", 0)) for row in completed), } args.out.with_name(f"{args.out.stem}.summary.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) print("FINAL_ORCHESTRATOR " + json.dumps(summary, sort_keys=True), flush=True) if errors or judge_errors: raise RuntimeError(f"incomplete evaluation: agent_errors={errors} judge_errors={judge_errors}") if __name__ == "__main__": asyncio.run(main())