Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(bench): read Harbor trial rewards and account recorded attempt metrics (#2089, from #2070)

xerj-org9b7af8aa68c2
diff --git a/tools/benchmarks/harbor-3arm/README.md b/tools/benchmarks/harbor-3arm/README.md
index 5f1d4332d..d6160af16 100644
--- a/tools/benchmarks/harbor-3arm/README.md
+++ b/tools/benchmarks/harbor-3arm/README.md
@@ -65,7 +65,13 @@ pauses, token expiry and crashes cost only the trial in flight.
`collect_results.py` reports per-cell resolve rates with Wilson 95% intervals
and a **complete matrix**: arm-vs-arm numbers count only tasks finished in
every arm of that benchmark+model. Do not quote cross-arm numbers from
-unaligned cells. Anthropic's published Frontier-Bench figures use the
+unaligned cells. The collector reads Harbor v0.21's `rewards`, `cost_usd`,
+`n_input_tokens` and `n_output_tokens` fields (including per-step usage),
+while retaining the older field aliases. Wall time comes from trial timestamps
+when no explicit duration is recorded. Per-cell cost/time includes recorded
+failed attempts; complete-matrix cost/time remains scoped to matched tasks.
+Unavailable metrics stay unknown and their coverage gaps are printed.
+Anthropic's published Frontier-Bench figures use the
mini-swe-agent harness with mean reward over 5 attempts (`-a mini-swe-agent
-k 5`); runs with `claude-code` measure the agent product, not that protocol —
label accordingly. FrontierCode v1.1 is Cognition's private held-out set and
diff --git a/tools/benchmarks/harbor-3arm/collect_results.py b/tools/benchmarks/harbor-3arm/collect_results.py
index d5d8aa031..036108b4c 100755
--- a/tools/benchmarks/harbor-3arm/collect_results.py
+++ b/tools/benchmarks/harbor-3arm/collect_results.py
@@ -16,6 +16,7 @@ import json
import math
import sys
from collections import defaultdict
+from datetime import datetime
from pathlib import Path
JOBS = Path(__file__).parent / "jobs"
@@ -31,6 +32,36 @@ def wilson(k, n, z=1.96):
return (max(0.0, (c - m) / d), min(1.0, (c + m) / d))
+def first_present(*values):
+ return next((value for value in values if value is not None), None)
+
+
+def agent_metric(trial, *names):
+ # Harbor v0.21 stores multi-step usage on each step instead of agent_result.
+ context = trial.get("agent_result")
+ contexts = [context] if context is not None else [
+ step["agent_result"] for step in trial.get("step_results") or []
+ if step.get("agent_result") is not None
+ ]
+ values = [first_present(*(context.get(name) for name in names)) for context in contexts]
+ known = [value for value in values if value is not None]
+ return sum(known) if known else None
+
+
+def elapsed_seconds(trial):
+ explicit = first_present(trial.get("elapsed_seconds"),
+ (trial.get("agent_result") or {}).get("elapsed_seconds"))
+ if explicit is not None:
+ return explicit
+ try:
+ start = datetime.fromisoformat(trial["started_at"].replace("Z", "+00:00"))
+ end = datetime.fromisoformat(trial["finished_at"].replace("Z", "+00:00"))
+ seconds = (end - start).total_seconds()
+ return seconds if seconds >= 0 else None
+ except (KeyError, AttributeError, TypeError, ValueError):
+ return None
+
+
def load_trials(job_dir: Path):
"""Yield (task, dict) per finished trial; tolerant of layout drift."""
for rj in sorted(job_dir.glob("**/result.json")):
@@ -41,7 +72,8 @@ def load_trials(job_dir: Path):
task = (r.get("task_name") or r.get("task", {}).get("name")
or rj.parent.name.split("__")[0])
reward = None
- for path in (("verifier_result", "reward"), ("reward",), ("result", "reward")):
+ for path in (("verifier_result", "rewards"), ("verifier_result", "reward"),
+ ("reward",), ("result", "reward")):
v = r
for k in path:
v = v.get(k) if isinstance(v, dict) else None
@@ -50,20 +82,20 @@ def load_trials(job_dir: Path):
break
if isinstance(reward, dict): # named rewards -> main one
reward = reward.get("reward", reward.get("resolved"))
- am = r.get("agent_result") or {}
yield task, {
"reward": reward,
"resolved": (reward or 0) >= 1 if reward is not None else None,
- "cost": am.get("total_cost_usd") or r.get("total_cost_usd"),
- "in_tok": am.get("input_tokens"),
- "out_tok": am.get("output_tokens"),
- "sec": r.get("elapsed_seconds") or am.get("elapsed_seconds"),
+ "cost": first_present(agent_metric(r, "cost_usd", "total_cost_usd"), r.get("total_cost_usd")),
+ "in_tok": agent_metric(r, "n_input_tokens", "input_tokens"),
+ "out_tok": agent_metric(r, "n_output_tokens", "output_tokens"),
+ "sec": elapsed_seconds(r),
"exception": r.get("exception_info") or r.get("error"),
}
def main():
cells = defaultdict(dict) # (bench, model, arm) -> {task: trial}
+ cell_trials = defaultdict(list) # all attempts, including failed retries
for job_dir in sorted(JOBS.iterdir()) if JOBS.exists() else []:
if not job_dir.is_dir():
continue
@@ -73,6 +105,7 @@ def main():
bench, model, arm = parts[0], ".".join(parts[1:-1]), parts[-1]
for task, t in load_trials(job_dir):
cells[(bench, model, arm)][task] = t
+ cell_trials[(bench, model, arm)].append(t)
if not cells:
sys.exit(f"no trials under {JOBS} — run run_matrix.sh first")
@@ -87,10 +120,15 @@ def main():
done = {t: v for t, v in tasks.items() if v["reward"] is not None}
k = sum(1 for v in done.values() if v["resolved"])
lo, hi = wilson(k, len(done))
- cost = sum(v["cost"] or 0 for v in done.values())
- hrs = sum(v["sec"] or 0 for v in done.values()) / 3600
- errs = sum(1 for v in tasks.values() if v["exception"])
+ attempts = cell_trials[(bench, model, arm)]
+ cost = sum(v["cost"] or 0 for v in attempts)
+ hrs = sum(v["sec"] or 0 for v in attempts) / 3600
+ errs = sum(1 for v in attempts if v["exception"])
note = f" !! {errs} errored" if errs else ""
+ missing_cost = sum(v["cost"] is None for v in attempts)
+ missing_time = sum(v["sec"] is None for v in attempts)
+ if missing_cost or missing_time:
+ note += f" metrics missing: cost {missing_cost}/{len(attempts)}, time {missing_time}/{len(attempts)} trials"
print(fmt.format(bench, model, arm, len(done), k,
f"[{lo:.0%},{hi:.0%}]", f"{cost:.2f}", f"{hrs:.1f}")
+ note)
diff --git a/tools/benchmarks/harbor-3arm/fixtures/harbor-0.21-result.json b/tools/benchmarks/harbor-3arm/fixtures/harbor-0.21-result.json
new file mode 100644
index 000000000..8f5dc4083
--- /dev/null
+++ b/tools/benchmarks/harbor-3arm/fixtures/harbor-0.21-result.json
@@ -0,0 +1,17 @@
+{
+ "_fixture_provenance": {
+ "kind": "synthetic serialized field slice, not a measured benchmark run",
+ "upstream_version": "v0.21.0",
+ "upstream_commit": "64afbbcb62165950301e1a6407c729aa26d844ff",
+ "models": [
+ "https://github.com/harbor-framework/harbor/blob/64afbbcb62165950301e1a6407c729aa26d844ff/src/harbor/models/verifier/result.py",
+ "https://github.com/harbor-framework/harbor/blob/64afbbcb62165950301e1a6407c729aa26d844ff/src/harbor/models/agent/context.py",
+ "https://github.com/harbor-framework/harbor/blob/64afbbcb62165950301e1a6407c729aa26d844ff/src/harbor/models/trial/result.py"
+ ]
+ },
+ "task_name": "fixture-task",
+ "verifier_result": {"rewards": {"reward": 1}},
+ "agent_result": {"cost_usd": 0.125, "n_input_tokens": 120, "n_cache_tokens": 20, "n_output_tokens": 30},
+ "started_at": "2026-01-01T01:00:00+01:00",
+ "finished_at": "2026-01-01T00:00:05Z"
+}
diff --git a/tools/benchmarks/harbor-3arm/test_collect_results.py b/tools/benchmarks/harbor-3arm/test_collect_results.py
new file mode 100644
index 000000000..c6bb568fa
--- /dev/null
+++ b/tools/benchmarks/harbor-3arm/test_collect_results.py
@@ -0,0 +1,87 @@
+#!/usr/bin/env python3
+"""Pinned schema slices and a real collector CLI; no Harbor/Docker/model dependency."""
+import json
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+import collect_results
+
+HERE = Path(__file__).resolve().parent
+FIXTURE = json.loads((HERE / "fixtures/harbor-0.21-result.json").read_text())
+
+
+class CollectorTests(unittest.TestCase):
+ def load(self, value):
+ with tempfile.TemporaryDirectory() as td:
+ trial = Path(td) / "fixture__trial"
+ trial.mkdir()
+ (trial / "result.json").write_text(json.dumps(value))
+ return list(collect_results.load_trials(Path(td)))[0][1]
+
+ def test_pinned_harbor_021_reward_metrics_and_wall_time(self):
+ value = self.load(FIXTURE)
+ self.assertEqual(value["reward"], 1)
+ self.assertIs(value["resolved"], True)
+ self.assertEqual((value["cost"], value["in_tok"], value["out_tok"], value["sec"]),
+ (0.125, 120, 30, 5))
+
+ def test_legacy_shape_remains_supported(self):
+ value = self.load({"task_name": "fixture", "verifier_result": {"reward": 0},
+ "agent_result": {"total_cost_usd": 0.5, "input_tokens": 12,
+ "output_tokens": 3, "elapsed_seconds": 2}})
+ self.assertEqual(value["reward"], 0)
+ self.assertIs(value["resolved"], False)
+ self.assertEqual((value["cost"], value["in_tok"], value["out_tok"], value["sec"]),
+ (0.5, 12, 3, 2))
+
+ def test_zero_metrics_are_not_replaced_by_legacy_fallbacks(self):
+ value = self.load({"task_name": "fixture", "verifier_result": {"rewards": {"reward": 0}},
+ "agent_result": {"cost_usd": 0, "total_cost_usd": 8,
+ "n_input_tokens": 0, "input_tokens": 99,
+ "n_output_tokens": 0, "output_tokens": 99},
+ "elapsed_seconds": 0, "total_cost_usd": 9})
+ self.assertEqual((value["reward"], value["cost"], value["in_tok"], value["out_tok"], value["sec"]),
+ (0, 0, 0, 0, 0))
+
+ def test_multistep_tokens_and_cost_follow_pinned_context_aggregation(self):
+ value = self.load({"task_name": "fixture", "verifier_result": {"rewards": {"reward": 1}},
+ "agent_result": None, "step_results": [
+ {"agent_result": {"cost_usd": 0.1, "n_input_tokens": 20}},
+ {"agent_result": {"cost_usd": 0.2, "n_input_tokens": 30, "n_output_tokens": 4}},
+ ]})
+ self.assertAlmostEqual(value["cost"], 0.3)
+ self.assertEqual((value["in_tok"], value["out_tok"]), (50, 4))
+
+ def test_missing_metrics_stay_unknown(self):
+ value = self.load({"task_name": "fixture", "verifier_result": None, "agent_result": None})
+ self.assertIsNone(value["reward"])
+ self.assertIsNone(value["cost"])
+ self.assertIsNone(value["sec"])
+
+ def test_cli_cell_totals_include_failed_attempts_but_matrix_stays_matched(self):
+ with tempfile.TemporaryDirectory() as td:
+ root = Path(td)
+ shutil.copyfile(HERE / "collect_results.py", root / "collect_results.py")
+ for arm in ("native", "xerj", "xerj-tuned"):
+ cell = root / "jobs" / f"fixture.model.{arm}"
+ for task, reward, cost in [("solved", 1, 0.5), ("failed", None, 0.25)]:
+ trial = cell / f"{task}__trial"
+ trial.mkdir(parents=True)
+ (trial / "result.json").write_text(json.dumps({
+ "task_name": "matched-task", "reward": reward, "total_cost_usd": cost,
+ "elapsed_seconds": 3600,
+ }))
+ result = subprocess.run([sys.executable, str(root / "collect_results.py")],
+ check=True, capture_output=True, text=True)
+ rows = [line for line in result.stdout.splitlines() if line.split()[:2] == ["fixture", "model"]]
+ self.assertEqual(len(rows), 3)
+ self.assertTrue(all("0.75" in line and line.endswith("2.0") for line in rows), result.stdout)
+ self.assertIn("$0.50 1.0h", result.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()