diff --git a/.agents/skills/flag-tasks/scripts/flags.py b/.agents/skills/flag-tasks/scripts/flags.py index 8be3c54fb..30b9d0b5c 100644 --- a/.agents/skills/flag-tasks/scripts/flags.py +++ b/.agents/skills/flag-tasks/scripts/flags.py @@ -67,7 +67,9 @@ def spot(args): run = seen.setdefault(ref.key, {}).setdefault(path, [0, 0]) run[0] += float(t.reward) >= 1 run[1] += 1 - where.setdefault(ref.key, (ref.name, t.dir)) + # what an import finds it by: its exact identity, else a raw unit as such, else its name + exact = {"id": ref.key} if ref.shared and ref.key != ref.name else {"unit": True} if t.unit else {} + where.setdefault(ref.key, (ref.name, t.dir, exact)) if not seen: sys.exit("no attempt with a reward: nothing to count") if len(datasets) > 1: @@ -81,7 +83,7 @@ def spot(args): with open(os.path.join(where[task][1], "result.json"), encoding="utf-8") as fh: task_id = json.load(fh).get("task_id") or {} cases.append({"task": where[task][0], "group": groups[task], "runs": list(seen[task].values()), - "task_folder": task_id.get("path")}) + "task_folder": task_id.get("path"), **where[task][2]}) write(args.out, "cases.json", cases) write(args.out, "for-readers.json", for_readers(cases)) count = Counter(groups.values()) @@ -196,7 +198,8 @@ def merge(args): if agree: lead = next(v for v in agree if flat(v["category"]) == categories[0]) flags.append({"task": task, "kind": result, "category": categories[0], - "evidence": f"{flat(lead['evidence'])} ({len(agree)} of {len(votes)})"}) + "evidence": f"{flat(lead['evidence'])} ({len(agree)} of {len(votes)})", + **{k: case[k] for k in ("id", "unit") if k in case}}) said = "; ".join(f"{v['reader']}: {v['verdict']}" for v in votes) rows.append((task, case["group"], result, ", ".join(categories), said, votes)) order = {k: i for i, k in enumerate(("third", "contested", "flawed", "ambiguous", "undecided", "unread", "fair"))} diff --git a/app/nullius/compare/comparison.py b/app/nullius/compare/comparison.py index 5d72d5f71..d613a6fd8 100644 --- a/app/nullius/compare/comparison.py +++ b/app/nullius/compare/comparison.py @@ -169,10 +169,10 @@ def n_differing(self) -> int: def task_key(selection: SelectedRun, trial: Trial) -> tuple: """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. - A standard trial adds its own key (``parse.task_ref``): its exact identity, else one of its job alone.""" + A standard trial adds its own key (``parse.task_ref``): its exact identity, else one of its column alone.""" ref = parse.task_ref(selection.job, trial) return (selection.job.dataset or f"[unidentified:{selection.value}]", ref.name, - None if ref.key == ref.name else (ref.key, ref.shared)) + None if ref.key == ref.name else (ref.key if ref.shared else (ref.key, selection.value), ref.shared)) def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: frozenset = frozenset()) -> Comparison: diff --git a/app/nullius/compare/flags.py b/app/nullius/compare/flags.py index acd5ed579..0843ebd91 100644 --- a/app/nullius/compare/flags.py +++ b/app/nullius/compare/flags.py @@ -9,11 +9,12 @@ def flag_filter(selected, exclude=()) -> dict: """The flag filters of a comparison: one list of tasks set aside in every column, the union of the runs' accepted flags of the kinds in ``exclude``, keyed as the comparison keys a task (`comparison.task_key`). A flag - counts only on the task version it names, and a task is set aside only when every column holding it ran the - same version; otherwise it stays, and is named in `differ` with the tasks the runs flag differently. - `flagged` counts each kind over all runs, for the switches; `unreadable` names runs whose file is broken.""" + counts only on the trials it applies to (`failure_analysis.holds`), and a task is set aside only when all its + trials, in every column, ran the same version; otherwise it stays, and is named in `differ` with the tasks the + runs flag differently. `flagged` counts each kind over all runs, for the switches; `unreadable` names runs whose + file is broken.""" on = [k for k in failure_analysis.KINDS if k in exclude] - runs, unreadable = [], [] # per run: {task key: version}, {task key: kind} + runs, unreadable = [], [] # per run: its trials and their keys, {task key: kind}, its keys for selection in selected: job = selection.job try: @@ -22,21 +23,22 @@ def flag_filter(selected, exclude=()) -> dict: analysis = failure_analysis.Analysis() unreadable.append(job.job_id) analysis = failure_analysis.for_job(job, analysis) - versions = failure_analysis.task_versions(job, analysis.flags) if analysis.flags else {} - tasks = {} # each task of the job to its comparison keys: one per identity it ran - for t in job.trials: - tasks.setdefault(failure_analysis.task_of(t), set()).add(comparison.task_key(selection, t)) - kinds = {key: kind for kind in failure_analysis.KINDS - for task in analysis.set_aside([kind], versions) & set(tasks) for key in tasks[task]} - runs.append((selection, tasks, kinds, set().union(*tasks.values()))) + versions = failure_analysis.trial_versions(job, analysis.flags) if analysis.flags else {} + trials, kinds = [(t, comparison.task_key(selection, t)) for t in job.trials], {} + for t, key in trials: + flag = analysis.flags.get(failure_analysis.task_of(t)) + if flag is not None and flag.status == "accepted" and failure_analysis.holds(flag, t, versions): + kinds[key] = flag.kind + runs.append((selection, trials, kinds, {key for _, key in trials})) flagged_keys = set().union(*(kinds for _, _, kinds, _ in runs)) - # the versions every column holding a flagged task ran, read once per run for those tasks + # the versions the trials of a flagged task ran in every column, read once per run for its tasks ran = {} - for selection, tasks, _, _ in runs: - names = {task for task, keys in tasks.items() if keys & flagged_keys} - for task, version in failure_analysis.task_versions(selection.job, names).items(): - for key in tasks[task]: - ran.setdefault(key, set()).add(version) + for selection, trials, _, _ in runs: + flagged = [(t, key) for t, key in trials if key in flagged_keys] + versions = failure_analysis.trial_versions(selection.job, {failure_analysis.task_of(t) for t, _ in flagged}) + for t, key in flagged: + if t.trial_name in versions: + ran.setdefault(key, set()).add(versions[t.trial_name]) holders = {key: [r for r in runs if key in r[3]] for key in flagged_keys} differ = sorted(key[1] for key in flagged_keys if len(ran.get(key, set())) > 1 or len({kinds.get(key) for _, _, kinds, _ in holders[key]}) > 1) diff --git a/app/nullius/runs/failure_analysis.py b/app/nullius/runs/failure_analysis.py index 509a3e001..aae8adac1 100644 --- a/app/nullius/runs/failure_analysis.py +++ b/app/nullius/runs/failure_analysis.py @@ -9,8 +9,8 @@ of ``LABELS``. - A *flag* belongs to one task of the job's dataset (``task_of``): ``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. + most one flag. A flag can name the task's version, and the benchmark versions it holds for; it applies to the + trials of those alone (``holds``). A flag that names neither applies to every trial of its task. - A flag is saved under its task's ``task_base``, or, marked ``unit``, under a standard trial's raw unit. An unmarked one, as every flag was once, applies while one task of the job has that name (``slots``). @@ -85,6 +85,8 @@ class Flag: accepted_by: str = "" accepted_at: str = "" unit: bool = False # saved under a raw unit whose display name another task shares; left out of the file when not + # the benchmark versions it holds for, when its job ran the task at others too (a copy, an import); left out when None + benchmark_versions: Optional[list] = None @dataclass @@ -104,7 +106,8 @@ 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", unit: bool = False) -> Optional[Flag]: + task_version: Optional[str] = None, source: str = "person", unit: bool = False, + benchmark_versions: Optional[list] = None) -> 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. *unit*: *task* is a raw unit.""" @@ -124,7 +127,7 @@ def set_flag(self, task: str, kind: str, category: str, *, by: str, evidence: st 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 "", unit) + by, now, by if person else "", now if person else "", unit, benchmark_versions) return self.flags[task] def accept(self, task: str, *, by: str) -> Flag: @@ -138,18 +141,18 @@ 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.""" + def set_aside(self, kinds: Iterable[str]) -> Set[str]: + """The tasks whose accepted flag is of the chosen kinds: what the filtered score leaves out, on the trials each + flag holds for (``holds``).""" 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 + return {task for task, flag in self.flags.items() if flag.status == "accepted" and flag.kind in chosen} + + +def holds(flag: Flag, trial, versions: Optional[Dict[str, str]] = None) -> bool: + """Whether *flag* applies to *trial*, a trial of its task: one of the benchmark versions it names and, with + *versions* (``trial_versions``), the task version it names. A flag that names neither applies to each.""" + return ((flag.benchmark_versions is None or trial.benchmark_version in flag.benchmark_versions) + and (versions is None or flag.task_version is None or versions.get(trial.trial_name) == flag.task_version)) def task_of(trial): @@ -229,6 +232,21 @@ def across(job) -> Dict[Any, Any]: return {ref.key: ref.local for ref in refs if ref.shared} +def _identities(job) -> Dict[Any, Set]: + """Each task of the job (``task_of``) to the keys its trials ran under (``parse.task_ref``).""" + out: Dict[Any, Set] = {} + for t in job.trials: + ref = parse.task_ref(job, t) + out.setdefault(ref.local, set()).add(ref.key) + return out + + +def _bound(ran: Set, keys: Set) -> Optional[list]: + """The benchmark versions a flag on a task that *ran* under those keys holds for, to cover *keys* alone: None when + they are all it ran under. Its keys differ by benchmark version only (``Job.task_id``).""" + return None if ran <= keys else sorted({key[1] for key in ran & keys if isinstance(key, tuple)}) + + @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. @@ -287,14 +305,18 @@ def load(job_dir: str) -> Analysis: 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") + versions = fl.benchmark_versions + if (fl.kind not in KINDS or fl.status not in STATUSES or not fl.category or not _source_ok(fl.source) + or not (versions is None or isinstance(versions, list) and all(isinstance(v, str) for v in versions))): + raise FailureAnalysisError(f"task {key!r}: kind, status, category, source or benchmark versions is not allowed") return Analysis(labels, flags) def record(flag: Flag) -> dict: - """A flag as its file holds it: ``unit`` only when set, so any other flag is written as it always was.""" - return {name: value for name, value in asdict(flag).items() if name != "unit" or value} + """A flag as its file holds it: ``unit`` and ``benchmark_versions`` only when set, so any other flag is written as + it always was.""" + return {name: value for name, value in asdict(flag).items() + if (name, value) not in (("unit", False), ("benchmark_versions", None))} def _save(job_dir: str, analysis: Analysis) -> None: @@ -328,92 +350,138 @@ class Filtered: 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.""" + every trial except those a set-aside task's flag applies to (``holds``); only the rate and its counts are read + from that copy. With *versions* (`trial_versions`), a flag applies to the trials of the task version it names.""" analysis = for_job(job, analysis) - tasks = {task_of(t) for t in job.trials} + accepted = analysis.set_aside(KINDS) & {task_of(t) for t in job.trials} + tasks = {task for t in job.trials if (task := task_of(t)) in accepted and holds(analysis.flags[task], t, versions)} 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) + flagged = {k: len(analysis.set_aside([k]) & tasks) for k in KINDS} + stale = len(accepted - tasks) if not on: return Filtered(flagged, stale, on, {}) - out = analysis.set_aside(on, versions) & tasks + out = analysis.set_aside(on) & 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 task_of(t) not in out]) + rest = replace(job, trials=[t for t in job.trials + if task_of(t) not in out or not holds(analysis.flags[task_of(t)], t, versions)]) return Filtered(flagged, stale, on, by_kind, rest.adjusted_solve_rate, rest.n_resolved, len(rest.trials) - rest.n_infra) +def version_of(trial) -> Optional[str]: + """The trial's task version: the ``task_checksum`` Harbor records in its ``result.json``; None without one.""" + try: + with open(os.path.join(trial.dir, "result.json"), encoding="utf-8") as fh: + checksum = (json.load(fh) or {}).get("task_checksum") + except (OSError, ValueError, AttributeError): + return None + return checksum if isinstance(checksum, str) and checksum else None + + def task_versions(job, tasks: Optional[Iterable[str]] = None) -> Dict[str, str]: - """Each task's version, by ``task_of``: the ``task_checksum`` Harbor records in a trial's ``result.json``. Only - *tasks* when given; a task whose trials record none is left out.""" + """Each task's version, by ``task_of``: its first trial's that records one (``version_of``). 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: task = task_of(t) if task in out or (wanted is not None and task 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: + checksum = version_of(t) + if checksum: out[task] = checksum return out +def trial_versions(job, tasks: Optional[Iterable[Any]] = None) -> Dict[str, str]: + """Each trial's task version (``version_of``), by its trial name: the trials of *tasks* (``task_of``) alone when + given. A trial that records none is left out.""" + wanted = None if tasks is None else set(tasks) + return {t.trial_name: checksum for t in job.trials + if (wanted is None or task_of(t) in wanted) and (checksum := version_of(t))} + + def copy_flags(source: Analysis, target: Analysis, source_job, target_job, *, by: str) -> Tuple[list, list, list]: """Copy *source*'s accepted flags into *target* as pending flags, keeping each flag's task version. A flag is read - in its own job (``slots``) and goes to the target job's task of the same key (``across``): never to another unit - of that name. Returns the saved names copied, those the target job does not hold, and those skipped because - *target* already holds an accepted flag.""" + in its own job (``slots``) and goes to the target job's task of a key it applies to (``across``), there for + those keys alone (``_bound``): never to another unit of that name. A flag on no task of a Harbor job goes by its + saved name; on no task, or none resolved, of a standard job, nowhere. Returns the saved names copied, those the + target job does not hold, and those skipped because *target* already holds an accepted flag.""" held = {key: task for task, (key, flag) in slots(source_job, source.flags).items() if flag} - keys: Dict[Any, list] = {} - for key, task in across(source_job).items(): - keys.setdefault(task, []).append(key) - there, where, shown = across(target_job), slots(target_job, target.flags), _shown(target_job) + refs: Dict[Any, list] = {} # each task of the source job to its trials and their keys + for t in source_job.trials: + ref = parse.task_ref(source_job, t) + refs.setdefault(ref.local, []).append((t, ref)) + by_name = all(ref.key == ref.local for pairs in refs.values() for _, ref in pairs) # a Harbor job's keys + there, ran = across(target_job), _identities(target_job) + where, shown = slots(target_job, target.flags), _shown(target_job) copied, unknown, skipped = [], [], [] for saved, flag in sorted(source.flags.items()): if flag.status != "accepted": continue - # a flag on no task of its job is a name, as it was saved: a unit's names nothing elsewhere - wanted = keys.get(held[saved], ()) if saved in held else () if flag.unit else (saved,) - tasks = {there[key] for key in wanted if there.get(key) in where} + if saved in held: + keys = {ref.key for t, ref in refs[held[saved]] if ref.shared and holds(flag, t)} + else: # a name, as it was saved: a unit's names nothing elsewhere + keys = {saved} if by_name and not flag.unit else set() + tasks = {there[key] for key in keys if there.get(key) in where} if not tasks: unknown.append(saved) for task in tasks: got = target.set_flag(where[task][0], flag.kind, flag.category, by=by, evidence=flag.evidence, task_version=flag.task_version, source=f"copy:{source_job.job_id}", - unit=_marked(shown, task, where[task][0])) + unit=_marked(shown, task, where[task][0]), benchmark_versions=_bound(ran[task], keys)) (copied if got is not None else skipped).append(saved) return copied, unknown, skipped -def import_flags(target: Analysis, job, records: Iterable[dict], *, source: str, by: str, prefix: str = "", - tasks: Optional[Dict[Any, Any]] = None) -> Tuple[list, list, list]: +def _key(value): + """A record's ``id``: a task's key across runs (``parse.task_ref``), as JSON holds it.""" + if isinstance(value, str) or isinstance(value, (list, tuple)) and value and all(isinstance(v, str) for v in value): + return value if isinstance(value, str) else tuple(value) + raise FailureAnalysisError(f"a flag's id {value!r} is no task's") + + +def import_flags(target: Analysis, job, records: Iterable[dict], *, source: str, by: str, + prefix: str = "") -> Tuple[list, list, list]: """Add flags from *records* (each with ``task``, ``kind``, ``category`` and an optional ``evidence``) as pending - flags on the job's tasks, each with its version and saved where ``slots`` says. A task is named (``named``) by - *prefix* plus the record's ``task``, or looked up in *tasks* when given; a name the job does not hold is not - guessed. Returns the names added, those not found, and those skipped because they hold an accepted flag.""" - known, where, shown = named(job) if tasks is None else tasks, slots(job, target.flags), _shown(job) - asked = [] + flags on the job's tasks, each with its version and saved where ``slots`` says. A record with ``id``, its task's + key across runs (``parse.task_ref``), goes to the job's task of that key alone, there for the keys the records + give it (``_bound``). Else its task is named (``named``) by *prefix* plus the record's ``task``: a raw unit + alone when it is marked ``unit``. A name the job does not hold is not guessed. Returns the names added, those + not found, and those skipped because they hold an accepted flag.""" + known, exact, ran = named(job), across(job), _identities(job) + where, shown = slots(job, target.flags), _shown(job) + asked, keys = [], {} 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") - name = rec["task"] if tasks is not None else prefix + str(rec["task"]) - asked.append((rec, name, known.get(name))) - versions = task_versions(job, {task for _, _, task in asked if task in where}) + name = prefix + str(rec["task"]) + if rec.get("id") is not None: + key = _key(rec["id"]) + task = exact.get(key) + keys.setdefault(task, set()).add(key) + asked.append((rec, str(rec["task"]), task, True)) + elif rec.get("unit"): # a raw unit, never another task shown under that name + asked.append((rec, name, (name,) if (name,) in ran else None, False)) + else: + asked.append((rec, name, known.get(name), False)) + versions, trials = trial_versions(job, {task for _, _, task, _ in asked if task in where}), {} + for t in job.trials: + trials.setdefault(task_of(t), []).append(t) added, unknown, skipped = [], [], [] - for rec, name, task in asked: + for rec, name, task, exactly in asked: if task not in where: unknown.append(name_of(name)) continue + bound = _bound(ran[task], keys[task]) if exactly else None + # its task version: that of the first trial it applies to + version = next((versions[t.trial_name] for t in trials[task] if t.trial_name in versions + and (bound is None or t.benchmark_version in bound)), None) got = target.set_flag(where[task][0], str(rec.get("kind", "")), str(rec.get("category", "")), by=by, - evidence=str(rec.get("evidence", "") or ""), source=source, - task_version=versions.get(task), unit=_marked(shown, task, where[task][0])) + evidence=str(rec.get("evidence", "") or ""), source=source, task_version=version, + unit=_marked(shown, task, where[task][0]), benchmark_versions=bound) (added if got is not None else skipped).append(name_of(name)) return added, unknown, skipped diff --git a/app/nullius/runs/flags_cli.py b/app/nullius/runs/flags_cli.py index a25e1d037..cf2d99cc2 100644 --- a/app/nullius/runs/flags_cli.py +++ b/app/nullius/runs/flags_cli.py @@ -69,10 +69,14 @@ def _list(job, args) -> int: "flags": {k: fa.record(v) for k, v in sorted(a.flags.items())}}, indent=1, ensure_ascii=False)) return EXIT_OK tasks = {key: task for task, (key, flag) in fa.slots(job, a.flags).items() if flag} # each flag's own task - versions = fa.task_versions(job, tasks.values()) + versions, trials = fa.trial_versions(job, tasks.values()), {} + for t in job.trials: + trials.setdefault(fa.task_of(t), []).append(t) rows = [] for task, f in sorted(a.flags.items()): - inert = f.task_version is not None and versions.get(tasks.get(task, task)) != f.task_version + # a flag that names a version and applies to none of its task's trials + inert = ((f.task_version is not None or f.benchmark_versions is not None) + and not any(fa.holds(f, t, versions) for t in trials.get(tasks.get(task), ()))) 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)) @@ -146,7 +150,8 @@ def accept(a): return names _report("accepted", fa.update(job.dir, accept)) elif args.action == "remove": - if isinstance(task, tuple) and flag is None: # a unit never answers for a flag under a name it shares + # a unit never answers for a flag under a name it shares; a record under the very name given goes, by it + if isinstance(task, tuple) and flag is None and key not in saved: print(f"no flag on {args.task}", file=sys.stderr) return EXIT_NOT_FOUND fa.update(job.dir, lambda a: a.remove_flag(key)) @@ -187,21 +192,30 @@ def accept(a): 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(map(fa.name_of, other)): - print(f"control ran another version: {t}", file=sys.stderr) + ran = _ran(job) # a row's task versions: those of its exact task, never another's + other = {key for cj in controls for key, versions in _ran(cj).items() if ran.get(key) and versions - ran[key]} + for name in sorted({r.task_base for r in report.rows if r.key in other}): + print(f"control ran another version: {name}", file=sys.stderr) mine = fa.across(job) # a row is this job's task when the job ran that exact task - rows = [r for r in report.rows if r.verdict in FEASIBILITY and mine.get(r.key, r.key) not in other] - records = [{"task": mine[r.key], "kind": "flawed", "category": FEASIBILITY[r.verdict], "evidence": r.why} - for r in rows if r.key in mine] + rows = [r for r in report.rows if r.verdict in FEASIBILITY and r.key not in other] + records = [{"task": r.task_base, "id": r.key, "kind": "flawed", "category": FEASIBILITY[r.verdict], + "evidence": r.why} for r in rows if r.key in mine] added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( - a, job, records, source="import:feasibility", by=by, tasks={task: task for task in mine.values()})) + a, job, records, source="import:feasibility", by=by)) _report("imported, pending:", added, [r.task_base for r in rows if r.key not in mine] + unknown, skipped) return EXIT_OK +def _ran(job) -> dict: + """Each task of the job by its key across runs (``parse.task_ref``), to the task versions its trials recorded.""" + versions, out = fa.trial_versions(job), {} + for t in job.trials: + if t.trial_name in versions: + out.setdefault(parse.task_ref(job, t).key, set()).add(versions[t.trial_name]) + return out + + 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") diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 406b38f6f..639952135 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -482,7 +482,7 @@

Trials

Open -{% macro task_flag(t) %}{%- set f = marks.flags.get(marks.task_of(t)) %}{% if f %}{{ f.kind }}{% if f.other %} · other version{% elif f.pending %} · pending{% endif %}{% endif %}{% endmacro %} +{% macro task_flag(t) %}{%- set f = marks.flags.get(t.trial_name) %}{% 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 %} @@ -491,7 +491,7 @@

Trials

+ {{ 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 %} @@ -517,7 +517,7 @@

Trials

{%- set name = 'attempt ' ~ k if group else task_labels[t.trial_name] %} {% if picking %}{% endif -%} diff --git a/app/tests/test_attempts.py b/app/tests/test_attempts.py index 4b4a71a5c..a60f49aaf 100644 --- a/app/tests/test_attempts.py +++ b/app/tests/test_attempts.py @@ -8,11 +8,13 @@ import tempfile import unittest import unittest.mock +from pathlib import Path from nullius.compare import cli as compare_cli, comparison from nullius.runs import attempts, failure_analysis as fa, feasibility, flags_cli, parse from nullius.standard.runner import job as runner, merge from tests.test_comparison import job, selected, trial +from tests.test_flags_cli import job as harbor_job T0 = datetime(2026, 9, 1, tzinfo=timezone.utc) @@ -123,7 +125,8 @@ def setUp(self): self.tmp = tmp.name def written(self, name, units, key="b", version="1", dataset="set", config=True, control=""): - """A job the runner wrote: one trial per (unit, reward). ``control``: the control it ran, nop or oracle.""" + """A job the runner wrote: one trial per (unit, reward[, the benchmark version it ran, else the job's]). + ``control``: the control it ran, nop or oracle.""" bench = {"key": key, "family": "agent", "needs": [], "score": {"kind": "pass", "says": "passed"}, "_version": version, "_ref": f"{key}@{version}"} where = os.path.join(self.tmp, name) os.makedirs(where) @@ -131,8 +134,9 @@ def written(self, name, units, key="b", version="1", dataset="set", config=True, with open(os.path.join(where, "config.json"), "w") as f: json.dump({"job_name": name, "runner": "standard", "standard": {"benchmark": key, "benchmark_version": version, "plugged": control or "original", **({"control": {"name": control}} if control else {})}, "datasets": [{"name": f"{key}/{dataset}"}]}, f) - for i, (unit, reward) in enumerate(units): - runner.write_trial(os.path.join(where, f"{name}-u{i}"), job=name, bench=bench, + for i, (unit, reward, *other) in enumerate(units): + runner.write_trial(os.path.join(where, f"{name}-u{i}"), job=name, + bench=dict(bench, _version=other[0], _ref=f"{key}@{other[0]}") if other else bench, other={"key": control, "_kind": "control"} if control else {"key": "original", "_kind": "upstream"}, model="m", unit=unit, t0=0, t1=1, produce=(0, 1), score={"reward": reward, "detail": {}}, exception=None, calls=[], trajectory=None) @@ -274,6 +278,8 @@ def test_one_run_shares_no_unresolved_task_with_itself(self): self.assertEqual((matched.shared_tasks, matched.tasks, matched.excluded_trials), (len(parse.shared_tasks([forced])), (), (1,))) self.assertEqual(len(comparison.build(selected(forced)).tasks), 1) # the whole run keeps its row self.assertEqual(comparison.build(selected(job([trial("a")])), "matched").shared_tasks, 1) # Harbor: as before + twice = comparison.build(selected(forced, forced)) # one run through two workspaces + self.assertEqual([r.shared for r in twice.tasks], [False, False]) # shares nothing, as matched says def test_two_rows_of_one_name_have_two_selectors(self): first, second = (parse.parse_job(self.written(n, [("same", 1.0)], version=v)) for n, v in (("v1", "1"), ("v2", "2"))) @@ -347,6 +353,9 @@ def test_a_proposal_under_a_shared_name_waits_and_is_removed_by_its_saved_name(s self.assertEqual(self.cli("remove", "both", "a/b/c")[::2], (flags_cli.EXIT_NOT_FOUND, "no flag on a/b/c\n")) self.assertEqual(self.cli("remove", "both", "a-b-c")[0], 0) self.assertEqual(fa.load(where).flags, {}) + legacy = self.written("legacy", [("group/1", 1.0), ("group-1", 0.0)]) # its saved name is a unit's too + fa.update(legacy, lambda a: a.set_flag("group-1", "flawed", "c", by="ann", source="import:old")) + self.assertEqual((self.cli("remove", "legacy", "group-1")[0], fa.load(legacy).flags), (0, {})) def test_a_copied_flag_goes_to_the_same_unit_never_to_one_of_its_name(self): source, target = self.written("source", [("group/1", 0.0)]), self.written("target", [("group/1", 0.0), ("group-1", 0.0)]) @@ -357,6 +366,31 @@ def test_a_copied_flag_goes_to_the_same_unit_never_to_one_of_its_name(self): self.assertEqual(self.cli("set", "raw", "group-1", "--kind", "flawed", "--category", "c")[0], 0) self.assertEqual(self.cli("copy", "raw", "alias")[1:], ("copied to alias, pending: 0\n", "not in the job: group-1\n")) self.assertEqual(fa.load(alias).flags, {}) + harbor = harbor_job(Path(self.tmp), "harbor", {"group-1": (0, "c")}, dataset="b/set") + fa.update(target, lambda a: a.set_flag("group-1", "flawed", "c", by="ann")) # on neither unit of target + self.assertEqual(self.cli("copy", "target", "harbor")[1:], ("copied to harbor, pending: 0\n", "not in the job: group-1\n")) + self.assertEqual(fa.load(str(harbor)).flags, {}) + + def test_a_flag_copied_or_imported_into_a_run_of_two_versions_covers_its_own(self): + both = self.written("both", [("x", 0.0), ("x", 1.0, "2")]) # x at version 1, and at 2 + self.written("one", [("x", 0.0)]) + self.cli("set", "one", "x", "--kind", "flawed", "--category", "c") + self.assertEqual(self.cli("copy", "one", "both")[1], "copied to both, pending: 1\n") + self.assertEqual(fa.load(both).flags["x"].benchmark_versions, ["1"]) + # nop at version 1 was accepted: a proposal; the oracle ran version 2 alone, at another task version + self.written("both-nop", [("x", 1.0)], control="nop") + self.written("both-oracle", [("x", 1.0)], version="2", control="oracle") + for run, trial_dir, checksum in (("both", "both-u0", "c1"), ("both", "both-u1", "c2"), + ("both-nop", "both-nop-u0", "c1"), ("both-oracle", "both-oracle-u0", "c2")): + self.edit(os.path.join(self.tmp, run), f"{trial_dir}/result.json", lambda res, c=checksum: res.update(task_checksum=c)) + fa.update(both, lambda a: a.flags.clear()) + self.assertEqual(self.cli("feasibility", "both")[1:], ("imported, pending: 1\n", "")) + flag = fa.load(both).flags["x"] + self.assertEqual((flag.benchmark_versions, flag.task_version), (["1"], "c1")) + self.cli("accept", "both", "--all-pending") + run = parse.parse_job(both) + view = fa.filtered(run, fa.load(both), ["flawed"], fa.trial_versions(run)) + self.assertEqual((view.ran, view.solved), (1, 1)) # version 2's trial stays def test_feasibility_flags_only_the_task_its_control_ran(self): agent = self.written("run-agent", [("x", 0.0), ("a/b", 0.0)]) diff --git a/app/tests/test_failure_analysis.py b/app/tests/test_failure_analysis.py index 597a9529d..f1f937799 100644 --- a/app/tests/test_failure_analysis.py +++ b/app/tests/test_failure_analysis.py @@ -86,15 +86,13 @@ def test_each_filter_sets_aside_its_own_kind(self): self.assertEqual(a.set_aside(["flawed", "ambiguous"]), {"b/t1", "b/t2"}) def test_a_flag_on_another_version_of_the_task_does_not_count(self): - a = fa.Analysis() - a.set_flag("b/t1", "flawed", "unreachable", by="ann", task_version="v1") - self.assertEqual(a.set_aside(["flawed"], versions={"b/t1": "v1"}), {"b/t1"}) - self.assertEqual(a.set_aside(["flawed"], versions={"b/t1": "v2"}), set()) + flag, t = fa.Analysis().set_flag("b/t1", "flawed", "unreachable", by="ann", task_version="v1"), trial("b/t1") + self.assertTrue(fa.holds(flag, t, {t.trial_name: "v1"})) + self.assertFalse(fa.holds(flag, t, {t.trial_name: "v2"})) def test_a_flag_with_no_version_applies_to_any_version(self): - a = fa.Analysis() - a.set_flag("b/t1", "flawed", "unreachable", by="ann") - self.assertEqual(a.set_aside(["flawed"], versions={"b/t1": "v2"}), {"b/t1"}) + flag, t = fa.Analysis().set_flag("b/t1", "flawed", "unreachable", by="ann"), trial("b/t1") + self.assertTrue(fa.holds(flag, t, {t.trial_name: "v2"})) def test_a_flag_needs_a_known_kind_and_a_category(self): a = fa.Analysis() diff --git a/app/tests/test_flag_tasks_skill.py b/app/tests/test_flag_tasks_skill.py index 695a251e3..9e3935ce9 100644 --- a/app/tests/test_flag_tasks_skill.py +++ b/app/tests/test_flag_tasks_skill.py @@ -67,6 +67,27 @@ def test_spot_keeps_two_units_of_one_name_apart_and_names_each_by_its_unit(self) self.run_script("spot", run, "--out", self.work, "--only", "nobody,always") self.assertEqual({c["task"]: c["group"] for c in json.loads((self.work / "cases.json").read_text())}, {"group/1": "always", "group-1": "nobody"}) + # with no exact identity, a proposal still names a raw unit: never another unit shown under that name + self.merge(a=[vote("group-1", "flawed")], b=[vote("group-1", "flawed")]) + alias = job(self.root / "units", "run-alias", {"u1": (0, "c")}) + f = alias / "u1__1" / "result.json" + f.write_text(json.dumps(dict(json.loads(f.read_text()), task_name="bench/group-1", standard={"unit": "group/1"}))) + for target in ("run-u", "run-alias"): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + flags_cli.main(["import", str(self.root / "units"), target, "--from", str(self.work / "flag-tasks.json")]) + self.assertEqual((set(fa.load(str(run)).flags), fa.load(str(alias)).flags), ({"group-1"}, {})) + + def test_a_proposal_imports_onto_its_exact_task_alone(self): + from types import SimpleNamespace + from tests.test_attempts import TaskIdentity + std = SimpleNamespace(tmp=str(self.root / "std")) + spotted, alias = (TaskIdentity.written(std, name, [(unit, 0.0)]) for name, unit in (("a", "group-1"), ("b", "group/1"))) + self.run_script("spot", spotted, "--out", self.work) + self.merge(a=[vote("group-1", "flawed")], b=[vote("group-1", "flawed")]) + for target in ("a", "b"): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + flags_cli.main(["import", std.tmp, target, "--from", str(self.work / "flag-tasks.json")]) + self.assertEqual((set(fa.load(spotted).flags), fa.load(alias).flags), ({"group-1"}, {})) def test_spot_leaves_out_infrastructure_errors_and_refuses_a_control_run(self): f = self.runs[0] / "t2__1" / "result.json" diff --git a/app/tests/test_flags_cli.py b/app/tests/test_flags_cli.py index a0774db9d..854019cf5 100644 --- a/app/tests/test_flags_cli.py +++ b/app/tests/test_flags_cli.py @@ -84,9 +84,9 @@ def test_copy_arrives_pending_and_keeps_the_version(self): b = fa.load(str(self.b)) self.assertEqual({t: f.status for t, f in b.flags.items()}, {"task-1": "pending", "task-2": "pending"}) self.cli("accept", "run-b", "--all-pending") - b = fa.load(str(self.b)) - versions = fa.task_versions(parse.parse_job(str(self.b))) - self.assertEqual(b.set_aside(["flawed", "ambiguous"], versions), {"task-1"}) # task-2 changed in run-b + run = parse.parse_job(str(self.b)) + view = fa.filtered(run, fa.load(str(self.b)), fa.KINDS, fa.trial_versions(run)) + self.assertEqual((view.set_aside, view.other_version), ({"flawed": 0, "ambiguous": 1}, 1)) # task-2 changed in run-b def test_copy_skips_tasks_the_target_does_not_hold_and_refuses_itself(self): c = job(self.root, "run-c", {"task-1": (1, "c1")}) diff --git a/app/ui_tests/test_failure_analysis_routes.py b/app/ui_tests/test_failure_analysis_routes.py index a6d2aaf57..2e6ba2e9a 100644 --- a/app/ui_tests/test_failure_analysis_routes.py +++ b/app/ui_tests/test_failure_analysis_routes.py @@ -56,6 +56,11 @@ def setUpClass(cls): result = g / "t1__1" / "result.json" body = json.loads(result.read_text()); body["task_checksum"] = "v2"; result.write_text(json.dumps(body)) fa.update(str(g), lambda x: x.set_flag("t1", "flawed", "x", by="ann", task_version="v1")) + h = plain_job(tmp / "jobs", "run-h", {"t1__1": ("t1", 0), "t1__2": ("t1", 1)}) # t1 changed between attempts + for name, version in (("t1__1", "v1"), ("t1__2", "v2")): + result = h / name / "result.json" + result.write_text(json.dumps(dict(json.loads(result.read_text()), task_checksum=version))) + fa.update(str(h), lambda x: x.set_flag("t1", "flawed", "x", by="ann", task_version="v1")) a = fa.Analysis() a.set_flag("t2", "flawed", "unreachable", by="ann") a.set_flag("t3", "ambiguous", "two_readings", by="ann") @@ -137,6 +142,15 @@ def test_the_switches_keep_the_pages_other_query_values(self): def test_with_every_task_left_out_there_is_no_rate(self): self.assertEqual(self.filtered_rate(self.page("/job/run-c?flawed=1")), "\u2014") + def test_a_flag_on_one_task_version_leaves_the_attempts_of_another(self): + from tests.test_comparison import selected + html = self.page("/job/run-h?flawed=1") + self.assertEqual(self.filtered_rate(html), "100%") # the v2 attempt passed + self.assertEqual(re.findall(r'data-trial="([^"]+)" data-task-flag="flawed"', html), ["t1__1"]) + with web.app.test_request_context("/compare?flawed=1"): + got = web.compare._flag_filter(selected(parse.parse_job(str(Path(self.temp.name) / "jobs" / "run-h")))) + self.assertEqual((got["set_aside"], got["differ"]), (frozenset(), ["t1"])) # Compare keeps both, and says so + def test_the_trial_table_tags_flagged_tasks_and_labelled_trials(self): html = self.page("/job/run-a") self.assertRegex(html, r']*data-trial="t2__1" data-task-flag="flawed"') @@ -237,6 +251,14 @@ def test_a_flag_on_one_unit_leaves_the_unit_that_shares_its_name(self): self.assertIn('Filtered score 100%', job) # group/1's pass stays self.assertEqual(len(re.findall(r']*data-task-flag="flawed"', job)), 1) + def test_a_record_two_units_share_is_neither_accepted_nor_removed_from_a_trial(self): + fa.update(str(self.units), lambda a: a.set_flag("group-1", "flawed", "c", by="bot", source="import:old")) + for action in ("accept", "remove_flag"): + r = self.client.post("/failure/run-u/u__2", data={"csrf": "tab-test", "action": action}) + self.addCleanup(r.close) + self.assertEqual(r.status_code, 400, action) + self.assertEqual(fa.load(str(self.units)).flags["group-1"].status, "pending") + def test_the_category_box_suggests_this_benchmarks_categories_first(self): fa.update(str(self.job), lambda a: a.set_flag("t1", "flawed", "flaky test", by="Ann")) html = self.page("/trial/run-t/t2__1") diff --git a/app/web/failure.py b/app/web/failure.py index eedc846dd..7a06cefdd 100644 --- a/app/web/failure.py +++ b/app/web/failure.py @@ -116,7 +116,9 @@ def failure_route(job_id, trial_name): def change(a: fa.Analysis): task = fa.task_of(trial) - key = fa.slots(job, a.flags).get(task, (None,))[0] # where its flag is saved + key, flag = fa.slots(job, a.flags).get(task, (None, None)) # where its flag is saved, and that flag + if action in ("accept", "remove_flag") and flag is None: # a record its task does not hold stays as it is + raise fa.FailureAnalysisError("no flag on this task") if action == "label": if not failed(trial): raise fa.FailureAnalysisError("only a failed trial takes a label") @@ -126,7 +128,7 @@ def change(a: fa.Analysis): a.clear_label(trial.trial_name) elif action == "flag": fa.put_flag(a, job, task, form.get("kind", ""), form.get("category", "").strip(), by=fa.who(), - evidence=form.get("evidence", "").strip()) + evidence=form.get("evidence", "").strip(), task_version=fa.version_of(trial)) elif action == "accept": a.accept(key, by=fa.who()) elif action == "remove_flag": diff --git a/app/web/runs.py b/app/web/runs.py index 1fdbc9910..81fc70472 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -623,33 +623,35 @@ def job(job_id): judgement=judge.job_summary(j) if j.trials else None, control=feasibility.summary_of(j), ended=ended, own=own, deletable=_deletable(job_id, ex), trial_rows=attempts.grouped(j), pass_k=attempts.for_job(j), - filtered=_filtered_of(j, analysis, versions), marks=_marks_of(analysis, versions), + filtered=_filtered_of(j, analysis, versions), marks=_marks_of(j, analysis, versions), again=execute.again_offer(j, ex), running_again=running_again, rerunning=again is not None, waiting=waiting, plan_sets=plan_sets(j, waiting), job_cap=execute.job_cap(j, ex), names=_identity_names(j.identity)) def _analysis_of(j): - """The job's failure analysis and the current version of each flagged task; (None, {}) when its file cannot + """The job's failure analysis and the version of each trial of a flagged task; (None, {}) when its file cannot be read.""" try: analysis = failure_analysis.for_job(j, failure_analysis.load(j.dir)) # its flags by the job's tasks except failure_analysis.FailureAnalysisError: return None, {} - return analysis, failure_analysis.task_versions(j, analysis.flags) # read for flagged tasks only + return analysis, failure_analysis.trial_versions(j, analysis.flags) # read for flagged tasks only -def _marks_of(analysis, versions): - """What the trial table marks: each flagged task (its kind, category, whether it is pending, or names another - version of the task) and each labelled trial.""" +def _marks_of(j, analysis, versions): + """What the trial table marks, by trial: its task's flag (its kind, category, whether it is pending, or is on + another version than this trial's), and its label.""" if analysis is None: - return {"flags": {}, "labels": {}, "task_of": failure_analysis.task_of} + return {"flags": {}, "labels": {}} flags = {} - for task, f in analysis.flags.items(): - other = f.task_version is not None and versions.get(task) != f.task_version - flags[task] = {"kind": f.kind, "category": f.category, "pending": f.status != "accepted", "other": other, - "counts": f.status == "accepted" and not other} - return {"flags": flags, "labels": analysis.labels, "task_of": failure_analysis.task_of} + for t in j.trials: + f = analysis.flags.get(failure_analysis.task_of(t)) + if f is not None: + other = not failure_analysis.holds(f, t, versions) + flags[t.trial_name] = {"kind": f.kind, "category": f.category, "pending": f.status != "accepted", + "other": other, "counts": f.status == "accepted" and not other} + return {"flags": flags, "labels": analysis.labels} def _filtered_of(j, analysis, versions): diff --git a/docs/field-guide.md b/docs/field-guide.md index ebf82dbe6..2da3aef7d 100644 --- a/docs/field-guide.md +++ b/docs/field-guide.md @@ -50,7 +50,7 @@ The job page and Compare show both for any run that tried every task at least tw ## User judge {#user-judge} -A person records why a failed attempt failed (`agent`, `model`, `environment` or `evaluator`) and whether its task is `flawed` or `ambiguous`, in the job's `failure-analysis.json`, from the trial page's User judge tab or [`nullius flags`](cli/flags.md). A flag covers every attempt of its task and counts only for the task version it names. The Decision model judge and the LLM judge answer the same two questions, for comparison only. +A person records why a failed attempt failed (`agent`, `model`, `environment` or `evaluator`) and whether its task is `flawed` or `ambiguous`, in the job's `failure-analysis.json`, from the trial page's User judge tab or [`nullius flags`](cli/flags.md). A flag covers every attempt of its task that ran the task version it names; a copied or imported one, only the benchmark versions of its source. The Decision model judge and the LLM judge answer the same two questions, for comparison only. The job page and Compare offer a switch per kind, off by default. With one on, the filtered score leaves out the trials of flagged tasks, in every Compare column alike; the official scores are unchanged.