diff --git a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json index 29f7c24d..4672d80f 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/benchmark.json +++ b/app/nullius/catalogue/benchmarks/osworld1/benchmark.json @@ -9,6 +9,7 @@ ], "origin": "official", "good_to_know": [ + "With any agent but OSWorld's own, a task cut short by its time (2 hours), by the run's cap of model calls or after its end is scored as the desktop stands.", "Original runs one of OSWorld's own agents, chosen by the Agent option (M3 by default), with a model it is published with.", "Providers: OpenAI for OpenAI CUA; OpenAI-compatible for Muse Spark (Meta's API) and for EvoCUA, AutoGLM-OS and Mano (your model server); OpenRouter for the others.", "At this version only the null control has run through Nullius. OSWorld's agents are the same code as in main (044bc33), where M3, PromptAgent and Qwen-CUA completed tasks.", @@ -36,7 +37,7 @@ "The agent's python and upload calls do not mark OSWorld's desktop as used; each unit's desktop is reset once, before the agent's first call.", "Only 12 of OSWorld's agents are offered; the others fail at the pinned commit or need services the relay cannot reach.", "The VMs run only on Docker's default socket, not on rootless Docker or a Docker context. Podman is untested.", - "A task run by one of OSWorld's own agents and still running after 2 hours is stopped and gets no score. For an agent, the task's setup may take 1 hour, the agent's turn 2 hours and the scoring 10 minutes; past any of them the task gets no score.", + "No score past: 2 hours with OSWorld's own agents; 1 hour of setup or 10 minutes of scoring with any other agent.", "Its evaluator fixes, key repeat turned off in the VM and one retired task make its scores comparable only with this version's, not with the paper's or main (044bc33)'s." ], "datasets": [ @@ -57,6 +58,7 @@ "versions": { "044bc33": { "good_to_know": [ + "With any agent but OSWorld's own, a task cut short by its time (2 hours), by the run's cap of model calls or after its end is scored as the desktop stands.", "Original runs one of OSWorld's own agents, chosen by the Agent option (M3 by default), with a model it is published with.", "Providers: OpenAI for OpenAI CUA; OpenAI-compatible for Muse Spark (Meta's API) and for EvoCUA, AutoGLM-OS and Mano (your model server); OpenRouter for the others.", "Only M3, PromptAgent and Qwen-CUA have completed tasks through Nullius. The other agents were checked up to their first model call.", @@ -77,7 +79,7 @@ "The agent's python and upload calls do not mark OSWorld's desktop as used; each unit's desktop is reset once, before the agent's first call.", "Only 12 of OSWorld's agents are offered; the others fail at the pinned commit or need services the relay cannot reach.", "The VMs run only on Docker's default socket, not on rootless Docker or a Docker context. Podman is untested.", - "A task run by one of OSWorld's own agents and still running after 2 hours is stopped and gets no score. For an agent, the task's setup may take 1 hour, the agent's turn 2 hours and the scoring 10 minutes; past any of them the task gets no score." + "No score past: 2 hours with OSWorld's own agents; 1 hour of setup or 10 minutes of scoring with any other agent." ], "datasets": { "osworld1": { diff --git a/app/nullius/catalogue/benchmarks/osworld1/driver.py b/app/nullius/catalogue/benchmarks/osworld1/driver.py index d8b89765..709c1aea 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/driver.py +++ b/app/nullius/catalogue/benchmarks/osworld1/driver.py @@ -18,8 +18,9 @@ asks for the agent's first step, setup answers the prompt (the instruction, a blank line and the desktop user's password line), the MCP server computer (the port's pipe, joined to the runner's - socket) and the agent's time. The options max_steps and pause are - the loop's + socket), the agent's time and, as progress, the port's progress + file inside the trial. The options max_steps and pause are the + loop's task_given - an agent's unit (driver.task_given): the agent is about to be given its task. The runner is told on its lifeline, closes the port's window before the task and says so; this answers then @@ -44,7 +45,9 @@ folder, never the workspace, and only from a runner this driver started that ended by itself with status 0, through folders opened without following a link. It copies result.txt, the call log and the - record of prepare calls to the trial's verifier/osworld/. + record of prepare calls to the trial's verifier/osworld/, and its + detail says the steps taken, the budget and what ended the loop, + from the progress file. For the null control, nop.py: the upstream's run_single_example with an agent that answers DONE at its first step, its result.txt read the same way @@ -108,6 +111,7 @@ for e in AGENTS["agents"].values()} VM =os.path.join(UP, "docker_vm_data", "Ubuntu.qcow2") # where the upstream's DockerVMManager puts it RESULTS = "results" +PROGRESS = "progress.json" # the port's progress file, in an agent's runner folder # VM starts on one machine, one after another: the upstream's docker provider creates each container under # /tmp/docker_port_allocation.lck, and a start that waits there more than 10 s fails (LOCK_TIMEOUT) START_LOCK = "/tmp/nullius-osworld1-vm-start.lck" @@ -479,6 +483,7 @@ def _start_runner(unit, dir, instruction, until): "--socket", os.path.join(sock_dir, "s"), "--ready", ready, "--lifeline", str(life_r), "--steps", "100" if steps == "default" else steps, "--pause", str(_option("pause", "3.0", float)), "--vm", vm, "--calls", os.path.join(where, "computer-calls.jsonl"), "--held", held, + "--progress", os.path.join(where, PROGRESS), "--prepared", os.path.join(where, "computer-prepare.jsonl"), "--given", os.path.join(sock_dir, "given.json")] lock = open(START_LOCK, "a") @@ -533,7 +538,7 @@ def _start_runner(unit, dir, instruction, until): pipe = os.path.join(os.path.dirname(os.path.abspath(_port().__file__)), "computer_pipe.py") return {"prompt": instruction + "\n\n" + PASSWORD_LINE.format(password=said.get("password") or ""), "mcp": [{"name": "computer", "server": "computer", "args": [pipe, os.path.join(sock_dir, "s")]}], - "agent_seconds": AGENT_SECONDS} + "agent_seconds": AGENT_SECONDS, "progress": os.path.join(".work", "osworld", PROGRESS)} def _has(log, text, start=0): @@ -805,13 +810,19 @@ def _agent_score(where, dir, domain, eid): except (OSError, RuntimeError): pass calls = kept["computer-calls.jsonl"] + try: + count = json.loads(_plain(trial, ".work", "osworld", PROGRESS)) + count = count if isinstance(count, dict) else {} + except (OSError, RuntimeError, ValueError): + count = {} out = os.path.join(trial, "verifier", "osworld") os.makedirs(out, exist_ok=True) for name, data in [("result.txt", result)] + sorted(kept.items()): with open(os.path.join(out, name), "wb") as f: f.write(data) return {"reward": value, "detail": {"result": value, "by": "runner.py, run_single_example, DesktopEnv.evaluate", - "tool_calls": len(calls.splitlines())}} + "tool_calls": len(calls.splitlines()), "steps": count.get("steps"), + "steps_limit": count.get("steps_limit"), "ended": count.get("ended")}} def _scored(where, how): diff --git a/app/nullius/catalogue/benchmarks/osworld1/runner.py b/app/nullius/catalogue/benchmarks/osworld1/runner.py index e2a98670..7b224f21 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/runner.py +++ b/app/nullius/catalogue/benchmarks/osworld1/runner.py @@ -2,7 +2,7 @@ they are, with the computer port's bridge as the loop's agent (nullius.standard.protocols.computer_port, agent.computer/v1). runner.py --example TASK_JSON --result-dir DIR --socket PATH --ready FILE --lifeline FD --steps N --pause SECONDS - --vm VM_IMAGE --calls FILE [--held FOLDER] [--prepared FILE] [--given FILE] + --vm VM_IMAGE --calls FILE [--held FOLDER] [--progress PROGRESS] [--prepared FILE] [--given FILE] The driver starts it in the unit's runner folder with the upstream and Nullius on its import path. It builds the upstream's DesktopEnv as the null control does (nop.py), serves the MCP server computer at PATH (a Unix socket in a folder of the user's alone, which the driver @@ -18,6 +18,7 @@ the runner then writes --given's file, {"ok": true}; its close stops the runner as SIGTERM does. - FILE, the call log: one line per tool call, {tool, start, end, isError}; --prepared's, one line per prepare call. - FOLDER, the run's folder of files sent once, when the driver gives one (computer_port.Held). +- PROGRESS, the progress file the bridge keeps, when the driver gives one: {steps, steps_limit, ended, open}. A stop is taken once. The clean-up (the bridge's end and the server's close, then the desktop's close within CLOSE_SECONDS) takes at most STOP_SECONDS; past it the runner exits 1 all the same. At every exit READY and the socket's folder are removed. The @@ -129,7 +130,7 @@ def main(argv=None): p = argparse.ArgumentParser() for name in ("--example", "--result-dir", "--socket", "--ready", "--vm", "--calls"): p.add_argument(name, required=True) - for name in ("--held", "--prepared", "--given"): + for name in ("--held", "--progress", "--prepared", "--given"): p.add_argument(name) p.add_argument("--lifeline", type=int, required=True) p.add_argument("--steps", type=int, required=True) @@ -175,7 +176,8 @@ def first(): # the loop asks for the agent's os.makedirs(where, exist_ok=True) desktop = Desktop(env, os.path.dirname(os.path.abspath(a.calls))) bridge = port.Bridge(desktop, a.steps, a.pause, SCREEN, FOLDER, on_first=first, - held=port.Held(a.held) if a.held else None, window=bool(a.given), prepared=a.prepared) + held=port.Held(a.held) if a.held else None, progress=a.progress, window=bool(a.given), + prepared=a.prepared) server = port.Server(bridge, a.socket, a.calls) turn.bridge = bridge lib_run_single.run_single_example(bridge, Watched(env, desktop), example, a.steps, example["instruction"], diff --git a/app/nullius/catalogue/benchmarks/osworld1/standard.json b/app/nullius/catalogue/benchmarks/osworld1/standard.json index 70fae6c7..42b94424 100644 --- a/app/nullius/catalogue/benchmarks/osworld1/standard.json +++ b/app/nullius/catalogue/benchmarks/osworld1/standard.json @@ -39,7 +39,12 @@ } }, "limits": { - "setup_seconds": 3600 + "setup_seconds": 3600, + "scored_cuts": [ + "time", + "calls", + "end" + ] }, "datasets": [ { diff --git a/app/nullius/compare/comparison.py b/app/nullius/compare/comparison.py index 8bb5902a..7ceca10a 100644 --- a/app/nullius/compare/comparison.py +++ b/app/nullius/compare/comparison.py @@ -197,14 +197,17 @@ def key(selection, trial): for trial in trials: by_task.setdefault(key(selection, trial), [[] for _ in selected])[column].append(trial) + scored_only = [selection.job.scored_only for selection in selected] + def task_row(task_key, columns): return TaskRow(*task_key, tuple(ts[-1] if ts else None for ts in columns), tuple(len(ts) for ts in columns), - tuple(task_attempts.Attempts(tuple(task_attempts.ordered(ts))) if ts else None for ts in columns)) + tuple(task_attempts.Attempts(tuple(task_attempts.ordered(ts)), scored_only[i]) if ts else None + for i, ts in enumerate(columns))) rows = [task_row(task_key, columns) for task_key, columns in by_task.items()] rows.sort(key=lambda row: (-round(row.movement, 3), not row.rate_moved, not row.differs, row.dataset, row.task)) # pass@k from the rows' own tasks, so the summary and the table count alike - pass_k = tuple(task_attempts.for_tasks(row.tried[column].trials for row in rows if row.tried[column]) + pass_k = tuple(None if scored_only[column] else task_attempts.for_tasks(row.tried[column].trials for row in rows if row.tried[column]) for column in range(len(selected))) return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common - set_aside), tuple(excluded), tuple(repeated), datasets_match, known, pass_k, tuple(aside)) diff --git a/app/nullius/runs/attempts.py b/app/nullius/runs/attempts.py index 743a2047..02f36b82 100644 --- a/app/nullius/runs/attempts.py +++ b/app/nullius/runs/attempts.py @@ -63,6 +63,10 @@ def ordered(trials) -> list: # the benchmark gives a score and no pass or fail. NO_VERDICT = frozenset({classify.UNKNOWN, classify.SCORED}) +# Outcomes the benchmark's own check gave. +VERIFIED = frozenset({classify.RESOLVED, classify.FAILED_VERIFICATION, classify.PATCH_FAILED_TESTS, classify.PATCH_NOT_APPLIED, + classify.NO_PATCH}) + # The numbers a task's row shows as a mean over its attempts. MEANS = ("tokens", "dur_total", "dur_env", "dur_agent", "dur_verifier") @@ -74,14 +78,17 @@ def ran(trials) -> tuple: def has_verdict(trials) -> bool: """Whether an attempt that ran was passed or failed, so a pass count over - them means something.""" - return any(t.outcome not in NO_VERDICT for t in ran(trials)) + them means something. Never beside a score with no pass or fail: an attempt + that crashed there was not failed by the benchmark.""" + graded = any(t.outcome == classify.SCORED and t.score is not None for t in ran(trials)) + return any(t.outcome not in NO_VERDICT and not (graded and t.outcome not in VERIFIED) for t in ran(trials)) @dataclass(frozen=True) class Attempts: - """Every attempt at one task in one job, numbered from 1.""" + """Every attempt at one task in one job, numbered from 1; ``scored_only``, the job's.""" trials: tuple + scored_only: bool = False @property def n(self) -> int: @@ -107,7 +114,7 @@ def n_passed(self) -> int: def has_verdicts(self) -> bool: """False when no attempt that ran was passed or failed (all unknown, scored or infra).""" - return has_verdict(self.trials) + return not self.scored_only and has_verdict(self.trials) @property def scores(self) -> list: @@ -171,13 +178,13 @@ def _by_task_name(job) -> dict[str, list]: def by_task(job) -> dict[str, Attempts]: """Every task of the job that was attempted more than once, by task name.""" - return {task: Attempts(tuple(ordered(ts))) for task, ts in _by_task_name(job).items() if len(ts) > 1} + return {task: Attempts(tuple(ordered(ts)), job.scored_only) for task, ts in _by_task_name(job).items() if len(ts) > 1} def of(job, trial) -> Attempts | None: """The attempts at this trial's task, or None when it was attempted once.""" same = [t for t in job.trials if t.task_name == trial.task_name] - return Attempts(tuple(ordered(same))) if len(same) > 1 else None + return Attempts(tuple(ordered(same)), job.scored_only) if len(same) > 1 else None def grouped(job) -> list[tuple]: @@ -237,5 +244,5 @@ def for_tasks(tasks: Iterable[Sequence]) -> dict | None: def for_job(job) -> dict | None: - """``for_tasks`` over a parsed job, its tasks by task name.""" - return for_tasks(_by_task_name(job).values()) + """``for_tasks`` over a parsed job, its tasks by task name; None for a job with scores and no pass or fail.""" + return None if job.scored_only else for_tasks(_by_task_name(job).values()) diff --git a/app/nullius/runs/cli.py b/app/nullius/runs/cli.py index 4accea49..48646b7a 100644 --- a/app/nullius/runs/cli.py +++ b/app/nullius/runs/cli.py @@ -106,6 +106,7 @@ def job_detail(job: parse.Job) -> dict: data["mean_score_planned"] = job.mean_score_planned for trial, raw in zip(job.trials, data["trials"]): raw["outcome_label"] = trial.outcome_label + raw["ended_label"] = trial.ended_label raw["is_infra"] = trial.is_infra raw["is_regression"] = trial.is_regression raw["has_trace"] = trial.has_trace @@ -120,6 +121,7 @@ def _trial_record(trial: parse.Trial) -> dict: derived ones the pages render, timestamps as ISO strings.""" raw = asdict(trial) raw["outcome_label"] = trial.outcome_label + raw["ended_label"] = trial.ended_label raw["is_infra"] = trial.is_infra raw["is_regression"] = trial.is_regression raw["has_trace"] = trial.has_trace @@ -195,6 +197,8 @@ def _print_trial(job: parse.Job, trial: parse.Trial) -> None: print(f" evidence: trajectory {'recorded' if t.has_trajectory else 'absent'} · " f"trace {'recorded' if t.has_trace else 'absent'} · " f"reward {'recorded' if t.reward is not None else 'absent'}") + if t.ended_by: + print(f" ended by: {t.ended_label} ({t.ended_by})") if t.exception_type: print(f" exception: {t.exception_type}: {_first_line(t.exception_message)}") for name in t.p2p_failures: @@ -325,6 +329,8 @@ def _show(args) -> int: width = max((len(t.trial_name) for t in job.trials), default=0) for t in job.trials: line = f" {t.trial_name:<{width}} {t.outcome}" + if t.ended_by: + line += f" ended by {t.ended_by}" if t.exception_type: line += f" {t.exception_type}" print(line) diff --git a/app/nullius/runs/live.py b/app/nullius/runs/live.py index a2751168..d0bab9d7 100644 --- a/app/nullius/runs/live.py +++ b/app/nullius/runs/live.py @@ -17,6 +17,11 @@ preparation window instead of nothing (its ``stage`` names what is being prepared; ``job.start`` keeps meaning "trials are about to be scheduled"). Payloads are read leniently — a missing counter is *absent*, never zero. +``trial.progress`` carries the counters of :data:`COUNTERS` and an +``activity`` line; the standard's runner also sends a running unit's +:data:`PROGRESS`: its step limit beside its ``step``, its agent's model calls +answered and the run's cap on them. A trial's snapshot holds these three only +once its feed reported one, so a feed without them folds as it always did. Four rules are load-bearing, and each has a test: @@ -74,6 +79,7 @@ "cancelled", "timeout", "budget") ERROR_OUTCOMES = {"agent_error", "infra_error", "timeout", "budget"} COUNTERS = ("step", "n_input_tokens", "n_cache_tokens", "n_output_tokens", "cost_usd") +PROGRESS = ("step_limit", "calls", "calls_limit") TOKEN_FIELDS = ("n_input_tokens", "n_cache_tokens", "n_output_tokens") RATE_WINDOW_SEC = 30.0 @@ -201,6 +207,9 @@ class TrialState: timeout_sec: float | None = None phases_done: list[str] = field(default_factory=list) step: int | None = None + step_limit: int | None = None + calls: int | None = None + calls_limit: int | None = None n_input_tokens: int | None = None n_cache_tokens: int | None = None n_output_tokens: int | None = None @@ -247,7 +256,9 @@ def snapshot(self, now: datetime) -> dict: "phase": self.phase, "since": _iso(self.since) if self.since else None, "elapsed_sec": elapsed, "timeout_sec": self.timeout_sec, "phases_done": list(self.phases_done), - "step": self.step, "n_input_tokens": self.n_input_tokens, + "step": self.step, + **({k: getattr(self, k) for k in PROGRESS} if any(getattr(self, k) is not None for k in PROGRESS) else {}), + "n_input_tokens": self.n_input_tokens, "n_cache_tokens": self.n_cache_tokens, "n_output_tokens": self.n_output_tokens, "cost_usd": self.cost_usd, "activity": self.activity, "last_line": self.last_line, "outcome": self.outcome, "reward": self.reward, "durations": dict(self.durations), @@ -605,7 +616,7 @@ def trial_of(e: Event) -> TrialState: # but it was paid for, and the board's cost goes on counting it if t.cost_usd is not None: t.cost_before = (t.cost_before or 0.0) + t.cost_usd - for key in COUNTERS: + for key in (*COUNTERS, *PROGRESS): setattr(t, key, None) t._series = [] if t.phase and t.phase not in t.phases_done and t.phase != d["phase"]: @@ -619,6 +630,9 @@ def trial_of(e: Event) -> TrialState: for key in COUNTERS: if key in d and d[key] is not None: setattr(t, key, _num(d[key], int if key != "cost_usd" else float)) + for key in PROGRESS: + if d.get(key) is not None: + setattr(t, key, _num(d[key], int)) if d.get("activity") is not None: t.activity = d["activity"] reported = {k: _num(d[k], int) for k in TOKEN_FIELDS if d.get(k) is not None} diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 1597a461..720f3853 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -31,7 +31,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "18" +SCHEMA = "19" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — @@ -75,6 +75,11 @@ def _retries_of(res: dict) -> int: return n if isinstance(n, int) and not isinstance(n, bool) and n > 0 else 0 +# What ended an agent's work on a standard trial (`Trial.ended_by`), by its name; any other end a benchmark's +# detail names reads as written: a tag up to ENDED_CHARS characters, a longer one in failure analysis. +ENDED_LABELS = {"agent": "Agent", "done": "Done", "fail": "Fail", "steps": "Step limit", "time": "Time limit", + "calls": "Call limit", "end": "Task end"} +ENDED_CHARS = 16 SCORE_BYTES = 1024 * 1024 @@ -171,6 +176,30 @@ def visit(values, path=""): return {"fields": fields, "groups": groups} if fields or groups else None +def _ended_by(res: dict, trial_dir: str) -> str: + """What ended the agent's work on a standard trial: the run's cut when its record has one (``standard.cut``: + ``time``, the agent's time; ``calls``, the run's cap on its model calls); else the benchmark's own end as its + score's detail says it (``detail.ended``: ``done``, ``fail``, ``steps``; ``turn``, the agent ended its turn + first: ``agent``; any other text of the benchmark's, redacted); ``end`` for a turn cut + after the benchmark's end with no detail to name it. "" when the trial says none of these.""" + std = res.get("standard") if isinstance(res.get("standard"), dict) else None + if std is None: + return "" + cut = std.get("cut") + if cut in ("time", "calls"): + return cut + said = _read_score(trial_dir) + detail = said.get("detail") if isinstance(said, dict) else None + ended = detail.get("ended") if isinstance(detail, dict) else None + if ended in ("done", "fail", "steps"): + return ended + if isinstance(ended, str) and ended.strip() and ended != "turn": + return redact(ended.strip()) # the benchmark's own end, which the pages have no label for + if cut == "end": + return "end" + return "agent" if ended == "turn" else "" + + def count_rate_limits(path: str) -> int | None: """Rate-limit records in a gateway log, or None when there is no log. @@ -296,6 +325,24 @@ class Trial: started_at: datetime | None = None finished_at: datetime | None = None phases: dict = field(default_factory=dict) + # What ended the agent's work on a standard trial (`_ended_by`): `agent`, + # `done`, `fail`, `steps`, `time`, `calls` or `end`, or the benchmark's own + # word for it; "" when it says none. + ended_by: str = "" + + @property + def ended_label(self) -> str: + return ENDED_LABELS.get(self.ended_by, self.ended_by) + + @property + def ended_tag(self) -> str: + """What cut the agent's work short, for a tag: "" for a normal end and for a reason too long for one.""" + return "" if self.is_infra or self.ended_by in ("agent", "done", "fail") or len(self.ended_label) > ENDED_CHARS else self.ended_label + + @property + def stop_reason(self) -> str: + """The benchmark's own reason when it is too long for a tag.""" + return self.ended_label if len(self.ended_label) > ENDED_CHARS else "" @property def dur_phases(self) -> float: @@ -815,6 +862,7 @@ def parse_trial(job_id: str, trial_dir: str) -> Trial | None: started_at=_iso(res.get("started_at")), finished_at=_iso(res.get("finished_at")), phases=phases, + ended_by=_ended_by(res, trial_dir), ) diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index ad1d9642..6803ee47 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -135,6 +135,10 @@ _MODEL_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$") APIS = ("chat", "responses", "messages") SCORES = ("pass", "score") +# What may cut an agent's work on a unit short and still leave it scored, for a benchmark that says so +# (``limits.scored_cuts``): the agent's time, the run's cap on its model calls, and the benchmark's own loop +# having ended while the agent went on +CUTS = ("time", "calls", "end") # A benchmark's controls, by the words Harbor calls them (``runs.parse.CONTROL_AGENTS``), # and who wrote each: the benchmark's authors, a harness adapter's author, or Nullius. CONTROLS = ("nop", "oracle") @@ -1609,6 +1613,10 @@ def problems(d: dict, kind: str) -> List[str]: v = lim.get(f) if v is not None and (isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 100000): bad.append(f"limits.{f}: a whole number from 1") + cuts = lim.get("scored_cuts") + if cuts is not None and (not isinstance(cuts, list) or not cuts or len(set(map(str, cuts))) != len(cuts) + or any(c not in CUTS for c in cuts)): + bad.append(f"limits.scored_cuts: the cuts after which an agent's unit is still scored, each once, of {CUTS}") a = lim.get("attempts") if a is not None and (not isinstance(a, str) or not a.strip()): bad.append("limits.attempts: how the upstream tells one attempt of a unit from another (its seed per trial), " diff --git a/app/nullius/standard/kits/agent-computer-v1/driver.py b/app/nullius/standard/kits/agent-computer-v1/driver.py index 80e74e92..7a60d1ba 100644 --- a/app/nullius/standard/kits/agent-computer-v1/driver.py +++ b/app/nullius/standard/kits/agent-computer-v1/driver.py @@ -7,12 +7,13 @@ driver's process, the port's server over that desktop (``computer_port.Bridge`` and ``Server``, its socket in a folder of this user's alone) and the kit's loop: a thread that asks the bridge for a step, runs its actions with ``Desktop.act`` and waits the pause after each, as a desktop benchmark's own loop does. The session gets the -server through ``computer_pipe.py`` (``mcp_servers.computer``). The server's window before the task is closed by -``task_given`` (which the definition's ``driver.task_given`` asks Nullius to send) or, for the reference, as it -starts; every prepare call is recorded in ``verifier/computer-prepare.jsonl``, the agent's folder is ``FOLDER``. -``score`` ends the turn, waits for the loop, reads the fixture's log, the actions' times and the call log, judges, -and removes the desktop and the socket. ``oracle`` is the reference: the right calls, sent to the unit's own server -as a client. +server through ``computer_pipe.py`` (``mcp_servers.computer``); setup's ``progress`` names the bridge's progress +file, beside the call log. The server's window before the task is closed by ``task_given`` (which the definition's +``driver.task_given`` asks Nullius to send) or, for the reference, as it starts; every prepare call is recorded in +``verifier/computer-prepare.jsonl``, the agent's folder is ``FOLDER``. ``score`` ends the turn, waits for the loop, +reads the fixture's log, the actions' times and the call log, judges, says the steps taken, the budget and what ended +the loop, and removes the desktop and the socket. ``oracle`` is the reference: the right calls, sent to the unit's own +server as a client. **late.** One labelled button appears ``LATE_SECONDS`` after the task is given, away from the screen's centre at a place drawn for the unit (``late_place``), so that no click at a fixed point finds it; the agent clicks it. It passes @@ -70,6 +71,7 @@ def _load(name, file): USE = "Use the tools of the MCP server named computer, given to this session: they show and drive a desktop. " DONE = " Then reply with the word done." NOT_RUN = "The desktop could not run this step, and none of it was run. It may be sent again." +PROGRESS = os.path.join("verifier", "computer-progress.json") def prompt(unit, expected): @@ -250,6 +252,7 @@ def __init__(self, unit, dir): self.values, self.expected = checks.draw(unit) self.steps = checks.steps(unit) self.log = os.path.join(self.trial, "verifier", "computer-calls.jsonl") + self.progress = os.path.join(self.trial, PROGRESS) self.prepared = os.path.join(self.trial, "verifier", "computer-prepare.jsonl") self.desktop = self.bridge = self.server = self.loop = self.folder = self.boxes = None self.final, self.error = "", None @@ -282,8 +285,8 @@ def act(code, seconds=PYTHON_SECONDS): # each action's start on the driver REAPER.tell(f"+folder {folder}") # named before it is made self.folder = folder os.mkdir(folder, 0o700) - self.bridge = KitBridge(Pictures(self.desktop, self), self.steps, PAUSE, desktop.SCREEN, FOLDER, window=True, - prepared=self.prepared) + self.bridge = KitBridge(Pictures(self.desktop, self), self.steps, PAUSE, desktop.SCREEN, FOLDER, + progress=self.progress, window=True, prepared=self.prepared) self.server = KitServer(self.bridge, self.socket(), log=self.log) self.loop = threading.Thread(target=self.run_loop, name=f"kit-loop-{self.unit}", daemon=True) self.loop.start() @@ -492,7 +495,7 @@ def setup(unit, dir, **_): u.close() raise return {"prompt": prompt(unit, u.expected), "mcp": [{"name": "computer", "server": "computer", "args": [u.socket()]}], - "agent_seconds": AGENT_SECONDS} + "agent_seconds": AGENT_SECONDS, "progress": PROGRESS} def task_given(unit, dir, **_): @@ -527,7 +530,8 @@ def score(unit, dir, transcript, answer, **_): else: v = checks.verdict(unit, u.expected, events, actions, message, calls, u.bridge.past) passed = v["passed"] and u.error is None - detail = {"said": (answer or "")[:200], "steps": u.steps, "steps_used": u.bridge.used, "past_budget": u.bridge.past, + detail = {"said": (answer or "")[:200], "steps": u.steps, "steps_used": u.bridge.used, "ended": u.bridge.ended_by, + "past_budget": u.bridge.past, "calls": [c.get("tool") for c in calls], "errors": sum(1 for c in calls if c.get("isError")), "actions": len(actions), "events": sum(1 for e in events if e.get("kind") in checks.POINTER + checks.KEYS)} why = v["why"] or u.error diff --git a/app/nullius/standard/protocols/acp.py b/app/nullius/standard/protocols/acp.py index 245c1545..777b5b36 100644 --- a/app/nullius/standard/protocols/acp.py +++ b/app/nullius/standard/protocols/acp.py @@ -24,9 +24,10 @@ that does not know them sends text, and :func:`last_message` keeps what it can of the answer apart. -A turn that outlives its timeout is cancelled (``session/cancel``) and, if the -agent does not stop, its process group is killed; :class:`Timeout` is raised -either way, and the events so far are kept on it. +A turn that outlives its timeout, or that its caller cuts, is cancelled +(``session/cancel``) and, if the agent does not stop, its process group is +killed; :class:`Timeout` is raised either way, and the events so far are kept +on it. """ from __future__ import annotations @@ -210,7 +211,7 @@ def tail(self) -> str: except OSError: return "no log" - def request(self, method: str, params: dict, timeout: float = 600): + def request(self, method: str, params: dict, timeout: float = 600, cut=None): if self.stopped is not None and self.stopped.is_set(): raise CancelledError("the run was stopped") self.n += 1 @@ -221,7 +222,7 @@ def request(self, method: str, params: dict, timeout: float = 600): except (BrokenPipeError, OSError): raise AgentFailed(f"{method}: the agent had already ended ({self.tail()})") try: - m = reply(q, timeout, self.stopped) + m = reply(q, timeout, self.stopped, cut) except queue.Empty: raise TimeoutError(method) finally: @@ -302,12 +303,14 @@ def authenticate(self) -> bool: return True return False - def prompt(self, sid: str, text: str, timeout: float = 600) -> Turn: + def prompt(self, sid: str, text: str, timeout: float = 600, cut=None) -> Turn: + """One turn. ``cut``, an event: once it is set the turn is ended as one past its ``timeout`` is.""" start = len(self.events) t0 = time.time() self.events.append({"t": t0, "update": {"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": text}}}) try: - res = self.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]}, timeout=timeout) + res = self.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]}, timeout=timeout, + cut=cut) except TimeoutError: try: self._send({"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": sid}}) diff --git a/app/nullius/standard/protocols/cancellation.py b/app/nullius/standard/protocols/cancellation.py index 6c0abd4c..e664334a 100644 --- a/app/nullius/standard/protocols/cancellation.py +++ b/app/nullius/standard/protocols/cancellation.py @@ -4,16 +4,18 @@ from concurrent.futures import CancelledError -def reply(messages, timeout, stopped=None): +def reply(messages, timeout, stopped=None, cut=None): + """The next message within ``timeout`` seconds; ``queue.Empty`` past them, and as soon as ``cut`` is set: the + wait then ends as if its time had run out.""" deadline = time.monotonic() + timeout while True: if stopped is not None and stopped.is_set(): raise CancelledError("the run was stopped") remaining = deadline - time.monotonic() - if remaining <= 0: + if remaining <= 0 or (cut is not None and cut.is_set()): raise queue.Empty try: - return messages.get(timeout=min(remaining, 0.1) if stopped is not None else remaining) + return messages.get(timeout=min(remaining, 0.1) if stopped is not None or cut is not None else remaining) except queue.Empty: if time.monotonic() >= deadline: raise diff --git a/app/nullius/standard/protocols/computer_port.py b/app/nullius/standard/protocols/computer_port.py index ead3f882..bed85394 100644 --- a/app/nullius/standard/protocols/computer_port.py +++ b/app/nullius/standard/protocols/computer_port.py @@ -20,7 +20,8 @@ step), and serves the reading calls that come before it, in the thread of the loop: one desktop operation at a time, in the order the calls arrived. An acting call is held until the loop has run its actions and their pause, then answered; a ``step`` with an ``end`` then hands the loop its DONE or FAIL, in the same step. Once the steps are used - up, every call but ``info`` is refused. + up, every call but ``info`` is refused. Given a path, it keeps the progress file there: the steps taken, the budget, + what ended the loop and the calls waiting at the desktop. - ``Server``: the MCP server over a Unix socket: JSON-RPC 2.0, one message a line; every connection of the unit's session accepted, the task's state kept in the bridge, outside them; one line per tool call in the call log (the tool, its start and end, whether it failed; no argument and no result). @@ -306,6 +307,7 @@ def __init__(self, tool, args, reply): self.end = None self.files = None # a step's or a prepare's files, [(as named, the desktop's path)] self.answered = False + self.on_answer = None # called once the call is answered (the bridge's count of it) self._lock = threading.Lock() def answer(self, value=None, image=None, error=None): @@ -313,7 +315,11 @@ def answer(self, value=None, image=None, error=None): if self.answered: return self.answered = True - self._reply(self, value, image, error) + try: + self._reply(self, value, image, error) + finally: + if self.on_answer is not None: + self.on_answer() def checked(call, screen, folder) -> None: @@ -406,12 +412,16 @@ class Bridge: ``steps`` is the loop's budget, ``pause`` the seconds it waits after each action, ``screen`` the screen's size in pixels, ``folder`` the agent's own folder in the desktop (an absolute path), made empty at the loop's first ``predict``. ``on_first`` is called at the loop's first ``predict``, before any call is served (a runner writes - its ready file there). ``held`` is a Held, or None. The window before the task is open when ``window`` is true - (the benchmark's side is told when the task is given, and calls ``close_window``); with no window, upload and - prepare are refused from the start. ``prepared``, a file, gets one JSON line per prepare call: its actions and the - files it names, before they run.""" - - def __init__(self, desktop, steps, pause, screen, folder, on_first=None, held=None, window=False, prepared=None): + its ready file there). ``held`` is a Held, or None. ``progress``, when given, is the path of the progress file: + ``{steps, steps_limit, ended, open}``, the steps taken, the budget, what ended the loop (empty while it runs, + ``done``, ``fail``, ``steps`` or ``turn``) and the calls taken in and not yet answered, which wait at the desktop. + It is rewritten whole at each change, so that a reader sees one state or the next, never part of one. The window + before the task is open when ``window`` is true (the benchmark's side is told when the task is given, and calls + ``close_window``); with no window, upload and prepare are refused from the start. ``prepared``, a file, gets one + JSON line per prepare call: its actions and the files it names, before they run.""" + + def __init__(self, desktop, steps, pause, screen, folder, on_first=None, held=None, progress=None, window=False, + prepared=None): self.desktop, self.steps, self.pause = desktop, int(steps), pause self.screen = (int(screen[0]), int(screen[1])) self.on_first, self.held = on_first, held @@ -428,10 +438,15 @@ def __init__(self, desktop, steps, pause, screen, folder, on_first=None, held=No self.calls = collections.deque() # calls waiting for the loop, in the order they came self.running = None # the acting call the loop is running self.ended = None # why no call is taken any more + self.ended_by = "" # what ended the loop: done, fail, steps or turn + self.open = 0 # calls taken in and not yet answered self.turn_ended = False self.first = True self.partial = {} # this unit's uploads being kept: path -> [sha256, hash, bytes] self.change = threading.Condition() + self.progress, self.written, self.unwritten = progress, None, False + self.counted = threading.Lock() # the count of calls waiting and the progress file; taken last + self._progress() # -- the loop's agent ------------------------------------------------------------------------------------------- def reset(self, *_, **__): @@ -564,10 +579,12 @@ def _next(self): call = self.calls.popleft() if call.tool in FINAL: self.used += 1 + self.ended_by = call.tool refused = self._end(f"the task has ended ({call.tool})") elif call.tool in ACTING: self.used += 1 self.running = call + self._progress() for c in refused: c.answer(error=self.ended) return call @@ -594,9 +611,14 @@ def _ran(self, call, ran): with self.change: self.running = None if ran and call.end: # the task has ended, as after done or fail + self.ended_by = call.end refused = self._end(f"the task has ended ({call.end})") + elif self.used >= self.steps: + self.ended_by = self.ended_by or "steps" + refused = self._end("the steps are used up") else: - refused = self._end("the steps are used up") if self.used >= self.steps else [] + refused = [] + self._progress() value = {"steps_left": self.steps - self.used, "done": self.ended is not None} turn_ended = self.turn_ended if not ran: @@ -711,10 +733,17 @@ def submit(self, call): self.booked += 1 if refusal is None: self.calls.append(call) + call.on_answer = self._answered + self._progress(opened=1) self.change.notify_all() if refusal is not None: call.answer(error=refusal) + def _answered(self): + """A call taken in has been answered. Not under the condition: an answer may be given while another thread + holds it.""" + self._progress(opened=-1) + def info(self): with self.change: left = self.steps - self.used @@ -745,6 +774,9 @@ def end_turn(self): with self.change: self.turn_ended = True refused = self._end("the agent's turn has ended", keep_final=True) + if not self.ended_by and not self.calls: # no done or fail kept for the loop + self.ended_by = "turn" + self._progress() for c in refused: c.answer(error=self.ended) @@ -771,6 +803,36 @@ def _end(self, why, keep_final=False): self.change.notify_all() return refused + def _progress(self, opened=0): + """``opened`` added to the calls waiting, then the progress file rewritten whole when its state changed, + through a part file replaced at once. Each change of the state is followed by a call here, so the last + write holds the last state. A write that fails leaves the task as it is, and is said once.""" + with self.counted: + self.open += opened + if self.progress is None: + return + state = {"steps": self.used, "steps_limit": self.steps, "ended": self.ended_by, "open": self.open} + if state == self.written: + return + fd = part = None + try: + fd, part = tempfile.mkstemp(prefix=".progress-", dir=os.path.dirname(self.progress)) + f, fd = os.fdopen(fd, "w", encoding="utf-8"), None + with f: + json.dump(state, f) + os.replace(part, self.progress) + self.written = state + except OSError as e: + if not self.unwritten: + self.unwritten = True + sys.stderr.write(f"computer: the progress file was not written: {type(e).__name__}: {e}\n") + finally: + if fd is not None: + os.close(fd) + if part is not None: + with contextlib.suppress(OSError): + os.unlink(part) + def frame(message) -> bytes: return (json.dumps(message) + "\n").encode() diff --git a/app/nullius/standard/runner/job.py b/app/nullius/standard/runner/job.py index aa903072..80a3860e 100644 --- a/app/nullius/standard/runner/job.py +++ b/app/nullius/standard/runner/job.py @@ -484,7 +484,7 @@ def write_trial(trial_dir: str, *, job: str, bench: dict, other: dict, model: st image: str = "", setup_end: Optional[float] = None, agent_ready: Optional[float] = None, agent_unready: Optional[float] = None, checking: tuple = (None, None), serving: Optional[Dict[str, List[str]]] = None, served_calls: Optional[List[dict]] = None, - retries: int = 0, retryable: bool = True) -> dict: + retries: int = 0, retryable: bool = True, cut: Optional[str] = None) -> dict: """Write one unit's trial and return its result. ``serving``: the run's pin of serving providers by model; ``standard.served`` says who served ``served_calls`` (the unit's calls on every route of its relay: its @@ -500,7 +500,10 @@ def write_trial(trial_dir: str, *, job: str, bench: dict, other: dict, model: st it has no run, as Harbor writes a failed agent setup; ``checking``: the check's start and end (its own step in the container, then the driver's score). ``retryable``: False for an exception a further try meets again - whatever its name (``retries``), which its record then says.""" + whatever its name (``retries``), which its record then says. ``cut``: + what cut the agent's work short before the unit was scored, for a + benchmark that scores that cut (``time``, ``calls`` or ``end``), which + its record says as ``standard.cut``; a unit no limit cut has none.""" os.makedirs(os.path.join(trial_dir, "agent"), exist_ok=True) os.makedirs(os.path.join(trial_dir, "verifier"), exist_ok=True) if produce and produce[0] and agent_ready: # its run starts once it is set up: the trace's window too @@ -525,7 +528,7 @@ def write_trial(trial_dir: str, *, job: str, bench: dict, other: dict, model: st "plugged": other.get("_ref") or other["key"], "job": job, **_version(bench), **_control(other), **_setup(other), **({"environment": environment} if environment else {}), **({"image": image} if image else {}), **({"served": who} if (who := served(calls if served_calls is None else served_calls, serving)) else {}), - **({"retries": retries} if retries else {})}} + **({"retries": retries} if retries else {}), **({"cut": cut} if cut else {})}} if score is not None: value = float(score.get("reward") or 0.0) # a pass benchmark leaves a reward, as a verifier does; a score diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 6e17a586..26a638de 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -70,7 +70,7 @@ import tempfile from collections import Counter from concurrent.futures import FIRST_EXCEPTION, CancelledError, ThreadPoolExecutor, wait -from contextlib import contextmanager +from contextlib import ExitStack, contextmanager from typing import Callable, Dict, List, Optional, Tuple from nullius import constraints as limits, paths, prices as price_list, progress, providers, settings @@ -440,6 +440,261 @@ def get(self, name: str) -> Optional[dict]: return {"kind": kind, "value": text} if text else None +TICK_SECONDS = 5.0 # how often the live feed is told the counts of each running unit (Ticker) +PROGRESS_BYTES = 4096 # the most of a progress file read: it holds a few small numbers +# how long an agent's turn may go on once its benchmark's own loop has ended (the progress file's ``ended``), for a +# benchmark that scores that cut (``limits.scored_cuts``); and how often a running turn's cuts are looked for +END_GRACE_SECONDS = 60.0 +CUT_LOOK_SECONDS = 1.0 + + +def progress_path(progress) -> Optional[str]: + """The progress file a setup named (``progress``), as a path relative to its trial; None for any other value: + not a string, absolute, or leading out of the trial.""" + if isinstance(progress, str) and progress and not os.path.isabs(progress): + norm = os.path.normpath(progress) + if norm != os.pardir and not norm.startswith(os.pardir + os.sep): + return norm + return None + + +def read_progress(trial: str, path: Optional[str]) -> Optional[dict]: + """A unit's progress file (``path``, from :func:`progress_path`) as it reads now: each folder from ``trial`` on + opened without following a link, the file read only when it is a plain one of at most PROGRESS_BYTES. None when + it is missing, half written, or anything else.""" + if path is None: + return None + try: + with ExitStack() as opened: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + parent = os.open(trial, flags) + opened.callback(os.close, parent) + parts = path.split(os.sep) + # Keep each folder open. A replacement cannot redirect the next open. + for part in parts[:-1]: + parent = os.open(part, flags, dir_fd=parent) + opened.callback(os.close, parent) + fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + opened.callback(os.close, fd) + raw = os.read(fd, PROGRESS_BYTES + 1) if stat.S_ISREG(os.fstat(fd).st_mode) else b"" + got = json.loads(raw) if 0 < len(raw) <= PROGRESS_BYTES else None + except (OSError, ValueError): + return None + return got if isinstance(got, dict) else None + + +class Ticker: + """The job's one thread that tells the live feed the counts of each running unit (``trial.progress``). + + Every ``every`` seconds, for each unit it watches, it reads the unit's progress file when its setup named one + (``progress``, a path inside the trial: ``{steps, steps_limit, ...}``) and the lines the unit's relay added to + the record of its agent's calls since the last read. It sends an event only when a value changed: ``step`` and + ``step_limit``; ``calls``, the calls answered, counted as a cap on them counts them, and ``calls_limit`` when the + run has that cap; the tokens and the cost, as the unit's end gives them. A progress file that is missing, half + written, not a plain file inside the trial or not readable gives nothing and is no error, and the last value + read stays; a record line not yet ended is read once it is. A unit's last counts are queued as it stops + being watched (:meth:`drop`). Its end waits at most one tick for them.""" + + def __init__(self, feed, every: Optional[float] = None): + self.feed, self.every = feed, TICK_SECONDS if every is None else every + self.units: Dict[str, dict] = {} # by trial name: what is read of it, and what was last sent + self.pending: List[tuple] = [] + self.lock = threading.Lock() + self.wake = threading.Event() + self.ended = threading.Event() + self.thread: Optional[threading.Thread] = None + + def start(self) -> "Ticker": + self.thread = threading.Thread(target=self._run, name="feed-ticker", daemon=True) + self.thread.start() + return self + + def _run(self) -> None: + while not self.ended.is_set(): + self.wake.wait(self.every) + self.wake.clear() + if not self.ended.is_set(): + self.tick() + + def close(self) -> None: + """The job's end: the thread stops, waited for one tick at most.""" + self.ended.set() + self.wake.set() + if self.thread is not None: + self.thread.join(self.every) + + def watch(self, name: str, *, task: str, agent: str, trial: str, record: Optional[str] = None, + progress=None, calls_limit: Optional[int] = None) -> None: + """A unit to read from now on: ``record``, its relay's record of its agent's calls; ``progress``, the + path its setup named, relative to ``trial`` (any other value is not read).""" + path = progress_path(progress) + with self.lock: + self.units[name] = {"task": task, "agent": agent, "trial": trial, "record": record, "progress": path, + "calls_limit": calls_limit, "at": 0, "counts": None, "steps": None, "sent": None} + + def drop(self, name: str) -> None: + """Queue a unit's last counts. Wait at most one tick for the read.""" + with self.lock: + u = self.units.pop(name, None) + if u is None: + return + done = threading.Event() + self.pending.append((name, u, done)) + self.wake.set() + done.wait(self.every) + + def tick(self) -> None: + with self.lock: + units = list(self.units.items()) + pending, self.pending = self.pending, [] + for name, u, done in pending: + try: + self._read(name, u) + finally: + done.set() + for name, u in units: + self._read(name, u) + + def _read(self, name: str, u: dict) -> None: + self._steps(u) + self._calls(u) + n, steps = u["counts"], u["steps"] or (None, None) + values = {"step": steps[0], "step_limit": steps[1], + **({"calls": n["calls"], "calls_limit": u["calls_limit"], "n_input_tokens": n["input"], + "n_cache_tokens": n["cached"], "n_output_tokens": n["output"], "cost_usd": n["cost"]} if n else {})} + if all(v is None for v in values.values()) or values == u["sent"]: + return + try: + self.feed.emit("trial.progress", name, task=u["task"], agent=u["agent"], **values) + except Exception: # noqa: BLE001 - a count the board misses is no unit's error + return + u["sent"] = values + + @staticmethod + def _steps(u: dict) -> None: + """The progress file's steps and limit, when it reads as one; the values before it otherwise.""" + got = read_progress(u["trial"], u["progress"]) + whole = lambda v, least: isinstance(v, int) and not isinstance(v, bool) and v >= least + if isinstance(got, dict) and whole(got.get("steps"), 0): + u["steps"] = (got["steps"], got["steps_limit"] if whole(got.get("steps_limit"), 1) else None) + + @staticmethod + def _calls(u: dict) -> None: + """The record's lines ended since the last read, added to the unit's counts.""" + if u["record"] is None: + return + try: + with open(u["record"], "rb") as f: + f.seek(u["at"]) + got = f.read() + except OSError: + return + end = got.rfind(b"\n") + 1 # a line the relay is still writing is read at the next look + u["at"] += end + n = u["counts"] = u["counts"] or {"calls": 0, "input": 0, "cached": 0, "output": 0, "cost": None} + number = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) + for line in got[:end].splitlines(): + try: + c = json.loads(line) + except ValueError: + continue + if not isinstance(c, dict) or c.get("status") != 200: + continue + reply = c.get("reply") if isinstance(c.get("reply"), dict) else {} + usage = reply.get("usage") if isinstance(reply.get("usage"), dict) else {} + for k in ("input", "cached", "output"): + n[k] += usage[k] if number(usage.get(k)) else 0 + if number(c.get("cost_usd")): + n["cost"] = (n["cost"] or 0) + c["cost_usd"] + if c.get("model") and not relay._free(str(c.get("path") or "")): + n["calls"] += 1 + + +class CutWatch: + """What may end an agent's turn on a unit before the agent ends it, for a benchmark that scores the cut + (``limits.scored_cuts``, ``kinds``), looked for by a thread of its own every CUT_LOOK_SECONDS while the turn runs: + ``calls``, the run's cap on the agent's model calls refused one (a line of its relay's ``record`` says + ``refused: calls``); ``end``, the benchmark's own loop ended (its ``progress`` file, inside ``trial``, says + ``ended``) END_GRACE_SECONDS before. ``event`` is set at the first of them, and ``by`` says which.""" + + def __init__(self, kinds, trial: str, record: Optional[str], progress=None): + self.kinds, self.trial, self.record, self.progress = frozenset(kinds), trial, record, progress_path(progress) + self.event, self.done, self.lock = threading.Event(), threading.Event(), threading.Lock() + self.by: Optional[str] = None + self.at, self.refusal, self.ended_at = 0, False, None + self.thread: Optional[threading.Thread] = None + + def start(self) -> "CutWatch": + if self.kinds & {"calls", "end"}: + self.thread = threading.Thread(target=self._run, name="cut-watch", daemon=True) + self.thread.start() + return self + + def stop(self) -> None: + self.done.set() + if self.thread is not None: + self.thread.join(2 * CUT_LOOK_SECONDS) + + def _run(self) -> None: + while not self.done.wait(CUT_LOOK_SECONDS): + by = self.look() + if by: + self.by = by + self.event.set() + return + + def look(self) -> Optional[str]: + """``calls`` or ``end`` when that cut has come, as the files read now; None otherwise.""" + if "calls" in self.kinds and self.refused(): + return self.capped() + if "end" in self.kinds and self.loop_ended() and time.monotonic() - self.ended_at >= END_GRACE_SECONDS: + return "end" + return None + + def capped(self) -> str: + """What a refusal at the run's cap cut: ``end`` when the benchmark's own loop had ended, else ``calls``.""" + return "end" if "end" in self.kinds and self.loop_ended() else "calls" + + def refused(self) -> bool: + """Whether the run's cap on model calls has refused one of the agent's calls: the record's lines ended since + the last look are read.""" + with self.lock: + if self.refusal or self.record is None: + return self.refusal + try: + with open(self.record, "rb") as f: + f.seek(self.at) + got = f.read() + except OSError: + return False + end = got.rfind(b"\n") + 1 # a line the relay is still writing is read at the next look + self.at += end + for line in got[:end].splitlines(): + try: + c = json.loads(line) + except ValueError: + continue + if isinstance(c, dict) and c.get("refused") == "calls": + self.refusal = True + break + return self.refusal + + def loop_ended(self) -> bool: + """Whether the benchmark's own loop has ended, as its progress file says; ``ended_at`` keeps when that was + first seen.""" + with self.lock: + if self.ended_at is None: + got = read_progress(self.trial, self.progress) or {} + if isinstance(got.get("ended"), str) and got["ended"].strip(): + self.ended_at = time.monotonic() + return self.ended_at is not None + + def steps(self) -> int: + """The steps the benchmark counted, as its progress file says now; 0 without one.""" + got = (read_progress(self.trial, self.progress) or {}).get("steps") + return got if isinstance(got, int) and not isinstance(got, bool) and got > 0 else 0 + + def resolve_bench_options(bench: dict, dataset: str, given: Optional[dict] = None, setup: str = "yours", which=shutil.which) -> Tuple[dict, dict]: """The benchmark's options for a run on ``dataset`` and what their values need; refused before anything starts.""" @@ -965,6 +1220,7 @@ def _start(self, lck, mine) -> str: self.loopback = None self.pace = pacing.Pace(self._stopped, self._halt) self._running = 0 + self.ticker = Ticker(self.feed) # each running unit's steps and calls, told to the live board again: Dict[str, dict] = {} # an attempt's last try, by its trial's name, when it was retried def work_unit(iur): @@ -988,6 +1244,7 @@ def work_unit(iur): pool = ThreadPoolExecutor(self.concurrency) futures = [] try: + self.ticker.start() # a model server on this machine's loopback, which the relays' containers cannot reach as written if (self.backend == "container" or self.relay_container) and self.base and container.on_loopback(self.base): self.loopback = container.Loopback(self.base, image=self.image, job=self.name).start() @@ -1011,6 +1268,7 @@ def work_unit(iur): finally: # a Stop or Ctrl-C: the units not begun are not begun, those running end with their agents pool.shutdown(wait=True, cancel_futures=True) + self.ticker.close() self.let_go() begun = [not f.cancelled() and f.exception() is None and f.result() is not None for f in futures] results = [again.get(f.result()["trial_name"], f.result()) for f, ran in zip(futures, begun) if ran] @@ -1345,6 +1603,17 @@ def phase(self, name: str, unit: str, phase: str, timeout: Optional[float] = Non if self.feed is not None: self.feed.emit("trial.phase", name, task=unit, agent=self.other["key"], phase=phase, timeout_sec=timeout) + def watch(self, name: str, unit: str, trial: str, setup: dict, rl, tag: str) -> None: + """A unit whose counts the live feed is told while it runs (:class:`Ticker`): the progress file its setup + named, and its relay's record of its agent's calls. A relay in a container writes that record into the + trial, as this machine's user, so the same file is read on every backend.""" + if getattr(self, "ticker", None) is None: + return + record = getattr(rl, "dir", None) if rl is not None else None + self.ticker.watch(name, task=unit, agent=self.other["key"], trial=trial, progress=setup.get("progress"), + record=os.path.join(record, tag + ".jsonl") if record else None, + calls_limit=getattr(self, "max_calls", None)) + def over_acp(self) -> bool: """Whether the unit's other is an agent driven over ACP: the one kind with a setup of its own, its start and its session. A command agent starts and runs in one call, an upstream setup and a @@ -1437,6 +1706,7 @@ def sent(): raise _Ended("EnvironmentSetupError", f"the unit's relay: {e}") if rl is not None: rl.unit_secrets = self.agent_licences(env_def, rl) + self.watch(name, unit, trial, setup, rl, tag) if own: self.phase(name, unit, "env_setup", self.phase_limit("image", IMAGE_SECONDS)) # its image, pulled or built when not here yet box = self.own_box(tag, setup, rl, home) @@ -1471,7 +1741,9 @@ def sent(): if box is not None: # what the agent (or the control) left in the container, before the check changes = self.box_changes(box) cut = self.cap_reached(rl, tag) - if cut: # cut off at a spending cap: nothing of it is checked, and its judge is asked nothing + if cut and not (cut[0] == relay.CALLS_ERROR and clock.get("cut")): + # cut off at a spending cap: nothing of it is checked, and its judge is asked nothing; at the cap on + # model calls too, unless its benchmark scores that cut raise _Ended(cut[0], cut[1], traj) step = setup.get("verify") if box is not None else None checking = (time.time(), None) @@ -1508,9 +1780,17 @@ def sent(): rl.stop() for ln in getattr(rl, "mcp_listeners", None) or []: ln.stop() + if getattr(self, "ticker", None) is not None: + self.ticker.drop(name) # Its last counts are given one tick before its end. calls = rl.calls(tag) if rl is not None else [] words = not self.bench.get("gated") failed = relay.failure(calls, words, agent=True) + if failed and clock.get("cut") and failed[0] not in (ledgers.ERROR, ledgers.UNIT_ERROR): + # its agent's work was cut and the unit went on to its score (``cut_of``): the cap's refusal, or one + # after the benchmark's own end, is not how it ended. At its time, a call begun before the cut whose + # refusal came after it is the provider's, as one that came before it + failed = relay.failure([c for c in calls if c.get("t0", 0) <= clock.get("cut_at", 0)], words, agent=True) \ + if clock["cut"] == "time" else None if failed and failed[0] not in (ledgers.ERROR, ledgers.UNIT_ERROR, relay.CALLS_ERROR) and exc is None \ and self.bench["score"]["kind"] == "pass" and score.get("reward") == 1.0: # a passed unit's failed last call came after its answer (jiuwenswarm's image probe, which some @@ -1532,7 +1812,7 @@ def sent(): exc = failed # what the endpoint said outranks how the agent took it score, retry_ok = None, True # a time run out under refused calls is the provider's: tried again cut = self.cap_reached(rl, tag) # at scoring too: its judge's call, or a refusal its agent made something else of - if cut: + if cut and not (cut[0] == relay.CALLS_ERROR and clock.get("cut")): exc, score = cut, None if exc and exc[0] in ("EnvironmentSetupError", "VerifierError") and getattr(self, "ledger", None) is not None \ and getattr(self, "bench_relay", None) is not None: @@ -1556,6 +1836,7 @@ def sent(): checking=checking, trajectory=traj, extra_logs=dict(logs or {}, **({"container-changes.txt": changes} if changes else {})), environment=environment or "", retries=retry, retryable=retry_ok, serving=getattr(self, "serving", None), + cut=clock.get("cut"), # who served the unit: its agent's calls and its judge's and simulated user's routes served_calls=calls + ([c for side in ("judge", "simulator") for c in rl.calls(f"{tag}-{side}")] if rl is not None else []), @@ -2295,6 +2576,33 @@ def agent_limit(self, setup: dict) -> float: return float(own) return self.turn_seconds + def scored_cuts(self) -> frozenset: + """The cuts after which a unit an agent ran is still scored, as its benchmark declares them + (``limits.scored_cuts``): none for any other participant, nor for a benchmark that declares none. Only an + agent over a session is cut (:meth:`drive_agent`); one started as a command keeps the errors.""" + if self.other.get("_kind") != "agent": + return frozenset() + return frozenset((self.bench.get("limits") or {}).get("scored_cuts") or ()) + + def cut_of(self, watch: Optional[CutWatch], rl, tag: str) -> Optional[str]: + """What cut an agent's turn that its ``watch`` ended, or that ran past the agent's time: ``calls``, ``end`` or + ``time``, when its benchmark scores that cut. None for a unit that stays an error, as it is without the + declaration: a cut the benchmark does not score; a time that ran out while the provider refused the agent's + last call (the unit is tried again); a unit where nothing moved, no model call answered and no step counted.""" + if watch is None: + return None + by = watch.by or (watch.capped() if "calls" in watch.kinds and watch.refused() else None) + if by is None and "end" in watch.kinds and watch.loop_ended(): + by = "end" # its time ran out within the grace: the benchmark's end came first + if by is not None or "time" not in watch.kinds: + return by + calls = rl.calls(tag) + if relay.failure(calls, agent=True) is not None: + return None + if not any(c.get("status") == 200 and not c.get("side") for c in calls) and not watch.steps(): + return None + return "time" + def drive_agent(self, unit, ws, home, tag, setup, transcript, rl, box=None, name="", clock=None): """The agent over ACP, its session's ``cwd`` the unit's workspace - in an own image (``box``), the container's working directory, which this @@ -2304,7 +2612,9 @@ def drive_agent(self, unit, ws, home, tag, setup, transcript, rl, box=None, name between the check and the open and reach any file of the user's. ``clock`` gets when its setup ended: ``ready``, its session open, or ``failed``, its start over with none (it never answered, it exited, the - run was stopped).""" + run was stopped); and ``cut``, what cut its work short (:meth:`cut_of`) + when its benchmark scores that cut: its turn then ends as at a timeout, + and the unit goes on to its score.""" a = self.other env = agent_env(a, self.inst, home, rl.unit_url, self.model, self.options) log = os.path.join(os.path.dirname(ws), "agent", "agent.log") @@ -2317,6 +2627,10 @@ def drive_agent(self, unit, ws, home, tag, setup, transcript, rl, box=None, name cmd, env = self.place(rl, cmd, env, ws, home, box=box) c = acp.Client(cmd, env, log, cwd=ws, grant=True, fs=box is None and self.backend == "local", stopped=self._stopped) events: List[dict] = [] + kinds, cut = self.scored_cuts(), None + record = getattr(rl, "dir", None) + watch = CutWatch(kinds, os.path.dirname(ws), os.path.join(record, tag + ".jsonl") if record else None, + setup.get("progress")) if kinds else None try: try: try: @@ -2350,14 +2664,19 @@ def left() -> float: prompt = prompt + "\n\n" + first["message"] if opened: self.task_given(unit, ws) # before the first prompt: the window from the session's start closes + if watch is not None: + watch.start() for _ in range(self.max_turns if opened else 0): transcript.append({"role": "user", "text": prompt}) try: - turn = c.prompt(sid, prompt, timeout=left()) + turn = c.prompt(sid, prompt, timeout=left(), **({"cut": watch.event} if watch is not None else {})) except acp.Timeout as e: # said as the whole work's limit, not the seconds this turn had left raise acp.Timeout(f"the agent did not end its work in {int(limit)} s", e.events) from e answer = turn.text transcript.append({"role": "agent", "text": turn.text, "stop": turn.stop}) + if watch is not None and "calls" in kinds and watch.refused(): + cut = watch.capped() # it ended its turn once the cap refused its next call + break if "agent.conversation/v1" not in self.bench["needs"]: break nxt = self.driver().request("turn", unit=unit, dir=ws, transcript=transcript, timeout=600, **sim, **self.attempt_kw()) @@ -2373,10 +2692,16 @@ def left() -> float: events = c.events except acp.Timeout as e: events = c.events - raise _Ended("AgentTimeoutError", str(e), job.trajectory_from_events(events, rl.calls(tag), a, self.model, f"{self.name}/{unit}")) + if clock is not None: + clock["cut_at"] = time.time() + cut = self.cut_of(watch, rl, tag) + if cut is None: + raise _Ended("AgentTimeoutError", str(e), job.trajectory_from_events(events, rl.calls(tag), a, self.model, f"{self.name}/{unit}")) except acp.AgentFailed as e: events = c.events - raise _Ended("NonZeroAgentExitCodeError", str(e), job.trajectory_from_events(events, rl.calls(tag), a, self.model, f"{self.name}/{unit}")) + cut = watch.capped() if watch is not None and "calls" in kinds and watch.refused() else None + if cut is None: # an agent that ends once the cap refused its next call is cut by the cap + raise _Ended("NonZeroAgentExitCodeError", str(e), job.trajectory_from_events(events, rl.calls(tag), a, self.model, f"{self.name}/{unit}")) except TimeoutError as e: events = c.events # a later request the agent never answered (a new session) raise _Ended("AgentTimeoutError", f"the agent did not answer {e} in time", @@ -2384,9 +2709,13 @@ def left() -> float: except jsonl.Failed as e: raise _Ended("VerifierError", "the benchmark's next turn: " + str(e), retryable=not isinstance(e, jsonl.NoReply)) finally: + if watch is not None: + watch.stop() if clock is not None and "ready" not in clock: clock["failed"] = time.time() # its start ended with no session: all of it was its setup c.close() + if cut is not None and clock is not None: + clock["cut"] = cut raw = "".join(json.dumps(e) + "\n" for e in events) return answer, job.trajectory_from_events(events, rl.calls(tag), a, self.model, f"{self.name}/{unit}"), {"acp.jsonl": raw} diff --git a/app/static/runs/board.css b/app/static/runs/board.css index 8bbbe5dd..de763873 100644 --- a/app/static/runs/board.css +++ b/app/static/runs/board.css @@ -303,15 +303,14 @@ .rp .group-toggle::before { color: var(--text-dim); } .rp .group-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; } .rp .group-pass { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; } -.rp .group-pass b { font: 600 12.5px/20px var(--mono); } +.rp .group-pass b { font: 600 12.5px/20px var(--mono); display: inline-block; min-width: 4ch; } .rp .sqs { display: inline-flex; gap: 3px; } +.rp .sw-fill { background: linear-gradient(to top, var(--oc) var(--fill), color-mix(in srgb, var(--oc) 22%, var(--surface)) var(--fill)); box-shadow: inset 0 0 0 1px var(--oc); } .rp .tt tr.in-group td:first-child { padding-left: 39px; } .rp .attempt-link { color: var(--text-dim); } .rp .tt td:first-child { min-width: 150px; } .rp tr:hover .task { text-decoration: underline; text-decoration-color: var(--hush); text-underline-offset: 4px; } .rp .tt .badge { margin-left: 6px; } -.rp .oc { display: inline-flex; align-items: center; gap: 8px; color: var(--text); white-space: nowrap; } -.rp .oc i { width: 8px; height: 8px; border-radius: 50%; background: var(--oc); flex: none; } .rp .exd summary { display: flex; align-items: center; min-height: 20px; font: 11px/20px var(--mono); color: var(--text-faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .rp .exd summary .tw { width: 12px; flex: none; } .rp .exd summary:hover { color: var(--text-dim); } @@ -416,3 +415,8 @@ .rp .tt .tlabel { border: 1px solid var(--text-faint); color: var(--text); font-style: italic; } .rp .tt[data-leave-out~="flawed"] tr[data-task-flag="flawed"] > td, .rp .tt[data-leave-out~="ambiguous"] tr[data-task-flag="ambiguous"] > td { opacity: .45; } + +.rp .w-stop { width: 260px; } +.rp .tt td.outcome { white-space: nowrap; } +.rp .oc-word { color: var(--text-dim); } +.rp .stop-reason .badge { vertical-align: middle; line-height: 1.2; } diff --git a/app/static/runs/live-board.css b/app/static/runs/live-board.css index f961e883..58fd7f6d 100644 --- a/app/static/runs/live-board.css +++ b/app/static/runs/live-board.css @@ -93,17 +93,20 @@ .lb-table th { text-align: left; font: 400 11.5px var(--sans); color: var(--text-dim); padding: 9px 12px 7px; border-bottom: 1px solid var(--lb-hair); white-space: nowrap; } .lb-table th:first-child, .lb-table td:first-child { padding-left: 18px; } .lb-table .num { text-align: right; font: 12.5px var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; } +.lb-table .lb-stepcell { text-align: left; } +.lb-table th.num { font: 400 11.5px var(--sans); } .lb-table td { padding: 9px 12px; border-bottom: 1px solid var(--lb-hair); vertical-align: middle; } .lb-row { cursor: pointer; transition: background .2s, opacity .2s; } .lb-row:hover, .lb-row[aria-current="true"] { background: var(--surface-2); } .lb-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } -.lb-row .task { display: inline-block; font: 500 12.5px var(--mono); max-width: 22rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; } +/* a long name wraps, never cut */ +.lb-row .task { display: inline-block; font: 500 12.5px var(--mono); width: max-content; max-width: 22rem; overflow-wrap: anywhere; vertical-align: bottom; } .lb-row small { font-size: 11.5px; color: var(--text-faint); margin-left: 6px; } .lb-phase { display: inline-flex; align-items: center; gap: 8px; white-space: nowrap; font-size: 12.5px; } .lb-ticks { display: inline-flex; gap: 3px; } .lb-ticks s { width: 11px; height: 4px; border-radius: 2px; background: var(--lb-track); text-decoration: none; } .lb-ticks s.done { background: var(--text-dim); } .lb-ticks s.now { background: var(--c); } -.lb-limit { display: grid; grid-template-columns: minmax(70px, 1fr) auto; gap: 9px; align-items: center; min-width: 170px; } +.lb-limit { display: grid; grid-template-columns: 90px auto; justify-content: start; gap: 9px; align-items: center; min-width: 170px; } .lb-bar { height: 5px; border-radius: 3px; background: var(--lb-track); overflow: hidden; } .lb-bar i { display: block; height: 100%; background: var(--c); border-radius: 0 3px 3px 0; transition: width .35s linear; } .lb-bar.near i { background: var(--patch_failed_tests); } diff --git a/app/static/runs/live-board.js b/app/static/runs/live-board.js index 5dda0e4e..c11e726f 100644 --- a/app/static/runs/live-board.js +++ b/app/static/runs/live-board.js @@ -55,6 +55,17 @@ return (t.n_input_tokens || 0) + (t.n_output_tokens || 0); } const pressure = t => (t.timeout_sec && t.elapsed_sec != null ? t.elapsed_sec / t.timeout_sec : 0); + // the steps of the limit where the benchmark counts them (a bar while the trial runs), else the bare count + function stepsCell(t, bar) { + if (t.step == null) return '
| ${busy ? 'Trial, the running nearest their limit first' : 'Trial'} | Phase, or how it ended | Time in phase, of its limit | ${has.steps ? 'Steps | ' : ''}${has.tokens ? 'Tokens | ' : ''}${has.line ? 'Last line, redacted | ' : ''}
|---|
| ${busy ? 'Trial, the running nearest their limit first' : 'Trial'} | Phase, or how it ended | Time in phase, of its limit | ${has.steps ? 'Steps | ' : ''}${has.calls ? 'Model calls | ' : ''}${has.tokens ? 'Tokens | ' : ''}${has.line ? 'Last line, redacted | ' : ''}
|---|
| {{ attempt_count(group, false) }} - | + {% if group.n_infra %}{{ group.n_infra }} infra{% endif %}{% for a in group.trials %}{{ 'Attempt ' ~ loop.index }}: {{ '%.2f'|format(a.score) if a.outcome == 'scored' and a.score is not none else a.outcome_label }}{{ ', ' if not loop.last }}{% endfor %} {% if show_fa %}{{ task_flag(t) }} | {% endif %} {% if job.retries %}{% endif %} {% if show_cause %} | {% endif %} @@ -459,8 +466,14 @@ | {{ t.outcome_label }} - {%- if t.score is not none %} {{ '%.2f'|format(t.score) }}{% endif %} + | {% set plain = t.outcome in ('resolved', 'scored') %}{# one form for every trial: its number, its square, and its outcome in words unless it passed or was scored #}
+
+ {%- if t.score is not none and (job.scored_only or t.outcome == 'scored') %}{{ '%.2f'|format(t.score) }}
+ {%- elif job.scored_only or t.is_infra or t.outcome in ('unknown', 'scored') %}—
+ {%- else %}{{ 1 if t.outcome == 'resolved' else 0 }}/1{% endif -%}
+ {{ t.outcome_label }}
+ {%- if t.score is not none and not (job.scored_only or t.outcome == 'scored') %} {{ '%.2f'|format(t.score) }}{% endif %}
+ {%- set stop = ending(t) %}{% if stop %} {{ stop }}{% endif %}
{%- if t.n_rate_limited_retries %} 429 ×{{ t.n_rate_limited_retries }}{% endif -%}
{%- if t.exception_type %}
{%- if t.exception_message %}{{ t.exception_type }}{{ t.exception_message }}Patch applied{{ 'Yes' if trial.patch_applied else 'No' }} {% endif -%}
{%- if trial.reward is not none %}Reward{{ trial.reward }} {% endif -%}
{%- if trial.score is not none %}Score{{ '%.2f'|format(trial.score) }} {% endif -%}
- {%- if trial.dur_agent is not none %}Agent time{{ trial.dur_agent|secs }} {% endif -%}
- {%- if traj and not traj.error %}Steps{{ traj.n_steps }} {% endif -%}
+ {%- if trial.dur_agent is not none %}Agent time{{ trial.dur_agent|secs }}{% if trial.ended_by == 'time' %}{{ ending(trial, true) }}{% endif %} {% endif -%}
+ {%- if steps_of %}Steps{{ steps_of.steps }} of {{ steps_of.limit }}{% if trial.ended_by == 'steps' %}{{ ending(trial, true) }}{% endif %} {% endif -%}
+ {%- if traj and not traj.error and not steps_of %}Trace steps{{ traj.n_steps }} {% endif -%}
+ {%- if trial.ended_tag and not (trial.ended_by == 'time' and trial.dur_agent is not none) and not (trial.ended_by == 'steps' and steps_of) %}Stopped by{{ ending(trial) }} {% endif -%}
{% endset %}
{% if attempts or tries %}
{% if attempts %}
@@ -64,7 +67,7 @@
{{ cells }} |