diff --git a/.agents/skills/flag-tasks/scripts/flags.py b/.agents/skills/flag-tasks/scripts/flags.py index 8be3c54fb..4c01e2732 100644 --- a/.agents/skills/flag-tasks/scripts/flags.py +++ b/.agents/skills/flag-tasks/scripts/flags.py @@ -55,19 +55,19 @@ def spot(args): if job.agent_name in ("nop", "oracle"): sys.exit(f"{path} is a control run ({job.agent_name})") datasets.add(job.dataset) - checksums = failure_analysis.task_versions(job) for t in job.trials: ref = parse.task_ref(job, t) # one task across the runs by its exact identity, named by its raw unit names.setdefault(ref.name, set()).add(ref.key) - if ref.local in checksums: - versions.setdefault(ref.key, set()).add(checksums[ref.local]) + checksum = failure_analysis.version_of(t) + if checksum: + versions.setdefault(ref.key, set()).add(checksum) if t.reward is None or t.is_infra: left_out += 1 continue 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)) + where.setdefault(ref.key, (ref.name, t.dir, ref.shared and ref.key != ref.name, not ref.shared)) if not seen: sys.exit("no attempt with a reward: nothing to count") if len(datasets) > 1: @@ -81,7 +81,10 @@ 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"), + # the checksum its attempts recorded and a standard task's exact identity, for the import + **({"task_version": min(versions[task])} if versions.get(task) and not where[task][3] else {}), + **({"identity": task} if where[task][2] else {"unresolved": True} if where[task][3] else {})}) write(args.out, "cases.json", cases) write(args.out, "for-readers.json", for_readers(cases)) count = Counter(groups.values()) @@ -193,10 +196,13 @@ def merge(args): third.append(case) agree = [v for v in votes if v["verdict"] == result] if result in KINDS else [] categories = [c for c, _ in Counter(flat(v["category"]) for v in agree).most_common()] - if agree: + if agree and case.get("unresolved"): # a standard task with no exact identity: a name could import onto another unit + notes.append(f"{task}: {result} not proposed, its trials record no exact task (benchmark, version, dataset, unit)") + elif 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 ("identity", "task_version") if case.get(k)})}) 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"))} @@ -215,11 +221,11 @@ def merge(args): lines.append(f" - category: {flat(v['category'])}; evidence: {flat(v['evidence'])}") lines += [f" - {flat(q['file'])}: \"{flat(q['text'])}\"" for q in v["quotes"]] if notes: - lines += ["", "## Votes not counted", ""] + [f"- {n}" for n in notes] + lines += ["", "## Not counted", ""] + [f"- {n}" for n in notes] write(args.out, "flag-tasks.json", {"flags": flags}) write(args.out, "third.json", for_readers(third)) write(args.out, "report.md", "\n".join(lines) + "\n") - print(summary + (f"; {len(notes)} votes not counted, see report.md" if notes else "")) + print(summary + (f"; {len(notes)} votes or flags not counted, see report.md" if notes else "")) def main(argv=None): diff --git a/app/nullius/compare/cli.py b/app/nullius/compare/cli.py index d71f8bf39..b73277d83 100644 --- a/app/nullius/compare/cli.py +++ b/app/nullius/compare/cli.py @@ -10,7 +10,7 @@ resolved and the cohort built by ``nullius.compare.comparison`` so ``--matched`` keeps exactly the trials the page keeps (the intersection of exact dataset/task identifiers, every recorded attempt), and the totals printed per column are the ``Job`` -properties the page's summary table reads over that cohort. ``--exclude`` sets aside the tasks the page's +properties the page's summary table reads over that cohort. ``--exclude`` sets aside the trials the page's Exclude does (``flags.flag_filter``). The task rows below the totals are the page's. A development build (source or unknown runtime) is @@ -141,6 +141,7 @@ def document(view: comparison.Comparison, filters: dict | None = None) -> dict: doc["flags"] = {"exclude": filters["on"], "flagged": filters["flagged"], "set_aside": sorted(key[1] for key in filters["set_aside"]), "set_aside_trials": list(view.set_aside_trials), + "set_aside_tasks": list(view.set_aside_tasks), "differ": filters["differ"], "unreadable": filters["unreadable"]} return doc @@ -172,9 +173,11 @@ def _print(view: comparison.Comparison, filters: dict | None = None) -> None: + (" · repeated attempts " + ", ".join(str(n) for n in view.repeated_trials) if any(view.repeated_trials) else "")) if filters: - aside, differ = doc["flags"]["set_aside"], filters["differ"] - print(f" filtered ({', '.join(filters['on'])}): {len(aside)} task{'' if len(aside) == 1 else 's'} set aside " - "in every column · trials set aside " + ", ".join(str(n) for n in view.set_aside_trials)) + gone, differ = view.set_aside_tasks, filters["differ"] + print(f" filtered ({', '.join(filters['on'])}): " + + (", ".join(str(n) for n in gone) + " tasks set aside, by column" if len(set(gone)) > 1 + else f"{gone[0]} task{'' if gone[0] == 1 else 's'} set aside in every column") + + " · trials set aside " + ", ".join(str(n) for n in view.set_aside_trials)) if differ: print(f" note: flags differ on {len(differ)} task{'' if len(differ) == 1 else 's'}: " + ", ".join(differ)) if filters["unreadable"]: @@ -241,8 +244,8 @@ def main(argv=None) -> int: help="the matched cohort: only the tasks every run attempted, by exact " "dataset and task id (the page's cohort=matched); whole runs otherwise") ap.add_argument("--exclude", action="append", default=[], choices=failure_analysis.KINDS, metavar="KIND", - help="set aside, in every column, the tasks a person flagged KIND (flawed or ambiguous) in any " - "of these runs, as the page's Exclude does; repeatable") + help="set aside, in every column, the trials of the tasks a person flagged KIND (flawed or " + "ambiguous) in any of these runs that the flag covers, as the page's Exclude does; repeatable") ap.add_argument("--json", action="store_true", help="one JSON document: the columns with their totals and the task rows") args = ap.parse_args(argv) @@ -270,7 +273,7 @@ def main(argv=None) -> int: {"": jobs}, {"": args.root}) filters = flags.flag_filter(selected, args.exclude) if args.exclude else None view = comparison.build(selected, "matched" if args.matched else "whole", - filters["set_aside"] if filters else frozenset()) + filters["trials"] if filters else ()) if args.json: _emit(document(view, filters)) else: diff --git a/app/nullius/compare/comparison.py b/app/nullius/compare/comparison.py index 5d72d5f71..932d95815 100644 --- a/app/nullius/compare/comparison.py +++ b/app/nullius/compare/comparison.py @@ -156,6 +156,7 @@ class Comparison: datasets_known: bool pass_k: tuple[dict | None, ...] = () set_aside_trials: tuple[int, ...] = () # trials of flagged tasks left out of each column + set_aside_tasks: tuple[int, ...] = () # tasks of each column's cohort whose every trial the flags left out @property def references(self) -> list[str]: @@ -169,13 +170,14 @@ 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, also + when two workspaces hold its job.""" 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, True) if ref.shared else (ref.key, False, selection.value)) -def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: frozenset = frozenset()) -> Comparison: +def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: Sequence[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. @@ -186,8 +188,10 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: fro 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*: ``task_key`` keys whose trials leave every column, after - the cohort: the flagged tasks of the page's filters, the same for all runs. + *set_aside*: per column, the names of the trials that leave it: those + the flags of the page's filters cover. A task is shared while a trial of + it is left in every column; a column sets a task aside when the flags take + its cohort's last trial of it. """ if cohort not in {"whole", "matched"}: raise ValueError("Choose whole runs or matched tasks as the comparison cohort.") @@ -197,24 +201,32 @@ def build(selected: Sequence[SelectedRun], cohort: str = "whole", set_aside: fro key = task_key # an unresolved standard trial is in no common set, also of one run: its key is its own job's - sets = [{k for k in (key(selection, trial) for trial in selection.job.trials) if k[2] is None or k[2][1]} - for selection in selected] - common = set.intersection(*sets) if sets else set() + def shared(left): + sets = [{k for k in (key(selection, trial) for trial in selection.job.trials if left(column, trial)) + if k[2] is None or k[2][1]} for column, selection in enumerate(selected)] + return set.intersection(*sets) if sets else set() + + stays = lambda column, trial: not set_aside or trial.trial_name not in set_aside[column] + before, common = shared(lambda column, trial: True), shared(stays) # each task's attempts, one list per run, the tasks in the order they appear - jobs, excluded, repeated, aside, by_task = [], [], [], [], {} + jobs, excluded, repeated, aside, gone, by_task, kept = [], [], [], [], [], {}, [] for column, selection in enumerate(selected): original = selection.job 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)) + if cohort == "whole" or key(selection, trial) in before] + left = [trial for trial in cohort_trials if stays(column, trial)] + aside.append(len(cohort_trials) - len(left)) + gone.append(len({key(selection, trial) for trial in cohort_trials} - {key(selection, trial) for trial in left})) + # a task whose trials another column's flag set aside is shared no more: its trial stays in whole runs only + trials = [trial for trial in left if cohort == "whole" or key(selection, trial) in common] # 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" or set_aside else {})) + **({"started_at": None, "finished_at": None} if cohort == "matched" or any(set_aside) else {})) jobs.append(view) - excluded.append(len(original.trials) - len(cohort_trials)) - repeated.append(len(trials) - len({key(selection, trial) for trial in trials})) + excluded.append(len(original.trials) - len(trials) - aside[-1]) + kept.append({key(selection, trial) for trial in trials}) + repeated.append(len(trials) - len(kept[-1])) for trial in trials: by_task.setdefault(key(selection, trial), [[] for _ in selected])[column].append(trial) @@ -230,8 +242,9 @@ def task_row(task_key, columns): # pass@k from the rows' own tasks, so the summary and the table count alike pass_k = tuple(None if scored_only[column] else task_attempts.for_tasks(row.tried[column].trials for row in rows if row.tried[column]) for column in range(len(selected))) - return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common - set_aside), - tuple(excluded), tuple(repeated), datasets_match, known, pass_k, tuple(aside)) + return Comparison(selected, cohort, tuple(jobs), tuple(rows), len(common.intersection(*kept)), + tuple(excluded), tuple(repeated), datasets_match, known, pass_k, tuple(aside), + tuple(gone)) diff --git a/app/nullius/compare/flags.py b/app/nullius/compare/flags.py index acd5ed579..dc5b9d115 100644 --- a/app/nullius/compare/flags.py +++ b/app/nullius/compare/flags.py @@ -7,13 +7,15 @@ 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. + """The flag filters of a comparison: the 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`). In each column such + a flag sets aside the trials it covers (`failure_analysis.applies`): `trials`, their names per column. Apart + from that, a task is set aside only when every column holding it ran the same versions; otherwise it stays, and is + named in `differ` with the tasks the runs flag differently: another kind, or other trials of the columns + (`covered`). `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: each trial's key, each covered key's flag, its keys for selection in selected: job = selection.job try: @@ -22,26 +24,40 @@ 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 + keys, flags = {}, {} # each trial's comparison key, and those a flag covers: one per identity 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()))) - 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 + keys[t.trial_name] = comparison.task_key(selection, t) + flag = analysis.flags.get(failure_analysis.task_of(t)) + if flag is not None and flag.status == "accepted" and failure_analysis.applies(flag, t): + flags[keys[t.trial_name]] = flag + runs.append((selection, keys, flags, set(keys.values()))) + flagged_keys = set().union(*(flags for _, _, flags, _ in runs)) + # the versions each column's trials of a flagged task ran: columns differ, attempts of one column do not 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, keys, _, _ in runs: + mine = {} + for t in selection.job.trials: + version = failure_analysis.version_of(t) if keys[t.trial_name] in flagged_keys else None + if version: + mine.setdefault(keys[t.trial_name], set()).add(version) + for key, versions in mine.items(): + ran.setdefault(key, set()).add(frozenset(versions)) holders = {key: [r for r in runs if key in r[3]] for key in flagged_keys} + kind = lambda flags, key: flags[key].kind if key in flags else None + + def covered(flags, key): + """What a column's flag on the task does: its kind, and the trials it covers in the columns holding the task.""" + return key in flags and (flags[key].kind, frozenset( + (selection.value, t.trial_name) for selection, keys, _, _ in holders[key] for t in selection.job.trials + if keys[t.trial_name] == key and failure_analysis.applies(flags[key], t))) 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) - set_aside = frozenset(key for key in flagged_keys if len(ran.get(key, set())) <= 1 - and any(kinds.get(key) in on for _, _, kinds, _ in holders[key])) - return {"on": on, "flagged": {k: sum(1 for key in flagged_keys if any(kinds.get(key) == k for _, _, kinds, _ in runs)) + if len(ran.get(key, ())) > 1 or len({covered(flags, key) for _, _, flags, _ in holders[key]}) > 1) + set_aside = frozenset(key for key in flagged_keys if len(ran.get(key, ())) <= 1 + and any(kind(flags, key) in on for _, _, flags, _ in holders[key])) + chosen = {key: [flags[key] for _, _, flags, _ in runs if kind(flags, key) in on] for key in set_aside} + trials = tuple(frozenset(t.trial_name for t in selection.job.trials + if any(failure_analysis.applies(flag, t) for flag in chosen.get(keys[t.trial_name], ()))) + for selection, keys, _, _ in runs) + return {"on": on, "flagged": {k: sum(1 for key in flagged_keys if any(kind(flags, key) == k for _, _, flags, _ in runs)) for k in failure_analysis.KINDS}, - "set_aside": set_aside, "differ": differ, "unreadable": unreadable} + "set_aside": set_aside, "trials": trials, "differ": differ, "unreadable": unreadable} diff --git a/app/nullius/runs/failure_analysis.py b/app/nullius/runs/failure_analysis.py index 509a3e001..922f9559f 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; when the task changes, that flag no longer applies: it covers + the trials that recorded that version (``applies``). A flag with no version applies to any version. - 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``). @@ -104,9 +104,11 @@ 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, + stale: Optional[bool] = 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. + *stale*, from a caller that knows the job: whether the accepted flag covers no trial there (``_gone``). *unit*: *task* is a raw unit.""" if not task: raise FailureAnalysisError("a flag needs a task") @@ -117,8 +119,9 @@ def set_flag(self, task: str, kind: str, category: str, *, by: str, evidence: st 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 stale is None: + 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() @@ -206,13 +209,22 @@ def named(job) -> Dict[str, Any]: **{task[0]: task for tasks in shown.values() for task in tasks if not isinstance(task, str)}} -def put_flag(analysis: Analysis, job, task, kind: str, category: str, **how) -> Optional[Flag]: - """``Analysis.set_flag`` on a task of the job (``task_of``), saved where ``slots`` says, its version included.""" +def put_flag(analysis: Analysis, job, task, kind: str, category: str, *, trial=None, **how) -> Optional[Flag]: + """``Analysis.set_flag`` on a task of the job (``task_of``), saved where ``slots`` says, its version included: + the one *trial* recorded when the flag is set from a trial. From a trial that recorded none while another of + its task did, the flag would cover that one too (``applies``): refused.""" slot = slots(job, analysis.flags).get(task) if slot is None: raise FailureAnalysisError(f"{name_of(task)!r} names more than one task of {job.job_id}, and this one records no unit") - how.setdefault("task_version", task_versions(job, [task]).get(task)) - return analysis.set_flag(slot[0], kind, category, unit=_marked(_shown(job), task, slot[0]), **how) + if trial is None: + how.setdefault("task_version", task_versions(job, [task]).get(task)) + else: + how["task_version"] = version_of(trial) + if how["task_version"] is None and task_versions(job, [task]): + raise FailureAnalysisError(f"{trial.trial_name} records no task version and another trial of its task does: " + "a flag set here would cover that version too") + return analysis.set_flag(slot[0], kind, category, unit=_marked(_shown(job), task, slot[0]), + stale=_gone(job, task, slot[1]), **how) def for_job(job, analysis: Analysis) -> Analysis: @@ -229,6 +241,28 @@ def across(job) -> Dict[Any, Any]: return {ref.key: ref.local for ref in refs if ref.shared} +def identities(job) -> Dict[Any, Dict[Any, list]]: + """Each task of the job (``task_of``) to its trials by their key (``parse.task_ref``): several keys where a + merged job ran one unit at several versions, which share the one flag.""" + out: Dict[Any, Dict[Any, list]] = {} + for t in job.trials: + out.setdefault(task_of(t), {}).setdefault(parse.task_ref(job, t).key, []).append(t) + return out + + +def _within(ran: Dict[Any, list], version: Optional[str], keys) -> bool: + """Whether a flag naming *version*, on a task whose trials are *ran* (``identities``), covers no trial outside + *keys*: what a flag from elsewhere must hold to, so it never covers more than its source.""" + return all(key in keys or (version is not None and not any(version_of(t) == version for t in trials)) + for key, trials in ran.items()) + + +def _gone(job, task, flag: Optional[Flag]) -> bool: + """Whether the task's flag covers no trial of the job any more (``applies``): only then does a flag from + elsewhere replace one a person accepted.""" + return flag is not None and not any(applies(flag, t) for t in job.trials if task_of(t) == task) + + @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. @@ -329,7 +363,8 @@ 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.""" + *versions* (`flag_versions`), a flag on another version of its task does not count, nor on a trial that + recorded another (``applies``).""" analysis = for_job(job, analysis) tasks = {task_of(t) for t in job.trials} on = tuple(k for k in KINDS if k in set(kinds)) @@ -339,83 +374,138 @@ def filtered(job, analysis: Analysis, kinds: Iterable[str], versions: Optional[D 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 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 (versions is None or applies(analysis.flags[task_of(t)], t))]) 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 version of its task a trial ran: 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 applies(flag: Flag, trial) -> bool: + """Whether a flag on the trial's task covers the trial: it names no version, or the one the trial recorded. + The one check of the job score and table, the trial's tab and its accept and remove, Compare, and of what a + copy takes from its source.""" + return flag.task_version is None or version_of(trial) == flag.task_version + + 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``: the first its trials record (``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 copy_flags(source: Analysis, target: Analysis, source_job, target_job, *, by: str) -> Tuple[list, list, list]: +def flag_versions(job, flags: Dict[Any, Flag]) -> Dict[Any, str]: + """``task_versions`` of the flagged tasks (``for_job``), as each flag meets its task: where the trials of one + recorded several versions, the one its flag names when a trial recorded it.""" + out = task_versions(job, flags) + for t in job.trials: + flag = flags.get(task_of(t)) + if flag is not None and flag.task_version not in (None, out.get(task_of(t))) and version_of(t) == flag.task_version: + out[task_of(t)] = flag.task_version + return out + + +def copy_flags(source: Analysis, target: Analysis, source_job, target_job, *, by: str) -> Tuple[list, 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.""" + of that name, nor to a task whose trials it would cover beyond that key (``_within``). Where its task ran at + one key or several, the flag's are those of the trials it covers (``applies``): a checksum alone names no + benchmark version, and a flag that covers no trial of its job names nothing. A flag on no single task of a + standard source job is not copied. Returns the saved names copied, those + the target job does not hold so, those skipped because *target* already holds an accepted flag, and those that + would also cover another version there.""" 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) + own, reach = identities(source_job), across(source_job) + standard = source_job.standard or any(not isinstance(key, str) for keys in own.values() for key in keys) there, where, shown = across(target_job), slots(target_job, target.flags), _shown(target_job) - copied, unknown, skipped = [], [], [] + ran, mine = identities(target_job), _shown(source_job) + copied, unknown, skipped, wider = [], [], [], [] 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} + # a flag on no task of its job is a name, as it was saved: a unit's names nothing elsewhere, nor does a + # name its job's units share, or a standard job's, also one only its trials tell (``parse.task_ref``) + loose = flag.unit or saved in mine or standard + keys = own[held[saved]] if saved in held else {} + wanted = ([key for key, trials in keys.items() if key in reach and any(applies(flag, t) for t in trials)] + if saved in held else () if loose else (saved,)) + found = {there[key] for key in wanted if there.get(key) in where} + tasks = {task for task in found if _within(ran[task], flag.task_version, wanted)} if not tasks: - unknown.append(saved) + (wider if found else 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]), + stale=_gone(target_job, task, where[task][1])) (copied if got is not None else skipped).append(saved) - return copied, unknown, skipped + return copied, unknown, skipped, wider -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 import_flags(target: Analysis, job, records: Iterable[dict], *, source: str, by: str, prefix: str = "") -> Tuple[list, 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) + *prefix* plus the record's ``task``; a name the job does not hold is not guessed. A record with an ``identity`` + (``parse.task_ref``'s key: a name, or a standard task's benchmark, version, dataset and unit) goes to the task + that ran exactly it (``across``), never by its name, and only where it covers no other trial of the task + (``_within``). Its version is its ``task_version``, the checksum of the trial it was made from, which a trial + of that task here must have recorded, under a name too; without one, the only version those trials recorded, + or under a name the first. Returns the names + added, those not found, those skipped because they hold an accepted flag, and those that would also cover + another version.""" + known, there, where, shown, ran = named(job), across(job), slots(job, target.flags), _shown(job), identities(job) asked = [] 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}) - added, unknown, skipped = [], [], [] - for rec, name, task in asked: - if task not in where: - unknown.append(name_of(name)) + key = rec.get("identity") + key = tuple(key) if isinstance(key, list) else key + if not (key is None or isinstance(key, str) or isinstance(key, tuple) and all(isinstance(part, str) for part in key)): + raise FailureAnalysisError("a flag's identity is a name, or a list of benchmark, version, dataset and unit") + if not (rec.get("task_version") is None or isinstance(rec["task_version"], str) and rec["task_version"]): + raise FailureAnalysisError("a flag's task_version is a checksum, or left out") + name = str(rec["task"]) if key is not None else prefix + str(rec["task"]) + asked.append((rec, name, there.get(key) if key is not None else known.get(name), key)) + versions = task_versions(job, {task for _, _, task, key in asked if key is None and task in where}) + added, unknown, skipped, wider = [], [], [], [] + for rec, name, task, key in asked: + version = rec.get("task_version") or versions.get(task) + recorded = {version_of(t) for k, trials in ran.get(task, {}).items() if key in (None, k) for t in trials} - {None} + if key is not None: + version = rec.get("task_version") or (next(iter(recorded)) if len(recorded) == 1 else None) + if task not in where or (rec.get("task_version") and version not in recorded): + unknown.append(name) + continue + if key is not None and (len(recorded) > 1 and version is None or not _within(ran[task], version, (key,))): + wider.append(name) continue 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])) - (added if got is not None else skipped).append(name_of(name)) - return added, unknown, skipped + task_version=version, unit=_marked(shown, task, where[task][0]), + stale=_gone(job, task, where[task][1])) + (added if got is not None else skipped).append(name) + return added, unknown, skipped, wider def categories(analyses: Iterable[Analysis]) -> list: diff --git a/app/nullius/runs/flags_cli.py b/app/nullius/runs/flags_cli.py index a25e1d037..b7932682d 100644 --- a/app/nullius/runs/flags_cli.py +++ b/app/nullius/runs/flags_cli.py @@ -69,7 +69,7 @@ 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 = fa.flag_versions(job, fa.for_job(job, a).flags) 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 @@ -83,10 +83,12 @@ def _list(job, args) -> int: return EXIT_OK -def _report(verb, done, unknown=(), skipped=()): +def _report(verb, done, unknown=(), skipped=(), wider=()): print(f"{verb} {len(done)}") for name in unknown: print(f"not in the job: {name}", file=sys.stderr) + for name in wider: + print(f"would also cover another version: {name}", file=sys.stderr) for name in skipped: print(f"kept, already accepted: {name}", file=sys.stderr) @@ -116,6 +118,8 @@ def run(args) -> int: _task(job, args.task) return EXIT_NOT_FOUND key, flag = fa.slots(job, saved).get(task, (args.task, None)) # where the task's flag is saved, and the flag + if args.action == "remove" and flag is None and args.task in saved: # no task's own: removed as it was saved + task, key = None, args.task args.task = args.task if task is None else fa.name_of(task) if args.action == "set": @@ -138,9 +142,11 @@ def run(args) -> int: return EXIT_NOT_FOUND def accept(a): - # a pending flag under a name two tasks share is on neither: it waits - unsure = {t.task_base for t in job.trials} - {k for k, held in fa.slots(job, a.flags).values() if held} - names = sorted(t for t, f in a.flags.items() if f.status == "pending" and t not in unsure) if args.all_pending else [key] + # a pending flag under a name two tasks share is on neither, a unit's whose trials are gone on none: it waits + held = {k for k, flag in fa.slots(job, a.flags).values() if flag} + unsure = {t.task_base for t in job.trials} - held + names = sorted(t for t, f in a.flags.items() if f.status == "pending" and t not in unsure + and (not f.unit or t in held)) if args.all_pending else [key] for name in names: a.accept(name, by=by) return names @@ -162,8 +168,7 @@ def accept(a): 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) - copied, unknown, skipped = fa.update(target.dir, lambda a: fa.copy_flags(source, a, job, target, by=by)) - _report(f"copied to {target.job_id}, pending:", copied, unknown, skipped) + _report(f"copied to {target.job_id}, pending:", *fa.update(target.dir, lambda a: fa.copy_flags(source, a, job, target, by=by))) elif args.action == "import": try: with open(args.from_file, encoding="utf-8") as fh: @@ -179,26 +184,34 @@ def accept(a): print(f"{args.from_file} holds no list of flags", file=sys.stderr) return EXIT_INVALID source = "import:" + os.path.basename(args.from_file) - added, unknown, skipped = fa.update(job.dir, lambda a: fa.import_flags( - a, job, records, source=source, by=args.by or by, prefix=args.prefix)) - _report("imported, pending:", added, unknown, skipped) + _report("imported, pending:", *fa.update(job.dir, lambda a: fa.import_flags( + a, job, records, source=source, by=args.by or by, prefix=args.prefix))) 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(map(fa.name_of, other)): - print(f"control ran another version: {t}", 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] - 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()})) - _report("imported, pending:", added, [r.task_base for r in rows if r.key not in mine] + unknown, skipped) + controls = {j.job_id: {t.trial_name: t for t in j.trials} + for c in report.executed for j in jobs if j.job_id == c.job_id and j is not job} + mine, ran = fa.across(job), fa.identities(job) # a row is this job's task when the job ran that exact task + other = set() # rows a control's own trial ran at another version than this job's + checksum = {} # each row's version: the one its controls' own trials recorded + for r in report.rows: + here = {fa.version_of(t) for t in ran[mine[r.key]][r.key]} - {None} if r.key in mine else set() + sides = (controls.get(s.job_id, {}).get(s.trial_name) for s in (r.nop, r.oracle)) + sides = {fa.version_of(t) for t in sides if t is not None} - {None} + if len(sides) > 1 or here and sides - here: + other.add(r.key) + print(("controls ran different versions: " if len(sides) > 1 else "control ran another version: ") + r.task_base, + file=sys.stderr) + elif sides: # known: the import refuses it where no trial here recorded it + checksum[r.key] = sides.pop() + rows = [r for r in report.rows if r.verdict in FEASIBILITY and r.key not in other] + records = [{"task": r.task_base, "identity": r.key, "kind": "flawed", "category": FEASIBILITY[r.verdict], + "evidence": r.why, "task_version": checksum.get(r.key)} for r in rows if r.key in mine] + added, unknown, skipped, wider = fa.update(job.dir, lambda a: fa.import_flags( + 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, wider) return EXIT_OK diff --git a/app/templates/compare/compare.html b/app/templates/compare/compare.html index becf10711..c253befca 100644 --- a/app/templates/compare/compare.html +++ b/app/templates/compare/compare.html @@ -119,7 +119,7 @@ {% endif %}{% endfor %} {% if ff.flagged.values()|sum %}{% endif %} - {% if ff.on %}Filtered: {{ ff.set_aside|length }} task{{ '' if ff.set_aside|length == 1 else 's' }} set aside in every column{% endif %} + {% set gone = comparison.set_aside_tasks %}{% if ff.on %}Filtered: {% if gone|unique|list|length > 1 %}{{ gone|join(', ') }} tasks set aside, by column{% else %}{{ gone[0] }} task{{ '' if gone[0] == 1 else 's' }} set aside in every column{% endif %}{% 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 %} diff --git a/app/templates/runs/job.html b/app/templates/runs/job.html index 406b38f6f..62042071a 100644 --- a/app/templates/runs/job.html +++ b/app/templates/runs/job.html @@ -491,11 +491,11 @@

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 %} - {% if show_fa %}{{ task_flag(t) }}{% endif %} + {% if show_fa %}{% if marks.covered(group.trials) in (0, group.n) %}{{ task_flag(t) }}{% endif %}{% endif %} {% if show_tries %}{% endif %} {% if show_cause %}{% endif %} {% if show_flags %}{% endif %} @@ -517,7 +517,7 @@

Trials

{%- set name = 'attempt ' ~ k if group else task_labels[t.trial_name] %} {% if picking %}{% endif -%} @@ -536,7 +536,7 @@

Trials

{{ t.exception_type }}{{ t.exception_message }} {%- else %}{{ t.exception_type }}{% endif %}{% endif %} - {% if show_fa %}{% if not group %}{{ task_flag(t) }}{% endif %}{{ trial_label(t) }}{% endif %} + {% if show_fa %}{% if not group or marks.covered(group.trials) != group.n and marks.covered([t]) %}{{ task_flag(t) }}{% endif %}{{ trial_label(t) }}{% endif %} {% if show_tries %}{% if t.n_retries %}{{ t.n_retries }}{% if job.retries %}/{{ job.retries }}{% endif %}{% else %}0{{ '/' ~ job.retries if job.retries }}{% endif %}{% endif %} {% if show_cause %} {%- if t.outcome == 'resolved' %}not asked diff --git a/app/templates/traces/_failure.html b/app/templates/traces/_failure.html index de210fe3a..d850f445a 100644 --- a/app/templates/traces/_failure.html +++ b/app/templates/traces/_failure.html @@ -25,8 +25,9 @@

{% if fp.attempt %}Why attempt {{ fp.attempt[0] }} failed{% else %}Why it fa {% 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 every = fp.attempt and fp.attempt[2] == fp.attempt[1] %} +

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

+

One flag per task in this run{% if every %}: it shows on every attempt{% elif fp.attempt %}: it shows on the attempts that ran this task version{% endif %}.

{% set fl = fp.flag %} {% if fp.can_write %}
diff --git a/app/tests/field_contract.json b/app/tests/field_contract.json index 0f0483571..e34b1e01f 100644 --- a/app/tests/field_contract.json +++ b/app/tests/field_contract.json @@ -331,6 +331,7 @@ "references", "repeated_trials", "selected", + "set_aside_tasks", "set_aside_trials", "shared_tasks", "tasks" diff --git a/app/tests/test_attempts.py b/app/tests/test_attempts.py index 4b4a71a5c..af1e11359 100644 --- a/app/tests/test_attempts.py +++ b/app/tests/test_attempts.py @@ -5,6 +5,7 @@ import io import json import os +import shutil import tempfile import unittest import unittest.mock @@ -207,7 +208,7 @@ def test_compare_matches_exact_tasks_and_leaves_an_unresolved_trial_in_its_colum self.assertEqual((alone.shared_tasks, alone.excluded_trials, alone.tasks), (0, (2, 1), ())) rows = comparison.build(selected(bare, bare.__class__(**{**vars(bare), "job_id": "twin"}))).tasks self.assertEqual([r.shared for r in rows], [False, False]) # each in its own column - flagged = comparison.build(selected(left, right), set_aside=frozenset({comparison.task_key(selected(right)[0], right.trials[0])})) + flagged = comparison.build(selected(left, right), set_aside=(frozenset(), frozenset({right.trials[0].trial_name}))) self.assertEqual((flagged.set_aside_trials, len(flagged.jobs[0].trials)), ((0, 1), 2)) def test_feasibility_never_pairs_two_units_under_one_name(self): @@ -273,7 +274,14 @@ def test_one_run_shares_no_unresolved_task_with_itself(self): matched = comparison.build(selected(forced), "matched") 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 + twice = tuple(comparison.SelectedRun(comparison.RunRef(ws, "forced"), forced, ws) for ws in ("one", "two")) + whole, matched = (comparison.build(twice, cohort) for cohort in ("whole", "matched")) # through two workspaces + self.assertEqual(([r.shared for r in whole.tasks], matched.shared_tasks, matched.tasks), ([False, False], 0, ())) self.assertEqual(comparison.build(selected(job([trial("a")])), "matched").shared_tasks, 1) # Harbor: as before + # a resolved row keeps the key its links were made from + run = parse.parse_job(self.written("plain", [("0", 1.0)])) + row = comparison.build(selected(run)).tasks[0] + self.assertEqual((row.key, row.selector), (("set", "0", (("b", "1", "set", "0"), True)), "78bb4922830cabd5")) 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"))) @@ -358,6 +366,118 @@ def test_a_copied_flag_goes_to_the_same_unit_never_to_one_of_its_name(self): 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, {}) + def mixed(self, name, checksums=("A", "B")): + """A job that ran unit x at versions 1 and 2, as a merge leaves it, each trial with its task checksum.""" + where = self.written(name, [("x", 0.0), ("x", 0.0)]) + for i, checksum in enumerate(checksums): + self.edit(where, f"{name}-u{i}/result.json", + lambda res: (res["standard"].update(benchmark_version=str(i + 1)), res.update(task_checksum=checksum))) + return where + + def checked(self, name, checksum, units=(("x", 0.0),), **kw): + """A written job whose first trial recorded *checksum*.""" + return self.edit(self.written(name, list(units), **kw), f"{name}-u0/result.json", lambda res: res.update(task_checksum=checksum)) + + def test_a_flag_for_one_version_never_reaches_the_other_in_a_job_that_ran_both(self): + self.checked("source", "A") + self.assertEqual(self.cli("set", "source", "x", "--kind", "flawed", "--category", "c")[0], 0) + target = self.mixed("run-agent") + self.checked("run-nop", "A", [("x", 1.0)], control="nop") + run = parse.parse_job(target) + self.assertEqual(len({parse.task_ref(run, t).key for t in run.trials}), 2) # one unit, one flag, two tasks + for bring in (("copy", "source", "run-agent"), ("feasibility", "run-agent")): + self.assertEqual(self.cli(*bring)[1][-11:], "pending: 1\n", bring) + self.assertEqual(self.cli("accept", "run-agent", "x")[0], 0) + flags = fa.for_job(run, fa.load(target)).flags + view = fa.filtered(run, fa.load(target), ["flawed"], fa.flag_versions(run, flags)) + self.assertEqual((flags[("x",)].task_version, view.ran, view.set_aside), ("A", 1, {"flawed": 1}), bring) + self.assertEqual(self.cli("remove", "run-agent", "x")[0], 0) + # the later trial's version: still its trial alone, whichever came first + fa.update(target, lambda a: a.set_flag("x", "flawed", "c", by="ann", task_version="B")) + flags = fa.for_job(run, fa.load(target)).flags + view = fa.filtered(run, fa.load(target), ["flawed"], fa.flag_versions(run, flags)) + self.assertEqual((view.ran, view.other_version, self.cli("list", "run-agent")[1].count("another version")), (1, 0, 0)) + # no checksum tells the two apart: the flag would cover both, so it is not brought + bare = self.mixed("bare-agent", (None, None)) + self.written("bare-nop", [("x", 1.0)], control="nop") + self.written("loose", [("x", 0.0)]) + self.assertEqual(self.cli("set", "loose", "x", "--kind", "flawed", "--category", "c")[0], 0) + for bring in (("copy", "loose", "bare-agent"), ("feasibility", "bare-agent")): + self.assertEqual(self.cli(*bring)[1:], (bring[0] == "copy" and "copied to bare-agent, pending: 0\n" or "imported, pending: 0\n", + "would also cover another version: x\n"), bring) + self.assertEqual(fa.load(bare).flags, {}) + + def test_a_flag_brought_in_is_on_the_version_its_evidence_ran(self): + agent = self.written("run-agent", [("x", 0.0), ("x", 0.0)]) # two attempts at one exact task + for i, checksum in enumerate("AB"): + self.edit(agent, f"run-agent-u{i}/result.json", lambda res: res.update(task_checksum=checksum)) + self.checked("run-nop", "B", [("x", 1.0)], control="nop") # passed with no work, on B + self.assertEqual(self.cli("feasibility", "run-agent")[1:], ("imported, pending: 1\n", "")) + self.assertEqual(fa.load(agent).flags["x"].task_version, "B") + self.assertEqual(self.cli("remove", "run-agent", "x")[0], 0) + self.checked("run-oracle", "A", [("x", 0.0)], control="oracle") # the two controls: two versions + self.assertEqual(self.cli("feasibility", "run-agent")[1:], ("imported, pending: 0\n", "controls ran different versions: x\n")) + # a record made from a trial at A never becomes a flag on B, nor one on both where it names none + record = {"task": "x", "identity": ["b", "1", "set", "x"], "kind": "flawed", "category": "c"} + run, later = parse.parse_job(agent), parse.parse_job(self.checked("later", "B")) + took = lambda job, **more: fa.import_flags(fa.Analysis(), job, [dict(record, **more)], source="import:f", by="ann") + self.assertEqual((took(later, task_version="A"), took(run), took(run, task_version="A")[0]), + (([], ["x"], [], []), ([], [], [], ["x"]), ["x"])) + + def test_a_copied_flag_reaches_only_the_versions_it_covered_in_its_own_job(self): + source = self.mixed("source") # v1 at A, v2 at B + fa.update(source, lambda a: a.set_flag("x", "flawed", "c", by="ann", task_version="A")) + target = self.checked("target", "A", version="2") # v2, with v1's checksum + self.assertEqual(self.cli("copy", "source", "target")[1:], ("copied to target, pending: 0\n", "not in the job: x\n")) + self.assertEqual(fa.load(target).flags, {}) + # a flag that covers no trial of its job any more, its records refreshed to v2 at B: it names nothing + stale = self.checked("stale", "B", version="2") + fa.update(stale, lambda a: a.set_flag("x", "flawed", "c", by="ann", task_version="A")) + self.assertEqual(self.cli("copy", "stale", "target")[1:], ("copied to target, pending: 0\n", "not in the job: x\n")) + self.assertEqual(fa.load(target).flags, {}) + + def test_accept_all_pending_leaves_a_unit_flag_whose_trials_are_gone(self): + where = self.written("job", [("a", 0.0)]) + fa.update(where, lambda a: a.set_flag("gone/1", "flawed", "c", by="bot", source="import:f", unit=True)) + self.assertEqual(self.cli("accept", "job", "--all-pending")[1], "accepted 0\n") + self.assertEqual(fa.load(where).flags["gone/1"].status, "pending") + + def test_a_control_on_another_version_leaves_a_proposal_its_own_control_made(self): + agent = self.checked("run-agent", "A") + self.checked("run-nop", "A", [("x", 1.0)], control="nop") # passed with no work, on v1 + self.checked("run-oracle", "B", [("x", 1.0)], version="2", control="oracle") + self.assertEqual(self.cli("feasibility", "run-agent")[1:], ("imported, pending: 1\n", "")) + self.assertEqual({k: f.task_version for k, f in fa.load(agent).flags.items()}, {"x": "A"}) + + def test_a_controls_version_is_kept_for_a_job_that_recorded_none(self): + agent = self.written("run-agent", [("x", 0.0)]) # no checksum + self.checked("run-nop", "A", [("x", 1.0)], control="nop") # passed with no work, on A + self.assertEqual(self.cli("feasibility", "run-agent")[1:], ("imported, pending: 0\n", "not in the job: x\n")) + self.checked("run-oracle", "B", [("x", 0.0)], control="oracle") # the two controls: two versions + self.assertEqual(self.cli("feasibility", "run-agent")[1:], ("imported, pending: 0\n", "controls ran different versions: x\n")) + self.assertEqual(fa.load(agent).flags, {}) + + def test_a_flag_on_no_single_unit_of_a_standard_job_is_not_copied(self): + source = self.written("source", [("group/1", 0.0), ("group-1", 0.0)]) + fa.update(source, lambda a: a.set_flag("group-1", "flawed", "c", by="ann")) # saved before units were told apart + harbor, target = job([trial("group-1")], dataset="b/set"), fa.Analysis() + self.assertEqual(fa.copy_flags(fa.load(source), target, parse.parse_job(source), harbor, by="ann"), ([], ["group-1"], [], [])) + self.assertEqual(target.flags, {}) + # a flag whose trial is gone, in a job only its trials tell is standard + orphan = self.written("orphan", [("x", 0.0), ("y", 0.0)]) + fa.update(orphan, lambda a: a.set_flag("x", "flawed", "c", by="ann")) + shutil.rmtree(os.path.join(orphan, "orphan-u0")) + self.edit(orphan, "config.json", lambda cfg: cfg.pop("standard")) + harbor = job([trial("x")], dataset="b/set") + self.assertEqual(fa.copy_flags(fa.load(orphan), target, parse.parse_job(orphan), harbor, by="ann"), ([], ["x"], [], [])) + + def test_a_record_under_a_name_two_units_share_is_removed_by_that_name(self): + where = self.written("job", [("group/1", 1.0), ("group-1", 0.0)]) + fa.update(where, lambda a: a.set_flag("group-1", "flawed", "c", by="ann")) # also the name of a unit + self.assertEqual(self.cli("remove", "job", "group/1")[0], flags_cli.EXIT_NOT_FOUND) + self.assertEqual(self.cli("remove", "job", "group-1")[:2], (0, "removed group-1\n")) + self.assertEqual(fa.load(where).flags, {}) + def test_feasibility_flags_only_the_task_its_control_ran(self): agent = self.written("run-agent", [("x", 0.0), ("a/b", 0.0)]) self.written("run-nop", [("x", 1.0), ("a-b", 1.0)], version="2", control="nop") # another version, another unit diff --git a/app/tests/test_flag_tasks_skill.py b/app/tests/test_flag_tasks_skill.py index 695a251e3..7d10abc75 100644 --- a/app/tests/test_flag_tasks_skill.py +++ b/app/tests/test_flag_tasks_skill.py @@ -68,6 +68,45 @@ def test_spot_keeps_two_units_of_one_name_apart_and_names_each_by_its_unit(self) self.assertEqual({c["task"]: c["group"] for c in json.loads((self.work / "cases.json").read_text())}, {"group/1": "always", "group-1": "nobody"}) + def test_a_proposal_for_a_unit_imports_onto_that_unit_never_one_of_its_name(self): + from types import SimpleNamespace + from tests.test_attempts import TaskIdentity + written = lambda name, units: Path(TaskIdentity.written(SimpleNamespace(tmp=str(self.root / "std")), name, units)) + both, alias = written("both", [("group/1", 1.0), ("group-1", 0.0)]), written("alias", [("group/1", 1.0)]) + self.run_script("spot", both, alias, "--out", self.work, "--only", "nobody") + (self.votes / "a.json").write_text(json.dumps([vote("group-1", "flawed")])) + (self.votes / "b.json").write_text(json.dumps([vote("group-1", "flawed")])) + self.run_script("merge", self.work / "cases.json", "--votes", self.votes, "--material", self.material, "--out", self.work) + proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + self.assertEqual([(f["task"], f["identity"]) for f in proposed], [("group-1", ["b", "1", "set", "group-1"])]) + for name in ("alias", "both"): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + flags_cli.main(["import", str(self.root / "std"), name, "--from", str(self.work / "flag-tasks.json")]) + self.assertEqual(fa.load(str(alias)).flags, {}) # group/1 is shown as group-1: not it + self.assertEqual({k: f.unit for k, f in fa.load(str(both)).flags.items()}, {"group-1": True}) + + def test_a_proposal_keeps_its_attempts_checksum_and_none_is_made_for_an_unresolved_task(self): + from types import SimpleNamespace + from tests.test_attempts import TaskIdentity + std = SimpleNamespace(tmp=str(self.root / "std")) + edit = lambda where, name, change: TaskIdentity.edit(std, where, name, change) + source = edit(TaskIdentity.written(std, "source", [("x", 0.0), ("group-1", 0.0)]), "source-u0/result.json", + lambda res: res.update(task_checksum="A")) + edit(source, "source-u1/result.json", lambda res: res["standard"].pop("benchmark_version")) # no exact task + later = edit(TaskIdentity.written(std, "later", [("x", 0.0), ("group/1", 1.0)]), "later-u0/result.json", + lambda res: res.update(task_checksum="B")) + self.run_script("spot", source, "--out", self.work, "--only", "nobody") + for reader in "ab": + (self.votes / f"{reader}.json").write_text(json.dumps([vote("x", "flawed"), vote("group-1", "flawed")])) + out = self.run_script("merge", self.work / "cases.json", "--votes", self.votes, "--material", self.material, "--out", self.work) + proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + self.assertEqual([(f["task"], f["task_version"]) for f in proposed], [("x", "A")]) + self.assertIn("1 votes or flags not counted", out) + self.assertIn("group-1: flawed not proposed", (self.work / "report.md").read_text()) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: + flags_cli.main(["import", std.tmp, "later", "--from", str(self.work / "flag-tasks.json")]) + self.assertEqual((fa.load(later).flags, err.getvalue()), ({}, "not in the job: x\n")) # later ran x at B + def test_spot_leaves_out_infrastructure_errors_and_refuses_a_control_run(self): f = self.runs[0] / "t2__1" / "result.json" f.write_text(json.dumps(dict(json.loads(f.read_text()), exception_info={ @@ -123,6 +162,13 @@ def test_the_flags_import_as_pending(self): flag = fa.load(str(self.runs[0])).flags["t1"] self.assertEqual((code, flag.kind, flag.status, flag.task_version, flag.by), (0, "flawed", "pending", "c1", "flag-tasks")) + # the proposal keeps the checksum its attempts recorded: not one for a run where the task changed + proposed = json.loads((self.work / "flag-tasks.json").read_text())["flags"] + self.assertEqual([(f["task"], f["task_version"], "identity" in f) for f in proposed], [("t1", "c1", False)]) + later = job(self.root / "jobs", "run-later", {"t1": (1, "new")}) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: + flags_cli.main(["import", str(self.root / "jobs"), "run-later", "--from", str(self.work / "flag-tasks.json")]) + self.assertEqual((fa.load(str(later)).flags, err.getvalue()), ({}, "not in the job: t1\n")) if __name__ == "__main__": diff --git a/app/tests/test_flags_cli.py b/app/tests/test_flags_cli.py index a0774db9d..ec86fdb94 100644 --- a/app/tests/test_flags_cli.py +++ b/app/tests/test_flags_cli.py @@ -97,6 +97,23 @@ def test_copy_skips_tasks_the_target_does_not_hold_and_refuses_itself(self): self.assertEqual(fa.load(str(c)).flags, {}) self.assertEqual(self.cli("copy", "run-a", "run-a")[0], 2) + def test_a_copy_leaves_an_accepted_flag_that_still_covers_an_attempt(self): + target = job(self.root, "run-t", {"x": (0, "A")}) # two attempts at x: A failed, B passed + body = json.loads((target / "x__1" / "result.json").read_text()) + (target / "x__2").mkdir() + (target / "x__2" / "result.json").write_text(json.dumps(dict(body, trial_name="x__2", task_checksum="B"))) + fa.update(str(target), lambda a: a.set_flag("x", "flawed", "c", by="Ann", task_version="A")) + job(self.root, "run-s", {"x": (0, "B")}) + self.cli("set", "run-s", "x", "--kind", "flawed", "--category", "c") + self.assertEqual(self.cli("copy", "run-s", "run-t")[1:], ("copied to run-t, pending: 0\n", "kept, already accepted: x\n")) + flag = fa.load(str(target)).flags["x"] + self.assertEqual((flag.status, flag.task_version), ("accepted", "A")) + # no attempt ran A any more: the accepted flag covers nothing, and the proposal takes its place + (target / "x__1" / "result.json").write_text(json.dumps(dict(body, task_checksum="C"))) + self.assertEqual(self.cli("copy", "run-s", "run-t")[1:], ("copied to run-t, pending: 1\n", "")) + flag = fa.load(str(target)).flags["x"] + self.assertEqual((flag.status, flag.task_version), ("pending", "B")) + def test_accept_takes_a_task_or_all_pending(self): self.assertEqual(self.cli("accept", "run-a")[0], 2) self.assertEqual(self.cli("accept", "run-a", "task-1", "--all-pending")[0], 2) @@ -111,7 +128,8 @@ def test_accept_takes_a_task_or_all_pending(self): def test_a_bad_import_file_writes_nothing(self): src = self.root / "bad.json" for body, code in (("{not json", 4), (json.dumps({"flags": "x"}), 4), (json.dumps(["x"]), 4), - (json.dumps([{"kind": "flawed", "category": "x"}]), 4)): + (json.dumps([{"kind": "flawed", "category": "x"}]), 4), + (json.dumps([{"task": "task-1", "kind": "flawed", "category": "x", "task_version": ["c1"]}]), 4)): src.write_text(body) self.assertEqual(self.cli("import", "run-a", "--from", str(src))[0], code, body) self.assertEqual(self.cli("import", "run-a", "--from", str(self.root / "none.json"))[0], 3) diff --git a/app/ui_tests/test_failure_analysis_routes.py b/app/ui_tests/test_failure_analysis_routes.py index a6d2aaf57..1ce833e98 100644 --- a/app/ui_tests/test_failure_analysis_routes.py +++ b/app/ui_tests/test_failure_analysis_routes.py @@ -237,6 +237,43 @@ 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_under_a_name_two_units_share_is_not_accepted_or_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"): # a form kept from before, on the unit of that name + 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({k: f.status for k, f in fa.load(str(self.units)).flags.items()}, {"group-1": "pending"}) + + def checksums(self, **by_trial): + for trial, checksum in by_trial.items(): + result = self.job / trial / "result.json" + body = {k: v for k, v in json.loads(result.read_text()).items() if k != "task_checksum"} + result.write_text(json.dumps(dict(body, **({"task_checksum": checksum} if checksum else {})))) + + def test_a_flag_set_from_an_attempt_is_on_the_version_that_attempt_ran(self): + self.checksums(t3__1="A", t3__2="B") + self.assertEqual(self.post("t3__2", action="flag", kind="flawed", category="c").status_code, 302) + self.assertEqual(fa.load(str(self.job)).flags["t3"].task_version, "B") + self.assertIn('id="fa-flag-value">Flawed', self.page("/trial/run-t/t3__2")) + self.assertNotIn('id="fa-flag-value"', self.page("/trial/run-t/t3__1")) # the other attempt: not its flag + job = self.page("/job/run-t?flawed=1") + self.assertEqual(re.findall(r'data-trial="([^"]+)" data-task-flag="flawed"', job), ["t3__2"]) + self.assertNotRegex(job, r']*data-task-flag') # the task keeps an attempt + rows = dict(re.findall(r']*?data-(?:trial|group)="([^"]+)"[^>]*>(.*?)', job, re.S)) + self.assertEqual([name for name in ("g-t3__1", "t3__1", "t3__2") if 'class="tflag' in rows[name]], ["t3__2"]) + for name in ("t3__1", "t3__2"): # the tab says what the flag covers + tab = self.page(f"/trial/run-t/{name}") + self.assertIn("

Task flag · 1 of 2 attempts

", tab) + self.assertIn('id="fa-flag-scope">One flag per task in this run: it shows on the attempts that ran this task version.

', tab) + for action in ("accept", "remove_flag"): + self.assertEqual(self.post("t3__1", action=action).status_code, 400, action) + self.assertEqual(self.post("t3__2", action="remove_flag").status_code, 302) + # an attempt that records no version would cover the other one's: refused + self.checksums(t3__2=None) + self.assertEqual(self.post("t3__2", action="flag", kind="flawed", category="c").status_code, 400) + self.assertEqual(fa.load(str(self.job)).flags, {}) + 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") @@ -428,8 +465,107 @@ def test_a_flag_sets_aside_every_identity_its_unit_ran_under(self): fa.update(where, lambda a: fa.put_flag(a, run, ("u",), "flawed", "x", by="ann")) self.assertEqual(fa.filtered(run, fa.load(where), ["flawed"]).ran, 1) with web.app.test_request_context("/compare?flawed=1"): - aside = web.compare._flag_filter(selected(run))["set_aside"] + aside = web.compare._flag_filter(selected(run))["trials"] self.assertEqual([t.unit for t in comparison.build(selected(run), set_aside=aside).jobs[0].trials], ["v"]) + # a flag that names a version: the attempt that recorded it alone, in the job's score and in Compare + for i, checksum in enumerate("AB"): + rj = Path(where) / f"twice-u{i}" / "result.json" + rj.write_text(json.dumps(dict(json.loads(rj.read_text()), task_checksum=checksum))) + fa.update(where, lambda a: a.set_flag("u", "flawed", "x", by="ann", task_version="B")) + with web.app.test_request_context("/job/twice?flawed=1"): + score = web.runs._filtered_of(run, *web.runs._analysis_of(run))["view"] + self.assertEqual((score.ran, score.set_aside), (2, {"flawed": 1})) + with web.app.test_request_context("/compare?flawed=1"): + aside = web.compare._flag_filter(selected(run))["trials"] + self.assertEqual([t.trial_name for t in comparison.build(selected(run), set_aside=aside).jobs[0].trials], ["twice-u0", "twice-u2"]) + + def test_a_flag_on_one_version_sets_aside_the_attempts_that_ran_it_in_one_column(self): + from nullius.compare import comparison + from tests.test_comparison import selected + where = plain_job(Path(self.temp.name) / "attempts", "run-v", {"t1__1": ("t1", 0), "t1__2": ("t1", 1)}) + fa.update(str(where), lambda a: a.set_flag("t1", "flawed", "x", by="ann", task_version="A")) + for checksums in (("A", "B"), ("A", None)): # the other attempt: another version, or none + for name, checksum in zip(("t1__1", "t1__2"), checksums): + rj = where / name / "result.json" + rj.write_text(json.dumps(dict(json.loads(rj.read_text()), task_checksum=checksum))) + run = parse.parse_job(str(where)) + with web.app.test_request_context("/compare?flawed=1"): + view = comparison.build(selected(run), set_aside=web.compare._flag_filter(selected(run))["trials"]) + self.assertEqual(([t.trial_name for t in view.jobs[0].trials], view.tasks[0].attempts, view.set_aside_trials), + (["t1__2"], (1,), (1,)), checksums) + + def versions(self, root, runs): + """Harbor runs under *root*: per run, each trial's task, reward and checksum (None: not recorded).""" + from tests.test_comparison import selected + out = [] + for name, trials in runs.items(): + where = plain_job(Path(self.temp.name) / root, name, {t: row[:2] for t, row in trials.items()}) + for t, (_, _, checksum) in trials.items(): + rj = where / t / "result.json" + rj.write_text(json.dumps(dict(json.loads(rj.read_text()), **({"task_checksum": checksum} if checksum else {})))) + out.append(where) + return out, lambda: selected(*(parse.parse_job(str(where)) for where in out)) + + def test_a_task_left_in_one_column_is_in_whole_runs_and_not_matched(self): + from nullius.compare import comparison + (left, _), picked = self.versions("jobs3", {"run-l": {"x__1": ("x", 0, "A"), "y__1": ("y", 1, None)}, + "run-r": {"x__1": ("x", 1, None), "y__1": ("y", 1, None)}}) + fa.update(str(left), lambda a: a.set_flag("x", "flawed", "c", by="ann", task_version="A")) + with web.app.test_request_context("/compare?flawed=1"): + ff = web.compare._flag_filter(picked()) + whole, matched = (comparison.build(picked(), cohort, ff["trials"]) for cohort in ("whole", "matched")) + tasks = lambda view: [[t.task_base for t in j.trials] for j in view.jobs] + self.assertEqual((tasks(whole), tasks(matched)), ([["y"], ["x", "y"]], [["y"], ["y"]])) + self.assertEqual((matched.shared_tasks, [r.task for r in matched.tasks], matched.set_aside_trials, matched.excluded_trials), + (1, ["y"], (1, 0), (0, 1))) + ws = workspace.create(str(Path(self.temp.name) / "ws"), [str(left.parent)], label="one-column") + with patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}): + web.shared.open_workspace(ws) + html = self.page(f"/compare?pick={ws.name}:run-l&pick={ws.name}:run-r&flawed=1") + web.shared.open_workspace(self.ws) + self.assertIn('id="compare-set-aside">Filtered: 1, 0 tasks set aside, by column', html) + + def test_a_task_outside_the_matched_cohort_is_not_counted_set_aside(self): + from nullius.compare import comparison + (left, _), picked = self.versions("jobs5", {"run-l": {"x__1": ("x", 0, None), "y__1": ("y", 1, None)}, + "run-r": {"y__1": ("y", 1, None)}}) + fa.update(str(left), lambda a: a.set_flag("x", "flawed", "c", by="ann")) + with web.app.test_request_context("/compare?flawed=1"): + ff = web.compare._flag_filter(picked()) + views = [comparison.build(picked(), cohort, ff["trials"]) for cohort in ("whole", "matched")] + self.assertEqual([view.set_aside_tasks for view in views], [(1, 0), (0, 0)]) + ws = workspace.create(str(Path(self.temp.name) / "ws"), [str(left.parent)], label="outside") + with patch.dict(web.shared.STATE, {"workspace": None, "roots": [], "label": "", "job_roots": []}): + web.shared.open_workspace(ws) + html = self.page(f"/compare?pick={ws.name}:run-l&pick={ws.name}:run-r&flawed=1&cohort=matched") + web.shared.open_workspace(self.ws) + self.assertIn('id="compare-set-aside">Filtered: 0 tasks set aside in every column', html) + + def test_two_columns_that_flag_different_attempts_of_a_task_are_named(self): + from nullius.compare import comparison + both = {"t1__1": ("t1", 0, "A"), "t1__2": ("t1", 0, "B")} + (a, b), picked = self.versions("jobs4", {"run-a": both, "run-b": both}) + fa.update(str(a), lambda x: x.set_flag("t1", "flawed", "c", by="ann", task_version="A")) + for version, differ in (("A", []), ("B", ["t1"])): + fa.update(str(b), lambda x: x.set_flag("t1", "flawed", "c", by="ann", task_version=version)) + with web.app.test_request_context("/compare?flawed=1"): + ff = web.compare._flag_filter(picked()) + self.assertEqual(ff["differ"], differ, version) + if version == "A": # one attempt of t1 leaves each column: the task stays + for cohort in ("whole", "matched"): + view = comparison.build(picked(), cohort, ff["trials"]) + self.assertEqual((view.set_aside_trials, view.set_aside_tasks), ((1, 1), (0, 0)), cohort) + # the command, for the same choice: the covered attempt alone leaves each column + import io + from contextlib import redirect_stdout + from nullius.compare import cli as compare_cli + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(compare_cli.main([str(a.parent), "run-a", "run-b", "--exclude", "flawed", "--json"]), 0) + doc = json.loads(out.getvalue()) + self.assertEqual(([r["totals"]["n_trials"] for r in doc["runs"]], [r["task"] for r in doc["tasks"]], + doc["flags"]["set_aside_trials"], doc["flags"]["set_aside_tasks"]), + ([1, 1], ["t1"], [1, 1], [0, 0])) def test_an_unreadable_flag_file_is_named(self): tmp = Path(self.temp.name) diff --git a/app/web/compare.py b/app/web/compare.py index 28bf2ecb1..75bedf211 100644 --- a/app/web/compare.py +++ b/app/web/compare.py @@ -628,7 +628,7 @@ def _columns_requested(): selected = comparison.resolve([ref.value for ref in refs if ref.job_id], {name: [job for _, job, _, _ in rs] for name, rs in runs.items()}, labels) g.flag_filter = _flag_filter(selected) - view = comparison.build(selected, request.args.get("cohort", "whole"), g.flag_filter["set_aside"]) + view = comparison.build(selected, request.args.get("cohort", "whole"), g.flag_filter["trials"]) except ValueError as exc: abort(400, description=str(exc)) place = {s.ref: k for k, s in enumerate(view.selected)} diff --git a/app/web/failure.py b/app/web/failure.py index eedc846dd..7a729c488 100644 --- a/app/web/failure.py +++ b/app/web/failure.py @@ -60,11 +60,13 @@ def _models(job, trial) -> list: return out -def _attempt(job, trial): - """(this attempt's number, the task's attempts) when the task was attempted more than once, else None: the - label belongs to the attempt, the flag to every attempt of the task.""" +def _attempt(job, trial, flag): + """(this attempt's number, the task's attempts, those its flag covers) when the task was attempted more than + once, else None: the label belongs to the attempt, the flag to every attempt of the task it covers + (``fa.applies``), as one set here would: those that ran this one's version.""" group = attempts.of(job, trial) - return (group.number(trial), group.n) if group else None + flag = flag or fa.Flag("", "", task_version=fa.version_of(trial)) + return (group.number(trial), group.n, sum(fa.applies(flag, t) for t in group.trials)) if group else None def _categories(job, analysis) -> list: @@ -88,6 +90,13 @@ def _categories(job, analysis) -> list: return seen + [c for c in CATEGORIES if norm(c) not in same] +def _flag(job, analysis, trial): + """Where the flag of the trial's task is saved, and that flag when it covers the trial (``fa.applies``): one on + another version is another trial's to show, accept or remove.""" + key, flag = fa.slots(job, analysis.flags).get(fa.task_of(trial), (None, None)) + return key, flag if flag is not None and fa.applies(flag, trial) else None + + def panel(job, trial) -> dict: """What the tab shows for *trial*. Only a browser on this machine gets the forms.""" try: @@ -96,10 +105,11 @@ def panel(job, trial) -> dict: analysis, error = fa.Analysis(), str(e) cause = _judge_cause(job, trial) if failed(trial) else None models = _models(job, trial) if trial.outcome != classify.RESOLVED else [] # asked of every unresolved trial + flag = _flag(job, analysis, trial)[1] return {"models": models, "model_labels": [m for m in models if m["label"]], "model_flags": [m for m in models if m["flag"]], "flag_names": FLAG_NAMES, - "attempt": _attempt(job, trial), "failed": failed(trial), "label": analysis.labels.get(trial.trial_name), - "flag": fa.for_job(job, analysis).flags.get(fa.task_of(trial)), "suggests": fa.suggestion(cause), + "attempt": _attempt(job, trial, flag), "failed": failed(trial), "label": analysis.labels.get(trial.trial_name), + "flag": flag, "suggests": fa.suggestion(cause), "labels": LABEL_NAMES, "kinds": fa.KINDS, "categories": _categories(job, analysis), "error": error, "can_write": shared._local_client() and error is None} @@ -116,7 +126,7 @@ 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 = _flag(job, a, trial) # where its flag is saved, and the flag if action == "label": if not failed(trial): raise fa.FailureAnalysisError("only a failed trial takes a label") @@ -126,7 +136,9 @@ 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(), trial=trial) + elif action in ("accept", "remove_flag") and flag is None: # a record that is not its own, or not this trial's, stays + raise fa.FailureAnalysisError(f"no flag on task {fa.name_of(task)!r} as this trial ran it") 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..3d4091b28 100644 --- a/app/web/runs.py +++ b/app/web/runs.py @@ -636,20 +636,30 @@ def _analysis_of(j): 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.flag_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.""" + version of the task), each labelled trial, `covered`: how many of the trials given, attempts of one task, its + flag covers (`failure_analysis.applies`), and `left_out`: the kind of the counting flag that covers them all.""" if analysis is None: - return {"flags": {}, "labels": {}, "task_of": failure_analysis.task_of} + return {"flags": {}, "labels": {}, "task_of": failure_analysis.task_of, "left_out": lambda trials: None, + "covered": lambda trials: 0} 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} + flags[task] = {"kind": f.kind, "category": f.category, "pending": f.status != "accepted", "other": other} + + def covered(trials): + f = analysis.flags.get(failure_analysis.task_of(trials[0])) + return sum(failure_analysis.applies(f, t) for t in trials) if f else 0 + + def left_out(trials): + f = analysis.flags.get(failure_analysis.task_of(trials[0])) + return f.kind if f and f.status == "accepted" and covered(trials) == len(trials) else None + return {"flags": flags, "labels": analysis.labels, "task_of": failure_analysis.task_of, "left_out": left_out, + "covered": covered} def _filtered_of(j, analysis, versions): diff --git a/docs/cli/flags.md b/docs/cli/flags.md index 190a6c0b9..868c204ea 100644 --- a/docs/cli/flags.md +++ b/docs/cli/flags.md @@ -14,4 +14,4 @@ nullius flags feasibility A task is named as `nullius runs show` prints it. When two units of a standard run share that name, name the unit itself. A flag saved under such a name is on neither unit: `accept --all-pending` leaves it, `remove` takes its saved name. -A flag from `set` counts at once. One from `set --pending`, `copy`, `import` or `feasibility` waits for `accept`, and never replaces an accepted flag. `import --by` names who proposes the flags; without it, the person running the import. Exit codes: `0` done, `2` usage, `3` not found, `4` invalid input. +A flag from `set` counts at once. One from `set --pending`, `copy`, `import` or `feasibility` waits for `accept`, and never replaces an accepted flag. A flag from `copy` or `feasibility`, or an imported record with an `identity`, goes to the exact task it names: a run that holds that unit at several versions takes it only when it covers that version's trials alone, else it `would also cover another version`. A record's `task_version` is the checksum its trial recorded: a run whose trials of that task recorded another is `not in the job`. `import --by` names who proposes the flags; without it, the person running the import. Exit codes: `0` done, `2` usage, `3` not found, `4` invalid input. diff --git a/docs/cli/read-jobs.md b/docs/cli/read-jobs.md index ecd6b2754..52562ff0c 100644 --- a/docs/cli/read-jobs.md +++ b/docs/cli/read-jobs.md @@ -43,7 +43,7 @@ nullius standard traces [--dry-run] | `nullius runs show ` | A trial: outcome, checks, usage, exception, steps. Tool arguments and observations stay on the page | | `nullius runs show --call N --request` | Call N's request as sent, rebuilt from the [exchange record](run.md#the-exchange-record); exit 4 when its hash differs | | `nullius runs show --calls` | The trial's Conversation by model call, as JSON, redacted | -| `nullius compare ... [--matched] [--exclude KIND]...` | `/compare`'s cohort: whole, or matched on the tasks every job ran, without the tasks flagged KIND (`flawed`, `ambiguous`) | +| `nullius compare ... [--matched] [--exclude KIND]...` | `/compare`'s cohort: whole, or matched on the tasks every job ran, without the trials a KIND flag (`flawed`, `ambiguous`) covers | | `nullius workspace list [--home DIR]` | The workspaces, as `/workspaces` lists them |