Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions .agents/skills/flag-tasks/scripts/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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())
Expand Down Expand Up @@ -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"))}
Expand All @@ -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):
Expand Down
17 changes: 10 additions & 7 deletions app/nullius/compare/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"]:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
47 changes: 30 additions & 17 deletions app/nullius/compare/comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand All @@ -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.
Expand All @@ -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.")
Expand All @@ -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)

Expand All @@ -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))



Expand Down
62 changes: 39 additions & 23 deletions app/nullius/compare/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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}
Loading
Loading