Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

bench: evaluate Sol Terra model shapes

Rach Pradhan0fc2d17d4316
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e0561760..70ab6688 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,6 +18,9 @@ jobs:
- name: Zig source-size guard integrity tests
run: python3 scripts/test-zig-lines.py
+ - name: Model-shape benchmark integrity
+ run: python3 benchmarks/test_model_shape.py
+
- name: Python SDK import smoke
run: python3 -c "import sys; sys.path.insert(0, 'sdk/py'); import harness_sdk; assert harness_sdk.MODELS and harness_sdk.TOOLS; print('py sdk ok:', len(harness_sdk.MODELS), 'models')"
diff --git a/benchmarks/README.md b/benchmarks/README.md
index fc43521a..d4f2d620 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -23,12 +23,14 @@ task, the model, and the network.
| `memory.py` | Peak RSS + CPU (`/usr/bin/time -l`) | graff **~25 MB** floor vs Node **~410 MB** vs Rust **~206 MB** |
| `latency.py` | One-shot turn latency, same gpt-5.5 endpoint, concurrent pairs | graff **4.4 s** vs codex **8.9 s** (one-shot only) |
| `memory_session.py` | RSS-vs-turn slope plus session/scratch arena capacity for ONE persistent `--json` session (the #124 leak detector; `memory.py` is one-shot peak RSS and structurally blind to per-turn growth) | flat slope after warmup = no per-turn leak |
+| `model_shape.py` | Correctness, latency, tool/model calls, and routing for all-Sol vs Sol-root/Terra-workers | writes a local correctness-first paired report; no default promotion |
```sh
python3 benchmarks/cost.py
python3 benchmarks/memory.py
python3 benchmarks/latency.py 8
python3 benchmarks/memory_session.py 50 # N turns, one persistent session
+python3 benchmarks/model_shape.py --graff zig-out/bin/graff --repetitions 1
```
`memory_session.py` drives and samples one turn at a time so the child remains
@@ -38,6 +40,33 @@ arena capacities beside process RSS.
Tasks live in `tasks.py` (edit to test other work).
+### Root/worker model shapes
+
+`model_shape.py` creates three disposable synthetic Python repositories and
+runs paired arms with the same `gpt-5.6-sol` root:
+
+- `all-sol`: both direct workers also use Sol;
+- `sol-terra`: both direct workers use `gpt-5.6-terra`.
+
+Every run must produce exactly two correctly routed child trajectory nodes.
+Visible tests provide normal agent feedback, while held-back cases grade the
+finished workspace afterward. The report selects correctness first and total
+tool economy second, but keeps promotion manual until at least 20 independent
+task pairs are present. One repetition is therefore a smoke/effect-size check;
+seven repetitions across the three fixtures provide 21 pairs:
+
+```sh
+python3 benchmarks/model_shape.py \
+ --graff zig-out/bin/graff \
+ --repetitions 7 \
+ --output-root /path/to/results
+```
+
+The runner disables external telemetry, behavioral upload, fleet sharing,
+Smolify, and optional companion tools. Only synthetic fixture content reaches
+the selected Codex account. Operational traces and the JSON report stay inside
+the output directory.
+
## Honest caveats (please read)
- **Cost is model freedom, not token savings.** On the *same* model, graff and
diff --git a/benchmarks/model_shape.py b/benchmarks/model_shape.py
new file mode 100644
index 00000000..08873552
--- /dev/null
+++ b/benchmarks/model_shape.py
@@ -0,0 +1,521 @@
+#!/usr/bin/env python3
+"""Correctness-first benchmark for Sol-root / Terra-worker model shapes.
+
+The benchmark creates fresh synthetic Python repositories, asks graff to use
+exactly two parallel direct subagents, grades the resulting code with visible
+and held-back tests, and reads run-local traces for latency/tool/model evidence.
+No source from the repository containing this script is sent to a model.
+"""
+
+from __future__ import annotations
+
+import argparse
+from dataclasses import asdict, dataclass
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import random
+import re
+import statistics
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any
+
+from model_shape_tasks import TASKS, Task
+
+
+ROOT_MODEL = "gpt-5.6-sol"
+WORKER_MODEL = "gpt-5.6-terra"
+MINIMUM_PAIRS_FOR_PROMOTION = 20
+
+
+@dataclass(frozen=True)
+class Arm:
+ name: str
+ worker_model: str
+
+
+COMMON_REQUEST = """
+This is a controlled benchmark in a disposable synthetic repository.
+Use exactly two direct `subagent` tool calls, issued together in one response
+so they run in parallel. Ask one worker to analyze the implementation and edge
+cases, and the other to inspect the tests/specification and propose a test
+matrix. The workers must only inspect and report; they must not edit files.
+After both reports return, integrate their findings yourself, edit only the
+implementation file, and run the visible unittest suite. Do not edit tests,
+do not use workflow/learn tools, and do not merely describe a solution.
+""".strip()
+
+def sha256(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def read_jsonl_files(paths: list[Path]) -> list[dict[str, Any]]:
+ rows = []
+ for path in paths:
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict):
+ rows.append(value)
+ return rows
+
+
+def count_unittest_results(output: str, expected: int, returncode: int) -> int:
+ match = re.search(r"Ran (\d+) tests?", output)
+ total = int(match.group(1)) if match else expected
+ if returncode == 0:
+ return min(total, expected)
+ failures = sum(
+ int(value)
+ for value in re.findall(r"(?:failures|errors)=(\d+)", output)
+ )
+ return max(0, min(expected, total - max(1, failures)))
+
+
+def run_checks(task: Task, root: Path, test_hash: str) -> dict[str, Any]:
+ visible = subprocess.run(
+ [sys.executable, "-m", "unittest", "-q"],
+ cwd=root,
+ text=True,
+ capture_output=True,
+ timeout=60,
+ check=False,
+ )
+ visible_output = visible.stdout + visible.stderr
+ visible_passed = count_unittest_results(
+ visible_output, task.visible_count, visible.returncode
+ )
+ hidden = subprocess.run(
+ [sys.executable, "-c", task.hidden_grader],
+ cwd=root,
+ text=True,
+ capture_output=True,
+ timeout=60,
+ check=False,
+ )
+ hidden_results: dict[str, Any] = {}
+ try:
+ hidden_results = json.loads(hidden.stdout.splitlines()[-1])
+ except (IndexError, json.JSONDecodeError):
+ pass
+ hidden_passed = sum(value is True for value in hidden_results.values())
+ tests_unchanged = sha256(root / "test_public.py") == test_hash
+ passed = visible_passed + hidden_passed if tests_unchanged else 0
+ total = task.visible_count + task.hidden_count
+ return {
+ "passed": passed,
+ "total": total,
+ "fully_correct": passed == total,
+ "visible_passed": visible_passed,
+ "hidden_passed": hidden_passed,
+ "hidden_results": hidden_results,
+ "tests_unchanged": tests_unchanged,
+ "visible_output": visible_output[-3000:],
+ "hidden_stderr": hidden.stderr[-1000:],
+ }
+
+
+def initialize_workspace(root: Path, task: Task) -> str:
+ root.mkdir(parents=True)
+ (root / task.source_name).write_text(task.source, encoding="utf-8")
+ test_path = root / "test_public.py"
+ test_path.write_text(task.visible_tests, encoding="utf-8")
+ harness = root / ".harness"
+ harness.mkdir()
+ (harness / "settings.json").write_text(
+ json.dumps({"ai_title": False, "skills": {"codedbpro": False}}),
+ encoding="utf-8",
+ )
+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)
+ subprocess.run(["git", "add", task.source_name, "test_public.py"], cwd=root, check=True)
+ subprocess.run(
+ [
+ "git", "-c", "user.name=shape-bench",
+ "-c", "user.email=shape-bench@invalid",
+ "commit", "--no-gpg-sign", "-qm", "fixture",
+ ],
+ cwd=root,
+ check=True,
+ )
+ return sha256(test_path)
+
+
+def trace_metrics(root: Path, arm: Arm) -> dict[str, Any]:
+ trace_rows = read_jsonl_files(sorted((root / ".graff/traces").glob("*.jsonl")))
+ traj_rows = read_jsonl_files(
+ sorted((root / ".graff/trajectories").glob("*.jsonl"))
+ )
+ api = [row for row in trace_rows if row.get("ev") == "api"]
+ tools = [row for row in trace_rows if row.get("ev") == "tool"]
+ children = [row for row in traj_rows if row.get("kind") == "subagent"]
+ root_api = [row for row in api if row.get("agent") == "main"]
+ worker_api = [row for row in api if row.get("agent") != "main"]
+ expected_children = all(row.get("model") == arm.worker_model for row in children)
+ expected_root = all(row.get("model") == ROOT_MODEL for row in root_api)
+ expected_worker_api = all(
+ row.get("model") == arm.worker_model for row in worker_api
+ )
+ return {
+ "api_calls": len(api),
+ "root_api_calls": len(root_api),
+ "worker_api_calls": len(worker_api),
+ "api_ms_sum": sum(max(0, row.get("ms", 0)) for row in api),
+ "root_api_ms_sum": sum(max(0, row.get("ms", 0)) for row in root_api),
+ "worker_api_ms_sum": sum(max(0, row.get("ms", 0)) for row in worker_api),
+ "context_tokens_sum": sum(max(0, row.get("context_tokens", 0)) for row in api),
+ "cache_read_tokens_sum": sum(
+ max(0, row.get("cache_read_tokens", 0)) for row in api
+ ),
+ "request_bytes_sum": sum(max(0, row.get("req_bytes", 0)) for row in api),
+ "response_bytes_sum": sum(max(0, row.get("resp_bytes", 0)) for row in api),
+ "tool_calls": len(tools),
+ "tool_errors": sum(bool(row.get("is_error")) for row in tools),
+ "root_tool_calls": sum(not bool(row.get("from_sub")) for row in tools),
+ "worker_tool_calls": sum(bool(row.get("from_sub")) for row in tools),
+ "child_nodes": len(children),
+ "child_models": [row.get("model") for row in children],
+ "shape_valid": (
+ len(children) == 2
+ and expected_children
+ and expected_root
+ and expected_worker_api
+ and len(worker_api) >= 2
+ ),
+ }
+
+
+def run_one(
+ graff: Path, output_root: Path, task: Task, arm: Arm, repetition: int
+) -> dict[str, Any]:
+ root = output_root / "runs" / f"r{repetition}-{task.name}-{arm.name}"
+ test_hash = initialize_workspace(root, task)
+ env = os.environ.copy()
+ controlled_path = os.pathsep.join(
+ dict.fromkeys((str(Path(sys.executable).parent), "/usr/bin", "/bin"))
+ )
+ env.update(
+ {
+ "GRAFF_FLEET": "off",
+ "GRAFF_BEHAVIOR_UPLOAD": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_NO_SMOLIFY": "1",
+ "GRAFF_NO_CODEDB_GUARD": "1",
+ "PATH": controlled_path,
+ }
+ )
+ command = [
+ str(graff),
+ "--model", ROOT_MODEL,
+ "--no-resume",
+ "--yolo",
+ "--json",
+ "--no-telemetry",
+ "--max-model-calls", "24",
+ "--max-tool-calls", "48",
+ ]
+ if arm.worker_model != ROOT_MODEL:
+ command.extend(["--subagent-model", arm.worker_model])
+ prompt = f"{COMMON_REQUEST}\n\n{task.request}"
+ stdin = (
+ json.dumps({"type": "set_effort", "level": "high"}) + "\n"
+ + json.dumps({"type": "user", "text": prompt}) + "\n"
+ )
+ started = time.monotonic()
+ timed_out = False
+ try:
+ proc = subprocess.run(
+ command,
+ cwd=root,
+ env=env,
+ input=stdin,
+ text=True,
+ capture_output=True,
+ timeout=600,
+ check=False,
+ )
+ returncode, stdout, stderr = proc.returncode, proc.stdout, proc.stderr
+ except subprocess.TimeoutExpired as exc:
+ timed_out = True
+ returncode = 124
+ stdout = exc.stdout if isinstance(exc.stdout, str) else ""
+ stderr = exc.stderr if isinstance(exc.stderr, str) else ""
+ wall_ms = round((time.monotonic() - started) * 1000)
+ checks = run_checks(task, root, test_hash)
+ metrics = trace_metrics(root, arm)
+ diff = subprocess.run(
+ ["git", "diff", "--numstat"],
+ cwd=root,
+ text=True,
+ capture_output=True,
+ check=False,
+ ).stdout
+ changed_lines = 0
+ for line in diff.splitlines():
+ fields = line.split("\t")
+ if len(fields) >= 2 and fields[0].isdigit() and fields[1].isdigit():
+ changed_lines += int(fields[0]) + int(fields[1])
+ events = []
+ for line in stdout.splitlines():
+ try:
+ value = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(value, dict):
+ events.append(value)
+ terminal = next(
+ (event for event in reversed(events) if event.get("type") == "turn"),
+ {},
+ )
+ return {
+ "task": task.name,
+ "arm": arm.name,
+ "root_model": ROOT_MODEL,
+ "worker_model": arm.worker_model,
+ "repetition": repetition,
+ "returncode": returncode,
+ "timed_out": timed_out,
+ "wall_ms": wall_ms,
+ "changed_lines": changed_lines,
+ "reported_cost_usd": terminal.get("cost_usd"),
+ "checks": checks,
+ "metrics": metrics,
+ "stdout_tail": stdout[-4000:],
+ "stderr_tail": stderr[-4000:],
+ "workspace": str(root),
+ }
+
+
+def aggregate(rows: list[dict[str, Any]], arms: tuple[Arm, ...]) -> dict[str, Any]:
+ result = {}
+ for arm in arms:
+ selected = [row for row in rows if row["arm"] == arm.name]
+ correct = [row["checks"]["fully_correct"] for row in selected]
+ shape = [row["metrics"]["shape_valid"] for row in selected]
+ result[arm.name] = {
+ "runs": len(selected),
+ "fully_correct": sum(correct),
+ "correctness_rate": sum(correct) / len(selected),
+ "cases_passed": sum(row["checks"]["passed"] for row in selected),
+ "cases_total": sum(row["checks"]["total"] for row in selected),
+ "shape_valid": sum(shape),
+ "median_wall_ms": statistics.median(row["wall_ms"] for row in selected),
+ "median_api_ms_sum": statistics.median(
+ row["metrics"]["api_ms_sum"] for row in selected
+ ),
+ "median_api_calls": statistics.median(
+ row["metrics"]["api_calls"] for row in selected
+ ),
+ "median_tool_calls": statistics.median(
+ row["metrics"]["tool_calls"] for row in selected
+ ),
+ "median_tool_errors": statistics.median(
+ row["metrics"]["tool_errors"] for row in selected
+ ),
+ "median_context_tokens_sum": statistics.median(
+ row["metrics"]["context_tokens_sum"] for row in selected
+ ),
+ "median_changed_lines": statistics.median(
+ row["changed_lines"] for row in selected
+ ),
+ }
+ return result
+
+
+def compare(rows: list[dict[str, Any]], arms: tuple[Arm, ...]) -> dict[str, Any]:
+ by_arm = {
+ arm.name: [row for row in rows if row["arm"] == arm.name]
+ for arm in arms
+ }
+ baseline, shaped = (by_arm[arm.name] for arm in arms)
+ def unit(row: dict[str, Any]) -> tuple[str, int]:
+ return row["task"], row.get("repetition", 1)
+
+ baseline_by_unit = {unit(row): row for row in baseline}
+ shaped_by_unit = {unit(row): row for row in shaped}
+ paired_units = sorted(set(baseline_by_unit) & set(shaped_by_unit))
+ baseline = [baseline_by_unit[unit_id] for unit_id in paired_units]
+ shaped = [shaped_by_unit[unit_id] for unit_id in paired_units]
+
+ def total(selected: list[dict[str, Any]], field: str) -> int:
+ if field == "wall_ms":
+ return sum(row[field] for row in selected)
+ return sum(row["metrics"][field] for row in selected)
+
+ def delta(shaped_value: int, baseline_value: int) -> float | None:
+ return (
+ (shaped_value / baseline_value - 1) * 100
+ if baseline_value
+ else None
+ )
+
+ paired_wall_deltas = [
+ delta(
+ shaped_by_unit[unit_id]["wall_ms"],
+ baseline_by_unit[unit_id]["wall_ms"],
+ )
+ for unit_id in paired_units
+ ]
+ def effective_correctness(row: dict[str, Any]) -> int:
+ return (
+ row["checks"]["passed"]
+ if row["metrics"].get("shape_valid", True)
+ else 0
+ )
+
+ baseline_correct = sum(effective_correctness(row) for row in baseline)
+ shaped_correct = sum(effective_correctness(row) for row in shaped)
+ baseline_shapes = sum(
+ row["metrics"].get("shape_valid", True) for row in baseline
+ )
+ shaped_shapes = sum(
+ row["metrics"].get("shape_valid", True) for row in shaped
+ )
+ baseline_tools = total(baseline, "tool_calls")
+ shaped_tools = total(shaped, "tool_calls")
+ provisional = (
+ arms[1].name
+ if shaped_correct > baseline_correct
+ or (shaped_correct == baseline_correct and shaped_tools < baseline_tools)
+ else arms[0].name
+ )
+ pairs = len(paired_units)
+ return {
+ "selection_policy": "correctness_first_then_tool_economy",
+ "provisional_winner": provisional,
+ "manual_promotion_required": (
+ pairs < MINIMUM_PAIRS_FOR_PROMOTION
+ or baseline_shapes != pairs
+ or shaped_shapes != pairs
+ ),
+ "minimum_pairs_for_promotion": MINIMUM_PAIRS_FOR_PROMOTION,
+ "observed_pairs": pairs,
+ "correctness": {
+ arms[0].name: baseline_correct,
+ arms[1].name: shaped_correct,
+ },
+ "valid_shapes": {
+ arms[0].name: baseline_shapes,
+ arms[1].name: shaped_shapes,
+ },
+ "total_wall_ms": {
+ arms[0].name: total(baseline, "wall_ms"),
+ arms[1].name: total(shaped, "wall_ms"),
+ },
+ "total_wall_delta_pct": delta(
+ total(shaped, "wall_ms"), total(baseline, "wall_ms")
+ ),
+ "median_paired_wall_delta_pct": (
+ statistics.median(value for value in paired_wall_deltas if value is not None)
+ if paired_wall_deltas
+ else None
+ ),
+ "faster_pairs": sum(
+ value is not None and value < 0 for value in paired_wall_deltas
+ ),
+ "total_tool_calls": {
+ arms[0].name: baseline_tools,
+ arms[1].name: shaped_tools,
+ },
+ "tool_call_delta_pct": delta(shaped_tools, baseline_tools),
+ "api_call_delta_pct": delta(
+ total(shaped, "api_calls"), total(baseline, "api_calls")
+ ),
+ "context_token_delta_pct": delta(
+ total(shaped, "context_tokens_sum"),
+ total(baseline, "context_tokens_sum"),
+ ),
+ "response_byte_delta_pct": delta(
+ total(shaped, "response_bytes_sum"),
+ total(baseline, "response_bytes_sum"),
+ ),
+ }
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--graff", default="zig-out/bin/graff")
+ parser.add_argument("--repetitions", type=int, default=1)
+ parser.add_argument("--seed", type=int, default=246)
+ parser.add_argument("--output-root")
+ parser.add_argument("--tasks", nargs="*", choices=[task.name for task in TASKS])
+ args = parser.parse_args()
+ if args.repetitions < 1:
+ parser.error("--repetitions must be positive")
+ graff = Path(args.graff).expanduser().resolve()
+ if not graff.is_file():
+ parser.error(f"graff binary not found: {graff}")
+ if args.output_root:
+ output_root = Path(args.output_root).expanduser().resolve()
+ output_root.mkdir(parents=True, exist_ok=False)
+ else:
+ output_root = Path(
+ tempfile.mkdtemp(
+ prefix=f"codegraff-model-shape-{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}-"
+ )
+ )
+ tasks = tuple(
+ task for task in TASKS if not args.tasks or task.name in args.tasks
+ )
+ arms = (
+ Arm("all-sol", ROOT_MODEL),
+ Arm("sol-terra", WORKER_MODEL),
+ )
+ schedule = []
+ rng = random.Random(args.seed)
+ for repetition in range(1, args.repetitions + 1):
+ shuffled = list(tasks)
+ rng.shuffle(shuffled)
+ ordered_arms = arms if repetition % 2 else tuple(reversed(arms))
+ for task in shuffled:
+ schedule.extend((task, arm, repetition) for arm in ordered_arms)
+ rows = []
+ for index, (task, arm, repetition) in enumerate(schedule, 1):
+ print(
+ f"[{index}/{len(schedule)}] {task.name} {arm.name} repetition {repetition}",
+ flush=True,
+ )
+ row = run_one(graff, output_root, task, arm, repetition)
+ rows.append(row)
+ print(
+ " "
+ f"correct={row['checks']['passed']}/{row['checks']['total']} "
+ f"shape={row['metrics']['shape_valid']} "
+ f"wall={row['wall_ms'] / 1000:.1f}s "
+ f"api={row['metrics']['api_calls']} "
+ f"tools={row['metrics']['tool_calls']}",
+ flush=True,
+ )
+ report = {
+ "schema": "codegraff.model-shape-benchmark.v1",
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ "graff": str(graff),
+ "seed": args.seed,
+ "repetitions": args.repetitions,
+ "tasks": [task.name for task in tasks],
+ "privacy": {
+ "workspace": "synthetic",
+ "external_telemetry": False,
+ "behavior_upload": False,
+ },
+ "arms": [asdict(arm) for arm in arms],
+ "runs": rows,
+ "aggregate": aggregate(rows, arms),
+ }
+ report["comparison"] = compare(rows, arms)
+ report_path = output_root / "report.json"
+ report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print("\n" + json.dumps(report["aggregate"], indent=2))
+ print("\ncomparison:\n" + json.dumps(report["comparison"], indent=2))
+ print(f"\nreport: {report_path}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/benchmarks/model_shape_tasks.py b/benchmarks/model_shape_tasks.py
new file mode 100644
index 00000000..6d4af50c
--- /dev/null
+++ b/benchmarks/model_shape_tasks.py
@@ -0,0 +1,438 @@
+"""Synthetic fixtures for the root/worker model-shape benchmark."""
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class Task:
+ name: str
+ source_name: str
+ source: str
+ visible_tests: str
+ visible_count: int
+ hidden_grader: str
+ hidden_count: int
+ request: str
+
+
+
+TASKS = (
+ Task(
+ name="expiring_lru",
+ source_name="lease_cache.py",
+ source="""\
+from collections import OrderedDict
+
+
+class ExpiringLRU:
+ def __init__(self, capacity, ttl, clock):
+ self.capacity = capacity
+ self.ttl = ttl
+ self.clock = clock
+ self._items = OrderedDict()
+
+ def put(self, key, value):
+ self._items[key] = (value, self.clock() + self.ttl)
+
+ def get(self, key):
+ return self._items[key][0]
+
+ def purge_expired(self):
+ return 0
+
+ def keys(self):
+ return list(self._items)
+
+ def __len__(self):
+ return len(self._items)
+""",
+ visible_tests="""\
+import unittest
+from lease_cache import ExpiringLRU
+
+
+class FakeClock:
+ def __init__(self):
+ self.now = 0.0
+ def __call__(self):
+ return self.now
+
+
+class CacheTests(unittest.TestCase):
+ def test_get_refreshes_recency_and_capacity_evicts_lru(self):
+ clock = FakeClock()
+ cache = ExpiringLRU(2, 10, clock)
+ cache.put("a", 1)
+ cache.put("b", 2)
+ self.assertEqual(cache.get("a"), 1)
+ cache.put("c", 3)
+ with self.assertRaises(KeyError):
+ cache.get("b")
+ self.assertEqual(cache.keys(), ["c", "a"])
+
+ def test_expiration_is_lazy_and_boundary_is_expired(self):
+ clock = FakeClock()
+ cache = ExpiringLRU(2, 5, clock)
+ cache.put("a", 1)
+ clock.now = 5
+ with self.assertRaises(KeyError):
+ cache.get("a")
+ self.assertEqual(len(cache), 0)
+
+ def test_overwrite_refreshes_ttl_and_recency(self):
+ clock = FakeClock()
+ cache = ExpiringLRU(2, 5, clock)
+ cache.put("a", 1)
+ clock.now = 4
+ cache.put("a", 9)
+ clock.now = 6
+ self.assertEqual(cache.get("a"), 9)
+
+ def test_purge_reports_removed_items(self):
+ clock = FakeClock()
+ cache = ExpiringLRU(3, 2, clock)
+ cache.put("a", 1)
+ cache.put("b", 2)
+ clock.now = 2
+ self.assertEqual(cache.purge_expired(), 2)
+ self.assertEqual(cache.keys(), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+from lease_cache import ExpiringLRU
+
+results = {}
+def check(name, fn):
+ try:
+ fn()
+ results[name] = True
+ except Exception as exc:
+ results[name] = f"{type(exc).__name__}: {exc}"
+
+class Clock:
+ def __init__(self): self.now = 0
+ def __call__(self): return self.now
+
+def validation():
+ for capacity, ttl in ((0, 1), (-1, 1), (1, 0), (1, -1)):
+ try:
+ ExpiringLRU(capacity, ttl, Clock())
+ except (ValueError, TypeError):
+ continue
+ raise AssertionError((capacity, ttl))
+
+def expired_before_capacity():
+ c = Clock(); x = ExpiringLRU(2, 2, c)
+ x.put("old", 1); c.now = 1; x.put("live", 2); c.now = 2
+ x.put("new", 3)
+ assert x.keys() == ["new", "live"]
+
+def order_and_len_purge():
+ c = Clock(); x = ExpiringLRU(3, 2, c)
+ x.put("a", 1); c.now = 1; x.put("b", 2)
+ assert x.keys() == ["b", "a"]
+ c.now = 2
+ assert len(x) == 1 and x.keys() == ["b"]
+
+def missing_key():
+ x = ExpiringLRU(1, 2, Clock())
+ try: x.get("missing")
+ except KeyError as exc: assert exc.args == ("missing",)
+ else: raise AssertionError("missing key did not raise")
+
+def clock_called_once_per_operation():
+ calls = [0]
+ def clock():
+ calls[0] += 1
+ return 0
+ x = ExpiringLRU(2, 2, clock)
+ x.put("a", 1); before = calls[0]; x.get("a")
+ assert calls[0] == before + 1
+
+for item in (
+ ("validation", validation),
+ ("expired_before_capacity", expired_before_capacity),
+ ("order_and_len_purge", order_and_len_purge),
+ ("missing_key", missing_key),
+ ("clock_called_once_per_operation", clock_called_once_per_operation),
+): check(*item)
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `lease_cache.py`. The required behavior is an expiring LRU cache:
+capacity and ttl must be positive; `put` refreshes TTL and MRU position;
+`get` returns a live value and moves it to MRU; an item is expired when
+`clock() >= deadline`; expired entries never consume capacity; `purge_expired`
+returns the number removed; `keys` returns live keys MRU-to-LRU; and `len`
+counts only live entries. Preserve normal `KeyError(key)` behavior.
+""",
+ ),
+ Task(
+ name="route_precedence",
+ source_name="router.py",
+ source="""\
+from urllib.parse import urlsplit
+
+
+class Router:
+ def __init__(self):
+ self._routes = []
+
+ def add(self, method, pattern, handler):
+ self._routes.append((method, pattern, handler))
+
+ def resolve(self, method, target):
+ path = urlsplit(target).path
+ for route_method, pattern, handler in self._routes:
+ if route_method == method and pattern == path:
+ return handler, {}
+ raise LookupError((method, target))
+""",
+ visible_tests="""\
+import unittest
+from router import Router
+
+
+class RouterTests(unittest.TestCase):
+ def test_params_and_query(self):
+ r = Router()
+ r.add("GET", "/teams/{team}/repos/{repo}", "repo")
+ self.assertEqual(
+ r.resolve("get", "/teams/acme/repos/widget?tab=issues"),
+ ("repo", {"team": "acme", "repo": "widget"}),
+ )
+
+ def test_static_route_beats_parameter_route(self):
+ r = Router()
+ r.add("GET", "/users/{name}", "profile")
+ r.add("GET", "/users/me", "self")
+ self.assertEqual(r.resolve("GET", "/users/me"), ("self", {}))
+
+ def test_head_falls_back_to_get(self):
+ r = Router()
+ r.add("GET", "/health", "ok")
+ self.assertEqual(r.resolve("HEAD", "/health"), ("ok", {}))
+
+ def test_duplicate_replaces_handler(self):
+ r = Router()
+ r.add("POST", "/jobs/{id}", "old")
+ r.add("post", "/jobs/{id}", "new")
+ self.assertEqual(r.resolve("POST", "/jobs/7"), ("new", {"id": "7"}))
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+from router import Router
+
+results = {}
+def check(name, fn):
+ try:
+ fn(); results[name] = True
+ except Exception as exc:
+ results[name] = f"{type(exc).__name__}: {exc}"
+
+def utf8_decode():
+ r = Router(); r.add("GET", "/cafes/{name}", "cafe")
+ assert r.resolve("GET", "/cafes/caf%C3%A9") == ("cafe", {"name": "café"})
+
+def reject_encoded_separator():
+ r = Router(); r.add("GET", "/files/{name}", "file")
+ try: r.resolve("GET", "/files/a%2Fb")
+ except (LookupError, ValueError): return
+ raise AssertionError("encoded slash accepted")
+
+def validate_patterns():
+ bad = ("relative", "/x/{bad-name}", "/x/{id}/{id}", "/x/{oops")
+ for pattern in bad:
+ try: Router().add("GET", pattern, "x")
+ except (ValueError, TypeError): continue
+ raise AssertionError(pattern)
+
+def equal_specificity_is_registration_order():
+ r = Router()
+ r.add("GET", "/{left}/fixed", "first")
+ r.add("GET", "/fixed/{right}", "second")
+ assert r.resolve("GET", "/fixed/fixed")[0] == "first"
+
+def explicit_head_wins():
+ r = Router()
+ r.add("GET", "/health", "get")
+ r.add("HEAD", "/health", "head")
+ assert r.resolve("HEAD", "/health") == ("head", {})
+
+for item in (
+ ("utf8_decode", utf8_decode),
+ ("reject_encoded_separator", reject_encoded_separator),
+ ("validate_patterns", validate_patterns),
+ ("equal_specificity_is_registration_order", equal_specificity_is_registration_order),
+ ("explicit_head_wins", explicit_head_wins),
+): check(*item)
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `router.py`. Methods are case-insensitive. Patterns start with `/` and
+contain literal segments or unique `{identifier}` parameters. Reject malformed
+patterns. Ignore the query string, percent-decode each target segment as strict
+UTF-8, and reject a decoded slash, NUL, or malformed escape. Match the route
+with the most literal segments; preserve registration order on ties. Re-adding
+the same method/pattern replaces its handler without changing precedence.
+An explicit HEAD route wins, otherwise HEAD may fall back to GET.
+""",
+ ),
+ Task(
+ name="atomic_inventory",
+ source_name="inventory.py",
+ source="""\
+class OrderConflict(Exception):
+ pass
+
+
+class InsufficientStock(Exception):
+ pass
+
+
+class Inventory:
+ def __init__(self, stock):
+ self._stock = dict(stock)
+ self._orders = {}
+
+ def reserve(self, order_id, request):
+ for sku, quantity in request.items():
+ self._stock[sku] = self._stock.get(sku, 0) - quantity
+ receipt = {"order_id": order_id, "items": dict(request)}
+ self._orders[order_id] = receipt
+ return receipt
+
+ def release(self, order_id):
+ receipt = self._orders.pop(order_id)
+ for sku, quantity in receipt["items"].items():
+ self._stock[sku] = self._stock.get(sku, 0) + quantity
+ return True
+
+ def snapshot(self):
+ return self._stock
+""",
+ visible_tests="""\
+import unittest
+from inventory import Inventory, InsufficientStock, OrderConflict
+
+
+class InventoryTests(unittest.TestCase):
+ def test_atomic_failure(self):
+ x = Inventory({"a": 3, "b": 1})
+ with self.assertRaises(InsufficientStock):
+ x.reserve("o1", {"a": 2, "b": 2})
+ self.assertEqual(x.snapshot(), {"a": 3, "b": 1})
+
+ def test_idempotent_same_order(self):
+ x = Inventory({"a": 3})
+ one = x.reserve("o1", {"a": 2})
+ two = x.reserve("o1", {"a": 2})
+ self.assertEqual(one, two)
+ self.assertEqual(x.snapshot(), {"a": 1})
+
+ def test_conflicting_reuse(self):
+ x = Inventory({"a": 3})
+ x.reserve("o1", {"a": 1})
+ with self.assertRaises(OrderConflict):
+ x.reserve("o1", {"a": 2})
+ self.assertEqual(x.snapshot(), {"a": 2})
+
+ def test_release_is_idempotent(self):
+ x = Inventory({"a": 3})
+ x.reserve("o1", {"a": 2})
+ self.assertTrue(x.release("o1"))
+ self.assertFalse(x.release("o1"))
+ self.assertEqual(x.snapshot(), {"a": 3})
+
+
+if __name__ == "__main__":
+ unittest.main()
+""",
+ visible_count=4,
+ hidden_grader="""\
+import json
+from inventory import Inventory, InsufficientStock, OrderConflict
+
+results = {}
+def check(name, fn):
+ try:
+ fn(); results[name] = True
+ except Exception as exc:
+ results[name] = f"{type(exc).__name__}: {exc}"
+
+def validate_stock_and_request():
+ for stock in ({"a": -1}, {"a": True}, {"a": 1.5}):
+ try: Inventory(stock)
+ except (ValueError, TypeError): continue
+ raise AssertionError(stock)
+ x = Inventory({"a": 2})
+ for req in ({}, {"a": 0}, {"a": -1}, {"a": True}, {"a": 1.5}):
+ try: x.reserve("o", req)
+ except (ValueError, TypeError): continue
+ raise AssertionError(req)
+
+def normalized_idempotency():
+ x = Inventory({"a": 3, "b": 4})
+ first = x.reserve("o", {"a": 1, "b": 2})
+ second = x.reserve("o", {"b": 2, "a": 1})
+ assert first == second and x.snapshot() == {"a": 2, "b": 2}
+
+def missing_sku_is_atomic():
+ x = Inventory({"a": 3})
+ try: x.reserve("o", {"a": 1, "missing": 1})
+ except InsufficientStock: pass
+ else: raise AssertionError("missing sku accepted")
+ assert x.snapshot() == {"a": 3}
+
+def defensive_copies():
+ initial = {"a": 3}; request = {"a": 1}
+ x = Inventory(initial); receipt = x.reserve("o", request)
+ initial["a"] = 99; request["a"] = 99; receipt["items"]["a"] = 99
+ assert x.snapshot() == {"a": 2}
+ x.release("o")
+ assert x.snapshot() == {"a": 3}
+
+def released_id_stays_idempotent():
+ x = Inventory({"a": 3})
+ receipt = x.reserve("o", {"a": 1})
+ x.release("o")
+ assert x.reserve("o", {"a": 1}) == receipt
+ assert x.snapshot() == {"a": 3}
+ try: x.reserve("o", {"a": 2})
+ except OrderConflict: return
+ raise AssertionError("released id accepted conflicting request")
+
+for item in (
+ ("validate_stock_and_request", validate_stock_and_request),
+ ("normalized_idempotency", normalized_idempotency),
+ ("missing_sku_is_atomic", missing_sku_is_atomic),
+ ("defensive_copies", defensive_copies),
+ ("released_id_stays_idempotent", released_id_stays_idempotent),
+): check(*item)
+print(json.dumps(results, sort_keys=True))
+""",
+ hidden_count=5,
+ request="""\
+Repair `inventory.py`. Initial stock must contain only nonnegative plain ints.
+Reservations require a nonempty order id and nonempty mapping of positive plain
+int quantities. A reservation is atomic: insufficient or missing stock raises
+`InsufficientStock` without mutation. Repeating an order id with the same
+normalized request is idempotent, even after release; a different request raises
+`OrderConflict`. Release restores stock at most once and returns whether it did
+work. Caller mutations must never alter internal state; `snapshot` is a copy.
+""",
+ ),
+)
+
diff --git a/benchmarks/test_model_shape.py b/benchmarks/test_model_shape.py
new file mode 100644
index 00000000..83c5affe
--- /dev/null
+++ b/benchmarks/test_model_shape.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python3
+"""Offline integrity checks for the live model-shape benchmark."""
+
+from __future__ import annotations
+
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).parent))
+
+import model_shape
+from model_shape_tasks import TASKS
+
+
+def fake_run(
+ task: str,
+ arm: str,
+ passed: int,
+ wall_ms: int,
+ tools: int,
+ repetition: int = 1,
+) -> dict:
+ return {
+ "task": task,
+ "arm": arm,
+ "repetition": repetition,
+ "wall_ms": wall_ms,
+ "checks": {"passed": passed},
+ "metrics": {
+ "tool_calls": tools,
+ "api_calls": 4,
+ "context_tokens_sum": 100,
+ "response_bytes_sum": 200,
+ },
+ }
+
+
+def check_selection() -> None:
+ arms = (
+ model_shape.Arm("all-sol", model_shape.ROOT_MODEL),
+ model_shape.Arm("sol-terra", model_shape.WORKER_MODEL),
+ )
+ rows = []
+ for index in range(3):
+ rows.append(fake_run(f"task-{index}", "all-sol", 9, 120, 12))
+ rows.append(fake_run(f"task-{index}", "sol-terra", 9, 90, 8))
+ comparison = model_shape.compare(rows, arms)
+ assert comparison["provisional_winner"] == "sol-terra"
+ assert comparison["selection_policy"] == "correctness_first_then_tool_economy"
+ assert comparison["manual_promotion_required"] is True
+ assert comparison["observed_pairs"] == 3
+ assert comparison["total_wall_delta_pct"] == -25
+
+ rows[-1]["checks"]["passed"] = 8
+ comparison = model_shape.compare(rows, arms)
+ assert comparison["provisional_winner"] == "all-sol"
+
+ powered = []
+ for repetition in range(1, 8):
+ for index in range(3):
+ powered.append(
+ fake_run(
+ f"task-{index}", "all-sol", 9, 120, 12, repetition
+ )
+ )
+ powered.append(
+ fake_run(
+ f"task-{index}", "sol-terra", 9, 90, 8, repetition
+ )
+ )
+ comparison = model_shape.compare(powered, arms)
+ assert comparison["observed_pairs"] == 21
+ assert comparison["manual_promotion_required"] is False
+
+ powered[-1]["metrics"]["shape_valid"] = False
+ comparison = model_shape.compare(powered, arms)
+ assert comparison["provisional_winner"] == "all-sol"
+ assert comparison["valid_shapes"]["sol-terra"] == 20
+ assert comparison["manual_promotion_required"] is True
+
+
+def check_fixtures() -> None:
+ expected_starter_scores = {
+ "expiring_lru": 2,
+ "route_precedence": 3,
+ "atomic_inventory": 0,
+ }
+ with tempfile.TemporaryDirectory(prefix="shape-fixture-check-") as raw:
+ base = Path(raw)
+ for task in TASKS:
+ root = base / task.name
+ digest = model_shape.initialize_workspace(root, task)
+ grade = model_shape.run_checks(task, root, digest)
+ assert grade["total"] == task.visible_count + task.hidden_count == 9
+ assert grade["passed"] == expected_starter_scores[task.name]
+ assert len(grade["hidden_results"]) == task.hidden_count == 5
+ assert grade["tests_unchanged"] is True
+
+
+def main() -> None:
+ check_selection()
+ check_fixtures()
+ print("ok model-shape selection policy and synthetic fixtures")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/releases/v0.0.215.md b/docs/releases/v0.0.215.md
index 90a7c958..1a3e55d0 100644
--- a/docs/releases/v0.0.215.md
+++ b/docs/releases/v0.0.215.md
@@ -99,6 +99,12 @@ and connects Streamable HTTP tools without a Node bridge.
- Aggregate receipt signature and deletion-token cross-checks
- Privacy efficacy suite, including an API-key canary that was absent from all
8/8 captured SDK egress cases
+- A live three-task paired root/worker benchmark kept both arms at 27/27
+ correctness and exact routing. Sol-root/Terra-workers used 29.3% fewer tools
+ and 11.4% less total wall time, but only 1.6% fewer model calls, used 1.4%
+ more summed context tokens, and was 2.5% slower on one task. Three pairs are
+ intentionally under the 20-pair promotion floor, so the result is provisional
+ and cannot change the default.
This branch intentionally requires manual promotion until the evidence is
adequately powered.