diff --git a/AGENTS.md b/AGENTS.md index 48829af0..402189ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,12 +39,12 @@ and its resources. workspace and its jobs, path resolution, the catalogue cache, the query helpers, the form-token guard), `filters` (template filters, page context), then `runs`, `traces`, `compare`, `builder`, `catalogue`, `agents`, - `settings`, `workspaces`, `execute`, `judge`, `feasibility`, `reconcile`, `judge_tasks`, `onboarding` (`agents` is the Agents + `settings`, `workspaces`, `execute`, `judge`, `feasibility`, `reconcile`, `judge_tasks`, `onboarding`, `failure` (`agents` is the Agents and Capabilities tabs and conformance Kits catalogue). Cross-module names are reached as attributes (`shared.STATE`, `traces._trial_evidence`): patch one, patched for all. - `app/nullius/` — its backend, one package per purpose: `runs/` (reading one Harbor job tree: `parse`, `classify`, `live`, `artifacts`, - `feasibility`, `launches`, `verifier` - a verifier's report read by its + `feasibility`, `failure_analysis` - a job's failure labels and task flags, beside its result.json, written by `flags_cli` too -, `launches`, `verifier` - a verifier's report read by its benchmark's report block - `attempts`, a task's attempts in one job with their pass count and pass@k, and the `cli`), `traces/` (`trace`, the reader, with its span tree `spans`, `fold`, time accounting `breakdown` and layout `waterfall`; `trajectory`, diff --git a/app/app.py b/app/app.py index cca07559..101100cb 100644 --- a/app/app.py +++ b/app/app.py @@ -28,11 +28,11 @@ if __package__: # the wheel's private web namespace from .web.core import app from .web import shared - from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding + from .web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure else: # python app/app.py, and the source route suite from web.core import app from web import shared - from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding + from web import filters, runs, traces, compare, builder, catalogue, agents, settings, workspaces, execute, judge, feasibility, reconcile, judge_tasks, onboarding, failure from nullius import execution, workspace # noqa: E402 - recorded runs, picked up again at start; the workspace left open diff --git a/app/nullius/cli.py b/app/nullius/cli.py index 0ac5fae3..aa960909 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -15,6 +15,7 @@ "serve": "open the web application", "runs": "inspect run output", "compare": "compare runs", + "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", "workspace": "manage workspaces", @@ -25,6 +26,7 @@ MODULES = { "runs": "nullius.runs.cli", "compare": "nullius.compare.cli", + "flags": "nullius.runs.flags_cli", "import": "nullius.importers.cli", "standard": "nullius.standard.cli", "workspace": "nullius.workspace_cli", diff --git a/app/nullius/compare/comparison.py b/app/nullius/compare/comparison.py index be28aba3..8bb5902a 100644 --- a/app/nullius/compare/comparison.py +++ b/app/nullius/compare/comparison.py @@ -137,6 +137,7 @@ class Comparison: datasets_match: bool datasets_known: bool pass_k: tuple[dict | None, ...] = () + set_aside_trials: tuple[int, ...] = () # trials of flagged tasks left out of each column @property def references(self) -> list[str]: @@ -147,7 +148,13 @@ def n_differing(self) -> int: return sum(row.differs for row in self.tasks) -def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: +def task_key(selection: SelectedRun, task_base: str) -> tuple[str, str]: + """A task's identity across columns: its recorded dataset and its name. Missing dataset identities cannot + prove that identical short names refer to the same task; a per-column sentinel keeps their rows apart.""" + return selection.job.dataset or f"[unidentified:{selection.value}]", task_base + + +def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: frozenset = frozenset()) -> Comparison: """Build a whole-run or exact shared-task view without changing any Job. Matching uses the dataset string as recorded, without alias/path guessing. @@ -158,6 +165,8 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: differ. Unknown outcomes remain in the adjusted-rate denominator because Job owns the arithmetic. A cohort cannot manufacture a new wall-clock run interval. + *set_aside*: ``(dataset, task_base)`` keys whose trials leave every column, after + the cohort: the flagged tasks of the page's filters, the same for all runs. """ if cohort not in {"whole", "matched"}: raise ValueError("Choose whole runs or matched tasks as the comparison cohort.") @@ -166,25 +175,24 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole") -> Comparison: datasets_match = len({selection.job.dataset for selection in selected}) <= 1 def key(selection, trial): - # Missing dataset identities cannot prove that identical short names - # refer to the same task. A per-column sentinel keeps their rows apart. - dataset = selection.job.dataset or f"[unidentified:{selection.value}]" - return dataset, trial.task_base + return task_key(selection, trial.task_base) sets = [{key(selection, trial) for trial in selection.job.trials} for selection in selected] common = set.intersection(*sets) if sets else set() # each task's attempts, one list per run, the tasks in the order they appear - jobs, excluded, repeated, by_task = [], [], [], {} + jobs, excluded, repeated, aside, by_task = [], [], [], [], {} for column, selection in enumerate(selected): original = selection.job - trials = [trial for trial in original.trials - if cohort == "whole" or key(selection, trial) in common] + cohort_trials = [trial for trial in original.trials + if cohort == "whole" or key(selection, trial) in common] + trials = [trial for trial in cohort_trials if key(selection, trial) not in set_aside] + aside.append(len(cohort_trials) - len(trials)) # Aggregate properties derive from trials; copied clocks are suppressed # for matched views because their interval still belongs to the full run. view = replace(original, trials=trials, - **({"started_at": None, "finished_at": None} if cohort == "matched" else {})) + **({"started_at": None, "finished_at": None} if cohort == "matched" or set_aside else {})) jobs.append(view) - excluded.append(len(original.trials) - len(trials)) + excluded.append(len(original.trials) - len(cohort_trials)) repeated.append(len(trials) - len({key(selection, trial) for trial in trials})) for trial in trials: by_task.setdefault(key(selection, trial), [[] for _ in selected])[column].append(trial) @@ -198,8 +206,8 @@ def task_row(task_key, columns): # 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]) for column in range(len(selected))) - return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common), - tuple(excluded), tuple(repeated), datasets_match, known, pass_k) + 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/judge/questions.py b/app/nullius/judge/questions.py index d24d9fa3..9271dd3f 100644 --- a/app/nullius/judge/questions.py +++ b/app/nullius/judge/questions.py @@ -171,6 +171,35 @@ def state_of(qid: str) -> str: }, }) +# --- the trial page: the same two questions a person answers on the User judge tab ----- +# A failed trial's cause in the tab's four labels, and whether its task is fair. Both models answer them beside the +# person, for comparison only: the Filtered score reads the person's flags alone (`runs.failure_analysis`). +register("trial", { + "failure_label": { + "label": 'Why it failed', "blurb": "The cause, in the User judge's four labels or other", + "type": "choice", "state": "failure", "when": "unresolved", + "instructions": "Why did this trial not resolve? Here `agent` means the program around the model, not the model's own steps. Pick the one layer the transcript, the recorded error and the verifier output blame most; pick `other` when they do not show which.", + "criteria": { + "agent": "The program around the model failed it: a step, turn or time limit it set was hit, a tool it provides returned an error or wrong data, or it lost or cut text the model needed", + "model": "The model's own mistake: a rule, document or tool result in view was not applied, a reasoning slip, a wrong or invented fact, a wrong or missing action", + "environment": "Something outside the agent broke the trial: the simulated user, an external service, the infrastructure, a model rate limit or an API error", + "evaluator": "The grading is at fault: the verifier or the expected outcome is wrong, or it rejects a defensible answer", + "other": "A cause outside this list, or the text shown does not say which layer is at fault", + }, + }, + "task_flag": { + "label": 'Task flag', "blurb": "Whether the task itself is sound, in the User judge's flags", + "type": "choice", "state": "failure", "when": "unresolved", + "instructions": "Is this task itself sound, judged from the instruction and the verifier output shown, not from the agent's work? Pick `cannot_tell` unless the text shown supports another option.", + "criteria": { + "flawed": "The verifier output shows an expected outcome that is wrong, or that the instruction gives no way to reach", + "ambiguous": "The instruction allows more than one defensible reading, and the verifier output accepts only one", + "fair": "The instruction has one defensible reading and the verifier output shows nothing wrong with the expected outcome", + "cannot_tell": "The text shown is not enough to judge the task: the expected outcome or the rules are not in view", + }, + }, +}) + # --- the compare page: a matched pair ------------------------------------------------- # Each side is scored on its own, over its own `trial` state, against one # rubric; the pick is made in code (`compare.comparison.better_of`), never by diff --git a/app/nullius/runs/failure_analysis.py b/app/nullius/runs/failure_analysis.py new file mode 100644 index 00000000..e43641e9 --- /dev/null +++ b/app/nullius/runs/failure_analysis.py @@ -0,0 +1,327 @@ +"""A run's failure analysis: why each failed trial failed, and which tasks a person found flawed or ambiguous. + +One file per job, ``failure-analysis.json`` beside the job's ``result.json``. A person writes it from the trial +page's User judge tab or the ``nullius flags`` command; nothing here calls a model. Every writer goes through +:func:`update`, which holds a lock for the whole read, change and write, so the tab and the command never drop each +other's changes. + +- A *label* belongs to one trial (its ``trial_name``, a retry's ``.try-N`` included): the cause of its failure, one + of ``LABELS``. +- A *flag* belongs to one task of the job's dataset (its ``task_base``, the key Compare uses within a dataset): + ``flawed`` (its expected outcome is wrong) or ``ambiguous`` (more than one reading is defensible). A task has at + most one flag. A flag can name the task's version; when the task changes, that flag no longer applies. A flag + with no version applies to any version. + +A flag a person sets is accepted at once. A flag that comes from elsewhere (an import, a copy from another run, a +proposal such as an agent's) starts ``pending``, counts only once a person accepts it, and never replaces a flag a person accepted. +""" + +from __future__ import annotations + +import getpass +import json +import os +import subprocess +from functools import lru_cache +from dataclasses import asdict, dataclass, field, replace +from datetime import datetime, timezone +from typing import Any, Callable, Dict, Iterable, Optional, Set, Tuple + +from nullius import ondisk + +FILE = "failure-analysis.json" +SCHEMA = "nullius.failure-analysis/v1" + +LABELS = ("agent", "model", "environment", "evaluator") +KINDS = ("flawed", "ambiguous") +STATUSES = ("pending", "accepted") + +# The judge's failure_cause answer (judge/questions.py), read as a suggestion for a label. agent_error covers both +# the agent and the model, so it suggests both and the person picks. +JUDGE_CAUSE = { + "agent_error": ("agent", "model"), + "environment_error": ("environment",), + "rate_limit_or_timeout": ("environment",), + "task_ambiguous": ("evaluator",), + "verifier_disagrees": ("evaluator",), +} + + +class FailureAnalysisError(ValueError): + """A label, a flag or a file that does not follow the rules above.""" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def _source_ok(source: str) -> bool: + prefixes = ("import:", "copy:", "proposed:") + return source == "person" or (source.startswith(prefixes) and len(source.split(":", 1)[1]) > 0) + + +@dataclass +class Label: + label: str + note: str = "" + by: str = "" + at: str = "" + judge_cause: Optional[str] = None # the judge's failure_cause when the label was set, if any + + +@dataclass +class Flag: + kind: str + category: str + evidence: str = "" # a pointer (a document, a tool), never the expected outcome + task_version: Optional[str] = None # the task_checksum its trial recorded when the flag was set + status: str = "accepted" + source: str = "person" # person | import: | copy: | proposed:, e.g. an agent + by: str = "" # who set or proposed it + at: str = "" + accepted_by: str = "" + accepted_at: str = "" + + +@dataclass +class Analysis: + labels: Dict[str, Label] = field(default_factory=dict) # by trial name + flags: Dict[str, Flag] = field(default_factory=dict) # by task_base + + def set_label(self, trial: str, label: str, *, by: str, note: str = "", judge_cause: Optional[str] = None) -> Label: + if not trial: + raise FailureAnalysisError("a label needs a trial name") + if label not in LABELS: + raise FailureAnalysisError(f"label {label!r} is not one of {', '.join(LABELS)}") + self.labels[trial] = Label(label, note, by, _now(), judge_cause) + return self.labels[trial] + + def clear_label(self, trial: str) -> None: + self.labels.pop(trial, None) + + def set_flag(self, task: str, kind: str, category: str, *, by: str, evidence: str = "", + task_version: Optional[str] = None, source: str = "person") -> Optional[Flag]: + """Set the task's flag. A flag from elsewhere never replaces one a person accepted for the same task version: it + returns None. An accepted flag on another version is inert, so a flag for the current one replaces it.""" + if not task: + raise FailureAnalysisError("a flag needs a task") + if kind not in KINDS: + raise FailureAnalysisError(f"kind {kind!r} is not one of {', '.join(KINDS)}") + if not category: + raise FailureAnalysisError("a flag needs a category") + if not _source_ok(source): + raise FailureAnalysisError(f"source {source!r} is not person, import:, copy: or proposed:") + old = self.flags.get(task) + stale = (old is not None and old.task_version is not None and task_version is not None + and old.task_version != task_version) + if source != "person" and old is not None and old.status == "accepted" and not stale: + return None + now = _now() + person = source == "person" + self.flags[task] = Flag(kind, category, evidence, task_version, "accepted" if person else "pending", source, + by, now, by if person else "", now if person else "") + return self.flags[task] + + def accept(self, task: str, *, by: str) -> Flag: + flag = self.flags.get(task) + if flag is None: + raise FailureAnalysisError(f"no flag on task {task!r}") + flag.status, flag.accepted_by, flag.accepted_at = "accepted", by, _now() + return flag + + def remove_flag(self, task: str) -> None: + """Remove the task's flag: how a person rejects a pending flag or withdraws an accepted one.""" + self.flags.pop(task, None) + + def set_aside(self, kinds: Iterable[str], versions: Optional[Dict[str, str]] = None) -> Set[str]: + """The tasks the filtered score leaves out: accepted flags of the chosen kinds. With *versions* (task to its current + digest), a flag that names another version does not count; a flag that names none still does.""" + chosen = set(kinds) + out = set() + for task, flag in self.flags.items(): + if flag.status != "accepted" or flag.kind not in chosen: + continue + if versions is not None and flag.task_version is not None and versions.get(task) != flag.task_version: + continue + out.add(task) + return out + + +@lru_cache(maxsize=1) +def who() -> str: + """The name a label or a flag is recorded under: git's global user.name on this machine, else the login name. + Read once per process.""" + try: + name = subprocess.run(["git", "config", "--global", "--get", "user.name"], capture_output=True, text=True, + timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + name = "" + if name: + return name + try: + return getpass.getuser() + except (OSError, KeyError): + return "unknown" + + +def suggestion(judge_cause: Optional[str]) -> Tuple[str, ...]: + """The labels a judge's failure_cause points to: none, one, or two for the person to pick from.""" + return JUDGE_CAUSE.get(judge_cause or "", ()) + + +def path(job_dir: str) -> str: + return os.path.join(job_dir, FILE) + + +def _records(raw: dict, name: str, cls): + block = raw.get(name) or {} + if not isinstance(block, dict): + raise FailureAnalysisError(f"{FILE}: {name} is not an object") + out = {} + for key, value in block.items(): + if not isinstance(value, dict): + raise FailureAnalysisError(f"{FILE}: {name} {key!r} is not an object") + try: + out[key] = cls(**value) + except TypeError as e: + raise FailureAnalysisError(f"{FILE}: {name} {key!r}: {e}") from e + return out + + +def load(job_dir: str) -> Analysis: + """The job's analysis; an empty one when the job has none yet.""" + try: + with open(path(job_dir), encoding="utf-8") as fh: + raw = json.load(fh) + except FileNotFoundError: + return Analysis() + except (OSError, json.JSONDecodeError) as e: + raise FailureAnalysisError(f"{FILE} cannot be read: {e}") from e + if not isinstance(raw, dict) or raw.get("schema") != SCHEMA: + raise FailureAnalysisError(f"{FILE} is not a {SCHEMA} file") + labels = _records(raw, "labels", Label) + flags = _records(raw, "flags", Flag) + for key, lab in labels.items(): + if lab.label not in LABELS: + raise FailureAnalysisError(f"trial {key!r}: label {lab.label!r} is not one of {', '.join(LABELS)}") + for key, fl in flags.items(): + if fl.kind not in KINDS or fl.status not in STATUSES or not fl.category or not _source_ok(fl.source): + raise FailureAnalysisError(f"task {key!r}: kind, status, category or source is not allowed") + return Analysis(labels, flags) + + +def _save(job_dir: str, analysis: Analysis) -> None: + body = {"schema": SCHEMA, + "labels": {k: asdict(v) for k, v in sorted(analysis.labels.items())}, + "flags": {k: asdict(v) for k, v in sorted(analysis.flags.items())}} + ondisk.write_whole(path(job_dir), lambda fh: (json.dump(body, fh, indent=1, ensure_ascii=False), fh.write("\n"))) + + +def update(job_dir: str, change: Callable[[Analysis], object]) -> object: + """Read the job's analysis, apply *change*, write it back, all under one lock. Returns what *change* returns.""" + # the lock is a file of its own: the analysis file is replaced on every write, so a lock on it would be lost + with ondisk.locked(path(job_dir) + ".lock"): + analysis = load(job_dir) + result = change(analysis) + _save(job_dir, analysis) + return result + + +@dataclass(frozen=True) +class Filtered: + """What the job page needs for its Filtered score.""" + flagged: Dict[str, int] # accepted flags on this job's tasks, by kind: what the switches offer + other_version: int # accepted flags that name another version of their task: they do not count + kinds: Tuple[str, ...] # the switches that are on + set_aside: Dict[str, int] # tasks left out, by kind + filtered_score: Optional[float] = None # the adjusted rate without those tasks; None if no switch is on or none left + solved: int = 0 + ran: int = 0 # trials left that ran (infra left out, as in the adjusted rate) + + +def filtered(job, analysis: Analysis, kinds: Iterable[str], versions: Optional[Dict[str, str]] = None) -> Filtered: + """The job's adjusted rate with the chosen filters on. It is computed by the job's own code on a copy that keeps + every trial except those of set-aside tasks; only the rate and its counts are read from that copy. With + *versions* (`task_versions`), a flag on another version of its task does not count.""" + tasks = {t.task_base for t in job.trials} + on = tuple(k for k in KINDS if k in set(kinds)) + flagged = {k: len(analysis.set_aside([k], versions) & tasks) for k in KINDS} + stale = len(analysis.set_aside(KINDS) & tasks) - len(analysis.set_aside(KINDS, versions) & tasks) + if not on: + return Filtered(flagged, stale, on, {}) + out = analysis.set_aside(on, versions) & tasks + by_kind = {k: sum(1 for t in out if analysis.flags[t].kind == k) for k in on} + rest = replace(job, trials=[t for t in job.trials if t.task_base not in out]) + return Filtered(flagged, stale, on, by_kind, rest.adjusted_solve_rate, rest.n_resolved, + len(rest.trials) - rest.n_infra) + + +def task_versions(job, tasks: Optional[Iterable[str]] = None) -> Dict[str, str]: + """Each task's version: the ``task_checksum`` Harbor records in a trial's ``result.json``. Only *tasks* when + given; a task whose trials record none is left out.""" + wanted = None if tasks is None else set(tasks) + out: Dict[str, str] = {} + for t in job.trials: + if t.task_base in out or (wanted is not None and t.task_base not in wanted): + continue + try: + with open(os.path.join(t.dir, "result.json"), encoding="utf-8") as fh: + checksum = (json.load(fh) or {}).get("task_checksum") + except (OSError, ValueError, AttributeError): + continue + if isinstance(checksum, str) and checksum: + out[t.task_base] = checksum + return out + + +def copy_flags(source: Analysis, target: Analysis, source_job: str, tasks: Iterable[str], *, + by: str) -> Tuple[list, list, list]: + """Copy *source*'s accepted flags on the target job's *tasks* into *target* as pending flags, keeping each flag's + task version. Returns the tasks copied, the tasks the target job does not hold, and the tasks skipped because + *target* already holds an accepted flag.""" + known = set(tasks) + copied, unknown, skipped = [], [], [] + for task, flag in sorted(source.flags.items()): + if flag.status != "accepted": + continue + if task not in known: + unknown.append(task) + continue + got = target.set_flag(task, flag.kind, flag.category, by=by, evidence=flag.evidence, + task_version=flag.task_version, source=f"copy:{source_job}") + (copied if got is not None else skipped).append(task) + return copied, unknown, skipped + + +def import_flags(target: Analysis, records: Iterable[dict], tasks: Iterable[str], *, source: str, by: str, + prefix: str = "", versions: Optional[Dict[str, str]] = None) -> Tuple[list, list, list]: + """Add flags from *records* (each with ``task``, ``kind``, ``category`` and an optional ``evidence``) as pending + flags. A task name is *prefix* plus the record's ``task``; a name the job does not hold is not guessed. Returns + the tasks added, the names not found, and the tasks skipped because they hold an accepted flag.""" + known = set(tasks) + added, unknown, skipped = [], [], [] + for rec in records: + if not isinstance(rec, dict): + raise FailureAnalysisError("each flag to import is an object") + if not rec.get("task"): + raise FailureAnalysisError("each flag to import names a task") + task = prefix + str(rec["task"]) + if task not in known: + unknown.append(task) + continue + got = target.set_flag(task, str(rec.get("kind", "")), str(rec.get("category", "")), by=by, + evidence=str(rec.get("evidence", "") or ""), source=source, + task_version=(versions or {}).get(task)) + (added if got is not None else skipped).append(task) + return added, unknown, skipped + + +def categories(analyses: Iterable[Analysis]) -> list: + """The categories of the accepted flags in *analyses*, most used first: what the tab suggests next to its + defaults. A pending flag does not count, so an unreviewed proposal never promotes its own category.""" + counts: Dict[str, int] = {} + for a in analyses: + for f in a.flags.values(): + if f.status == "accepted": + counts[f.category] = counts.get(f.category, 0) + 1 + return sorted(counts, key=lambda c: (-counts[c], c)) diff --git a/app/nullius/runs/flags_cli.py b/app/nullius/runs/flags_cli.py new file mode 100644 index 00000000..407fd159 --- /dev/null +++ b/app/nullius/runs/flags_cli.py @@ -0,0 +1,241 @@ +"""Write a run's failure analysis from a shell: the task flags the trial page's User judge tab writes, and +their import, copy and acceptance. + + nullius flags list [--json] + nullius flags set --kind flawed|ambiguous --category C [--evidence E] [--pending [--by NAME]] + nullius flags accept ( | --all-pending) + nullius flags remove + nullius flags copy + nullius flags import --from FILE [--prefix P] + nullius flags feasibility + +```` is anything ``nullius runs`` reads. A task is named as the job names it (its ``task_base``, the name +``nullius runs show`` prints). A flag set here is accepted at once, unless ``--pending`` (a flag an agent proposes); a flag copied, imported +or read from the feasibility controls is pending until a person accepts it, and never replaces an accepted one. Each change writes +only the job's ``failure-analysis.json``. Exit codes are those of ``docs/cli/exit-codes.md``. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from dataclasses import asdict + +from nullius.runs import failure_analysis as fa, feasibility, parse + +EXIT_OK = 0 +EXIT_USAGE = 2 +EXIT_NOT_FOUND = 3 +EXIT_INVALID = 4 + +# the feasibility verdicts that say the task, not the agent, is at fault +FEASIBILITY = {feasibility.TASK_BROKEN: "task broken", feasibility.REFERENCE_REJECTED: "reference rejected", + feasibility.UNEXPECTED_REWARD: "unexpected reward"} + + +def _jobs(root): + if not os.path.isdir(root): + print(f"no such directory: {root}", file=sys.stderr) + return None + return parse.load_all([root]) + + +def _job(jobs, job_id, root): + """The job of that id, or its exit code: not found, or ambiguous when two jobs under *root* share it.""" + found = [j for j in jobs if j.job_id == job_id] + if not found: + known = ", ".join(j.job_id for j in jobs) or "none" + print(f"no job named {job_id!r} under {root} (jobs there: {known})", file=sys.stderr) + return EXIT_NOT_FOUND + if len(found) > 1: + print(f"ambiguous job id {job_id!r}: {', '.join(j.dir for j in found)}", file=sys.stderr) + return EXIT_INVALID + return found[0] + + +def _task(job, task): + if task in {t.task_base for t in job.trials}: + return True + print(f"no task named {task!r} in {job.job_id}", file=sys.stderr) + return False + + +def _list(job, args) -> int: + a = fa.load(job.dir) + if args.json: + print(json.dumps({"job": job.job_id, "labels": {k: asdict(v) for k, v in sorted(a.labels.items())}, + "flags": {k: asdict(v) for k, v in sorted(a.flags.items())}}, indent=1, ensure_ascii=False)) + return EXIT_OK + versions = fa.task_versions(job, a.flags) + rows = [] + for task, f in sorted(a.flags.items()): + inert = f.task_version is not None and versions.get(task) != f.task_version + rows.append((task, f.kind, f.category, f.status + (" (another version)" if inert else ""), f.by)) + for trial, lab in sorted(a.labels.items()): + rows.append((trial, "label", lab.label, lab.note, lab.by)) + # columns padded to their widest cell, the last one left as it is + widths = [max((len(r[i]) for r in rows), default=0) for i in range(4)] + for r in rows: + print((" ".join(cell.ljust(w) for cell, w in zip(r, widths)) + " " + r[4]).rstrip()) + return EXIT_OK + + +def _report(verb, done, unknown=(), skipped=()): + print(f"{verb} {len(done)}") + for name in unknown: + print(f"not in the job: {name}", file=sys.stderr) + for name in skipped: + print(f"kept, already accepted: {name}", file=sys.stderr) + + +def run(args) -> int: + jobs = _jobs(args.root) + if jobs is None: + return EXIT_NOT_FOUND + job = _job(jobs, args.job_id, args.root) + if isinstance(job, int): + return job + if args.action == "list": + return _list(job, args) + by = fa.who() + tasks = {t.task_base for t in job.trials} + + if args.action == "accept" and args.task and args.all_pending: + print("accept takes a task or --all-pending, not both", file=sys.stderr) + return EXIT_USAGE + if args.action in ("set", "remove") or (args.action == "accept" and not args.all_pending): + if not args.task: + print(f"{args.action} needs a task" + (" or --all-pending" if args.action == "accept" else ""), + file=sys.stderr) + return EXIT_USAGE + if not _task(job, args.task): + return EXIT_NOT_FOUND + + if args.action == "set": + version = fa.task_versions(job, [args.task]).get(args.task) + if args.by and not args.pending: + print("--by names who proposes a flag: it goes with --pending", file=sys.stderr) + return EXIT_USAGE + proposer = args.by or by + source = f"proposed:{proposer}" if args.pending else "person" + before = fa.load(job.dir).flags.get(args.task) + got = fa.update(job.dir, lambda a: a.set_flag(args.task, args.kind, args.category, by=proposer, + evidence=args.evidence or "", task_version=version, + source=source)) + if got is None: + print(f"kept, already accepted: {args.task}", file=sys.stderr) + else: + if before is not None and before.status == "pending": + print(f"replaced the pending flag from {before.source}: {args.task}", file=sys.stderr) + print(f"flagged {args.task} {args.kind}" + (", pending" if args.pending else "")) + elif args.action == "accept": + if not args.all_pending and args.task not in fa.load(job.dir).flags: + print(f"no flag on {args.task}", file=sys.stderr) + return EXIT_NOT_FOUND + + def accept(a): + names = sorted(t for t, f in a.flags.items() if f.status == "pending") if args.all_pending else [args.task] + for name in names: + a.accept(name, by=by) + return names + _report("accepted", fa.update(job.dir, accept)) + elif args.action == "remove": + fa.update(job.dir, lambda a: a.remove_flag(args.task)) + print(f"removed {args.task}") + elif args.action == "copy": + target = _job(jobs, args.to_job_id, args.root) + if isinstance(target, int): + return target + if target is job: + print("copy needs two different jobs", file=sys.stderr) + return EXIT_USAGE + if job.dataset and target.dataset and job.dataset != target.dataset: + print(f"{job.job_id} ran {job.dataset}, {target.job_id} ran {target.dataset}: not copied", file=sys.stderr) + return EXIT_INVALID + source = fa.load(job.dir) + target_tasks = {t.task_base for t in target.trials} + copied, unknown, skipped = fa.update(target.dir, lambda a: fa.copy_flags(source, a, job.job_id, target_tasks, + by=by)) + _report(f"copied to {target.job_id}, pending:", copied, unknown, skipped) + elif args.action == "import": + try: + with open(args.from_file, encoding="utf-8") as fh: + raw = json.load(fh) + except OSError as e: + print(f"cannot read {args.from_file}: {e}", file=sys.stderr) + return EXIT_NOT_FOUND + except ValueError as e: + print(f"{args.from_file} is not JSON: {e}", file=sys.stderr) + return EXIT_INVALID + records = raw.get("flags") if isinstance(raw, dict) else raw + if not isinstance(records, list): + print(f"{args.from_file} holds no list of flags", file=sys.stderr) + return EXIT_INVALID + versions = fa.task_versions(job, {args.prefix + str(r.get("task", "")) for r in records if isinstance(r, dict)}) + source = "import:" + os.path.basename(args.from_file) + added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( + a, records, tasks, source=source, by=by, prefix=args.prefix, versions=versions)) + _report("imported, pending:", added, unknown, skipped) + elif args.action == "feasibility": + report = feasibility.report(job, jobs) + if not report.executed: + print(f"no nop or oracle control found for {job.job_id}", file=sys.stderr) + return EXIT_NOT_FOUND + versions = fa.task_versions(job) + controls = [j for c in report.executed for j in jobs if j.job_id == c.job_id and j is not job] + other = {t for cj in controls for t, v in fa.task_versions(cj).items() if versions.get(t) not in (None, v)} + for t in sorted(other): + print(f"control ran another version: {t}", file=sys.stderr) + records = [{"task": r.task_base, "kind": "flawed", "category": FEASIBILITY[r.verdict], "evidence": r.why} + for r in report.rows if r.verdict in FEASIBILITY and r.task_base not in other] + added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( + a, records, tasks, source="import:feasibility", by=by, versions=versions)) + _report("imported, pending:", added, unknown, skipped) + return EXIT_OK + + +def parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser(prog="nullius flags", description="Write a run's task flags.", + epilog="exit codes: 0 done, 2 usage, 3 not found, 4 invalid input") + sub = p.add_subparsers(dest="action", required=True) + for name, helptext in (("list", "show the run's flags and labels"), ("set", "flag a task: accepted at once, or pending with --pending"), + ("accept", "accept a pending flag"), ("remove", "remove a task's flag"), + ("copy", "copy accepted flags to another run of the same dataset, as pending"), + ("import", "import flags from a file, as pending"), + ("feasibility", "import the feasibility controls' task verdicts, as pending")): + s = sub.add_parser(name, help=helptext) + s.add_argument("root") + s.add_argument("job_id") + if name in ("set", "accept", "remove"): + s.add_argument("task", nargs="?" if name == "accept" else None) + if name == "list": + s.add_argument("--json", action="store_true") + if name == "set": + s.add_argument("--kind", required=True, choices=fa.KINDS) + s.add_argument("--category", required=True) + s.add_argument("--evidence") + s.add_argument("--pending", action="store_true", + help="wait for a person to accept it: for a flag an agent proposes") + s.add_argument("--by", help="who proposes it, e.g. the agent's name (with --pending)") + if name == "accept": + s.add_argument("--all-pending", action="store_true") + if name == "copy": + s.add_argument("to_job_id") + if name == "import": + s.add_argument("--from", dest="from_file", required=True) + s.add_argument("--prefix", default="") + return p + + +def main(argv=None) -> int: + args = parser().parse_args(argv) + try: + return run(args) + except fa.FailureAnalysisError as e: + print(str(e), file=sys.stderr) + return EXIT_INVALID + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index 59c4a7d0..4f848e9f 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -100,6 +100,7 @@ nav: - cli/README.md - Read jobs: cli/read-jobs.md - Import a run: cli/import.md + - Task flags: cli/flags.md - Definitions: cli/definitions.md - Run a benchmark: cli/run.md - Prove a benchmark: cli/prove.md diff --git a/app/static/compare/comparison.css b/app/static/compare/comparison.css index 884e4ccc..f1991978 100644 --- a/app/static/compare/comparison.css +++ b/app/static/compare/comparison.css @@ -150,3 +150,9 @@ .fig-head .tools-menu a::before { content: ""; flex: 0 0 1em; text-align: center; color: var(--accent); } /* every item keeps the check's slot, so the names align */ .fig-head .tools-menu a[aria-current="true"]::before { content: "✓"; } /* the card's style or metric */ .fig-note { margin: 0; font-size: .84rem; color: var(--text-dim); } +/* the flag filters: one list of flagged tasks set aside in every column */ +.compare-flags{display:flex;flex-wrap:wrap;gap:.45rem;align-items:center;margin:.6rem 0} +.compare-flags .lead{color:var(--text-faint);font-size:.75rem} +.compare-flags #compare-set-aside{font-size:1rem;color:var(--text)} +.compare-flags .chip::before{display:none} +.compare-flags .warn{color:var(--warn,var(--text-dim))} diff --git a/app/static/runs/board.css b/app/static/runs/board.css index 2c943dff..43fe2e66 100644 --- a/app/static/runs/board.css +++ b/app/static/runs/board.css @@ -103,7 +103,7 @@ .rp .meter .bar1 span.x { background: none; box-shadow: inset 0 0 0 1.5px var(--track-res); } .rp .meter b { font: 500 13px/1 var(--sans); color: var(--text); white-space: nowrap; } .rp .board.pv .meter i.lit { box-shadow: 0 0 0 2px var(--surface), 0 0 0 3.5px var(--text); } -.rp .hk { margin: 14px 18px 0; font-size: 12px; line-height: 22px; } +.rp .hk { margin: 24px 18px 0; font-size: 12px; line-height: 22px; } .rp .hk p { margin: 0; color: var(--text-faint); white-space: nowrap; } .rp .hk dl { display: grid; grid-template-columns: auto auto; justify-content: start; column-gap: 6px; margin: 0; } .rp .hk dt { color: var(--text-faint); white-space: nowrap; } @@ -372,3 +372,22 @@ box-shadow: var(--shadow); font: 12px/1.45 var(--sans); color: var(--text); pointer-events: none; } @media (prefers-reduced-motion: reduce) { .rp *, .rp *::before, .rp *::after { transition: none !important; } } +/* the Filtered score under the adjusted rate: a switch per kind of flag, and the rate without those tasks */ +.rp .filtered { display: flex; flex-wrap: wrap; gap: .65rem; align-items: center; margin: 1rem 18px 0; } +.rp .filtered .filter-heading { flex-basis: 100%; color: var(--text-faint); font-size: .8rem; } +.rp .filtered .filter-choice { display: flex; align-items: center; gap: .5rem; flex-basis: 100%; font-size: .8rem; cursor: pointer; } +.rp .filtered input[type=checkbox] { margin: 0; flex: none; accent-color: var(--accent); } +.rp .filtered p { margin: .5rem 0 0; flex-basis: 100%; color: var(--text-dim); font-size: 1rem; } +.rp .filtered p b { color: var(--text); font-weight: 600; font-size: 1.4rem; margin-left: .2rem; } + +/* the trial table's marks: a task's flag and a trial's failure label; a task left out of the Filtered score fades */ +.rp .tt .w-fa { width: 7.5rem; } +.rp .tt td.fa { white-space: nowrap; } +.rp .tt .tflag + .tlabel { margin-left: .3rem; } +.rp .tt .tflag, .rp .tt .tlabel { display: inline-block; padding: 0 .35rem; border-radius: 3px; + font-size: .72rem; line-height: 1.35; white-space: nowrap; vertical-align: middle; } +.rp .tt .tflag { border: 1px solid var(--text-dim); color: var(--text-dim); } +.rp .tt .tflag.tf-pending, .rp .tt .tflag.tf-other { border-style: dashed; color: var(--text-faint); border-color: var(--text-faint); } +.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; } diff --git a/app/static/runs/board.js b/app/static/runs/board.js index 780956f1..d15aea2b 100644 --- a/app/static/runs/board.js +++ b/app/static/runs/board.js @@ -154,3 +154,22 @@ apply(); })(); + +// Each checkbox independently excludes one flag kind. The GET form works without JavaScript. +(() => { + const box = document.getElementById('filtered-score'); if (!box) return; + const choices = [...box.querySelectorAll('input[data-kind]')], rates = [...box.querySelectorAll('.filtered-rate')]; + const said = document.getElementById('filtered-live'); + const show = () => { + const on = choices.filter(c => c.checked).map(c => c.dataset.kind); + let shown = null; + rates.forEach(p => { const hit = p.dataset.kinds === on.join(','); p.hidden = !hit; if (hit) { p.id = 'filtered-rate'; shown = p; } else p.removeAttribute('id'); }); + const url = new URL(location.href); + choices.forEach(c => { if (c.checked) url.searchParams.set(c.dataset.kind, '1'); else url.searchParams.delete(c.dataset.kind); }); + const table = document.querySelector('.tt[data-leave-out]'); if (table) table.dataset.leaveOut = on.join(' '); + url.hash = ''; history.replaceState(null, '', url); + if (said) said.textContent = shown ? shown.textContent.replace(/\s+/g, ' ').trim() : 'Filtered score off'; + }; + choices.forEach(c => c.addEventListener('change', show)); + box.addEventListener('submit', e => { e.preventDefault(); show(); }); +})(); diff --git a/app/static/style.css b/app/static/style.css index de6b267c..2bf6eeaa 100644 --- a/app/static/style.css +++ b/app/static/style.css @@ -303,12 +303,13 @@ h3 .total { margin-left: .15rem; color: var(--text); font-weight: 600; text-tran .judgement-provenance { margin: 0 0 8px; } .judgement-hygiene { margin: 0 0 6px; } /* the outcome questions as cards */ -.jcards { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: .9rem; margin: 1rem 0 1.6rem; } +.jcards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, max(230px, calc((100% - 2.7rem) / 4))), 1fr)); gap: .9rem; margin: 1rem 0 1.6rem; } .jcard { background: var(--surface); border: 1px solid var(--border-soft); border-radius: var(--radius); padding: 1.1rem 1.2rem; display: flex; flex-direction: column; gap: .45rem; } .jcard-title { color: var(--text-dim); font-size: .85rem; } -.jcard-value { display: flex; align-items: baseline; gap: .5rem; } +.jcard-value { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; } +.jcard-value .jpill { max-width: 100%; white-space: normal; overflow-wrap: anywhere; } .jcard-value .jnum { font-size: 2rem; font-weight: 500; letter-spacing: -0.04em; font-variant-numeric: tabular-nums; line-height: 1; } -.jcard-value .junit { color: var(--text-dim); font-size: .95rem; } +.jcard-value .junit { white-space: nowrap; color: var(--text-dim); font-size: .95rem; } .jcard-blurb { min-height: 2.4em; } .jcard-foot { display: flex; justify-content: space-between; border-top: 1px solid var(--border-soft); padding-top: .55rem; margin-top: auto; } /* the pill says how an answer reads */ diff --git a/app/static/traces/failure.css b/app/static/traces/failure.css new file mode 100644 index 00000000..5b7baeea --- /dev/null +++ b/app/static/traces/failure.css @@ -0,0 +1,10 @@ +/* the User judge tab: the trial's label and its task's flag, each a short form */ +.failure-analysis{display:grid;gap:1.4rem;max-width:46rem;padding:.4rem 0} +.failure-analysis h3{font-size:.85rem;margin:0 0 .5rem;color:var(--text-dim);font-weight:500} +.failure-analysis p{margin:.2rem 0} +.fa-form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem} +.fa-form input[type=text]{flex:1 1 14rem;min-width:0} +.fa-choices{display:flex;flex-wrap:wrap;gap:.4rem;flex-basis:100%} +.fa-choices .chip::before{display:none} +.fa-choices .chip input{margin:0} +.chip-pending{font-size:.72rem;color:var(--warn,var(--text-dim));border:1px solid currentColor;border-radius:99px;padding:.05rem .45rem} diff --git a/app/static/traces/failure.js b/app/static/traces/failure.js new file mode 100644 index 00000000..893cefe5 --- /dev/null +++ b/app/static/traces/failure.js @@ -0,0 +1,39 @@ +// Save only the submitted section; drafts in the other section stay in the DOM. +(() => { + const panel = document.getElementById('failure-analysis'); + if (!panel) return; + panel.addEventListener('change', event => { + const input = event.target; + if (!input.matches('input[type=radio]')) return; + input.closest('.fa-choices').querySelectorAll('label').forEach(label => { + label.classList.toggle('active', label.querySelector('input').checked); + }); + }); + panel.addEventListener('submit', async event => { + const form = event.target; + if (!form.matches('.fa-form')) return; + event.preventDefault(); + if (form.getAttribute('aria-busy') === 'true') return; + const section = form.closest('.fa-part'); + const data = new FormData(form); + data.set('action', event.submitter ? event.submitter.value : form.querySelector('button[name=action]').value); + const controls = [...form.elements].filter(control => !control.disabled); + controls.forEach(control => { control.disabled = true; }); + form.setAttribute('aria-busy', 'true'); + try { + const response = await nulliusFetch(form.getAttribute('action'), {method: 'POST', body: data}); + if (!response.ok) throw new Error('Save failed'); + const doc = new DOMParser().parseFromString(await response.text(), 'text/html'); + const updated = doc.getElementById(section.id); + if (!updated) throw new Error('Missing saved section'); + section.replaceWith(updated); + nulliusNotify('Saved', {key: section.id}); + updated.querySelector('button[type=submit]')?.focus({preventScroll: true}); + } catch (_) { + nulliusNotify('Could not save. Your edits are still here; try again.', {error: true, key: section.id}); + } finally { + controls.forEach(control => { control.disabled = false; }); + form.removeAttribute('aria-busy'); + } + }); +})(); diff --git a/app/templates/compare/compare.html b/app/templates/compare/compare.html index c35d24be..fea4194c 100644 --- a/app/templates/compare/compare.html +++ b/app/templates/compare/compare.html @@ -71,6 +71,7 @@ {% if j is not none %} {% if c.shards %}{% for s in c.shards %}{{ shard_link(s, workspace=c.ref.workspace) }}{% endfor %}{% else %}{{ j.job_id }}{% endif %} {% if cohort == 'matched' %}{{ comparison.excluded_trials[c.i] }} of {{ selections[c.i].job.trials|length }} trials outside this cohort{% endif %} + {% if comparison.set_aside_trials and comparison.set_aside_trials[c.i] %}{{ comparison.set_aside_trials[c.i] }} trials of flagged tasks set aside{% endif %} {% endif %} @@ -110,6 +111,18 @@ {{ controls(view or 'side', [], sort=false, views=side_views, actions=side_actions) }} {% if jobs %} {% if cohort == 'matched' and not n_shared %}

No shared cohort is available. Choose runs with overlapping coverage or return to whole runs.

{% endif %} +{% set ff = flag_filter %}{% if ff and ((ff.flagged.values()|sum) or ff.unreadable) %} +
+ Leave out + {% for k in ('flawed', 'ambiguous') %}{% if ff.flagged[k] %} + {{ ff.flagged[k] }} {{ k }} + {% endif %}{% endfor %} + {% if ff.on %}Filtered: {{ ff.set_aside|length }} task{{ '' if ff.set_aside|length == 1 else 's' }} set aside in every column{% endif %} + {% if ff.unreadable %}Flags unreadable: {{ ff.unreadable|join(', ') }}{% endif %} + {% if ff.differ %}Flags differ on {{ ff.differ|length }} task{{ '' if ff.differ|length == 1 else 's' }}{% endif %} +
+{% endif %} {% if comparison.datasets_known and not comparison.datasets_match %}

The recorded datasets differ: pick runs of the baseline's dataset to compare the same tasks.

{% endif %} {% endif %} {% if view == 'chart' %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 92ce1898..f65a7aca 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -202,12 +202,27 @@ {% else %}
—
{% endif %} + {% if filtered %}{% set fv = filtered.view %} +
+ {% if fv.flagged.flawed or fv.flagged.ambiguous %}Exclude:{% endif %} + {% for key, value in request.args.items() if key not in ('flawed', 'ambiguous') %}{% endfor %} + {% for k in ('flawed', 'ambiguous') %}{% if fv.flagged[k] %} + + {% endif %}{% endfor %} + {% if fv.other_version %}{{ fv.other_version }} on another version{% endif %} + + {#- every combination of the switches, the one in the URL shown: runs/board.js switches between them in place #} + {% for v in filtered.views %} +

Filtered score {{ v.filtered_score|pct }} {{ v.solved }}/{{ v.ran }}

+ {% endfor %} + {% if fv.flagged.flawed or fv.flagged.ambiguous %}{% endif %} +
+ {% endif %}
- {% if job.has_verdict and job.raw_solve_rate == job.adjusted_solve_rate %}

raw = adjusted

{% endif %}
{% if not job.has_verdict or job.raw_solve_rate != job.adjusted_solve_rate %}
raw rate
{{ job.raw_solve_rate|pct }}
{% endif %} -
infra
{{ job.n_infra }} -
broke tests
{{ job.n_regressions }} + {% if job.n_infra %}
infra
{{ job.n_infra }}
{% endif %} + {% if job.n_regressions %}
broke tests
{{ job.n_regressions }}
{% endif %}
{% if pass_k %} {%- set ks = range(1, pass_k.attempts + 1)|select('le', 3)|list + ([pass_k.attempts] if pass_k.attempts > 3 else []) %} @@ -358,19 +373,20 @@

Trials

+ {% set show_fa = marks.flags or marks.labels %} {% set show_cause = show_judge %} {% set show_flags = show_judge and judgement.judged %} {% set n_judge = (1 if show_cause else 0) + (1 if show_flags else 0) + (1 if show_ins else 0) %}
- +
- {% if job.retries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} + {% if show_fa %}{% endif %}{% if job.retries %}{% endif %}{% if show_cause %}{% endif %}{% if show_flags %}{% endif %}{% if show_ins %}{% endif %} {% if vocab.gained %}{% endif %}{% if vocab.held %}{% endif %} - + {% if n_judge %}{% endif %} {% if vocab.gained or vocab.held %}{% endif %} @@ -380,6 +396,7 @@

Trials

+ {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} @@ -394,6 +411,8 @@

Trials

Open +{% macro task_flag(t) %}{%- set f = marks.flags.get(t.task_base) %}{% if f %}{{ f.kind }}{% if f.other %} · other version{% elif f.pending %} · pending{% endif %}{% endif %}{% endmacro %} +{% macro trial_label(t) %}{%- set l = marks.labels.get(t.trial_name) %}{% if l %}{{ l.label }}{% endif %}{% endmacro %} {% macro instruction(t) %}{%- set q = task_quality_of(job, t) %}{% if q %}{{ '%.1f'|format(q.score) }}/{{ q.top }}{% else %}—{% endif %}{% endmacro %} {% for t, group in trial_rows %} @@ -401,10 +420,11 @@

Trials

+ + {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} @@ -425,7 +445,7 @@

Trials

{%- if group %} @@ -438,6 +458,7 @@

Trials

{{ t.exception_type }}{{ t.exception_message }} {%- else %}{{ t.exception_type }}{% endif %}{% endif %} + {% if show_fa %}{% endif %} {% if job.retries %}{% endif %} {% if show_cause %}
Judge{% if tq %}instructions scored {{ tq.judged }}/{{ tq.tasks }}{% endif %}TestsTask OutcomeUser judgeRetriesCause{% if show_flags %} · flags{% endif %}Flags
{{ attempt_count(group, false) }} {{ task_flag(t) }}attempt {{ k }}{% if not group %}{{ task_flag(t) }}{% endif %}{{ trial_label(t) }}{% if t.n_retries %}{{ t.n_retries }}/{{ job.retries }}{% else %}0/{{ job.retries }}{% endif %} {%- if t.outcome == 'resolved' %}not asked diff --git a/app/templates/traces/_failure.html b/app/templates/traces/_failure.html new file mode 100644 index 00000000..de210fe3 --- /dev/null +++ b/app/templates/traces/_failure.html @@ -0,0 +1,50 @@ +{#- The User judge tab: the trial's label (failed trials only) and its task's flag. A person writes both. -#} +{% set fp = failure %}{% set act = url_for('failure_route', job_id=job.job_id, trial_name=trial.trial_name) %} +
+ {% if fp.error %}

{{ fp.error }}

{% endif %} + {% if fp.failed %} +
+

{% if fp.attempt %}Why attempt {{ fp.attempt[0] }} failed{% else %}Why it failed{% endif %}

+ {% if fp.can_write %} +
+
+ {% for key, name in fp.labels.items() %} + + {% endfor %} +
+ + + {% if fp.label %}{% endif %} +
+ {% elif fp.label %} +

{{ fp.labels[fp.label.label] }}{% if fp.label.note %} · {{ fp.label.note }}{% endif %}

+ {% endif %} + {% if fp.label %}

{{ fp.labels[fp.label.label] }} · {{ fp.label.by }} · {{ fp.label.at[:10] }}

{% endif %} + {% if fp.model_labels %}

{% for m in fp.model_labels %}{{ ' · ' if not loop.first }}{{ m.name }}: {{ fp.labels.get(m.label, m.label|capitalize) }}{% if m.label_p is not none %} {{ '%.0f'|format(m.label_p * 100) }}%{% endif %}{% endfor %}

+ {% elif fp.suggests %}

Judge suggests {% for k in fp.suggests %}{{ ' or ' if not loop.first }}{{ fp.labels[k] }}{% endfor %}

{% endif %} +
+ {% endif %} +
+

{% if fp.attempt %}Task flag · all {{ fp.attempt[1] }} attempts{% else %}Task flag{% endif %}

+

One flag per task in this run{% if fp.attempt %}: it shows on every attempt{% endif %}.

+ {% set fl = fp.flag %} + {% if fp.can_write %} +
+
+ {% for k in fp.kinds %}{% endfor %} +
+ + {% for c in fp.categories %} + + + {% if fl and fl.status == 'pending' %}{% endif %} + {% if fl %}{% endif %} +
+ {% elif fl %} +

{{ fl.category|replace('_', ' ') }}

+ {% if fl.evidence %}

{{ fl.evidence }}

{% endif %} + {% else %}

Not flagged

{% endif %} + {% if fl %}

{{ fl.kind|capitalize }} · {{ fl.by }} · {{ fl.at[:10] }}{% if fl.status == 'pending' %} pending{% endif %}{% if fl.accepted_by and fl.accepted_by != fl.by %} · accepted by {{ fl.accepted_by }}{% endif %}

{% endif %} + {% if fp.model_flags %}

{% if fp.attempt %}On this attempt: {% endif %}{% for m in fp.model_flags %}{{ ' · ' if not loop.first }}{{ m.name }}: {{ fp.flag_names.get(m.flag, m.flag) }}{% if m.flag_p is not none %} {{ '%.0f'|format(m.flag_p * 100) }}%{% endif %}{% endfor %}

{% endif %} +
+
diff --git a/app/templates/traces/trial.html b/app/templates/traces/trial.html index 892653b0..8dd4819b 100644 --- a/app/templates/traces/trial.html +++ b/app/templates/traces/trial.html @@ -27,6 +27,7 @@ {% from '_page.html' import page_head %} {% block body %} + {% set sub %} @@ -69,7 +70,7 @@ {% endif %} @@ -283,6 +284,9 @@

{{ job.runner }}'s score gives the {{ judgement_panel(llm_judgement, job, trial, csrf) }} {% endif %} +{% if failure is not none %}
+{% include "traces/_failure.html" %} +
{% endif %}
{# The task's instruction, scored on its own text: once per dataset and task, the same for every attempt, nothing of any run read. The score changes no outcome. #} @@ -629,6 +633,7 @@

Waterfall

{% endif %}
+