"""Measuring how much a check actually constrains -- mutation testing for agent claims. A verification reward is worth exactly what its checks are worth, and the first dry run showed why that cannot be assumed: the model wrote ``test -f data.fasta && echo True``, which passes for every analysis anyone could ever run on that file. Counting it toward `rho` rewards writing vacuous checks. This is the same failure that makes a green test suite meaningless when no mutation breaks it, so it takes the same remedy. **Definition.** A check has strength 1 if it passes on the real artifact and fails on every corrupted version of it, and strength 0 if it cannot tell them apart. Both halves are required: a check that fails on the original is broken, not strong, and is reported with strength 0 and ``valid=False`` so it is never mistaken for a sensitive one. Perturbations are deliberately *semantic* violations of the kinds of invariant these analyses rest on -- rows silently dropped, a column shuffled out of correspondence, values rescaled, a file truncated mid-write. Each is a real pipeline bug, not noise. """ from __future__ import annotations import random import shutil from dataclasses import dataclass from pathlib import Path from typing import Callable, Sequence from .protocol import CheckSpec, verdict_from_output @dataclass(frozen=True) class Strength: """How much one check constrains its artifact. Attributes: name: The check's name. valid: Whether the check passed on the unmodified artifact. A check that fails there is broken; its `score` is meaningless and is reported as 0. score: Fraction of perturbations the check detected, in [0, 1]. detected: Names of the perturbations it caught. missed: Names of the perturbations it did not. """ name: str valid: bool score: float detected: tuple[str, ...] = () missed: tuple[str, ...] = () @property def vacuous(self) -> bool: """True if the check cannot distinguish a real artifact from a corrupted one.""" return self.valid and self.score == 0.0 def drop_rows(text: str, rng: random.Random, frac: float = 0.1) -> str: """Silently delete a fraction of lines -- the classic filter-loses-rows bug.""" lines = text.splitlines(keepends=True) if len(lines) < 2: return text keep = max(1, int(len(lines) * (1 - frac))) idx = sorted(rng.sample(range(len(lines)), keep)) return "".join(lines[i] for i in idx) def shuffle_column(text: str, rng: random.Random, sep: str = "\t") -> str: """Permute one column, breaking row correspondence while preserving every marginal. The nastiest class of bug in these pipelines: totals, counts and distributions all still check out, but the rows no longer line up. """ lines = text.splitlines() rows = [l.split(sep) for l in lines] width = min((len(r) for r in rows if len(r) > 1), default=0) if width < 2 or len(rows) < 3: return text col = rng.randrange(width) body = rows[1:] values = [r[col] for r in body if len(r) > col] rng.shuffle(values) it = iter(values) for r in body: if len(r) > col: r[col] = next(it) return "\n".join(sep.join(r) for r in [rows[0]] + body) + "\n" def scale_numbers(text: str, rng: random.Random, factor: float = 1.1) -> str: """Rescale every number by a constant -- a units or normalisation error.""" import re def rep(m): try: return f"{float(m.group(0)) * factor:g}" except ValueError: return m.group(0) return re.sub(r"(? str: """Cut the artifact short -- an interrupted write or a partial download.""" return text[: max(1, int(len(text) * frac))] # ---------------------------------------------------------------- sequence corruptions # # The tabular perturbations above cannot damage a genome: `scale_numbers` and # `shuffle_column` are no-ops on FASTA, and both `drop_rows` and `truncate` leave the # single `>` header intact, so a check like `grep -c '^>' -eq 1` scored VACUOUS for a # reason that had nothing to do with the check. These corrupt the *sequence* instead, # and each is chosen to defeat a different class of claim. _COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan") def _split_fasta(text: str) -> tuple[list[str], list[str]]: """Separate a FASTA into its header lines and its sequence lines.""" headers, seqs = [], [] for line in text.splitlines(): (headers if line.startswith(">") else seqs).append(line) return headers, seqs def _rebuild(header: str, seq: str, width: int = 70) -> str: """Reassemble one record with the usual line wrapping.""" lines = [seq[i:i + width] for i in range(0, len(seq), width)] or [""] return header + "\n" + "\n".join(lines) + "\n" def mutate_bases(text: str, rng: random.Random, frac: float = 0.05) -> str: """Substitute a fraction of bases -- defeats claims about exact sequence content.""" headers, seqs = _split_fasta(text) if not headers: return text seq = list("".join(seqs)) if not seq: return text for i in rng.sample(range(len(seq)), max(1, int(len(seq) * frac))): seq[i] = rng.choice([b for b in "ACGT" if b != seq[i].upper()]) return _rebuild(headers[0], "".join(seq)) def reverse_complement(text: str, rng: random.Random) -> str: """Reverse-complement the sequence -- preserves GC exactly, destroys every motif. The sharpest test of a composition-only check: length, GC content and base counts are all unchanged, so anything that still passes is not looking at the sequence itself. """ headers, seqs = _split_fasta(text) if not headers: return text seq = "".join(seqs).translate(_COMPLEMENT)[::-1] return _rebuild(headers[0], seq) def shuffle_sequence(text: str, rng: random.Random) -> str: """Permute the bases -- preserves composition and length, destroys all structure.""" headers, seqs = _split_fasta(text) if not headers: return text seq = list("".join(seqs)) rng.shuffle(seq) return _rebuild(headers[0], "".join(seq)) def splice_foreign(text: str, rng: random.Random, frac: float = 0.2) -> str: """Replace a contiguous block with foreign sequence -- models a contaminated assembly.""" headers, seqs = _split_fasta(text) if not headers: return text seq = "".join(seqs) n = len(seq) if n < 20: return text span = max(10, int(n * frac)) start = rng.randrange(0, max(1, n - span)) foreign = "".join(rng.choice("ACGT") for _ in range(span)) return _rebuild(headers[0], seq[:start] + foreign + seq[start + span:]) TABULAR_PERTURBATIONS: dict[str, Callable[[str, random.Random], str]] = { "drop_rows": drop_rows, "shuffle_column": shuffle_column, "scale_numbers": scale_numbers, "truncate": truncate, } SEQUENCE_PERTURBATIONS: dict[str, Callable[[str, random.Random], str]] = { "mutate_bases": mutate_bases, "reverse_complement": reverse_complement, "shuffle_sequence": shuffle_sequence, "splice_foreign": splice_foreign, "truncate": truncate, } PERTURBATIONS: dict[str, Callable[[str, random.Random], str]] = { **TABULAR_PERTURBATIONS, **SEQUENCE_PERTURBATIONS, } def perturbations_for(text: str) -> dict[str, Callable[[str, random.Random], str]]: """Choose the corruption set matching the artifact's type. Applying tabular corruptions to a genome (or the reverse) produces no-ops, and a no-op is not evidence about a check -- it silently understates or overstates strength depending on how it is counted. Detection is deliberately crude: FASTA is the only special case these benchmarks need, and anything else is treated as tabular text. """ head = text.lstrip()[:1] return dict(SEQUENCE_PERTURBATIONS) if head == ">" else dict(TABULAR_PERTURBATIONS) MAX_ARTIFACT_BYTES = 200 * 1024 * 1024 def measure_strength( spec: CheckSpec, artifact: Path, workspace: Path, runner: Callable[..., object], *, perturbations: Sequence[str] | None = None, seed: int = 0, timeout: int = 120, ) -> Strength: """Measure how much `spec` constrains `artifact`, by corrupting it and re-checking. The artifact is copied aside and restored afterwards, so the agent's workspace is left exactly as found even if a check crashes. Args: spec: The check to measure. artifact: File the check reads. Must exist and be text. workspace: Directory to run the check in. runner: ``(workspace, command, timeout=) -> result`` with ``stdout``/``exit_code``. perturbations: Names from `PERTURBATIONS`; defaults to all of them. seed: RNG seed, so a reported strength is reproducible. timeout: Per-check wall clock. Returns: A `Strength`. If the check does not pass on the unmodified artifact it is reported ``valid=False, score=0.0`` -- broken, not strong. Raises: FileNotFoundError: If `artifact` does not exist. ValueError: If the artifact is larger than `MAX_ARTIFACT_BYTES`, since this routine holds it in memory. """ artifact = Path(artifact) if not artifact.is_file(): raise FileNotFoundError(f"artifact not found: {artifact}") size = artifact.stat().st_size if size > MAX_ARTIFACT_BYTES: raise ValueError(f"artifact too large to perturb in memory: {size} bytes") probe = artifact.read_text(errors="replace") applicable = perturbations_for(probe) names = list(perturbations if perturbations is not None else applicable) unknown = [n for n in names if n not in PERTURBATIONS] if unknown: raise ValueError(f"unknown perturbation(s): {unknown}") def passes() -> bool: try: res = runner(workspace, spec.command, timeout=timeout) except Exception: return False if getattr(res, "timed_out", False) or getattr(res, "exit_code", 0) != 0: return False return verdict_from_output(getattr(res, "stdout", "")) is True backup = artifact.with_suffix(artifact.suffix + ".vera_orig") shutil.copy2(artifact, backup) try: if not passes(): return Strength(spec.name, valid=False, score=0.0) original = backup.read_text(errors="replace") detected, missed = [], [] for name in names: rng = random.Random(seed) corrupted = PERTURBATIONS[name](original, rng) if corrupted == original: continue # perturbation was a no-op on this artifact; not evidence artifact.write_text(corrupted) (detected if not passes() else missed).append(name) shutil.copy2(backup, artifact) total = len(detected) + len(missed) score = (len(detected) / total) if total else 0.0 return Strength(spec.name, True, score, tuple(detected), tuple(missed)) finally: shutil.copy2(backup, artifact) backup.unlink(missing_ok=True) def weighted_rho(pairs: Sequence[tuple[bool, Strength]]) -> float: """Verification score with each check weighted by its measured strength. An unweighted `rho` treats ``test -f data.fasta`` as worth as much as an invariant that actually constrains the analysis, which is what makes vacuous checks profitable. Args: pairs: ``(passed, strength)`` for each check on a node. Returns: Strength-weighted pass fraction, or 0.0 when every check is vacuous or invalid -- consistent with `vera.checks.rho`, where unverified scores zero. """ total = sum(s.score for _, s in pairs if s.valid) if total == 0: return 0.0 return sum(s.score for passed, s in pairs if s.valid and passed) / total