Download code/vera/protocol.py from ryan-superman/bio-agent-trajectories: direct link, hf CLI and curl.
- Browser
- Download file 9.78 kB
-
https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/protocol.py
- Command line
-
hf download hf://datasets/ryan-superman/bio-agent-trajectories/code/vera/protocol.py
-
curl -L -o protocol.py https://huggingface.co/datasets/ryan-superman/bio-agent-trajectories/resolve/main/code/vera/protocol.py
9.78 kB
| """The agent-facing protocol: declaring nodes, and *executing* their checks. | |
| The integrity property of VERA lives here. A verification score is only a reward signal | |
| if the model cannot set it. If the model were allowed to emit ``check: cells preserved, | |
| passed=true``, the score would be self-report and would measure confidence -- the very | |
| thing the benchmark shows to be miscalibrated. | |
| So the protocol splits the two roles: | |
| * the **model** declares *what should be true* of its artifact (a check specification, | |
| written as a command whose output decides), and | |
| * the **harness** runs that command against the workspace and reads the verdict. | |
| A specification that errors, times out, or prints something unparseable **fails**. That | |
| direction is deliberate: an unrunnable check must not earn credit, or the cheapest way to | |
| a high score becomes emitting checks that cannot execute. | |
| Wire format, one block per step:: | |
| <command>zcat counts.mtx.gz | wc -l</command> | |
| NODE kind=qc summary="14,203 of 34,460 cells pass QC" artifact=qc.mtx parents=n1 | |
| CHECK conservation "genes preserved" :: test $(zcat genes.tsv.gz|wc -l) -eq 18082 && echo True || echo False | |
| **Why the node and its checks are line-oriented and the command is not.** An earlier | |
| XML-shaped format lost a whole strength measurement to quoting: models write | |
| ``name="length > 1000"`` (the tag pattern stops at the inner ``>``) and | |
| ``command="python3 -c "`` (the attribute terminates at the inner quote, spilling the rest | |
| of the program into the element body). Both produced fragments of Python that could never | |
| run, scored as failures, and were indistinguishable from genuine analysis errors. A CHECK | |
| is therefore one line split on a ``::`` sentinel: everything after it is the command, | |
| verbatim, and no quoting rule can corrupt it. ``<command>`` keeps its tags because it | |
| carries multi-line shell and has no attributes to mis-parse. | |
| A consequence worth stating: **check commands must be single-line.** Multi-line analysis | |
| belongs in ``<command>``, writing a script the check then invokes. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Callable, Sequence | |
| from .checks import CheckResult, KINDS as CHECK_KINDS | |
| from .state import KINDS as NODE_KINDS | |
| _TRUE = {"true", "1", "yes", "pass", "passed", "ok"} | |
| _FALSE = {"false", "0", "no", "fail", "failed"} | |
| class CheckSpec: | |
| """A check the model declared, before the harness has run it. | |
| Attributes: | |
| kind: One of `vera.checks.KINDS`. | |
| name: What is being checked. | |
| command: Shell command whose final non-empty stdout line must be a boolean | |
| literal (``True``/``False``, ``1``/``0``, ``pass``/``fail``). | |
| """ | |
| kind: str | |
| name: str | |
| command: str | |
| class Emission: | |
| """One parsed agent turn.""" | |
| command: str | |
| kind: str = "" | |
| summary: str = "" | |
| artifact: str = "" | |
| parents: tuple[str, ...] = () | |
| checks: tuple[CheckSpec, ...] = () | |
| answer: str = "" | |
| error: str = "" | |
| def declares_node(self) -> bool: | |
| """True if this turn declared a node (as opposed to only running a command).""" | |
| return bool(self.kind) | |
| _ATTR = re.compile(r'(\w+)\s*=\s*(?:"([^"]*)"|(\S+))') | |
| _NODE_LINE = re.compile(r"^\s*NODE\s+(.*)$", re.M) | |
| _CHECK_LINE = re.compile(r'^\s*CHECK\s+(\w+)\s+"([^"]*)"\s*::[ \t]*(.+?)\s*$', re.M) | |
| # Any CHECK line that does not match the strict form, so the model can be told why. | |
| _CHECK_LOOSE = re.compile(r"^\s*CHECK\b(.*)$", re.M) | |
| _LEGACY_TAG = re.compile(r"<(?:node|check)\b") | |
| def _attrs(text: str) -> dict[str, str]: | |
| """Parse ``key=value`` or ``key="value"`` pairs from a NODE line.""" | |
| return {k: (q or b) for k, q, b in _ATTR.findall(text)} | |
| def parse_emission(text: str) -> Emission: | |
| """Parse one agent turn into a command, an optional node, and its check specs. | |
| Malformed structure is reported through `Emission.error` rather than raised: a model | |
| emitting a bad block is an expected event in a long run, and the loop must be able to | |
| nudge it rather than crash. | |
| Args: | |
| text: The model's raw turn. | |
| Returns: | |
| An `Emission`. Unknown node or check kinds, and CHECK lines missing the ``::`` | |
| sentinel, are rejected into `error` so a malformed check can never silently | |
| become an unverified node. | |
| """ | |
| answer = "" | |
| m_ans = re.search(r"FINAL ANSWER:\s*(.+?)\s*$", text, re.S | re.M) | |
| if m_ans: | |
| answer = m_ans.group(1).strip() | |
| m_cmd = re.search(r"<command>(.*?)</command>", text, re.S) | |
| command = m_cmd.group(1).strip() if m_cmd else "" | |
| if _LEGACY_TAG.search(text): | |
| return Emission(command, answer=answer, error=( | |
| "use the line format, not XML tags: " | |
| 'NODE kind=... summary="..." artifact=... / ' | |
| 'CHECK <kind> "<name>" :: <one-line command>')) | |
| m_node = _NODE_LINE.search(text) | |
| if not m_node: | |
| if not command and not answer: | |
| return Emission("", error="no <command>, NODE line or FINAL ANSWER in turn") | |
| return Emission(command, answer=answer) | |
| attrs = _attrs(m_node.group(1)) | |
| kind = attrs.get("kind", "") | |
| if kind not in NODE_KINDS: | |
| return Emission(command, answer=answer, | |
| error=f"unknown node kind {kind!r}; expected one of {NODE_KINDS}") | |
| # Only CHECK lines *after* the NODE line belong to it. Models routinely echo the | |
| # instruction template back, and scanning the whole turn turned those examples -- | |
| # including the ones labelled WRONG -- into real checks, inflating a node's check | |
| # count fivefold and making rho meaningless. | |
| tail = text[m_node.end():] | |
| strict = _CHECK_LINE.findall(tail) | |
| loose = _CHECK_LOOSE.findall(tail) | |
| if len(loose) != len(strict): | |
| return Emission(command, answer=answer, error=( | |
| f"{len(loose) - len(strict)} CHECK line(s) malformed; each must read " | |
| 'CHECK <kind> "<name>" :: <one-line command>')) | |
| specs: list[CheckSpec] = [] | |
| for ckind, cname, body in strict: | |
| if ckind not in CHECK_KINDS: | |
| return Emission(command, answer=answer, | |
| error=f"unknown check kind {ckind!r}; expected one of {CHECK_KINDS}") | |
| body = body.strip() | |
| if not body: | |
| return Emission(command, answer=answer, | |
| error=f"check {cname!r} has no command after ::") | |
| specs.append(CheckSpec(ckind, cname or "unnamed", body)) | |
| parents = tuple(p.strip() for p in attrs.get("parents", "").split(",") if p.strip()) | |
| return Emission( | |
| command=command, | |
| kind=kind, | |
| summary=attrs.get("summary", "").strip(), | |
| artifact=attrs.get("artifact", "").strip(), | |
| parents=parents, | |
| checks=tuple(specs), | |
| answer=answer, | |
| ) | |
| def verdict_from_output(stdout: str) -> bool | None: | |
| """Read a boolean verdict from a check command's stdout. | |
| Reads the **last** non-empty line, so a check may print diagnostics before its | |
| verdict. | |
| Returns: | |
| True/False, or None if no line parses as a boolean -- which the caller must | |
| treat as a failure, not as unknown. | |
| """ | |
| for line in reversed([l.strip() for l in (stdout or "").splitlines() if l.strip()]): | |
| low = line.lower() | |
| if low in _TRUE: | |
| return True | |
| if low in _FALSE: | |
| return False | |
| return None | |
| def run_checks( | |
| specs: Sequence[CheckSpec], | |
| workspace: Path, | |
| runner: Callable[[Path, str], object], | |
| *, | |
| timeout: int = 120, | |
| ) -> tuple[CheckResult, ...]: | |
| """Execute check specifications and return their verdicts. | |
| Args: | |
| specs: Declared checks. | |
| workspace: Directory to run them in. | |
| runner: Callable ``(workspace, command) -> result`` exposing ``stdout``, | |
| ``exit_code`` and ``timed_out``. `bmb.sandbox.run_bash` satisfies this; it is | |
| injected rather than imported so this module stays independent of either | |
| benchmark harness. | |
| timeout: Per-check wall-clock limit, seconds. | |
| Returns: | |
| One `CheckResult` per spec. A check that exits non-zero, times out, or fails to | |
| print a boolean is **failed**, never skipped -- an unrunnable check must not earn | |
| credit. | |
| """ | |
| out: list[CheckResult] = [] | |
| for spec in specs: | |
| try: | |
| res = runner(workspace, spec.command, timeout=timeout) # type: ignore[call-arg] | |
| except TypeError: | |
| res = runner(workspace, spec.command) | |
| except Exception as exc: # a broken check is a failed check | |
| out.append(CheckResult(spec.name, spec.kind, False, f"check raised: {exc}")) | |
| continue | |
| if getattr(res, "timed_out", False): | |
| out.append(CheckResult(spec.name, spec.kind, False, f"check timed out after {timeout}s")) | |
| continue | |
| if getattr(res, "exit_code", 0) != 0: | |
| err = (getattr(res, "stderr", "") or "").strip().splitlines() | |
| out.append(CheckResult(spec.name, spec.kind, False, | |
| f"check exited {res.exit_code}: {err[-1] if err else ''}"[:200])) | |
| continue | |
| verdict = verdict_from_output(getattr(res, "stdout", "")) | |
| if verdict is None: | |
| out.append(CheckResult(spec.name, spec.kind, False, | |
| f"check printed no boolean verdict: " | |
| f"{(getattr(res, 'stdout', '') or '')[-120:]!r}")) | |
| continue | |
| out.append(CheckResult(spec.name, spec.kind, verdict, | |
| "" if verdict else "check evaluated False")) | |
| return tuple(out) | |