Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 15,811 Bytes
eae0824
48157bc
 
eae0824
 
48157bc
 
 
 
 
 
 
 
 
 
32539d2
 
48157bc
 
32539d2
 
 
 
 
 
48157bc
 
 
 
 
32539d2
48157bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32539d2
 
 
7059e24
eae0824
7059e24
 
eae0824
7059e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32539d2
eae0824
7059e24
32539d2
 
7059e24
 
32539d2
 
 
 
eae0824
32539d2
 
 
 
48157bc
eae0824
32539d2
 
 
 
 
48157bc
32539d2
 
 
48157bc
32539d2
 
 
 
 
48157bc
 
32539d2
 
 
 
48157bc
 
 
 
32539d2
 
 
 
 
 
48157bc
 
 
 
 
32539d2
48157bc
 
 
 
 
 
 
 
 
 
32539d2
48157bc
 
 
 
 
 
 
 
 
 
 
 
 
6db0e7c
48157bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One row per team from s³ runs (huggingface/legion#115): `uv run eval/metrics.py
RUN_DIR [RUN_DIR ...] [--out rows.jsonl]`.

A run directory is one team: a local run's bundle (`.legion/<swarm>-<time>/`, docs/local.md), or
a Slurm run's directory (`legion init`'s RUN_DIR, docs/slurm.md), where the workers copy what a
run is graded on into `results/`. Under either, each agent's Trials
(`<agent>/trials/<swarm>-<agent>-tN/`: Harbor's `result.json` and `verifier/`) and the board
export (`resources/message_board/{board.jsonl,channels.json}`) are found anywhere. Each row (one
JSON line; README.md has every field):
- the task and team size, how the run ended, and `success`: any agent's reward is 1;
- per agent: its reward (its latest Trial with a verifier result), tokens and board posts;
- the message graph: an edge from a sender to each teammate it mentions (`@agent-002`; a group
  mention such as `@all` names every member) or messages directly (a DM or a private channel of
  the two), with in-degree centralization and reciprocity as in the s³ paper's Appendix M. A
  post that mentions no one adds no edge;
- `missing`: what the run directory lacks (an agent's reward, the board export) or where its
  spec and its Trials disagree, so a row never passes for complete when it is not.

A local run's `run.json` gives the spec, the agents, their tokens (summed over models), the
cost and how the run ended. A Slurm run has no such bundle: the task and the roster come from
its `experiment/spec.yaml` as the run resolved it (its `${VAR}`s from `cluster.env` and
`run.env`, else their defaults), each agent's tokens from its Trials' results (no reasoning
split), and the run's span from its Trials. Every agent the spec planned has a row entry, so
one without results shows in `missing`; so do Trials of an unplanned agent or of another task
than the spec selects (e.g. a run directory whose `run.env` is gone, read with the defaults). The board may hold earlier runs' messages (a reused Space):
only those posted within the run's span count. `EXTRAS` takes per-environment metrics (s3-maze:
moves per agent and room overlap, from the move logs its verifier copies next to the reward).
"""

import argparse
import fnmatch
import json
import re
import sys
from collections import Counter
from collections.abc import Callable
from datetime import datetime
from pathlib import Path

import yaml

TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning")


def load_json(path: Path):
    return json.loads(path.read_text(encoding="utf-8"))


def epoch(value) -> float:
    return float(value) if isinstance(value, int | float) else datetime.fromisoformat(
        value).timestamp()


def bundle(run_dir: Path) -> dict | None:
    """A local run's run.json; None for a Slurm run (its controller's run.json, in the bucket,
    holds neither the spec nor the agents)."""
    path = run_dir / "run.json"
    doc = load_json(path) if path.is_file() else {}
    return doc if "spec" in doc and "agents" in doc else None


def all_trials(run_dir: Path) -> dict[str, list[Path]]:
    """Each agent's Trial directories, oldest first: `<agent>/trials/<swarm>-<agent>-t<N>/`
    (a local run's agents/_harbor/, a Slurm run's results/<swarm>/), one per Trial name."""
    found: dict[str, dict[str, tuple[int, Path]]] = {}
    for trial in run_dir.rglob("trials/*"):
        agent = trial.parent.parent.name
        m = re.fullmatch(rf"(?:.+-)?{re.escape(agent)}-t(\d+)", trial.name)
        if m and trial.is_dir():
            found.setdefault(agent, {}).setdefault(trial.name, (int(m[1]), trial))
    return {a: [p for _, p in sorted(t.values())] for a, t in sorted(found.items())}


def results(trials: list[Path]) -> list[dict]:
    return [load_json(t / "result.json") for t in trials if (t / "result.json").is_file()]


def reward(trials: list[Path]) -> float | None:
    """The reward of the agent's latest Trial that has one."""
    for trial in reversed(trials):
        result = trial / "result.json"
        rewards = ((load_json(result).get("verifier_result") or {}).get("rewards")
                   if result.is_file() else None)
        if rewards and "reward" in rewards:
            return float(rewards["reward"])
        text = trial / "verifier" / "reward.txt"
        if text.is_file() and not text.is_symlink() and text.read_text().strip():
            return float(text.read_text().strip())
    return None


def bundle_tokens(agent: dict) -> dict[str, int]:
    usage = dict.fromkeys(TOKEN_FIELDS, 0)
    for by_model in (agent.get("tokens") or {}).values():
        for key in TOKEN_FIELDS:
            usage[key] += int(by_model.get(key) or 0)
    return usage


def trial_tokens(trials: list[Path]) -> dict[str, int]:
    """Harbor's counts: its input includes the cached tokens."""
    usage = dict.fromkeys(TOKEN_FIELDS, 0)
    for result in results(trials):
        agent = result.get("agent_result") or {}
        cached = int(agent.get("n_cache_tokens") or 0)
        usage["input"] += int(agent.get("n_input_tokens") or 0) - cached
        usage["cache_read"] += cached
        usage["output"] += int(agent.get("n_output_tokens") or 0)
    return usage


def board(run_dir: Path, start: float, end: float) -> tuple[list[dict], dict[int, dict], bool]:
    """(the run's messages, oldest first, channels by id, whether an export was found)."""
    messages, channels, found = {}, {}, False
    for export in run_dir.rglob("resources/message_board/board.jsonl"):
        found = True
        listing = export.with_name("channels.json")
        for channel in load_json(listing) if listing.is_file() else []:
            channels[channel["id"]] = channel
        for line in export.read_text(encoding="utf-8").splitlines():
            if line.strip():
                record = json.loads(line)
                message = record["message"] | {"channel_id": record["channel_id"]}
                if start <= epoch(message["created_at"]) <= end:
                    messages[message["id"]] = message
    return sorted(messages.values(), key=lambda m: m["id"]), channels, found


def sender(message: dict) -> str | None:
    return (message.get("sender") or {}).get("external_id")


def edges(messages: list[dict], channels: dict[int, dict], team: list[str]) -> set[tuple]:
    """(sender, receiver) for each teammate a message mentions or is sent to directly."""
    members = set(team)
    out = set()
    for message in messages:
        source = sender(message)
        if source not in members:
            continue
        targets = {m.get("external_id") for m in message.get("mentions") or []}
        channel = channels.get(message["channel_id"]) or {}
        if channel.get("kind") in ("dm", "private"):
            inside = {m.get("external_id") for m in channel.get("members") or []} & members
            if len(inside) == 2 and source in inside:  # a DM, or a private channel of the two
                targets |= inside
        out |= {(source, target) for target in targets & members if target != source}
    return out


def centralization(graph: set[tuple], team: list[str]) -> float | None:
    """Appendix M: sum over agents of (k* - k_j) / (N - 1)^2, k_j agent j's in-degree and k*
    the largest: 0 when everyone receives from as many teammates, 1 when one agent receives
    from everyone and no one else from anyone. None for a team of one."""
    n = len(team)
    if n < 2:
        return None
    degree = Counter(target for _, target in graph)
    k = [degree[a] for a in team]
    return sum(max(k) - kj for kj in k) / (n - 1) ** 2


def reciprocity(graph: set[tuple]) -> float | None:
    """Appendix M: the fraction of edges whose reverse edge exists. None without edges."""
    return sum((b, a) in graph for a, b in graph) / len(graph) if graph else None


# Per-environment metrics: f(run_dir, team, Trial dirs by agent) -> extra row fields.
# s3-maze adds moves per agent and room overlap, (V - U) / V, from its move logs here.
EXTRAS: list[Callable[[Path, list[str], dict[str, list[Path]]], dict]] = []


def local_run(run: dict) -> dict:
    """What a local bundle says about the run."""
    harbor = next((t.get("harbor") or {} for t in run["spec"]["types"].values()), {})
    task = (harbor.get("config") or {}).get("task") or {}
    agents = sorted(run["agents"], key=lambda a: a["name"])
    return {"swarm": run.get("swarm"), "task": task, "team": [a["name"] for a in agents],
            "start": epoch(run["started_at"]), "end": epoch(run["ended_at"]),
            "stop_reason": run.get("stop_reason"), "duration_s": run.get("duration_s"),
            "cost_usd": (run.get("totals") or {}).get("cost_usd"),
            "tokens": {a["name"]: bundle_tokens(a) for a in agents},
            "turns": {a["name"]: a.get("turns_completed") for a in agents}}


PLACEHOLDER = re.compile(r"\$\{([A-Z_][A-Z0-9_]*)(?::-([^}]*))?\}")


def env_values(path: Path) -> dict[str, str]:
    """NAME=value lines as Legion reads them (legion.specrender.read_env_file): an `export `
    prefix and `#` comment lines allowed; a quoted value ends at its closing quote (what follows
    is a comment), and an unquoted one at whitespace followed by `#`. A line that isn't
    NAME=value is skipped, where Legion refuses the file."""
    values = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        name, sep, raw = line.removeprefix("export ").partition("=")
        name, value = name.strip(), raw.strip()
        if not sep or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name):
            continue
        if value and value[0] in "'\"" and (end := value.find(value[0], 1)) > 0:
            value = value[1:end]
        else:
            value = re.split(r"\s+#", raw, maxsplit=1)[0].strip()
        values[name] = value
    return values


def run_values(run_dir: Path) -> dict[str, str]:
    """The run's `cluster.env` then `run.env` (later wins), as Legion reads them: what fills the
    spec's `${VAR}`s."""
    values = {}
    for name in ("cluster.env", "run.env"):
        if (run_dir / name).is_file():
            values |= env_values(run_dir / name)
    return values


def expand(text: str, values: dict[str, str]) -> str:
    """`${VAR}` and `${VAR:-default}` in the spec's text, as Legion fills them (empty = unset)."""
    return PLACEHOLDER.sub(lambda m: values.get(m[1]) or (m[2] if m[2] is not None else m[0]),
                           text)


def slurm_run(run_dir: Path, trials: dict[str, list[Path]]) -> dict:
    """What a Slurm run's directory says: its spec as the run resolved it (`legion init`'s copy
    of the experiment, its `${VAR}`s filled from `cluster.env` then `run.env`, else their
    defaults) and the Trials the workers kept. The spec gives the task and the roster: every
    agent it planned is in the row, so one whose results are missing is flagged, not dropped.
    `problems` says where the spec and the Trials disagree (e.g. a `run.env` that is gone, its
    values replaced by the defaults)."""
    path = run_dir / "experiment" / "spec.yaml"
    spec = (yaml.safe_load(expand(path.read_text(), run_values(run_dir)))
            if path.is_file() else None) or {}
    problems = [] if spec else ["spec: no experiment/spec.yaml"]
    agents = spec.get("agents") or {}
    count = agents.get("count") if type(agents.get("count")) is int else None
    if spec and count is None:
        problems.append(f"spec: agents.count is {agents.get('count')!r}, not a number")
    if spec.get("naming") == "consecutive-id" and count is not None:
        team = [f"agent-{k:03d}" for k in range(1, count + 1)]
    else:
        team = list(trials)
        if count is not None and len(team) < count:
            problems.append(f"agents: {len(team)} of the {count} planned have Trials")
    if outside := sorted(set(trials) - set(team)):
        problems.append(f"agents: Trials of agents the spec didn't plan: {', '.join(outside)}")
    times = [(epoch(r["started_at"]), epoch(r["finished_at"]))
             for ts in trials.values() for r in results(ts)
             if r.get("started_at") and r.get("finished_at")]
    start, end = (min(t[0] for t in times), max(t[1] for t in times)) if times else (0, 0)
    ran = sorted({r["task_name"].split("/")[-1] for ts in trials.values() for r in results(ts)
                  if r.get("task_name")})
    task = spec.get("task") or {"selector": ran[0] if len(ran) == 1 else None}
    selector = task.get("selector") or ""
    if odd := [name for name in ran if not fnmatch.fnmatchcase(name, selector)]:
        problems.append(f"task: the spec selects {selector!r}, the Trials ran {', '.join(odd)}")
    swarm = next((t.name.removesuffix(f"-{a}-t{t.name.rsplit('-t', 1)[1]}")
                  for a, ts in trials.items() for t in ts), spec.get("name"))
    return {"swarm": swarm, "task": task, "team": team, "start": start, "end": end,
            "stop_reason": None, "duration_s": round(end - start, 1) if times else None,
            "cost_usd": None, "tokens": {a: trial_tokens(trials.get(a, [])) for a in team},
            "turns": dict.fromkeys(team), "problems": problems}


def row(run_dir: Path) -> dict:
    trials = all_trials(run_dir)
    run = bundle(run_dir)
    info = local_run(run) if run is not None else slurm_run(run_dir, trials)
    team = info["team"]
    messages, channels, exported = board(run_dir, info["start"], info["end"])
    posts = Counter(sender(m) for m in messages)
    graph = edges(messages, channels, team)
    per_agent, missing = {}, list(info.get("problems", []))
    for name in team:
        value = reward(trials.get(name, []))
        if value is None:
            missing.append(f"reward: {name}")
        per_agent[name] = {"reward": value, "tokens": info["tokens"][name],
                           "posts": posts[name], "turns": info["turns"][name]}
    if not exported:
        missing.append("board export")
    rewards = [a["reward"] for a in per_agent.values() if a["reward"] is not None]
    task = info["task"]
    out = {
        "run": run_dir.name,
        "swarm": info["swarm"],
        "task": re.sub(r"-s\*$", "", task.get("selector") or "") or None,  # a team's slots
        "dataset": task.get("repo"),
        "revision": task.get("revision"),
        "agents": len(team),
        "stop_reason": info["stop_reason"],
        "duration_s": info["duration_s"],
        "success": any(r == 1 for r in rewards) if rewards else None,
        "rewards": {name: a["reward"] for name, a in per_agent.items()},
        "tokens": {key: sum(a["tokens"][key] for a in per_agent.values())
                   for key in TOKEN_FIELDS},
        "cost_usd": info["cost_usd"],
        "posts": sum(posts[name] for name in team),
        "other_posts": sum(n for who, n in posts.items() if who not in team),
        "per_agent": per_agent,
        "edges": sorted([a, b] for a, b in graph),
        "centralization": centralization(graph, team),
        "reciprocity": reciprocity(graph),
        "missing": missing,
    }
    for extra in EXTRAS:
        out |= extra(run_dir, team, trials)
    return out


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="One row per team (JSON lines) from s³ runs.")
    parser.add_argument("run_dirs", nargs="+", type=Path)
    parser.add_argument("--out", type=Path, help="append the rows here (default: stdout)")
    args = parser.parse_args(argv)
    rows = [json.dumps(row(d)) for d in args.run_dirs]
    if args.out:
        with args.out.open("a", encoding="utf-8") as f:
            f.write("".join(r + "\n" for r in rows))
    else:
        print("\n".join(rows))
    return 0


if __name__ == "__main__":
    sys.exit(main())