File size: 9,779 Bytes
a1b575d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""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"}


@dataclass(frozen=True)
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


@dataclass(frozen=True)
class Emission:
    """One parsed agent turn."""

    command: str
    kind: str = ""
    summary: str = ""
    artifact: str = ""
    parents: tuple[str, ...] = ()
    checks: tuple[CheckSpec, ...] = ()
    answer: str = ""
    error: str = ""

    @property
    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)