"""A typed analysis graph that replaces transcript replay. Motivation is a measurement, not an aesthetic. On BioMysteryBench with a 25-step budget, a step costs a median **9,267 tokens** while contributing only **~400 tokens** of genuinely new content (921 chars of tool output plus 684 chars of command). Roughly 96% of the spend is the loop re-sending its own history, so cost grows as O(T^2) and the step budget binds long before the task is finished -- 75% of attempts exhaust it, and the median *correct* answer uses every step it is given. This module makes the conditioning context a bounded, structured summary instead. A node stores an artifact **handle** (a path) rather than the artifact, so the graph stays small regardless of how much data the analysis touches. Step cost becomes O(B) for a rendering budget B, and the total becomes O(T*B): at the measured rate of new content, a 4k-token state supports roughly 100 steps for the token cost that buys 25 today. The graph is also what makes verification composable: each node carries the checks that its own artifact must satisfy (see `vera.checks`), so a dense progress signal falls out of the structure rather than being bolted on. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable, Sequence from .checks import CheckResult, rho # Node kinds, ordered by their position in a typical analysis pipeline. Used only for # rendering and weighting; the graph itself imposes no ordering constraint. KINDS = ("load", "qc", "transform", "test", "interpret", "answer") # Rough chars-per-token for budget accounting. Deliberately conservative: overestimating # tokens truncates a little early, which is safe, whereas underestimating overflows the # context, which is not. CHARS_PER_TOKEN = 3.5 @dataclass(frozen=True) class Node: """One step of an analysis, with its artifact and the checks it must satisfy. Attributes: id: Short unique handle, e.g. ``n7``. kind: One of `KINDS`. summary: One line stating what this node established. This is what the model reads on later steps, so it must carry the *finding*, not the activity ("14,203 of 34,460 cells pass QC", not "ran QC"). artifact: Path to the produced file, or "" if the node produced only a scalar. Never the contents -- holding contents here would reintroduce the O(T^2) cost this module exists to remove. parents: Ids of nodes this one consumed. command: The shell command that produced it, for provenance and replay. checks: Consistency checks over this node's artifact. """ id: str kind: str summary: str artifact: str = "" parents: tuple[str, ...] = () command: str = "" checks: tuple[CheckResult, ...] = () def __post_init__(self) -> None: if self.kind not in KINDS: raise ValueError(f"unknown node kind {self.kind!r}; expected one of {KINDS}") @property def rho(self) -> float: """Verification score of this node: the fraction of its checks that passed.""" return rho(self.checks) def render(self) -> str: """One-line rendering for the model-facing state summary.""" n_ok = sum(c.passed for c in self.checks) mark = f"{n_ok}/{len(self.checks)}" if self.checks else "unverified" parents = f" <- {','.join(self.parents)}" if self.parents else "" art = f" [{self.artifact}]" if self.artifact else "" return f"({self.id}) {self.kind}: {self.summary}{art} checks={mark}{parents}" class AnalysisState: """The agent's working memory: a DAG of nodes, rendered under a token budget. Use `add` after each step and `render` to build the next prompt. `reward` gives the dense per-step signal that test-time steering consumes. """ def __init__(self) -> None: self._nodes: dict[str, Node] = {} self._order: list[str] = [] def __len__(self) -> int: return len(self._nodes) def __contains__(self, node_id: object) -> bool: return node_id in self._nodes def __getitem__(self, node_id: str) -> Node: return self._nodes[node_id] @property def nodes(self) -> tuple[Node, ...]: """All nodes, in insertion order.""" return tuple(self._nodes[i] for i in self._order) def add(self, node: Node) -> Node: """Insert a node. Args: node: The node to add. Raises: ValueError: If the id is already used, or a parent is unknown. Both are programming errors that would silently corrupt provenance, so they raise rather than being tolerated. """ if node.id in self._nodes: raise ValueError(f"duplicate node id {node.id!r}") missing = [p for p in node.parents if p not in self._nodes] if missing: raise ValueError(f"node {node.id!r} references unknown parents {missing}") self._nodes[node.id] = node self._order.append(node.id) return node def leaves(self) -> tuple[Node, ...]: """Nodes that no other node consumes -- the current analysis frontier.""" consumed = {p for n in self._nodes.values() for p in n.parents} return tuple(self._nodes[i] for i in self._order if i not in consumed) def ancestors(self, node_id: str) -> set[str]: """Ids of all transitive parents of `node_id` (excluding itself).""" seen: set[str] = set() stack = list(self._nodes[node_id].parents) while stack: cur = stack.pop() if cur in seen: continue seen.add(cur) stack.extend(self._nodes[cur].parents) return seen def reward(self, new_nodes: Iterable[Node], weights: dict[str, float] | None = None) -> float: """Dense progress signal contributed by this step. Args: new_nodes: Nodes added at this step. weights: Optional per-kind weight. Missing kinds default to 1.0. Returns: Sum over new nodes of ``weight(kind) * rho(node)``. Zero for no new nodes, and zero for nodes carrying no checks -- see `vera.checks.rho`. """ weights = weights or {} return sum(weights.get(n.kind, 1.0) * n.rho for n in new_nodes) def render(self, budget_tokens: int = 4000) -> str: """Render the state as model-facing text, never exceeding `budget_tokens`. Priority when the budget binds, highest first: the current frontier (leaves), then their ancestors, then everything else by recency. Frontier nodes are what the next action builds on, and their ancestors are what makes them interpretable; an unrelated early branch is the first thing that can be dropped. Args: budget_tokens: Cap on the rendering, in tokens (estimated at `CHARS_PER_TOKEN` chars per token). Returns: The rendering. If nodes were dropped, a final line says how many, so the model knows its view is partial rather than believing the analysis is smaller than it is. """ if not self._nodes: return "(no analysis steps yet)" # Frontier first, most recent first: when every node is a leaf (parallel # branches), the newest is the one the next action builds on. Then the # ancestors that make those leaves interpretable, then the rest by recency. leaf_ids = [n.id for n in reversed(self.leaves())] ordered = list(leaf_ids) for lid in leaf_ids: ordered.extend(sorted(self.ancestors(lid))) rank: dict[str, int] = {} for i, nid in enumerate(ordered): rank.setdefault(nid, i) for i, nid in enumerate(nid for nid in reversed(self._order) if nid not in rank): rank[nid] = len(ordered) + i budget_chars = int(budget_tokens * CHARS_PER_TOKEN) # Reserve room for the elision note up front, so adding it cannot overflow. note_tmpl = "\n... %d earlier node(s) elided to fit the state budget" reserve = len(note_tmpl % len(self._order)) fill = max(0, budget_chars - reserve) chosen: set[str] = set() used = 0 for nid in sorted(self._order, key=lambda x: rank[x]): line = self._nodes[nid].render() if used + len(line) + 1 > fill: continue chosen.add(nid) used += len(line) + 1 # Render in pipeline order, not priority order, so the analysis reads forwards. body = "\n".join(self._nodes[nid].render() for nid in self._order if nid in chosen) dropped = len(self._order) - len(chosen) if dropped: body += note_tmpl % dropped if not body: body = "(state budget too small to render any node)" # Belt and braces: the cap is a guarantee callers size their context against. return body[:budget_chars]