diff --git a/.agents/skills/import-benchmark/SKILL.md b/.agents/skills/import-benchmark/SKILL.md index ec4f69819..31186f9c9 100644 --- a/.agents/skills/import-benchmark/SKILL.md +++ b/.agents/skills/import-benchmark/SKILL.md @@ -188,6 +188,10 @@ ours: none | then one row per thing that cannot run or differs from the paper (skip / local change / issue), and the questions, with the question tool. +An entry with a `standard.json`: hand over to `/label-benchmark` for its +Leaderboard labels, unless the user declines. A Harbor-only entry has no labels +yet: say so. + ## Catalogue presentation Keep the benchmark description and each option summary to a short sentence. diff --git a/.agents/skills/import-standard/SKILL.md b/.agents/skills/import-standard/SKILL.md index db816a93e..ee83c759f 100644 --- a/.agents/skills/import-standard/SKILL.md +++ b/.agents/skills/import-standard/SKILL.md @@ -402,6 +402,9 @@ question tool. No account of what was read: a `checked:` list at most. Every change is local first. Pull requests, issues and anything upstream are asked about once it works, never by default. +A benchmark that fits: hand over to `/label-benchmark` for its Leaderboard +labels, unless the user declines. + ## Catalogue presentation Keep the benchmark description and each option summary to a short sentence. diff --git a/.agents/skills/label-benchmark/SKILL.md b/.agents/skills/label-benchmark/SKILL.md new file mode 100644 index 000000000..23a0a7d8e --- /dev/null +++ b/.agents/skills/label-benchmark/SKILL.md @@ -0,0 +1,203 @@ +--- +name: label-benchmark +description: Propose a benchmark's Leaderboard labels - which capabilities and domains each dataset and task counts for - as a labels.json for a person to accept. Use it after importing a benchmark (the import skills hand over to it), when a benchmark gets a new version, or when the user asks to label, tag or classify a benchmark's tasks for the Leaderboard, or to review or update its labels. Never runs the benchmark. +--- + +# Label a benchmark + +Propose which Leaderboard axes each task of a benchmark counts for: what a field of the task's own data **declares** +(step 1), then **decision models** on every pair left (step 2). What is asked is never your choice: two runs give the +same proposal. You write it. A person accepts it. + +- **Never run the benchmark.** Read its definition, README or paper, task listing and each task's input, expected + output or judge prompt. A first `units` listing may fetch the upstream and install its environment: say so first. +- **Never use the keys configured in Nullius.** They are for evaluations. Step 2's decisions go through + `SKILL/scripts/decide.py` alone, which has a key of its own: never through your own subagents, another model or + another route. Never read, print or pass `NULLIUS_LABEL_OPENROUTER_KEY`: the user sets it before starting you, + ideally a dedicated OpenRouter key with a low credit limit. Not set: ask, or stop after step 1. +- **Only the axes of `labels.AXES`** (`REPO/app/nullius/leaderboard/labels.py`), each defined in `definitions.json`. + A label outside them is reported as a proposal and never written. +- **Write only the format below.** The file is valid after any step: the user chooses how deep to go. +- **A reason never restates a task.** It states the evidence in general terms ("asks for confirmation before + paying"), never the task's question, its answer or its data. The same holds for the report. + +Below, `REPO` is the absolute path of the checkout this skill is in, `SKILL` is `REPO/.agents/skills/label-benchmark`, +`KEY` the benchmark's key, `REF` the version labelled (`KEY` for its default or its only one, else `KEY@VERSION`) and +`WORK` a new folder outside the checkout, agreed with the user. + +Choose the source entry first and keep it to the end: releases, prior labels, terms and tasks come from it alone. Only +a contribution the user asked for by name takes the bundled entry, even beside the user's own copy of `KEY`: each +`PYTHONPATH=` command then starts with the variable below, and `ENTRY` is `REPO/app/nullius/catalogue/benchmarks/KEY`. +Anything else takes the entry Nullius reads and never sets the variable. + +A benchmark with no `standard.json` (a Harbor-only entry) cannot be labelled yet: say so and stop. The first command +prints where the entry, and a `labels.json` it already has, is read; the second, each release's identity and datasets. +Read `SKILL/definitions.json` whole first: its rules, and per axis its definition, when it holds (`in`) and when not +(`out`), which you and a person judge by, and the `questions` step 2 asks. A test not clearly met gives no label. +```bash +# a contribution: NULLIUS_CATALOGUE=REPO/app/nullius/catalogue before each PYTHONPATH=, here and below +PYTHONPATH=REPO/app python3 -c 'from nullius.catalogue import catalog; print(catalog.entry_dir("KEY"))' +PYTHONPATH=REPO/app python3 -c 'from nullius.standard.contract import definitions as d; [print(d.version_identity(b), [x["id"] for x in b.get("datasets") or []]) for b in d.load("benchmark", every=True)[0] if b["key"] == "KEY"]' +``` + +Never for a contribution, else last and only to write: this prints `ENTRY`, where the proposal goes, and copies a +bundled entry into user storage, where it replaces the bundled one. Say so first. +```bash +PYTHONPATH=REPO/app python3 -c 'from nullius.catalogue import catalog; print(catalog.writable_dir("KEY"))' +``` + +## The terms come first + +Before any task text, read at the pinned commit and where the data is hosted: the code's and the data's licences +(`LICENSE*`, the README, the dataset card), a gate (terms or a form before the download), and a request against +resharing or training on the data (a canary line in the README, the card or the data files). Data kept in the code +repository with no card: each `LICENSE*` and README from the root down to the data's folder; a code licence silent on +the data is reported as that. Put each in the report, quoted, with its place, or `none found` with those searched. + +Gated data, or data its authors ask not to reshare or to keep out of training: propose `units.redistribute: false` in +the benchmark's definition, as a ```diff block for the user. With it, proposed or already set, no task id goes anywhere: +not into `labels.json`, the report or a model. Skip both steps. Write dataset rules alone (no `tasks`), each from the +benchmark's own statement in its README, paper or dataset description: the one domain it defines the dataset as, or a +capability it says every task of the dataset is graded on. Never your reading of what a dataset is about. Such a rule +labels the dataset in every release the second command lists it in: the statement must hold for each. Then hand over. + +## The format + +`ENTRY/labels.json`: +```json +{"schema": 1, "labels": [ + {"dataset": "retail", "checked": ["IDENTITY"], "tasks": ["17", "42"], "axes": ["Safety"]}, + {"dataset": "retail", "checked": ["IDENTITY"], "tasks": ["42"], "not": ["Execution"]} +]} +``` + +- Under `units.redistribute: false`, dataset rules instead, never both: `{"dataset": "retail", "axes": ["Shopping"]}`. +- A rule selects the whole benchmark (no `dataset`), one dataset, or the listed `tasks` of one dataset. A task's axes + are the union of its rules' `axes`, minus their `not`. No other key, no prefix, no pattern. +- `dataset` is a dataset of the definition, never a cut of another (`subset_of`): name the dataset it is cut from. +- `tasks` are the exact ids `units` prints, never empty, and only on a rule with a `dataset`. Such a rule carries + `checked`, which a rule without `tasks` never does: the versions whose tasks you read, each by the identity a run + records for it, never a tag or a name read from the definition by hand: + + ```bash + PYTHONPATH=REPO/app python3 -c 'from nullius.standard.contract import definitions as d; print(d.version_identity(d.get("benchmark", "REF")))' + ``` +- A new version: add its identity, as the command above prints it for the new `REF`, to `checked` only for the tasks + whose bytes did not change, and only when the `policy` and whatever else a state is built from or a task is graded + by did not change either. Every other task goes through the steps. + +## 1. Field rules + +```bash +PYTHONPATH=REPO/app python3 -m nullius standard units REF --dataset D --json +PYTHONPATH=REPO/app python3 -m nullius standard units REF --dataset D --category FIELD=VALUE --json +PYTHONPATH=REPO/app python3 -c 'from nullius.standard.requirements import install; print(install.HOME)' +``` + +`units` prints each task's id, title and text, not its expected outcome or grading. Read those in the dataset's own +file: its `path` under `STANDARD/upstreams/KEY/TESTED/`, or under `STANDARD/datasets/` with a `url` (`STANDARD`: the +last command's output; `TESTED`: `upstream.tested` of `REF`). With neither: the upstream's own task loader there. + +Labels cover the tasks `units` lists for each dataset with every option at its default. Those only another option +value lists (`--bench-option NAME=VALUE`, a split) go through the steps when the user asks; else the report names +those values. Two datasets with one task file (the same `path` and `sha256`) and the same assembled `policy` text, compared exactly (step 2): take one +through the steps and write its `tasks` rules for both. Either differs (a workflow variant's policy): both go through. + +This step decides only a yes, and only from a field of the task's data that anyone can check again. A field whose +value, when present and not empty, is the axis's test gives a `tasks` rule over those tasks: a graded check that +lists what the agent must tell the user (Communication), a category the benchmark defines as one domain. A count, a +keyword, a tool's name or what the dataset is about is no such field. Show each field and its rule to the user. + +## 2. Decision models + +Decision models answer typed questions with a probability, without reasons. Write `WORK/tasks.jsonl`, a line per task: +a `state` of its own fields, as its data gives them. Every axis of `definitions.json` is asked, domain or capability, +but those in `skip`: the axes step 1 gave it, `[]` or left out for none. A line with `axes` is refused. +```json +{"dataset": "retail", "task": "42", "skip": ["Shopping"], "state": {"request": {...}, "checks": {...}, "given": {...}}} +``` + +- `request`: the task's input as the agent or the simulated person gets it, an object or a text. Required. +- `checks`: what the benchmark grades, and nothing else: where a task names the checks that count (a `reward_basis`, + a weight of zero), leave the others out. An empty value is evidence and stays: no action expected, an empty list. +- `policy`: the rules the agent actually receives for this dataset, whole, as the benchmark's driver assembles + them with each option at the `default` the definition gives it (a retrieval kind). Never a raw template. +- `given`: what the task hands the agent beyond those three: sources to consult, tools, by name, starting state, + earlier material (earlier sessions), who the person is (a profile, a history). From the task's own data: a + shared resource is named, not pasted; a per-task list wins over a benchmark-wide one. Never the answer or the grading: those stay in `checks`. +- `purpose`, `notes`, `ticket`: the task's own, when it has them. Any JSON, kept whole, under the data's own key + names. No other field. None is null itself (a field the task lacks is left out); a nested null stays. + +One task of τ³-bench, a simulated-customer benchmark whose criteria hold a `reward_basis` and reference `actions`: + +- `request`: the whole user scenario, persona and instructions, as the data nests them. The persona is not `given`. +- `checks`: the `reward_basis`, then only the criteria it names: what to tell the user under `COMMUNICATE`, the + assertions under `NL_ASSERTION` or `ENV_ASSERTION`. The reference `actions` go in when the basis grades the actions + (`ACTION`) or the state they lead to (`DB`): they define the target. Under neither, leave them out. +- `given`: `{"required_documents": [ids], "tools": {"agent": [names], "user": [names]}, "initial_state": {...}}`, + the tool names as the driver's environment lists them for the dataset: no schema, no database, no document text. + +The state leaves the machine, to OpenRouter and to providers asked not to keep it. After the dry run, tell the user +how many tasks, pairs and calls, which models and the characters it counts: a dry run shows no cost. Its summary is +the last line of stderr; stdout, here `WORK/dryrun.jsonl`, holds every request whole and can reach tens of megabytes. +Wait for a yes. Without `--model`, the script asks `typesafe/jev-1.14`, `perplexity/pplx-decider-v1.2` and +`liquid/d1.3-ultra`; two or three others, from different makers, replace them. +```bash +python3 SKILL/scripts/decide.py --list-models +touch WORK/decisions.jsonl +python3 SKILL/scripts/decide.py WORK/tasks.jsonl --max-calls N --decided WORK/decisions.jsonl --dry-run > WORK/dryrun.jsonl +python3 SKILL/scripts/decide.py WORK/tasks.jsonl --max-calls N --decided WORK/decisions.jsonl >> WORK/decisions.jsonl +python3 SKILL/scripts/decide.py WORK/tasks.jsonl --decided WORK/decisions.jsonl --results > WORK/results.jsonl +``` + +One request per task and model, with every question of its axes. A model says `yes` to an axis when any of its +questions is above 0.7, `no` when all are below 0.3, else `unsure`; a refused question is neither, and a reply that +does not read is `unsure` on the task's axes. A pair decided in the `--decided` file, for the same definitions, +questions, models and state, is not asked again, nor is a model whose answers to a task are there, unreadable ones +included: after a failed call, the same commands ask only the models missing. N is a total over that file: the +answered calls it holds count (`calls_before`), failed ones do not, and the first whole tasks left that fit in the +rest are kept. A resumed run takes the same N, a further batch a larger one, each after its own preview and the user's +yes. Create the file first; give every command the same file and `--model`, the dry run and the send the same N: the +dry run then shows exactly what the send may send. The send first removes a last line cut short; a whole line that is +not JSON is refused by its number. + +The send adds a line per pair: each model's answer and each question's `p`, then `agreed` (every model yes, or every +model no) or `disagreement`. Each answered call adds a line with its answers and its `cost_usd`, even when its task +gets no decision: the cost so far is the sum over `WORK/decisions.jsonl`. Stderr gets a line per task as it ends, then +this run's counts, with each `skipped` task's dataset, task, model and HTTP status. Exit 0 done, 2 usage, 3 no call +answered, 4 partial: a call failed or did not read, or `--max-calls` stopped the run or the dry run. + +Each request carries `provider.data_collection: "deny"`: what a provider then keeps cannot be checked from here, say +so to the user, and never work around a refusal of that field. A call that gets HTTP 429 is sent again after 2, 4 +and 8 seconds, then fails. A task with a failed call is skipped and reported, the run goes on, and only 401, 402, 403 +and 404 stop it. On 402 the key is out of credit: stop, report the calls and cost so far, resume after a top-up. + +Take results from `WORK/results.jsonl` alone, never from the last lines of `WORK/decisions.jsonl`: per pair, the last +decision for the current state, definitions, questions and models, else `pending`, which is asked or reported, never +labelled. An agreed `yes` proposes the label. An agreed `no` proposes none. A disagreement stays **unlabelled**. +Updating an existing `labels.json`: each result, step 1's field rules included, must also be what the file gives that +task at `REF`'s identity, all rules counted. Change only that task there; a rule that also holds others is split. + +- A yes, from a field rule or agreed: add the task to a `tasks` rule with the axis, `checked` at the identity, and + take it out of every `tasks` rule whose `not` holds the axis there. +- Agreed `no`: take the task out of every `tasks` rule that gives the axis there. Still given by a rule without + `tasks`: add a `tasks` rule with the axis in `not`, `checked` at the identity. +- Disagreement: take the task out of every `tasks` rule that gives the axis there, add no `not`, report it unlabelled. +- A rule without `tasks` still in the way (its `not` over a yes, its axis over a disagreement) is never lifted: + report each such conflict to the user before presenting the proposal as complete. + +## Hand over + +This checks `ENTRY/labels.json` itself against `ENTRY`'s versions, fails without it, and prints `()` or what to fix: +```bash +PYTHONPATH=REPO/app python3 -c 'import json; from nullius.standard.contract import definitions as d; from nullius.leaderboard import labels; v = [b for b in d.load("benchmark", "ENTRY/../..", every=True)[0] if b["key"] == "KEY"]; print(labels.check(json.load(open("ENTRY/labels.json")), v).problems if v else exit("no KEY in ENTRY"))' +``` + +Then report in a few lines, in `WORK/report.md` and to the user: + +- the terms read, and `units.redistribute` as proposed; calls and cost, every run counted; +- per rule: the step or statement that gave it, and for step 2 the models and how many pairs agreed; +- per axis: tasks labelled, disagreements left unlabelled, conflicts with a rule kept; the option values left out; + labels proposed outside `labels.AXES`, written nowhere. + +Show the diff of `labels.json`, or the whole file when it is new: a person accepts it. Nothing is committed or sent upstream without the user's word. diff --git a/.agents/skills/label-benchmark/definitions.json b/.agents/skills/label-benchmark/definitions.json new file mode 100644 index 000000000..01c29b5b7 --- /dev/null +++ b/.agents/skills/label-benchmark/definitions.json @@ -0,0 +1,297 @@ +{ + "version": "2026-11", + "rules": [ + "A label holds when the task needs the property to pass, not when its dataset is about it.", + "Each test is asked of one task: its input, its expected output, its checks.", + "Labels are sparse: a test not clearly met gives no label. A task may have no capability or no domain.", + "A task may hold several capabilities and several domains.", + "A domain is the purpose of the errand, not the app used. A profession's subject decides its domain: a clinician's order is Health.", + "A person's needs (diet, access, health) belong to no domain. A stated need is a part of the request; a known unstated one is Personalization; one whose neglect harms is Safety." + ], + "axes": { + "Memory": { + "family": "capabilities", + "definition": "Uses what it was told earlier and kept, and only where it applies", + "in": "passing needs information the task gave earlier and does not present again where it is needed: a new session or a reset the benchmark imposes, or material it withholds within one session", + "out": "the information is still in the input, or in a record the task lets the agent read. A system compacting its own context does not make a task Memory", + "questions": [ + { + "id": "memory", + "instructions": "Does a check in `checks` need a fact that the task gives earlier and does not give again where the agent needs it, because a new session or reset starts in between or the task withholds it later?", + "true": "The task gives a fact, then starts a new session, resets the conversation, or no longer shows it, and a check passes only if the agent uses that fact later without being told it again.", + "false": "Every fact the checks need is in the request where it is needed, or in a record the agent can read at that point." + } + ] + }, + "Safety": { + "family": "capabilities", + "definition": "Prevents harm to the user, the party it acts for, or third parties: to health or physical safety, to money, to privacy, or through an irreversible step. Acts only on confirmed intent; asks before anything costly or irreversible", + "in": "a check passes only on a protective act, and doing the literal request without it fails", + "out": "no check tests the policy; the task is only impossible (Abstention)", + "questions": [ + { + "id": "safety_decline", + "instructions": "Does a check in `checks` pass only if the agent declines, or stops short of, a step the person in `request` asks for, because that step would harm someone's health or physical safety, money or privacy, or could not be undone?", + "true": "The person asks the agent to do something, and a check expects the agent not to do it because doing it would endanger someone's health or physical safety, lose someone money, expose someone's private information, or could not be undone; doing exactly what was asked fails that check.", + "false": "Every step the person asks for is one the checks expect the agent to carry out; or the agent must hold back only because a rule of a game or of the task says so, and going ahead would harm no one's health, physical safety, money or privacy and could be undone." + }, + { + "id": "safety_withhold", + "instructions": "Does a check in `checks` expect the agent to keep from the person it is talking to a piece of information whose disclosure would harm someone's privacy, money, or health or physical safety?", + "true": "A check fails if the agent reveals a specific piece of information that would harm someone once disclosed, such as another person's details, account data the caller has no right to see, or a credential.", + "false": "No check penalizes the agent for what it reveals; or the information is kept back only because a game or the task says so, such as a spoiler, a hidden answer or a secret word, and revealing it would harm no one's privacy, money, health or physical safety." + }, + { + "id": "safety_confirm", + "instructions": "Does a check in `checks` expect the agent to get the person's explicit confirmation before a costly or irreversible step?", + "true": "A check passes only if the agent asks for and receives a clear yes before it charges money, cancels, deletes, or takes another step that cannot be undone.", + "false": "The checks read only the final actions, state or messages, and none of them looks at whether the agent asked the person first." + } + ] + }, + "Consistency": { + "family": "capabilities", + "definition": "When information has changed, acts on the newest and removes what is outdated", + "in": "an older and a newer version of one fact are visible and passing needs the newer; or stale state must be undone", + "out": "one version only; the same result over repeated attempts (pass^k)", + "questions": [ + { + "id": "consistency", + "instructions": "Does `request` give an older and a newer value of one fact, with a check in `checks` that passes only on the newer one?", + "true": "A detail changes during the task, such as a date, an address or a quantity replaced by a new one, and a check passes only if the agent acts on the new value or undoes what it did with the old one.", + "false": "Each fact has one value in the request, and no check depends on telling an old value from a new one." + } + ] + }, + "Personalization": { + "family": "capabilities", + "definition": "Chooses as the user, or the person served, would", + "in": "with the request unchanged, another person's profile or history changes the right outcome, and the request does not state the preference", + "out": "the request states the preference; the preference is only recalled (Memory)", + "questions": [ + { + "id": "personalization", + "instructions": "Does a check in `checks` expect a choice that follows from who the person in `request` is, their profile or history, and not from a preference they state?", + "true": "The person does not say what they prefer, and a check passes only on the option their profile or past choices point to; another person making the same request would get a different right outcome.", + "false": "The person states what they want, or the checks expect the same outcome whoever makes the request." + } + ] + }, + "Proactivity": { + "family": "capabilities", + "definition": "Takes a step nobody asked for but the situation requires, and takes it correctly", + "in": "passing needs a step the instruction does not name and the stated goal does not already require", + "out": "the instruction names the step; any plan for the goal includes it", + "questions": [ + { + "id": "proactivity", + "instructions": "Does a check in `checks` expect a step that the person in `request` does not ask for and that their stated goal does not already require?", + "true": "A check passes only if the agent also does something nobody asked for that the situation calls for, such as warning about a conflict or fixing a related problem it noticed.", + "false": "Every step the checks expect is one the person names, or one that any way of reaching their stated goal includes." + } + ] + }, + "Retrieval": { + "family": "capabilities", + "definition": "Gets facts right from an outside source, any source other than the prompt and the system's own past", + "in": "the expected output or a check holds a fact found in such a source, pointed to or not", + "out": "the fact is in the prompt; it comes from the system's own past (Memory); closed-book by design", + "questions": [ + { + "id": "retrieval", + "instructions": "Does a check in `checks` expect a fact that is not in `request` and that the agent must look up in a source outside it?", + "true": "A checked value or the expected answer comes from a document, a database, a web page or another source the agent must consult.", + "false": "Every fact the checks expect is stated in the request, or the task gives the agent no source to look anything up." + } + ] + }, + "Communication": { + "family": "capabilities", + "definition": "The messages a task requires reach the right people with the right content", + "in": "a check reads a message to a person: sent with a tool, or said to the person in the conversation when the check lists what they must be told", + "out": "the message is the task's own answer", + "questions": [ + { + "id": "communication", + "instructions": "Does a check in `checks` read a message the agent must send or say to a person, or list what that person must be told?", + "true": "A check reads a message the agent sends with a tool, such as an email or a notice, or lists the information the agent must tell the person in the conversation.", + "false": "The checks read only actions, the resulting state, or the task's own final answer." + } + ] + }, + "Execution": { + "family": "capabilities", + "definition": "Carries out what was asked in an environment, with tools used correctly", + "in": "the agent changes an environment over several tool steps, and the verifier reads the resulting state", + "out": "the verifier reads only an answer, even one in a file", + "questions": [ + { + "id": "execution", + "instructions": "Do the checks in `checks` read the state of a system that the agent changes through several tool actions?", + "true": "The checks list several tool actions that change records or settings, or assertions on the resulting state, and grading compares that state.", + "false": "The checks read only what the agent says or answers, and none of their actions changes a record or setting." + } + ] + }, + "Reasoning": { + "family": "capabilities", + "definition": "Derives a conclusion that none of the given facts states", + "in": "every needed fact is given or trivially fetched, and the expected answer is a value none of them states", + "out": "the answer is stated in a source (Retrieval); the hard part is finding or doing", + "questions": [ + { + "id": "reasoning", + "instructions": "Is a value that a check in `checks` expects one that no fact in `request` states, and that the agent must work out from the facts it is given?", + "true": "The agent has every fact it needs, and the expected value, such as a total, a date or the one option that fits, comes from combining or calculating them.", + "false": "The expected value is stated in the request or in a source the agent can read, or the hard part is finding the facts or carrying out steps." + } + ] + }, + "Abstention": { + "family": "capabilities", + "definition": "Says that a thing cannot be done or is not known, instead of inventing a result", + "in": "the task has no valid solution or answer, and passing needs the agent to say so", + "out": "acting would harm (Safety); the task is solvable", + "questions": [ + { + "id": "abstention", + "instructions": "Does a check in `checks` expect the agent to tell the person that what they ask for in `request` cannot be done or is not known?", + "true": "What the person asks for has no valid result, and a check passes only if the agent says so instead of producing a made-up result.", + "false": "What the person asks for can be done or answered, and the checks expect the agent to do it or give the answer; or the agent could do it but a check expects it to refuse because doing it would cause harm." + } + ] + }, + "Exactness": { + "family": "capabilities", + "definition": "Does every stated part of the request, each exactly once, with tools used correctly", + "in": "several stated parts, or a part whose effect must not repeat, and the checks read each part", + "out": "one part only; the parts are only steps toward one result (Execution)", + "questions": [ + { + "id": "exactness_parts", + "instructions": "Does the person in `request` ask for two or more separate outcomes, each with its own check in `checks`?", + "true": "The person asks for several distinct results, such as changes to two different items or a change and a separate piece of information, and the checks read each of them.", + "false": "The person asks for one result; the other actions in the checks are only steps needed to reach that one result." + }, + { + "id": "exactness_once", + "instructions": "Does `checks` hold an action that, done twice, would leave a result the checks reject?", + "true": "An action in the checks has an effect that adds up when repeated, such as a payment, an order, a booking or a transfer, so doing it a second time makes the checked result wrong.", + "false": "Every action in the checks only reads data, or sets a value that ends the same whether it is done once or twice." + } + ] + }, + "Travel": { + "family": "domains", + "definition": "Getting somewhere and staying there", + "in": "the errand plans, books, changes or recovers a journey", + "out": "the trip is only the occasion", + "questions": [ + { + "id": "travel", + "instructions": "Is the purpose of the errand in `request` to plan, book, change or recover a journey or a stay?", + "true": "The errand is about getting somewhere or staying there: booking or changing a flight, a train, a car or a hotel, or recovering from a delay or a cancellation.", + "false": "The errand is about something else, and a trip is only its occasion, such as buying gear or paying a bill while away." + } + ] + }, + "Dining": { + "family": "domains", + "definition": "Meals prepared by others, out or delivered", + "in": "the errand chooses, books or orders a meal", + "out": "groceries and goods (Shopping)", + "questions": [ + { + "id": "dining", + "instructions": "Is the purpose of the errand in `request` to choose, book or order a meal that others prepare?", + "true": "The errand picks a restaurant, books a table, or orders a meal for delivery or pickup.", + "false": "The errand buys groceries or other goods, or is about something else and food is only mentioned." + } + ] + }, + "Shopping": { + "family": "domains", + "definition": "Acquiring goods, and acting on recalls and safety notices", + "in": "the errand buys, returns or tracks a product", + "out": "the purchase belongs to another domain", + "questions": [ + { + "id": "shopping", + "instructions": "Is the purpose of the errand in `request` to buy, return, exchange or track a product, or to act on a product recall?", + "true": "The errand turns on goods: ordering an item, returning or exchanging it, following its delivery, or acting on a recall or a safety notice.", + "false": "The errand is about a service, a trip, a meal or an account, and any purchase only serves that other purpose." + } + ] + }, + "Money": { + "family": "domains", + "definition": "Money itself", + "in": "the hard part is an amount, an account or a payment", + "out": "paying is the last step of another errand", + "questions": [ + { + "id": "money", + "instructions": "Is the hardest part of the errand in `request` getting an amount, an account or a payment right?", + "true": "The errand turns on money itself: working out a charge or refund amount, managing a bank or billing account, or making or disputing a payment.", + "false": "The errand is about something else, such as a trip, a product or a service, and any payment is only its last step." + } + ] + }, + "Health": { + "family": "domains", + "definition": "The care of a person's or an animal's body or mind", + "in": "the errand serves someone's care", + "out": "the errand only surrounds care", + "questions": [ + { + "id": "health", + "instructions": "Is the purpose of the errand in `request` the care of a person's or an animal's body or mind?", + "true": "The errand serves someone's care, such as booking a doctor or a vet, managing a prescription, or carrying out a clinician's order.", + "false": "The errand only surrounds care, such as paying a clinic's bill or getting to an appointment, or has nothing to do with care." + } + ] + }, + "Home": { + "family": "domains", + "definition": "Keeping a household or family running", + "in": "the errand keeps a household or family running", + "out": "the errand has a domain of its own above", + "questions": [ + { + "id": "home", + "instructions": "Is the purpose of the errand in `request` to keep a household or a family running?", + "true": "The errand handles chores, repairs, utilities, a family's schedule or the upkeep of a home.", + "false": "The errand has a purpose beyond the household, such as booking a trip, buying a product or paying a bill, even when it is done for the family." + } + ] + }, + "Work": { + "family": "domains", + "definition": "Someone's job, business or studies, as such", + "in": "the errand serves a job, business or studies", + "out": "software work (Coding)", + "questions": [ + { + "id": "work", + "instructions": "Is the purpose of the errand in `request` someone's job, business or studies?", + "true": "The errand serves work or school: a task for an employer or a client, running a business, or a course assignment.", + "false": "The errand is personal, or the work is building or operating software." + } + ] + }, + "Coding": { + "family": "domains", + "definition": "Building or operating software", + "in": "what is graded is code, a repository, a build, or a system set up through a shell", + "out": "code is only a means to an answer", + "questions": [ + { + "id": "coding", + "instructions": "Is the purpose of the errand in `request` to build or operate software, so that what `checks` grade is code, a repository, a build or a system set up through a shell?", + "true": "A check runs tests on code the agent writes, inspects a repository or a build, or reads the state of a system the agent set up from a shell.", + "false": "The checks read only an answer, and any code the agent writes is only a way to reach it." + } + ] + } + } +} diff --git a/.agents/skills/label-benchmark/scripts/decide.py b/.agents/skills/label-benchmark/scripts/decide.py new file mode 100644 index 000000000..a2683fbcc --- /dev/null +++ b/.agents/skills/label-benchmark/scripts/decide.py @@ -0,0 +1,465 @@ +"""Ask decision models whether a benchmark task carries each axis, for /label-benchmark's second step. + + python3 decide.py TASKS.jsonl [--model A --model B [--model C]] [--max-calls N] [--decided FILE] [--dry-run] >> decisions.jsonl + python3 decide.py TASKS.jsonl [--model A --model B [--model C]] --decided FILE --results + python3 decide.py --list-models + +A line of TASKS is ``{"dataset", "task", "state": {"request": ..., "checks": ..., ...}}``, the state's fields any +JSON (STATE names them). Every axis of ``definitions.json`` is asked, but those the line lists in ``skip``, which +may be empty or left out; ``axes`` is refused. One request per task and model: the state as given, and every +question of every axis asked (a ``noul`` each), from ``definitions.json`` so every model gets the same ones. A model +says ``yes`` to an +axis when any of its questions is above YES_ABOVE, ``no`` when all are below NO_BELOW, else ``unsure``. A line out +per (task, axis): each model's answer and the probability of each question, then ``agreed`` (every model yes, or +every model no) or ``disagreement``. Without ``--model``, the MODELS are asked. A refused question is flagged by +its id, its text never kept. A reply that completed and does not read makes its model ``unsure`` on the task's axes +(``unreadable``); the other models are still asked. A task with a failed call gets no decision and its other models +are not asked. A call that answers gets a line of its own as it ends, ``{"dataset", "task", "model"}`` with its +``cost_usd`` when known and what the model said to each axis (``answers``, ``unsure`` and ``unreadable`` for a reply +that does not read), whether or not its task then gets a decision: summed over the lines kept, each once, ``cost_usd`` is the cost so far, also after a run +that was cut short. ``--decided`` names the file the run's output is appended to: a pair with a decision there, for +the same definitions, questions (``questions``, a digest of the axis's as sent and of the thresholds), set of models +and state, is not asked again (``reused``), and a model whose answers to a task are there, for the same definitions, +questions and state, is not called again for it (``kept``): after a failed call, only the models missing are asked. +Before a run appends, that file is ended at a whole line: a last line cut short is removed, and a dry run reads past +it. A whole line that is not JSON is refused by its number. A decision whose models' answers are missing or do not +give its result is not reused. ``--results`` sends nothing and needs no key: per pair of TASKS, the last decision +of the file for the current definitions, questions, state and set of models, or ``pending``. ``--max-calls`` is a +total over that file: the calls it already holds a line for (``calls_before``) count, and the whole tasks that fit in +the rest are picked in order, among those with a pair left to ask, before anything is printed or sent: with the same +``--decided``, models and cap, the dry run and the run cover the same ones. HTTP 429 is waited out: the call is sent +again after each of BACKOFF's seconds (``retries``), then fails. A run writes a line to stderr per task as it ends. +The last line of stderr counts tasks, pairs, calls, the characters of the requests as sent and their cost (a run's +alone: nothing prices a dry run), and lists the skipped tasks by status. ``--list-models`` prints OpenRouter's public decision models; no +key is sent. + +Standard library only, and nothing of Nullius: its settings and keys are never read. +The key is read from NULLIUS_LABEL_OPENROUTER_KEY alone, and sent to OpenRouter's two decision endpoints alone. +Every request asks providers not to keep data (``provider.data_collection``). Both endpoints were seen to accept +this request live: the object state and that field. What providers then keep cannot be checked from here. A task +they refuse is skipped and listed, and never sent again without the field. Only 401, 402, 403 and 404 (the key, its +credit, a refusal, an unknown model) stop the run. A message here never repeats an argument, a path or a reply. +Exit: 0 done, 2 usage, 3 no call answered, 4 partial (a call failed or did not read, or --max-calls stopped the run +or the dry run). +""" +import argparse +import hashlib +import http.client +import json +import os +import re +import sys +import time +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +# Fixed: no option, argument or variable changes them. TypeSafe's models, and the others SYSTEMONE names, are asked +# on `systemone`; another maker's on `decisions`. Both take the same request and give the same reply. +URLS = {"systemone": "https://openrouter.ai/api/v1/systemone", "decisions": "https://openrouter.ai/api/alpha/decisions"} +MODELS_URL = "https://openrouter.ai/api/v1/models?output_modalities=decisions" +SYSTEMONE = ("jaredpalmer/kev-4b",) +KEY_VAR = "NULLIUS_LABEL_OPENROUTER_KEY" +DENY = {"data_collection": "deny"} +YES_ABOVE, NO_BELOW = 0.7, 0.3 # TypeSafe's starting thresholds for a noul +STATE = ("request", "purpose", "notes", "ticket", "given", "checks", "policy") # the state's fields; `request` is required +MODELS = ("typesafe/jev-1.14", "perplexity/pplx-decider-v1.2", "liquid/d1.3-ultra") # three makers, when none is named +MODEL = re.compile(r"~?[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._:-]*") +TIMEOUT = 120 +BACKOFF = (2, 4, 8) # seconds before each new try of a call that got HTTP 429 +OK, USAGE, NETWORK, PARTIAL = 0, 2, 3, 4 +ANSWERS = ("yes", "no", "unsure") +NO_ANSWER, UNREADABLE = 0, 200 # a failed call's status when it is not an HTTP error +MAX_COST = 1e6 # a cost outside 0..this is no cost + + +class Failed(Exception): + """A call that gave no answers, by its status alone: a reply's body is never kept, it may hold task text.""" + + def __init__(self, status): + super().__init__(status) + self.status = status + + def __str__(self): + return {NO_ANSWER: "no answer", UNREADABLE: "an error or an unreadable reply in an HTTP 200"}.get( + self.status, f"HTTP {self.status}") + + @property + def stops(self): # the key, its credit, a refusal or the model: + return self.status in (401, 402, 403, 404) # no later call would pass; any other failure skips the task + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): # a redirect would carry the key to another address + return None + + +def definitions(): + with open(os.path.join(HERE, "..", "definitions.json"), encoding="utf-8") as fh: + return json.load(fh) + + +def url_of(model): + typesafe = "typesafe/" in model or model.startswith("jev") or model in SYSTEMONE + return URLS["systemone" if typesafe else "decisions"] + + +def questions(defs, axes): + """Every question of these axes, by its id: ids are unique in definitions.json, so each maps back to its axis.""" + return {q["id"]: {"type": "noul", "instructions": q["instructions"], "criteria": {"true": q["true"], "false": q["false"]}} + for name in axes for q in defs["axes"][name]["questions"]} + + +def combine(said): + """One model on one axis, from what it said to each of the axis's questions: yes if any is, no if all are.""" + answers = [s["answer"] for s in said.values()] + return "yes" if "yes" in answers else "no" if answers and set(answers) == {"no"} else "unsure" + + +def request(defs, task, model): + """One request, as the bytes sent: what is counted is what leaves.""" + return json.dumps({"model": model, "state": task["state"], "questions": questions(defs, task["axes"]), + "provider": DENY}).encode() + + +def call(url, raw, key): + """One request: (answers by question, or None for a reply that completed and does not read; cost or None). + A reply that did not complete, an HTTP error or an error envelope raises Failed.""" + req = urllib.request.Request(url, raw, method="POST", headers={ + "Authorization": "Bearer " + key, "Content-Type": "application/json", "Accept": "application/json"}) + try: + with urllib.request.build_opener(_NoRedirect).open(req, timeout=TIMEOUT) as resp: + text = resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError as exc: + exc.close() + raise Failed(exc.code) from None + except (OSError, http.client.HTTPException): + raise Failed(NO_ANSWER) from None + try: + data = json.loads(text) + except (ValueError, RecursionError): + return None, None + if not isinstance(data, dict): + return None, None + if data.get("error"): # an error envelope in a 200 is no answer + code = data["error"].get("code") if isinstance(data["error"], dict) else None + raise Failed(code if isinstance(code, int) and not isinstance(code, bool) and 400 <= code < 600 else UNREADABLE) + usage = data.get("usage") + cost = usage.get("cost") if isinstance(usage, dict) else None # read apart from the answers: it is optional + usable = isinstance(cost, (int, float)) and not isinstance(cost, bool) and 0 <= cost <= MAX_COST # never NaN + return data["answers"] if isinstance(data.get("answers"), dict) else None, cost if usable else None + + +def ask(url, raw, key, count): + """A call, sent again after each of BACKOFF's waits while the endpoint says 429: a rate limit, not a refusal.""" + for wait in (*BACKOFF, None): + try: + return call(url, raw, key) + except Failed as exc: + if exc.status != 429 or wait is None: + raise + count["retries"] += 1 + time.sleep(wait) + + +def read(answer): + """One model on one question: its probability and what it reads as. A refusal (flagged, its text never kept), an + answer of another type, or anything but a probability, is unsure.""" + if isinstance(answer, dict) and (answer.get("type") == "refusal" or answer.get("refusal")): + return {"answer": "unsure", "refused": True} + p = answer.get("noul") if isinstance(answer, dict) and answer.get("type", "noul") == "noul" else None + if isinstance(p, bool) or not isinstance(p, (int, float)) or not 0 <= p <= 1: + return {"answer": "unsure"} + return {"answer": "yes" if p > YES_ABOVE else "no" if p < NO_BELOW else "unsure", "p": p} + + +def digest(state): + """What tells one state from another in a decision, with nothing of the state in it.""" + return hashlib.sha256(json.dumps(state, sort_keys=True).encode()).hexdigest()[:16] + + +def fingerprint(defs, axis): + """What an axis's answer is read from, beside the state: its questions as sent, and the thresholds.""" + return hashlib.sha256(json.dumps([questions(defs, [axis]), YES_ABOVE, NO_BELOW], sort_keys=True).encode()).hexdigest()[:16] + + +def result_of(models): + """A pair's result from what each model said: agreed when every model says yes, or every model no.""" + return "agreed" if {m["answer"] for m in models.values()} in ({"yes"}, {"no"}) else "disagreement" + + +def end_at_a_line(path): + """Before a run appends to the file: a last line cut short is removed, a whole one gets its newline.""" + with open(path, "r+b") as fh: + data = fh.read() + if not data or data.endswith(b"\n"): + return + start = data.rfind(b"\n") + 1 + try: + json.loads(data[start:]) + fh.write(b"\n") + except (ValueError, RecursionError): + fh.truncate(start) + + +def read_decided(path, defs, models): + """The last decision of each (dataset, task, axis, state digest) an earlier run made with these definitions, + questions and models, in any order; what each model said to a (dataset, task, state digest), by axis, for these + definitions and questions; and how many calls the file holds a line for. Read as bytes, a line at a time: a last + line cut short, even inside a character, is nothing; a whole line that is not JSON is a ValueError by its number.""" + decided, kept, calls, prints = {}, {}, 0, {axis: fingerprint(defs, axis) for axis in defs["axes"]} + with open(path, "rb") as fh: + for n, raw in enumerate(fh, 1): + if not raw.strip(): + continue + try: + d = json.loads(raw) + except (ValueError, RecursionError): + if raw.endswith(b"\n"): + raise ValueError(f"the decided file, line {n}: not JSON. Repair or remove that line") from None + continue # an append cut short: the run removes it before it appends + if isinstance(d, dict) and isinstance(d.get("model"), str): # a call's own line + calls += 1 + said, asked = d.get("answers"), d.get("questions") + if d.get("definitions") == defs["version"] and isinstance(said, dict) and isinstance(asked, dict) \ + and all(isinstance(d.get(k), str) for k in ("dataset", "task", "state")): + kept.setdefault((d["dataset"], d["task"], d["state"], d["model"]), {}).update( + {a: s for a, s in said.items() if a in prints and asked.get(a) == prints[a] + and isinstance(s, dict) and s.get("answer") in ANSWERS}) + continue + said = d.get("models") if isinstance(d, dict) else None + if isinstance(said, dict) and d.get("definitions") == defs["version"] and set(said) == set(models) \ + and all(isinstance(s, dict) and s.get("answer") in ANSWERS for s in said.values()) \ + and d.get("result") == result_of(said) \ + and all(isinstance(d.get(k), str) for k in ("dataset", "task", "axis", "state", "questions")) \ + and d["questions"] == prints.get(d["axis"]): + decided[d["dataset"], d["task"], d["axis"], d["state"]] = d + return decided, kept, calls + + +def read_tasks(path, defs): + """The tasks, each with the axes to ask, or a ValueError that names a line and never repeats what it holds.""" + tasks, seen = [], {} + with open(path, encoding="utf-8") as fh: + for n, line in enumerate(fh, 1): + if not line.strip(): + continue + try: + task = json.loads(line) + except (ValueError, RecursionError): + task = None + where = f"tasks file, line {n}" + if not isinstance(task, dict) or not all(isinstance(task.get(k), str) and task[k] for k in ("dataset", "task")): + raise ValueError(f"{where}: needs dataset and task, each a string, and state") + if seen.setdefault((task["dataset"], task["task"]), n) != n: + raise ValueError(f"{where}: the dataset and task of line {seen[task['dataset'], task['task']]} again") + state = task.get("state") + if "axes" in task: + raise ValueError(f"{where}: axes is not read: every axis is asked. Remove it, and list in skip the axes " + "step 1 gave this task") + named = task.get("skip", []) + if not isinstance(named, list) or not all(isinstance(a, str) for a in named) or len(set(named)) != len(named): + raise ValueError(f"{where}: skip is a list of different axes") + for i, axis in enumerate(named): + if axis not in defs["axes"]: + raise ValueError(f"{where}: skip[{i}] is no axis of definitions.json: report it as a proposal, never label it") + task["axes"] = [a for a in defs["axes"] if a not in named] + if not task["axes"]: + raise ValueError(f"{where}: skip leaves no axis to ask: leave the task out") + if not isinstance(state, dict) or state.get("request") in (None, "", [], {}) or set(state) - set(STATE) \ + or any(v is None for v in state.values()): + raise ValueError(f"{where}: state holds request, never empty, and {', '.join(STATE[1:])} when there are any, none null") + tasks.append(task) + return tasks + + +def list_models(out, err): + """OpenRouter's decision models by id, from its public list: no key sent, no redirect followed.""" + req = urllib.request.Request(MODELS_URL, headers={"Accept": "application/json"}) + try: + with urllib.request.build_opener(_NoRedirect).open(req, timeout=TIMEOUT) as resp: + rows = json.loads(resp.read().decode("utf-8", "replace"))["data"] + models = sorted(r["id"] for r in rows if "decisions" in r["architecture"]["output_modalities"]) + except urllib.error.HTTPError as exc: + exc.close() + print(f"HTTP {exc.code}", file=err) # its status alone + return NETWORK + except (OSError, http.client.HTTPException): + print("no answer", file=err) + return NETWORK + except (ValueError, KeyError, TypeError, RecursionError): + models = [] + for model in models: + print(model, file=out) + if not models: + print("no decision model in the list", file=err) + return OK if models else NETWORK + + +class _Parser(argparse.ArgumentParser): + def error(self, message): # argparse's own message repeats the argument: never shown + raise argparse.ArgumentError(None, "") + + +def main(argv=None, out=None, err=None): + out, err = out or sys.stdout, err or sys.stderr + + def usage(message): # ours alone: no argument, path or file content in it + print(f"decide.py: {message}", file=err) + raise SystemExit(USAGE) + + ap = _Parser(description=__doc__.split("\n")[0], allow_abbrev=False, exit_on_error=False) + ap.add_argument("tasks", nargs="?", help="JSON lines: dataset, task, state, and skip") + ap.add_argument("--model", action="append", default=[], help="an OpenRouter decision model id; give 2 or 3, " + "else " + ", ".join(MODELS)) + ap.add_argument("--max-calls", help="send only the whole tasks that fit in this many calls, those the " + "--decided file already holds counted") + ap.add_argument("--decided", help="the file the output is appended to: a pair it holds is not asked again") + ap.add_argument("--dry-run", action="store_true", help="print the requests, without the key; send nothing") + ap.add_argument("--results", action="store_true", help="print each pair's current decision in --decided, or pending; send nothing") + ap.add_argument("--list-models", action="store_true", help="print OpenRouter's decision models; no key is sent") + try: + args, unknown = ap.parse_known_args(argv) + except argparse.ArgumentError as exc: # the option's name at most, never what came with it + name = exc.argument_name if exc.argument_name in ("--model", "--max-calls", "--decided", "--dry-run", "--results", "--list-models") else None + usage(f"{name or 'the arguments'}: not usable as given; see --help") + if unknown: # never repeated: one may be a key given by mistake + usage(f"{len(unknown)} unknown argument(s); the key is read from {KEY_VAR} alone") + if args.list_models: + if args.dry_run or args.results or args.tasks or args.model or args.max_calls is not None or args.decided is not None: + usage("--list-models goes alone: it asks OpenRouter for its list") + return list_models(out, err) + args.model = args.model or list(MODELS) + if not 2 <= len(args.model) <= 3 or len(set(args.model)) != len(args.model) \ + or not all(MODEL.fullmatch(m) for m in args.model): + usage("give two or three different --model, each MAKER/NAME") + if args.max_calls is not None and not (args.max_calls.isascii() and args.max_calls.isdigit()): + usage("--max-calls takes a whole number") + cap = None if args.max_calls is None else int(args.max_calls) + if not args.tasks: + usage("give the tasks file") + if args.results and (args.decided is None or args.dry_run or cap is not None): + usage("--results takes the tasks file, --decided and the run's --model, nothing else") + defs = definitions() + try: + tasks = read_tasks(args.tasks, defs) + except (OSError, UnicodeError) as exc: # the kind of error alone: the path may be a key by mistake + usage(f"the tasks file cannot be read ({type(exc).__name__})") + except ValueError as exc: + usage(str(exc)) + version, costs, prints = defs["version"], [], {axis: fingerprint(defs, axis) for axis in defs["axes"]} + try: + if args.decided is not None and not (args.dry_run or args.results): + end_at_a_line(args.decided) + decided, kept, before = read_decided(args.decided, defs, args.model) if args.decided is not None else ({}, {}, 0) + except (OSError, UnicodeEncodeError) as exc: + usage(f"the decided file cannot be read ({type(exc).__name__})") + except ValueError as exc: + usage(str(exc)) + if args.results: # what the journal now says of each pair, for these models + for task in tasks: + pair = {"dataset": task["dataset"], "task": task["task"]} + for axis in task["axes"]: + line = decided.get((*pair.values(), axis, digest(task["state"]))) or {**pair, "axis": axis, "result": "pending"} + print(json.dumps(line, ensure_ascii=False), file=out) + return OK + key = "" if args.dry_run else os.environ.get(KEY_VAR, "") + if not args.dry_run and not key: + usage(f"set {KEY_VAR} in the environment before starting; it is read from nowhere else") + + count = {"definitions": version, "models": args.model, "tasks": 0, "pairs": 0, "reused": 0, "agreed": 0, + "disagreement": 0, "calls": 0, "calls_before": before, "kept": 0, "retries": 0, "chars": 0, "failed": 0, "unreadable": 0, "cost_usd": 0, "calls_with_cost": 0, "stopped": None, + "skipped": []} + # The whole tasks that fit the cap, picked once: what the dry run shows is what the run may send, whatever fails. + for task in tasks: # a pair decided before is not asked again + task["digest"] = digest(task["state"]) + left = [a for a in task["axes"] if (task["dataset"], task["task"], a, task["digest"]) not in decided] + count["reused"] += len(task["axes"]) - len(left) + task["axes"] = left + said = {m: kept.get((task["dataset"], task["task"], task["digest"], m), {}) for m in args.model} + task["kept"] = {m: s for m, s in said.items() if all(a in s for a in left)} # a model that answered them all + tasks = [task for task in tasks if task["axes"]] + fit, room = 0, None if cap is None else max(0, cap - before) # the cap is a total over the file + for task in tasks: + need = len(args.model) - len(task["kept"]) + if room is not None and need > room: + count["stopped"] = "max-calls" + break + fit, room = fit + 1, room if room is None else room - need + for n, task in enumerate(tasks[:fit], 1): + said, failed = {axis: {} for axis in task["axes"]}, None + for model in args.model: + if model in task["kept"]: # it answered before its task failed: not called again + count["kept"] += 1 + for axis in task["axes"]: + said[axis][model] = task["kept"][model][axis] + continue + url, raw = url_of(model), request(defs, task, model) + count["calls"] += 1 # the calls attempted, or shown + count["chars"] += len(raw.decode()) + if args.dry_run: + print(json.dumps({"definitions": version, "url": url, "headers": {"Authorization": "Bearer [REDACTED]"}, + "body": json.loads(raw)}, ensure_ascii=False), file=out) + continue + try: + answers, cost = ask(url, raw, key, count) + except Failed as exc: # the task stays unsure: its other models are not asked + failed = exc + count["failed"] += 1 + break + if cost is not None: + costs.append(cost) + if answers is None: # it answered, and nothing reads: unsure, the others are asked + count["unreadable"] += 1 + for axis in task["axes"]: + asked = {q["id"]: read((answers or {}).get(q["id"])) for q in defs["axes"][axis]["questions"]} + said[axis][model] = {"answer": combine(asked), "p": {qid: s.get("p") for qid, s in asked.items()}} + refused = [qid for qid, s in asked.items() if s.get("refused")] + if refused: # which questions, never the refusal's text: it may quote the task + said[axis][model]["refused"] = refused + if answers is None: + said[axis][model]["unreadable"] = True + line = {"dataset": task["dataset"], "task": task["task"], "model": model} + if cost is not None: + line["cost_usd"] = cost + line.update(definitions=version, state=task["digest"], questions={a: prints[a] for a in task["axes"]}, + answers={a: said[a][model] for a in task["axes"]}) # for a later run: its task may get no decision + print(json.dumps(line, ensure_ascii=False), file=out, flush=True) # journalled now, a line per answered call + if failed and failed.stops: + count["stopped"] = f"{failed} from {model}, dataset {task['dataset']}, task {task['task']}" + break + if not args.dry_run: # progress: a line per task, never its text + print(f"{n}/{fit} {task['dataset']} {task['task']}: " + (f"skipped, {failed}" if failed else + f"{len(task['axes'])} pairs"), file=err, flush=True) + if failed: # its status alone: a body may hold task text + count["skipped"].append({"dataset": task["dataset"], "task": task["task"], "model": model, + "status": failed.status}) + continue + count["tasks"] += 1 + count["pairs"] += len(task["axes"]) + if args.dry_run: + continue + for axis, models in said.items(): + result = result_of(models) + count[result] += 1 + line = {"definitions": version, "dataset": task["dataset"], "task": task["task"], "axis": axis, + "state": task["digest"], "questions": prints[axis], "models": models, "result": result} + if result == "agreed": + line["answer"] = next(iter(models.values()))["answer"] + print(json.dumps(line, ensure_ascii=False), file=out, flush=True) + count["cost_usd"], count["calls_with_cost"] = round(sum(costs), 6), len(costs) + if any(s["status"] in (400, 422) for s in count["skipped"]): + print("HTTP 400 or 422: the endpoint may have refused the field that asks providers not to keep data " + "(provider.data_collection: deny). It is never sent without that.", file=err) + if args.dry_run: # nothing was priced: the characters are its size + del count["cost_usd"], count["calls_with_cost"] + print(json.dumps(count, allow_nan=False), file=err) + if args.dry_run: + return PARTIAL if count["stopped"] else OK + if count["calls"] and count["failed"] == count["calls"]: + return NETWORK + return PARTIAL if count["failed"] or count["unreadable"] or count["stopped"] else OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/AGENTS.md b/AGENTS.md index eae7003c3..95d77197b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,6 +174,7 @@ Short and plain: issues, pull requests, their comments, docs. | Judgement; the PR judge | `docs/judgement.md`; docstring of `.github/scripts/judge_pr.py` | | A run that looks wrong, comparing runs | `/run-analysis` | | Tasks that may be flawed or ambiguous | `/flag-tasks` | +| A benchmark's Leaderboard labels | `/label-benchmark` | | Stale docs | `/docs-drift` | | The website; a release | `app/site/README.md`; `app/packaging/README.md` | | This machine | `.claude/environment.local.md`, if present | diff --git a/app/tests/test_label_benchmark_skill.py b/app/tests/test_label_benchmark_skill.py new file mode 100644 index 000000000..ab250edd8 --- /dev/null +++ b/app/tests/test_label_benchmark_skill.py @@ -0,0 +1,621 @@ +"""The /label-benchmark skill's script: where its key goes, what it sends, and how it reads a reply.""" + +import contextlib +import importlib.util +import io +import json +import os +import re +import shutil +import tempfile +import threading +import unittest +import warnings +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from unittest import mock + +from nullius.leaderboard import labels +from nullius.standard.contract import definitions + +SKILL = Path(__file__).resolve().parents[2] / ".agents/skills/label-benchmark" +SCRIPT = SKILL / "scripts/decide.py" +spec = importlib.util.spec_from_file_location("label_benchmark_script", SCRIPT) +script = importlib.util.module_from_spec(spec) +spec.loader.exec_module(script) + +KEY = "sk-or-v1-0123456789abcdef" +DECOY = "sk-or-v1-the-evaluation-key" +JEV, YES, NO, NO2, MID = "typesafe/jev-1.14", "acme/yes", "acme/no", "~acme/no-latest", "acme/mid" +P = {JEV: 0.9, YES: 0.71, NO: 0.1, NO2: 0.29, MID: 0.7, # 0.7 itself is not above the threshold + "acme/busy": 0.9, **{m: 0.9 for m in script.MODELS}} +ONE = {"safety_withhold": 0.9, "execution": 0.5} # acme/one: 0.1 to every other question +STATUS = {"acme/denied": 401, "acme/strict": 422, "acme/down": 500} +USAGE = {"input_tokens": 9, "output_tokens": 0, "cost": 0.00000049} + + +class Fake(BaseHTTPRequestHandler): + seen, sizes, busy = [], [], 0 # busy: how many calls to acme/busy still get a 429 + + def reply(self, status, body, length=None): + body = body if isinstance(body, bytes) else json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Length", str(length or len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self): + raw = self.rfile.read(int(self.headers["Content-Length"])) + body = json.loads(raw) + model = body["model"] + Fake.sizes.append(len(raw.decode())) + Fake.seen.append((self.path, self.headers["Authorization"], body)) + if model in STATUS: + return self.reply(STATUS[model], {"error": {"message": f"bad key {KEY} for TASK TEXT"}}) + if model == "acme/busy" and Fake.busy: + Fake.busy -= 1 + return self.reply(429, {"error": {"message": "TASK TEXT"}}) + if model == "acme/moved": + self.send_response(302) + self.send_header("Location", f"http://127.0.0.1:{self.server.server_port}/elsewhere") + return self.end_headers() + if model == "acme/envelope": + return self.reply(200, {"error": {"code": 402, "message": "credit exhausted"}}) + if model == "acme/cut": + return self.reply(200, b'{"answers"', length=500) + if model == "acme/blank": # completed and charged, no answers in it + return self.reply(200, {"usage": {"cost": 0.125}}) + if model == "acme/prose": + return self.reply(200, b"I think so") + if model in ("acme/usage", "acme/nan"): # the answers read, the cost does not + usage = "unavailable" if model == "acme/usage" else {"cost": float("nan")} + return self.reply(200, {"answers": {a: {"noul": 0.9} for a in body["questions"]}, "usage": usage}) + if model == "acme/choice": # another type, with a stray probability + return self.reply(200, {"answers": {a: {"type": "choice", "noul": 0.9} for a in body["questions"]}}) + if model == "acme/odd": # one answer no probability, one refused, echoing key and task + return self.reply(200, {"answers": {"execution": {"noul": 7}, "safety_decline": { + "type": "refusal", "refusal": f"no\n evidence {KEY} in TASK TEXT"}}}) + if model == "acme/one": + return self.reply(200, {"answers": {q: {"noul": ONE.get(q, 0.1)} for q in body["questions"]}}) + if self.path == "/systemone": # TypeSafe's shape + answers = {a: {"type": "noul", "noul": P[model]} for a in body["questions"]} + else: # OpenRouter's decisions: a confidence beside it + answers = {a: {"noul": P[model], "confidence": 0.8} for a in body["questions"]} + self.reply(200, {"model": model, "answers": answers, "usage": USAGE}) + + def do_GET(self): + Fake.seen.append((self.path, self.headers["Authorization"], None)) + if self.path != "/models": + return self.reply(503, {"error": {"message": "TASK TEXT"}}) + self.reply(200, {"data": [{"id": "b/decides", "architecture": {"output_modalities": ["decisions"]}}, + {"id": "a/decides", "architecture": {"output_modalities": ["text", "decisions"]}}, + {"id": "c/chats", "architecture": {"output_modalities": ["text"]}}]}) + + def log_message(self, *args): + pass + + +class Decide(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = HTTPServer(("127.0.0.1", 0), Fake) + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + cls.addClassCleanup(cls.server.server_close) + cls.addClassCleanup(cls.server.shutdown) + + def setUp(self): + Fake.seen.clear() + Fake.sizes.clear() + tmp = tempfile.TemporaryDirectory(prefix="nullius-label-benchmark-") + self.addCleanup(tmp.cleanup) + self.tasks = Path(tmp.name) / "tasks.jsonl" + self.write(["Execution", "Safety"], ["Travel"]) + + def write(self, *axes, **state): # each task asked these axes alone + every = script.definitions()["axes"] + self.tasks.write_text("".join(json.dumps({"dataset": "d", "task": str(n), "skip": [x for x in every if x not in a], + "state": {"request": "TASK TEXT", "checks": {"expected": "CHECKS"}, **state}}) + "\n" + for n, a in enumerate(axes))) + + def run_script(self, *models, argv=(), key=KEY, tasks=True, listing="/models"): + out, err = io.StringIO(), io.StringIO() + here = f"http://127.0.0.1:{self.server.server_port}" + # another key and a Decision setting in the shell: neither is read + env = {"OPENROUTER_API_KEY": DECOY, "DECISION_PROTOCOL": "decisions", **({script.KEY_VAR: key} if key else {})} + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.dict(script.URLS, {"systemone": here + "/systemone", "decisions": here + "/decisions"}), \ + mock.patch.object(script, "MODELS_URL", here + listing), mock.patch("sys.stderr", err): + try: + code = script.main([*([str(self.tasks)] if tasks else []), *(a for m in models for a in ("--model", m)), *argv], out, err) + except SystemExit as exc: + code = exc.code + self.assertNotIn(KEY, out.getvalue() + err.getvalue()) + self.assertNotIn("TASK TEXT", err.getvalue()) + if "--dry-run" not in argv: # a decision never quotes the task + self.assertNotIn("TASK TEXT", out.getvalue()) + self.assertNotIn(DECOY, json.dumps(Fake.seen)) + self.raw = out.getvalue() + lines = [json.loads(line) for line in self.raw.splitlines() if line.startswith("{")] + self.costs = [line for line in lines if "model" in line] # a line per answered call, apart + return code, [line for line in lines if "model" not in line] if lines else self.raw.split(), err.getvalue() + + def test_one_request_per_task_and_model_read_by_the_thresholds(self): + code, lines, err = self.run_script(JEV, YES) + count, costs = json.loads(err.splitlines()[-1]), self.costs + self.assertEqual((code, len(Fake.seen)), (script.OK, 4)) # 2 tasks, 2 models: the axes are bundled + self.assertEqual([path for path, _, _ in Fake.seen[:2]], ["/systemone", "/decisions"]) + _, auth, body = Fake.seen[0] + self.assertEqual(auth, "Bearer " + KEY) + self.assertEqual(body["provider"], {"data_collection": "deny"}) + self.assertEqual(body["state"], {"request": "TASK TEXT", "checks": {"expected": "CHECKS"}}) + safety = [q["id"] for q in script.definitions()["axes"]["Safety"]["questions"]] + self.assertEqual((list(body["questions"]), body["questions"]["execution"]["type"]), ([*safety, "execution"], "noul")) + asked = script.definitions()["axes"]["Execution"]["questions"][0] + self.assertEqual(body["questions"]["execution"]["criteria"], {"true": asked["true"], "false": asked["false"]}) + self.assertEqual([(line["axis"], line["result"], line.get("answer"), line["definitions"]) for line in lines], + [(a, "agreed", "yes", script.definitions()["version"]) for a in ("Safety", "Execution", "Travel")]) + self.assertEqual(lines[0]["state"], script.digest({"request": "TASK TEXT", "checks": {"expected": "CHECKS"}})) + self.assertEqual(lines[1]["models"], {JEV: {"answer": "yes", "p": {"execution": 0.9}}, + YES: {"answer": "yes", "p": {"execution": 0.71}}}) + self.assertEqual((count["tasks"], count["pairs"], count["calls"], count["failed"]), (2, 3, 4, 0)) + self.assertEqual((count["cost_usd"], count["calls_with_cost"]), (0.000002, 4)) # summed, then rounded once + self.assertEqual([(c["task"], c["model"], c["cost_usd"]) for c in costs], # a line per answered call + [(t, m, 0.00000049) for t in "01" for m in (JEV, YES)]) + + results = lambda *models: [(line["result"], line.get("answer")) for line in self.run_script(*models)[1]] + self.assertEqual(results(NO, NO2), [("agreed", "no")] * 3) + self.assertEqual(results(JEV, NO), [("disagreement", None)] * 3) + self.assertEqual(results(JEV, YES, MID), [("disagreement", None)] * 3) # one unsure model: left unlabelled + self.assertEqual(script.read({"noul": 0.29}), {"answer": "no", "p": 0.29}) + self.assertEqual(script.read({"noul": 0.3}), {"answer": "unsure", "p": 0.3}) + self.assertEqual(script.read({"type": "noul", "noul": 0.9}), {"answer": "yes", "p": 0.9}) + for odd in (None, "yes", {"answer": "yes"}, {"noul": True}, {"noul": "0.9"}, {"noul": 1.5}, {"noul": float("nan")}, + {"type": "choice", "noul": 0.9}, {"type": None, "noul": 0.9}): # another type confers nothing + self.assertEqual(script.read(odd), {"answer": "unsure"}) # no probability, no decision + + code, lines, _ = self.run_script(JEV, "acme/odd") + self.assertEqual(code, script.OK) + self.assertEqual(lines[1]["models"]["acme/odd"], {"answer": "unsure", "p": {"execution": None}}) + self.assertEqual(lines[0]["models"]["acme/odd"], {"answer": "unsure", "p": dict.fromkeys(safety), + "refused": ["safety_decline"]}) # its id, never its text + self.assertEqual([line["result"] for line in self.run_script("acme/choice", YES)[1]], ["disagreement"] * 3) + + def test_an_axis_is_yes_on_any_question_no_on_all(self): + code, lines, _ = self.run_script("acme/one", NO) + self.assertEqual(code, script.OK) + said = {line["axis"]: line["models"]["acme/one"] for line in lines} + self.assertEqual({axis: s["answer"] for axis, s in said.items()}, # one yes among three; 0.5; all 0.1 + {"Safety": "yes", "Execution": "unsure", "Travel": "no"}) + self.assertEqual(said["Safety"]["p"], {"safety_decline": 0.1, "safety_withhold": 0.9, "safety_confirm": 0.1}) + for axis, body in script.definitions()["axes"].items(): # every id maps back to one axis + self.assertTrue(all(q["id"].startswith(axis.lower()) for q in body["questions"]) and body["questions"], axis) + + def test_without_a_model_the_defaults_are_asked(self): + code, lines, _ = self.run_script() + self.assertEqual(code, script.OK) + self.assertEqual([body["model"] for _, _, body in Fake.seen], [*script.MODELS] * 2) + self.assertEqual(list(lines[0]["models"]), list(script.MODELS)) + + def test_the_cap_stops_before_a_task_and_says_so(self): + code, lines, err = self.run_script(JEV, YES, argv=["--max-calls", "3"]) + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, len(lines), len(Fake.seen)), (script.PARTIAL, 2, 2)) + self.assertEqual((count["calls"], count["stopped"], count["tasks"]), (2, "max-calls", 1)) + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=["--max-calls", "3", "--dry-run"], key="") + self.assertEqual((code, len(lines), Fake.seen), (script.PARTIAL, 2, [])) # a capped preview is not a whole one + shown = [line["body"] for line in lines] + + code, lines, err = self.run_script("acme/strict", JEV, argv=["--max-calls", "3"]) # its first call refused: + count = json.loads(err.splitlines()[-1]) # the calls left never go to a task not shown + self.assertEqual((code, lines, count["calls"], count["stopped"]), (script.NETWORK, [], 1, "max-calls")) + self.assertEqual([list(body["questions"]) for _, _, body in Fake.seen], [list(shown[0]["questions"])]) + self.assertNotIn("travel", json.dumps([body["questions"] for _, _, body in Fake.seen])) + + def test_the_key_comes_from_its_variable_alone_and_goes_nowhere_else(self): + code, lines, err = self.run_script(JEV, YES, key="") + self.assertEqual((code, lines, Fake.seen), (script.USAGE, [], [])) # another key in the shell is not used + self.assertIn(script.KEY_VAR, err) + for argv in (["--key", KEY], ["--base-url", KEY], [f"--key={KEY}"], ["--max-calls", KEY], ["--mod", KEY]): + self.assertEqual(self.run_script(JEV, YES, argv=argv)[0], script.USAGE) # and never repeated: run_script + for models in ((JEV,), (JEV, JEV), (JEV, YES, NO, MID), (JEV, KEY)): + self.assertEqual(self.run_script(*models)[0], script.USAGE) + for argv in ([f"--dry-run={KEY}"], [f"--list-models={KEY}"], [KEY]): # a key where a flag or the file goes + code, lines, err = self.run_script(JEV, YES, argv=argv, tasks=False) + self.assertEqual((code, lines), (script.USAGE, []), argv) + self.assertIn("FileNotFoundError", err) # the kind of error, never the path + self.assertIn("--dry-run", self.run_script(JEV, YES, argv=[f"--dry-run={KEY}"])[2]) + self.assertEqual(Fake.seen, []) + + code, lines, err = self.run_script(JEV, YES, argv=["--dry-run"], key="") + self.assertEqual((code, len(lines), Fake.seen), (script.OK, 4, [])) + self.assertEqual(lines[0]["headers"], {"Authorization": "Bearer [REDACTED]"}) + self.assertEqual([line["url"].rpartition("/")[2] for line in lines[:2]], ["systemone", "decisions"]) + self.assertEqual((script.URLS["systemone"], script.URLS["decisions"], script.url_of("jaredpalmer/kev-4b")), + ("https://openrouter.ai/api/v1/systemone", "https://openrouter.ai/api/alpha/decisions", script.URLS["systemone"])) + self.assertEqual((lines[0]["body"]["provider"], lines[0]["definitions"]), ({"data_collection": "deny"}, script.definitions()["version"])) + count = json.loads(err.splitlines()[-1]) + sent = sum(len(json.dumps(line["body"], ensure_ascii=False)) for line in lines) + self.assertEqual((count["tasks"], count["pairs"], count["calls"], count["chars"]), (2, 3, 4, sent)) + + code, lines, err = self.run_script("acme/denied", JEV) + self.assertEqual((code, lines, len(Fake.seen)), (script.NETWORK, [], 1)) # a refused key stops the run + self.assertIn("HTTP 401", err) # its status, never its body: run_script + + Fake.seen.clear() + code, lines, _ = self.run_script("acme/moved", JEV) + self.assertEqual((code, lines, len(Fake.seen)), (script.NETWORK, [], 2)) # no redirect followed with the key + + Fake.seen.clear() + code, lines, _ = self.run_script(argv=["--list-models"], key="", tasks=False) + self.assertEqual((code, lines, Fake.seen), (script.OK, ["a/decides", "b/decides"], [("/models", None, None)])) + + Fake.seen.clear() # a dry run opens no connection + code, lines, _ = self.run_script(argv=["--list-models", "--dry-run"], key="", tasks=False) + self.assertEqual((code, lines, Fake.seen), (script.USAGE, [], [])) + code, lines, err = self.run_script(argv=["--list-models"], key="", tasks=False, listing="/gone") + self.assertEqual((code, lines, err), (script.NETWORK, [], "HTTP 503\n")) # its status alone + + def test_a_call_that_gives_no_answers_is_a_failed_call(self): + code, lines, err = self.run_script(JEV, "acme/envelope") # a 402 in a 200 stops the run + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines, len(Fake.seen)), (script.PARTIAL, [], 2)) + self.assertEqual((count["failed"], count["agreed"], count["disagreement"]), (1, 0, 0)) + self.assertIn("acme/envelope", count["stopped"]) + + Fake.seen.clear() + code, lines, err = self.run_script(JEV, "acme/strict") # a refused task is skipped, the run goes on + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines, len(Fake.seen)), (script.PARTIAL, [], 4)) + self.assertEqual((count["failed"], count["stopped"]), (2, None)) + self.assertEqual(count["skipped"], [{"dataset": "d", "task": t, "model": "acme/strict", "status": 422} for t in "01"]) + self.assertEqual(err.count("data_collection"), 1) # the 422 says what it may have refused, once + self.assertTrue(all("provider" in body for _, _, body in Fake.seen)) # and nothing was sent without it + + for model in ("acme/cut", "acme/down"): # the batch goes on to its summary + Fake.seen.clear() + code, lines, err = self.run_script(JEV, model, YES) + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines), (script.PARTIAL, []), model) + self.assertEqual((count["calls"], count["failed"], count["stopped"]), (4, 2, None), model) + self.assertNotIn(YES, [body["model"] for _, _, body in Fake.seen]) # a task already unsure costs no more + + def test_a_reply_that_does_not_read_is_unsure_and_a_cost_that_does_not_is_no_cost(self): + code, lines, err = self.run_script("acme/prose", JEV, YES) # a completed 200, not JSON + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, len(Fake.seen)), (script.PARTIAL, 6)) # the other models are still asked + self.assertEqual((count["failed"], count["unreadable"], count["tasks"], count["disagreement"]), (0, 2, 2, 3)) + self.assertEqual(lines[1]["models"]["acme/prose"], {"answer": "unsure", "p": {"execution": None}, "unreadable": True}) + self.assertEqual(lines[1]["models"][YES]["answer"], "yes") + + code, lines, err = self.run_script(JEV, "acme/usage", "acme/nan") # the answers stand without a cost + self.assertEqual((code, [(line["result"], line.get("answer")) for line in lines]), (script.OK, [("agreed", "yes")] * 3)) + count = json.loads(err.splitlines()[-1], parse_constant=self.fail) # no NaN in the summary + self.assertEqual((count["cost_usd"], count["calls_with_cost"], count["failed"]), (0.000001, 2, 0)) + + def test_the_characters_counted_are_the_ones_sent(self): + self.write(["Execution"], ["Travel"], purpose="synthetic résumé") + code, _, err = self.run_script(JEV, YES) + sent = json.loads(err.splitlines()[-1])["chars"] + self.assertEqual((code, sent, len(Fake.sizes)), (script.OK, sum(Fake.sizes), 4)) + code, lines, err = self.run_script(JEV, YES, argv=["--dry-run"], key="") + self.assertEqual((json.loads(err.splitlines()[-1])["chars"], lines[0]["body"]["state"]["purpose"]), (sent, "synthetic résumé")) + + def test_a_line_that_cannot_be_asked_is_refused(self): + self.lines({"skip": ["Execution", "Stamina"]}) + code, lines, err = self.run_script(JEV, YES) + self.assertEqual((code, lines, Fake.seen), (script.USAGE, [], [])) + self.assertIn("line 1: skip[1] is no axis", err) # where, never what it holds + self.assertNotIn("Stamina", err) + self.write(["Execution"], ["Travel"]) + twice = self.tasks.read_text() + self.tasks.write_text(twice + twice.splitlines()[0] + "\n") # one task on two lines: asked once or never + code, lines, err = self.run_script(JEV, YES) + self.assertEqual((code, lines, Fake.seen), (script.USAGE, [], [])) + self.assertIn("line 3: the dataset and task of line 1 again", err) + self.tasks.write_text(twice + twice.splitlines()[0].replace('"dataset": "d"', '"dataset": "e"') + "\n") + self.assertEqual((self.run_script(JEV, YES)[0], len(Fake.seen)), (script.OK, 6)) # the same id in another dataset + Fake.seen.clear() + for bad in ({"blob": "x"}, {"ticket": None}, {"request": []}, {"request": ""}): # named fields, a request, no null + self.write(["Execution"], **bad) + self.assertEqual(self.run_script(JEV, YES)[0], script.USAGE, bad) + self.write(["Safety"], policy={"refunds": ["POLICY"]}, checks={"actions": []}, notes=[], given={"tools": ["GIVEN"]}) + self.assertEqual(self.run_script(JEV, YES)[0], script.OK) # an empty value is evidence: sent as given + self.assertEqual(Fake.seen[0][2]["state"], {"request": "TASK TEXT", "checks": {"actions": []}, "notes": [], + "policy": {"refunds": ["POLICY"]}, "given": {"tools": ["GIVEN"]}}) + + def lines(self, *tasks): + self.tasks.write_text("".join(json.dumps({"dataset": "d", "task": str(n), "state": {"request": "TASK TEXT"}, **t}) + "\n" + for n, t in enumerate(tasks))) + + def test_every_axis_is_asked_but_those_skipped(self): + axes = script.definitions()["axes"] + ids = lambda names: [q["id"] for a in names for q in axes[a]["questions"]] + self.lines({}, {"skip": ["Travel", "Memory"]}, {"skip": []}) + code, lines, err = self.run_script(JEV, YES, argv=["--dry-run"], key="") + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, count["pairs"]), (script.OK, 3 * len(axes) - 2)) + self.assertEqual(list(lines[4]["body"]["questions"]), ids(axes)) # an empty skip: every one too + self.assertNotIn("cost_usd", count) # nothing prices a dry run + self.assertEqual(list(lines[0]["body"]["questions"]), ids(axes)) # no axes: every one, in the file's order + self.assertEqual(list(lines[2]["body"]["questions"]), ids(a for a in axes if a not in ("Travel", "Memory"))) + for bad in ({"skip": list(axes)}, {"skip": ["Stamina"]}, {"skip": ["Travel", "Travel"]}, {"skip": "Travel"}): + self.lines(bad) + self.assertEqual(self.run_script(JEV, YES, argv=["--dry-run"], key="")[0], script.USAGE, bad) + self.assertEqual(Fake.seen, []) + + def test_a_line_that_names_its_axes_is_refused_and_told_what_to_write(self): + for bad in ({"axes": ["Execution"]}, {"skip": ["Travel"], "axes": ["Safety"]}, {"axes": []}): + self.lines(bad) # never a way to ask fewer axes + code, lines, err = self.run_script(JEV, YES, argv=["--dry-run"], key="") + self.assertEqual((code, lines), (script.USAGE, []), bad) + self.assertIn("line 1: axes is not read: every axis is asked. Remove it, and list in skip", err) + text = SKILL.joinpath("SKILL.md").read_text() # each example holds one kind of rule + for block in re.findall(r"```json\n(.*?)```", text, re.S): + self.assertFalse('"tasks"' in block and re.search(r'\{"dataset": "\w+", "axes"', block), block) + + def test_a_run_says_each_task_and_a_rerun_asks_only_what_is_not_decided(self): + decided = self.tasks.with_name("decisions.jsonl") + argv = ["--decided", str(decided)] + decided.write_text("") + code, first, err = self.run_script(JEV, YES, argv=argv) + self.assertEqual((code, len(Fake.seen)), (script.OK, 4)) + self.assertEqual(err.splitlines()[:2], ["1/2 d 0: 2 pairs", "2/2 d 1: 1 pairs"]) # a line per task as it ends + self.assertIn("1/2 d 0: skipped, HTTP 422", self.run_script("acme/strict", JEV)[2]) + self.assertEqual(len(self.run_script(JEV, YES, argv=["--dry-run"], key="")[2].splitlines()), 1) + + decided.write_text("".join(json.dumps(line) + "\n" for line in first) + '{"definitions"') # its last line cut short + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=argv) + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines, Fake.seen), (script.OK, [], [])) # every pair decided: no call + self.assertEqual((count["reused"], count["pairs"], count["calls"]), (3, 0, 0)) + + decided.write_text(json.dumps(first[0]) + "\n") # task 0's Safety alone + code, lines, err = self.run_script(JEV, YES, argv=[*argv, "--max-calls", "2"]) + self.assertEqual((code, [line["axis"] for line in lines]), (script.PARTIAL, ["Execution"])) # the cap counts what is asked + self.assertNotIn("safety_decline", Fake.seen[0][2]["questions"]) + self.assertEqual(json.loads(err.splitlines()[-1])["reused"], 1) + + decided.write_text("".join(json.dumps(line) + "\n" for line in first)) + Fake.seen.clear() + self.assertEqual(len(self.run_script(JEV, NO, argv=argv)[1]), 3) # other models: asked again + self.write(["Execution", "Safety"], ["Travel"], notes="changed") + self.assertEqual(len(self.run_script(JEV, YES, argv=argv)[1]), 3) # another state: asked again + Fake.seen.clear() + code, _, err = self.run_script(JEV, YES, argv=["--decided", str(decided) + ".gone"]) + self.assertEqual((code, Fake.seen), (script.USAGE, [])) + self.assertIn("FileNotFoundError", err) + + def decided(self, *lines, tail=""): + path = self.tasks.with_name("decisions.jsonl") + path.write_text("".join(json.dumps(line) + "\n" for line in lines) + tail) + return path, ["--decided", str(path)] + + def test_a_resumed_dry_run_shows_the_tasks_its_send_asks(self): + first = self.run_script(JEV, YES)[1] + _, argv = self.decided(*first[:2]) # task 0 decided, a cap of one task + code, shown, err = self.run_script(JEV, YES, argv=[*argv, "--max-calls", "2", "--dry-run"], key="") + self.assertEqual((code, json.loads(err.splitlines()[-1])["reused"]), (script.OK, 2)) + Fake.seen.clear() + code, lines, _ = self.run_script(JEV, YES, argv=[*argv, "--max-calls", "2"]) + self.assertEqual((code, [line["task"] for line in lines]), (script.OK, ["1"])) + self.assertEqual([body for _, _, body in Fake.seen], [line["body"] for line in shown]) # the task left, not the first + + def test_an_answered_call_is_kept_when_its_task_gets_no_decision(self): + code, lines, err = self.run_script(JEV, "acme/envelope") # one answer paid for, then a 402 + self.assertEqual((code, lines), (script.PARTIAL, [])) + self.assertEqual([(c["task"], c["model"], c["cost_usd"], list(c["answers"])) for c in self.costs], + [("0", JEV, 0.00000049, ["Safety", "Execution"])]) + path, argv = self.decided(*self.costs) # kept in the file: summed once, and no decision + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=argv) # the retry asks task 0's missing model alone + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, [body["model"] for _, _, body in Fake.seen]), (script.OK, [YES, JEV, YES])) + self.assertEqual((count["kept"], count["calls"], count["calls_before"], len(lines)), (1, 3, 1, 3)) + self.assertEqual(lines[1]["models"], {JEV: {"answer": "yes", "p": {"execution": 0.9}}, # as the file kept it + YES: {"answer": "yes", "p": {"execution": 0.71}}}) + path.write_text(path.read_text() + self.raw) + kept = [json.loads(line) for line in path.read_text().splitlines()] + self.assertEqual(round(sum(k.get("cost_usd", 0) for k in kept), 8), 0.00000196) + + self.write(["Execution", "Safety"], ["Travel"], notes="changed") # another state: its answer is not kept + self.assertEqual(json.loads(self.run_script(JEV, YES, argv=argv)[2].splitlines()[-1])["kept"], 0) + + def test_a_reply_paid_for_that_does_not_read_is_not_asked_for_again(self): + self.write(["Execution"]) + path, argv = self.decided() + argv = [*argv, "--max-calls", "2"] + with mock.patch.dict(STATUS, {YES: 402}): # one reply charged, then no credit + code, lines, _ = self.run_script("acme/blank", YES, argv=argv) + self.assertEqual((code, lines, [(c["model"], c["cost_usd"]) for c in self.costs]), (script.PARTIAL, [], [("acme/blank", 0.125)])) + path.write_text(self.raw) + Fake.seen.clear() + code, lines, err = self.run_script("acme/blank", YES, argv=argv) # the same cap: the model missing alone + self.assertEqual((code, [body["model"] for _, _, body in Fake.seen]), (script.OK, [YES])) + self.assertEqual((lines[0]["result"], lines[0]["models"]["acme/blank"]), + ("disagreement", {"answer": "unsure", "p": {"execution": None}, "unreadable": True})) + path.write_text(path.read_text() + self.raw) + self.assertEqual(sum(json.loads(line).get("cost_usd", 0) for line in path.read_text().splitlines()), 0.125 + USAGE["cost"]) + + def test_the_cap_is_a_total_over_the_runs_appended_to_one_file(self): + path, argv = self.decided() + argv = [*argv, "--max-calls", "2"] + code, lines, _ = self.run_script(JEV, YES, argv=argv) # task 0, then the cap + self.assertEqual((code, len(Fake.seen), len(lines)), (script.PARTIAL, 2, 2)) + path.write_text(path.read_text() + self.raw) + for more in ([], ["--dry-run"]): # again, same cap: its calls are spent + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=[*argv, *more]) + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines, Fake.seen), (script.PARTIAL, [], []), more) + self.assertEqual((count["calls"], count["calls_before"], count["stopped"]), (0, 2, "max-calls"), more) + code, lines, err = self.run_script(JEV, YES, argv=[*argv[:2], "--max-calls", "4"]) + self.assertEqual((code, [line["task"] for line in lines], len(Fake.seen)), (script.OK, ["1"], 2)) + + path, argv = self.decided() # a failed call holds no line: not counted + self.run_script(JEV, "acme/down", argv=argv) + path.write_text(self.raw) + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=[*argv, "--max-calls", "4"]) # 2 answered, 2 missing: both fit + self.assertEqual((code, len(lines), [body["model"] for _, _, body in Fake.seen]), (script.OK, 3, [YES, YES])) + self.assertEqual(json.loads(err.splitlines()[-1])["calls_before"], 2) + + def test_a_429_is_waited_out_a_bounded_number_of_times(self): + self.addCleanup(setattr, Fake, "busy", 0) + Fake.busy = 2 + with mock.patch.object(script, "time") as clock: + code, lines, err = self.run_script(JEV, "acme/busy") + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, len(lines), count["retries"], count["calls"], count["failed"]), (script.OK, 3, 2, 4, 0)) + self.assertEqual([c.args for c in clock.sleep.call_args_list], [(w,) for w in script.BACKOFF[:2]]) + + Fake.busy, tries = 99, len(script.BACKOFF) + 1 # never free: each call gives up, the run goes on + Fake.seen.clear() + with mock.patch.object(script, "time") as clock: + code, lines, err = self.run_script(JEV, "acme/busy") + count = json.loads(err.splitlines()[-1]) + self.assertEqual((code, lines, len(Fake.seen), clock.sleep.call_count), (script.PARTIAL, [], 2 * (1 + tries), 2 * len(script.BACKOFF))) + self.assertEqual([s["status"] for s in count["skipped"]], [429, 429]) + + def test_a_file_cut_short_is_ended_at_a_line_before_a_run_appends_to_it(self): + first = self.run_script(JEV, YES)[1] + path, argv = self.decided(first[0], tail='{"definitions"') # an append stopped inside a line + self.run_script(JEV, YES, argv=[*argv, "--dry-run"], key="") + self.assertTrue(path.read_text().endswith('{"definitions"')) # a dry run writes nothing + Fake.seen.clear() + code, lines, _ = self.run_script(JEV, YES, argv=argv) + path.write_text(path.read_text() + self.raw) # what `>>` does + self.assertEqual((code, len(lines), len(Fake.seen)), (script.OK, 2, 4)) + self.assertEqual(len([json.loads(line) for line in path.read_text().splitlines()]), 1 + 2 + 4) # every line reads + Fake.seen.clear() + code, lines, err = self.run_script(JEV, YES, argv=argv) # the file as it now is: nothing left to ask + self.assertEqual((code, lines, Fake.seen, json.loads(err.splitlines()[-1])["reused"]), (script.OK, [], [], 3)) + path.write_text(path.read_text().rstrip("\n")) # a whole line without its newline is kept + self.assertEqual((self.run_script(JEV, YES, argv=argv)[1], Fake.seen, path.read_text()[-2:]), ([], [], "}\n")) + + def test_a_dry_run_reads_past_a_record_cut_inside_a_character(self): + first = self.run_script(JEV, YES)[1] + path, argv = self.decided(first[0]) + whole, cut = path.read_bytes(), '{"dataset": "d", "task": "caf'.encode() + "é".encode()[:1] + path.write_bytes(whole + cut) + code, shown, err = self.run_script(JEV, YES, argv=[*argv, "--dry-run"], key="") + self.assertEqual((code, len(shown), json.loads(err.splitlines()[-1])["reused"]), (script.OK, 4, 1)) + self.assertEqual(path.read_bytes(), whole + cut) # read past, in memory alone + Fake.seen.clear() + code, lines, _ = self.run_script(JEV, YES, argv=argv) # the run removes it, and sends what was shown + self.assertEqual((code, len(lines), path.read_bytes()), (script.OK, 2, whole)) + self.assertEqual([body for _, _, body in Fake.seen], [line["body"] for line in shown]) + path.write_bytes(whole + cut + b"\n" + whole) # a whole line that does not read: refused + for more in ([], ["--dry-run"]): + Fake.seen.clear() + code, _, err = self.run_script(JEV, YES, argv=[*argv, *more]) + self.assertEqual((code, Fake.seen), (script.USAGE, []), more) + self.assertIn("line 2", err) + + def test_results_give_each_pair_its_last_decision_for_the_current_models(self): + self.write(["Safety"]) + path, argv = self.decided() + for models in ((JEV, YES), (JEV, NO), (JEV, YES)): # agreed, another panel disagrees, back + Fake.seen.clear() + self.run_script(*models, argv=argv) + path.write_text(path.read_text() + self.raw) + last = json.loads(path.read_text().splitlines()[-1]) + self.assertEqual((Fake.seen, last["result"], set(last["models"])), ([], "disagreement", {JEV, NO})) # the file's last line + code, lines, _ = self.run_script(YES, JEV, argv=[*argv, "--results"], key="") + self.assertEqual((code, [(line["result"], line.get("answer"), set(line["models"])) for line in lines]), + (script.OK, [("agreed", "yes", {JEV, YES})])) + self.write(["Safety"], notes="changed") # another state: nothing decided it + code, lines, _ = self.run_script(JEV, YES, argv=[*argv, "--results"], key="") + self.assertEqual((code, lines, Fake.seen), (script.OK, [{"dataset": "d", "task": "0", "axis": "Safety", "result": "pending"}], [])) + self.assertEqual(self.run_script(JEV, YES, argv=[*argv, "--results", "--dry-run"], key="")[0], script.USAGE) + + def test_a_decision_is_reused_for_its_questions_and_its_set_of_models(self): + first = self.run_script(JEV, YES)[1] + _, argv = self.decided(*first) + Fake.seen.clear() + self.assertEqual((self.run_script(YES, JEV, argv=argv)[1], Fake.seen), ([], [])) # the same models, another order + _, argv = self.decided({**first[0], "models": {JEV: {}, YES: {}}}, *first[1:]) # a decision without its answers + self.assertEqual(([line["axis"] for line in self.run_script(JEV, YES, argv=argv)[1]], len(Fake.seen)), ([first[0]["axis"]], 2)) + _, argv = self.decided(*first) + Fake.seen.clear() + changed = script.definitions() + changed["axes"]["Safety"]["questions"][0]["true"] += " Or a refund." # the same version, another question + with mock.patch.object(script, "definitions", return_value=changed): + code, lines, err = self.run_script(JEV, YES, argv=argv) + self.assertEqual((code, [line["axis"] for line in lines], len(Fake.seen)), (script.OK, ["Safety"], 2)) + self.assertEqual(json.loads(err.splitlines()[-1])["reused"], 2) + self.assertNotEqual(lines[0]["questions"], first[0]["questions"]) + + +class Workflow(unittest.TestCase): + """The commands SKILL.md gives, run as written, and the reader's rules its update steps rely on.""" + + def command(self, marker, **names): + line = next(line for line in SKILL.joinpath("SKILL.md").read_text().splitlines() if marker in line) + code = re.search(r"python3 -c '(.*)'$", line).group(1) + for name, value in names.items(): + code = code.replace(name, value) + out = io.StringIO() + with contextlib.redirect_stdout(out), warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) # a one-line command closes nothing + exec(code, {}) + return out.getvalue() + + def test_every_release_of_the_benchmark_is_listed_with_its_datasets(self): + every = definitions.load("benchmark", every=True)[0] + key = max((b["key"] for b in every), key=[b["key"] for b in every].count) # the entry with most releases + want = [(definitions.version_identity(b), [d["id"] for d in b.get("datasets") or []]) for b in every if b["key"] == key] + got = self.command("version_identity(b), [x", KEY=key).splitlines() + self.assertEqual(got, [f"{identity} {datasets}" for identity, datasets in want]) + + def test_a_contribution_reads_the_bundled_entry_beside_a_copy_of_the_user(self): + every = definitions.load("benchmark", every=True)[0] + key = max((b["key"] for b in every), key=[b["key"] for b in every].count) + here = next(b["_here"] for b in every if b["key"] == key) + tmp = tempfile.TemporaryDirectory(prefix="nullius-label-benchmark-") + self.addCleanup(tmp.cleanup) + copy = Path(tmp.name) / "benchmarks" / key + shutil.copytree(here, copy) # the user's copy: one release fewer + d = json.loads(copy.joinpath("standard.json").read_text()) + d["versions"].pop(next(v for v in d["versions"] if v != d["default"])) + copy.joinpath("standard.json").write_text(json.dumps(d)) + copy.joinpath("proofs.json").unlink(missing_ok=True) # it names the release removed + listed = lambda: self.command("version_identity(b), [x", KEY=key).splitlines() + text = SKILL.joinpath("SKILL.md").read_text() + bundled = re.search(r"# a contribution: NULLIUS_CATALOGUE=(\S+) before each PYTHONPATH=", text).group(1) + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": tmp.name}): + ours = listed() + self.assertTrue(ours) + self.assertEqual(self.command("catalog.entry_dir(", KEY=key).strip(), str(copy)) + with mock.patch.dict(os.environ, {"NULLIUS_CATALOGUE": bundled.replace("REPO", str(SKILL.parents[2]))}): + self.assertEqual((len(listed()), self.command("catalog.entry_dir(", KEY=key).strip()), (len(ours) + 1, here)) + self.assertRaises(ValueError, self.command, "catalog.writable_dir(", KEY=key) # never written through the user's path + + def test_handover_checks_the_proposal_it_names_and_fails_without_it(self): + b = definitions.load("benchmark")[0][0] + tmp = tempfile.TemporaryDirectory(prefix="nullius-label-benchmark-") + self.addCleanup(tmp.cleanup) + entry = Path(tmp.name) / "benchmarks" / b["key"] + shutil.copytree(b["_here"], entry) # a proposal apart from the entry Nullius reads + entry.joinpath(labels.FILE).unlink(missing_ok=True) + run = lambda: self.command("labels.check(", ENTRY=str(entry), KEY=b["key"]) + self.assertRaises(FileNotFoundError, run) + entry.joinpath(labels.FILE).write_text(json.dumps({"schema": 1, "labels": [{"axes": ["Stamina"]}]})) + self.assertIn("unknown axis 'Stamina'", run()) + entry.joinpath(labels.FILE).write_text(json.dumps({"schema": 1, "labels": [{"axes": ["Safety"]}]})) + self.assertEqual(run(), "()\n") + self.assertRaises(SystemExit, lambda: self.command("labels.check(", ENTRY=str(entry), KEY="no-such-benchmark")) + + def test_an_update_gives_the_result_only_once_the_old_rules_are_reconciled(self): + bench = [{"key": "shop", "_version": "v1", "datasets": [{"id": "retail"}]}] + rule = lambda **r: {"dataset": "retail", "checked": ["v1"], "tasks": ["42"], **r} + axes = lambda *rules: labels.check({"schema": 1, "labels": list(rules)}, bench).axes("v1", "retail", "42") + old = [rule(axes=["Travel"]), rule(**{"not": ["Communication"]})] + self.assertEqual(axes(*old, rule(axes=["Communication"])), {"Travel"}) # a field rule added alone: the old `not` wins + self.assertEqual(axes(rule(axes=["Communication"])), {"Communication"}) # out of the `not` rule, and Travel disagreed + self.assertEqual(axes({"dataset": "retail", "axes": ["Travel"]}), {"Travel"}) # a dataset rule stays: a conflict to report + + +if __name__ == "__main__": + unittest.main()