ContextBench: paper task set (256 instances) and Harbor tasks
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.mdAdded+132
- data/kv_store.parquetAdded+3
- data/log_triage.parquetAdded+3
- data/needle_retention.parquetAdded+3
- data/sudoku_sketchpad.parquetAdded+3
- harbor/kv-store-R1000-seed42/environment/stream/chunks.jsonlAdded
- harbor/kv-store-R1000-seed42/instruction.mdAdded+61
- harbor/kv-store-R1000-seed42/solution/solve.shAdded+79
- harbor/kv-store-R1000-seed42/task.tomlAdded+44
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/__init__.pyAdded+56
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/__init__.pyAdded+70
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/base.pyAdded+305
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/kv.pyAdded+87
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/log.pyAdded+116
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/needle.pyAdded+109
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/sudoku.pyAdded+225
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/__init__.pyAdded+32
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/mixin.pyAdded+122
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/reward.pyAdded+98
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/turn_source.pyAdded+399
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/runner.pyAdded+216
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/stream.pyAdded+244
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/tokens.pyAdded+171
- harbor/kv-store-R1000-seed42/tests/feasibility_receipt.jsonAdded+38
- harbor/kv-store-R1000-seed42/tests/gold.jsonAdded+138
- harbor/kv-store-R1000-seed42/tests/meta.jsonAdded+14
- harbor/kv-store-R1000-seed42/tests/test.shAdded+10
- harbor/kv-store-R1000-seed43/environment/stream/chunks.jsonlAdded
- harbor/kv-store-R1000-seed43/instruction.mdAdded+61
- harbor/kv-store-R1000-seed43/solution/solve.shAdded+79
- harbor/kv-store-R1000-seed43/task.tomlAdded+44
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/__init__.pyAdded+56
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/__init__.pyAdded+70
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/base.pyAdded+305
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/kv.pyAdded+87
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/log.pyAdded+116
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/needle.pyAdded+109
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/sudoku.pyAdded+225
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/__init__.pyAdded+32
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/mixin.pyAdded+122
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/reward.pyAdded+98
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/turn_source.pyAdded+399
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/runner.pyAdded+216
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/stream.pyAdded+244
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/tokens.pyAdded+171
- harbor/kv-store-R1000-seed43/tests/feasibility_receipt.jsonAdded+38
- harbor/kv-store-R1000-seed43/tests/gold.jsonAdded+138
- harbor/kv-store-R1000-seed43/tests/meta.jsonAdded+14
- harbor/kv-store-R1000-seed43/tests/test.shAdded+10
- harbor/kv-store-R1000-seed44/environment/stream/chunks.jsonlAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132---license: apache-2.0pretty_name: ContextBenchlanguage:- entags:- agents- long-context- context-management- benchmarksize_categories:- n<1Kconfigs:- config_name: all default: true data_files: - split: test path: data/*.parquet- config_name: kv_store data_files: - split: test path: data/kv_store.parquet- config_name: log_triage data_files: - split: test path: data/log_triage.parquet- config_name: needle_retention data_files: - split: test path: data/needle_retention.parquet- config_name: sudoku_sketchpad data_files: - split: test path: data/sudoku_sketchpad.parquet---
# ContextBench
ContextBench measures what an agent keeps, updates, and offloads when its input doesnot fit in its context window. Each task streams a sequence of operations as ordinaryuser turns, more than the context budget holds, and the reward is read from theagent's own messages: what survived in its context, not what it wrote to disk.
Paper: [https://huggingface.co/papers/2609.37725](https://huggingface.co/papers/2609.37725)
## Families
| config | task | reward ||---|---|---|| `kv_store` | batches of `SET key = value`, then `GET key` queries | fraction of GETs answered with the right value || `log_triage` | batches of service log lines, then count and lookup questions | fraction of questions answered correctly || `needle_retention` | chunks with a few needle lines inside a large filler block | fraction of needle lines still present verbatim || `sudoku_sketchpad` | one fully specified move per turn on a 16x16 board | fraction of gold board versions the agent displayed |
The `all` config holds every instance. This release has 256 instances:64 `kv_store`, 56 `log_triage`, 80 `needle_retention`, 56 `sudoku_sketchpad` (32 levels, seeds 42-49), with a context budget of 32768 tokensand a reserve of 2048.
## Columns
| column | type | meaning ||---|---|---|| `task_id` | string | `<family>-<level>-seed<seed>`, also the Harbor task directory name || `family` | string | task family || `level` | string | difficulty level || `seed` | int | generator seed || `budget` | int | context budget in tokens || `reserve` | int | tokens reserved for the reply; the agent may use `budget - reserve` || `n_ops` | int | number of streamed operations || `streamed_tokens` | int | tokens streamed over the episode (`o200k_base`) || `pressure` | float | `streamed_tokens / budget` || `chunks` | list of `{index, header, body}` | the operations, one user turn each || `gold` | string (JSON) | the answers the graders score against || `meta` | string (JSON) | generator settings and instance statistics |
Each operation is shown to the agent as`=== {header} ({remaining} op(s) remaining after this) ===` followed by its body.
## Usage
### With `datasets`
```pythonimport jsonfrom datasets import load_dataset
ds = load_dataset("context-language-model/ContextBench", "kv_store", split="test") # or "all"row = ds[0]ops = row["chunks"] # list of {"index", "header", "body"}gold = json.loads(row["gold"])```
To evaluate an agent from Python, install the `contextbench` package, write aninstance to disk, and pass your agent to `contextbench.run`:
```pythonfrom pathlib import Pathfrom contextbench import run
inst = Path("instances") / row["task_id"]inst.mkdir(parents=True, exist_ok=True)(inst / "chunks.jsonl").write_text( "".join(json.dumps(c) + "\n" for c in row["chunks"]))(inst / "gold.json").write_text(row["gold"])(inst / "meta.json").write_text(row["meta"])
result = run(my_agent, inst, budget=row["budget"], reserve=row["reserve"], out_dir=Path("runs") / row["task_id"])```
### With Harbor
The `harbor/` directory holds one Harbor task per instance, and `registry.json`lists the datasets `contextbench` (every task) and `contextbench-<family>`(for example `contextbench-kv-store`). Download the repository, then run Harborfrom inside it:
```bashhf download context-language-model/ContextBench --repo-type dataset --local-dir contextbench-hfcd contextbench-hfharbor jobs start --registry-path registry.json -d contextbench \ -a contextbench.harbor.agents:Terminus2Stream -m <model>```
Use `-d contextbench-sudoku-sketchpad` for one family, `-i <task_id>` for one task,`-p harbor/` to run the directory without the registry, or `-a oracle` to check atask with its reference solution. Agents that deliver operations into a runningconversation ship with the `contextbench` package (`contextbench.harbor.agents`).
## License
Apache-2.0.123version https://git-lfs.github.com/spec/v1oid sha256:7cf5f19812143495fdec73e097d67ba6a36b3ebe98cb63dcacdae4cab5440e11size 11894440123version https://git-lfs.github.com/spec/v1oid sha256:99ba1f0f479c5cc4780c61572323db642e90a50b45736c9459c9c97cc12bc3basize 5891832123version https://git-lfs.github.com/spec/v1oid sha256:4676617211f8beb029303629922630cb27458c9254794093a06eef3ff0ec2bfesize 40076404123version https://git-lfs.github.com/spec/v1oid sha256:5130d8cd005f47dbe7f0ffaedf0ec5b56b4d9429ed1a777b8835e3e70aece9d2size 14418212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Key-Value Store - process graded (interactive)
Operations are delivered to you ONE AT A TIME, as messages in this conversation.You do NOT fetch them: each operation arrives automatically as the next usermessage, and you receive the following operation only after you finish thecurrent turn. The stream has two phases:
1. a long run of **SET-BATCH** blocks, each delimited by unique `<<<SET-BATCH <id> BEGIN ...>>>` / `<<<SET-BATCH <id> END>>>` sentinel lines and carrying many lines of the form `SET <key> = <value>` (each `<value>` is a random, unguessable token; each key is set exactly once), then2. a run of **GET** ops at the end: `GET <key>` - report the value you stored earlier for `<key>`.
Because every `SET` arrives before any `GET`, you cannot predict which keys willbe queried - you must be able to recall **any** value you have seen.
## Turn protocol (IMPORTANT)Each incoming message is ONE operation. Do whatever work it needs FIRST (offload,`grep`, emit an ANSWER block, ...). When you are done with the current operation,**end your turn** by running this single command with the `bash` tool to receivethe next operation:
```echo READY_FOR_NEXT_OP```
This is a multi-turn task: the harness RUNS this command and then delivers thenext operation as the next user message. You MAY bundle real work into the SAMEcommand — in fact the cleanest way to answer a GET is to pipe the stored valuestraight into an ANSWER block and emit the marker together, e.g.:
```printf '<<<ANSWER key=K00084>>>\n%s\n<<<ANSWER END>>>\n' "$val"; echo READY_FOR_NEXT_OP```
ONLY running `echo READY_FOR_NEXT_OP` advances to the next operation — a replywith no tool call does NOT advance (it just prompts you to keep going). Do NOT runthe marker until you have fully handled the current operation (offloaded thebatch, or emitted the GET ANSWER block).
## How to answer a GET
When you read a `GET <key>`, reply with an **ANSWER block** on its own lines,carrying the value **verbatim**:
```<<<ANSWER key=<key>>>><the exact value you stored for <key>><<<ANSWER END>>>```
## How you are graded
Process-graded: for every `GET`, the ANSWER block you emit must contain thecorrect value. Grading reads your **context** (the ANSWER blocks across yourturns). You MAY use the disk as scratch/storage, but FINDING a value (e.g. with`grep`) is NOT answering — only an ANSWER block that actually appears in yourcontext is scored, so you must PRINT the value inside `<<<ANSWER ...>>>` ...`<<<ANSWER END>>>`.The run ends automatically after the final operation; you do not need to submit.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#!/usr/bin/env bash# Oracle: writes every gold answer into the agent log dir as a final report.# Graded as graded_from=final_report, never comparable to a context grade.set -euo pipefailmkdir -p /logs/agentcat > /logs/agent/final_report.txt <<'CONTEXTBENCH_ORACLE_EOF'<<<ANSWER key=K00048>>>kindle boulder garnet fathom cinder thistle ember pewter cinder vellum marble onyx verdant garnet spruce onyx thistle glacier cinder glacier indigo lattice willow russet #948823b5<<<ANSWER END>>><<<ANSWER key=K00465>>>harbor lattice zebra boulder willow crimson thistle pewter glacier fathom fathom copper pewter auburn zebra willow auburn cobalt meadow marble fathom onyx mistral ember #a95c5171<<<ANSWER END>>><<<ANSWER key=K00600>>>ember glacier lattice spruce kindle spruce marble copper onyx thistle marble garnet willow cedar lantern fathom thistle cobble willow meadow trellis falcon spruce trellis #b68a208a<<<ANSWER END>>><<<ANSWER key=K00135>>>pewter falcon meadow copper indigo thistle lantern orbit auburn vellum onyx harbor onyx cobble auburn copper mistral auburn thistle russet marble harbor vellum meadow #38614f46<<<ANSWER END>>><<<ANSWER key=K00224>>>onyx nimbus harbor boulder nimbus garnet lattice zebra cobalt trellis glacier lattice auburn meadow cinder meadow boulder russet quartz ember saffron verdant kindle onyx #4191f4d6<<<ANSWER END>>><<<ANSWER key=K00492>>>verdant glacier harbor lattice kindle lantern spruce onyx orbit meadow cedar fathom willow saffron cobalt nimbus vellum zebra saffron cedar fathom onyx nimbus lantern #f68ab589<<<ANSWER END>>><<<ANSWER key=K00798>>>copper quartz lattice copper pewter falcon willow harbor willow vellum marble cedar kindle nimbus lantern boulder lattice russet marble copper marble quartz marble cinder #a0f5d114<<<ANSWER END>>><<<ANSWER key=K00150>>>cobble cobalt quartz cinder cinder spruce cinder russet auburn lantern zebra mistral cedar lattice lantern glacier kindle cedar crimson lantern falcon marble copper trellis #94342d3b<<<ANSWER END>>><<<ANSWER key=K00603>>>russet indigo mistral cobalt cobalt falcon thistle garnet auburn verdant falcon russet zebra glacier trellis vellum pewter onyx thistle lantern quartz crimson fathom vellum #71fb2dea<<<ANSWER END>>><<<ANSWER key=K00568>>>harbor lattice crimson cinder trellis willow zebra garnet onyx mistral marble spruce quartz copper pewter spruce onyx onyx garnet vellum vellum auburn garnet lattice #a66280c1<<<ANSWER END>>><<<ANSWER key=K00147>>>glacier quartz crimson cobble boulder indigo onyx spruce auburn zebra cedar verdant marble mistral russet copper fathom trellis harbor nimbus boulder thistle russet quartz #0d8bf269<<<ANSWER END>>><<<ANSWER key=K00396>>>cedar cobble nimbus boulder crimson trellis harbor nimbus spruce cedar meadow willow meadow cinder falcon garnet spruce thistle kindle quartz lantern thistle auburn auburn #144b8f86<<<ANSWER END>>><<<ANSWER key=K00566>>>willow glacier orbit ember meadow onyx kindle mistral crimson harbor glacier lattice zebra willow thistle marble lantern auburn lantern orbit auburn ember marble zebra #6438087d<<<ANSWER END>>><<<ANSWER key=K00621>>>onyx trellis harbor kindle meadow marble cobalt orbit nimbus boulder russet cinder harbor falcon crimson cedar meadow meadow thistle saffron nimbus mistral ember garnet #92830246<<<ANSWER END>>><<<ANSWER key=K00914>>>cinder falcon lantern mistral marble zebra spruce glacier indigo orbit harbor copper glacier thistle marble marble quartz garnet harbor cobble nimbus mistral cobalt harbor #bebb22d5<<<ANSWER END>>><<<ANSWER key=K00236>>>quartz lantern willow willow vellum mistral boulder auburn vellum cedar pewter glacier trellis trellis cinder copper cobalt lantern fathom spruce quartz boulder orbit lattice #ebf3e4e4<<<ANSWER END>>><<<ANSWER key=K00229>>>pewter kindle trellis nimbus ember lattice zebra cedar cobalt vellum fathom crimson russet fathom willow cedar verdant russet kindle trellis glacier willow thistle kindle #ff2f10be<<<ANSWER END>>><<<ANSWER key=K00281>>>garnet zebra zebra nimbus trellis harbor cobble cinder quartz trellis auburn cobble ember cobble mistral russet russet harbor fathom orbit spruce indigo cobble auburn #6244f10d<<<ANSWER END>>><<<ANSWER key=K00927>>>cobalt harbor harbor falcon saffron cobalt boulder nimbus lantern lantern onyx spruce harbor vellum zebra quartz onyx spruce lantern indigo verdant orbit lattice cinder #0da51e66<<<ANSWER END>>><<<ANSWER key=K00723>>>fathom ember zebra pewter crimson onyx marble thistle vellum spruce saffron cobalt cobble harbor cinder kindle zebra mistral lantern kindle thistle lattice vellum thistle #bdfdd7d5<<<ANSWER END>>><<<ANSWER key=K00523>>>trellis fathom trellis glacier kindle russet thistle trellis pewter willow glacier harbor cedar spruce harbor harbor harbor glacier kindle russet onyx saffron marble indigo #76d686b6<<<ANSWER END>>><<<ANSWER key=K00678>>>zebra cedar orbit kindle pewter lattice auburn spruce cobalt crimson auburn willow garnet meadow glacier pewter thistle nimbus pewter indigo verdant copper orbit cinder #a4fdac81<<<ANSWER END>>><<<ANSWER key=K00952>>>falcon pewter glacier russet spruce fathom garnet cobble vellum nimbus lattice cinder lantern trellis ember falcon indigo kindle nimbus orbit kindle indigo falcon thistle #1629cb95<<<ANSWER END>>><<<ANSWER key=K00869>>>zebra copper vellum garnet quartz lantern saffron saffron meadow crimson orbit cobble saffron thistle pewter harbor saffron lattice falcon meadow orbit russet trellis thistle #64a082b2<<<ANSWER END>>>CONTEXTBENCH_ORACLE_EOF1234567891011121314151617181920212223242526272829303132333435363738394041424344[metadata]author_name = "contextbench"difficulty = "medium"category = "context-management"tags = ["context-management", "contextbench", "kv-store", "storage-offloading"]contextbench_family = "kv_store"contextbench_budget_tokens = 32768contextbench_reserve_tokens = 2048contextbench_pressure = 1.516contextbench_feasible = truecontextbench_regime = "pressure"contextbench_stream_count = 34contextbench_stream_sha256 = "5f0799fab3470cf468bf2936f0a487da6f85e2c1ff6e8f5aa55af259c210cc9c"instance_approx_per_value_tokens = 48instance_approx_value_tokens = 48457instance_n_actions = 34instance_n_batches = 10instance_n_get = 24instance_n_set = 1000instance_queries = 24instance_records = 1000instance_records_per_chunk = 100instance_seed = 42instance_task_family = "kv_store"instance_value_words = 24
[verifier]timeout_sec = 600.0
[agent]timeout_sec = 14400.0
[environment]docker_image = "python:3.12-slim"workdir = "/app"build_timeout_sec = 600.0cpus = 1memory_mb = 2048storage_mb = 4096
[environment.env]CONTEXTBENCH_STREAM_COUNT = "34"CONTEXTBENCH_STREAM_SHA256 = "5f0799fab3470cf468bf2936f0a487da6f85e2c1ff6e8f5aa55af259c210cc9c"CONTEXTBENCH_STREAM_PATH = "/app/stream/chunks.jsonl"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""ContextBench: benchmarking what an agent keeps, updates, and offloads.
Four task families stream more input than fits in an agent's context window andgrade what survived. Everything the agent has to do is expressed as ordinary userturns, so any chat agent can be evaluated.
Quickstart::
from contextbench import run from contextbench.oracle import OracleAgent # task self-check only, not a baseline
result = run(OracleAgent(instance_dir), instance_dir, budget=32768, reserve=2048, out_dir="runs/kv-R1000-seed42") print(result["reward"], result["terminated_by"])
The core imports nothing outside the standard library: ``tiktoken`` and``harbor`` are optional extras and never required to generate, run or grade."""
from __future__ import annotations
from .graders import grade_run, grader_forfrom .runner import ( DEFAULT_SYSTEM_PROMPT, ContextAgent, Instance, instruction_for, load_instance, run,)from .stream import ADVANCE_MARKER, SUBMIT_MARKER, TERMINATED_BY, Op, render_opfrom .tokens import count_tokens, record_snapshot
__version__ = "0.1.0"
FAMILIES = ("kv_store", "log_triage", "needle_retention", "sudoku_sketchpad")
__all__ = [ "ADVANCE_MARKER", "ContextAgent", "DEFAULT_SYSTEM_PROMPT", "FAMILIES", "Instance", "Op", "SUBMIT_MARKER", "TERMINATED_BY", "__version__", "count_tokens", "grade_run", "grader_for", "instruction_for", "load_instance", "record_snapshot", "render_op", "run",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""ContextBench graders: one per task family, plus the shared context readers.
Every grader takes a run directory and the parsed ``gold.json`` and returns areward dict carrying ``graded_from`` -- the context source it actually read."""
from __future__ import annotations
import jsonfrom pathlib import Path
from .base import ( ContextSource, Grader, read_context, read_final_report, read_snapshots, read_trajectory,)from .kv import KVStoreGraderfrom .log import LogTriageGraderfrom .needle import NeedleRetentionGraderfrom .sudoku import SudokuSketchpadGrader
__all__ = [ "ContextSource", "Grader", "GRADERS", "KVStoreGrader", "LogTriageGrader", "NeedleRetentionGrader", "SudokuSketchpadGrader", "grade_run", "grader_for", "read_context", "read_final_report", "read_snapshots", "read_trajectory",]
GRADERS: dict[str, type[Grader]] = { "kv_store": KVStoreGrader, "log_triage": LogTriageGrader, "needle_retention": NeedleRetentionGrader, "sudoku_sketchpad": SudokuSketchpadGrader,}
def grader_for(family: str) -> Grader: """The grader instance for one family.""" try: return GRADERS[family]() except KeyError: raise KeyError( f"no grader for family {family!r}; known: {', '.join(sorted(GRADERS))}" ) from None
def grade_run(run_dir: Path | str, gold: dict | Path | str) -> dict: """Grade a run directory against a gold object or a ``gold.json`` path.
The family comes from ``gold["meta"]["task_family"]``, so a grader can never be pointed at the wrong family's instance by accident. """ if not isinstance(gold, dict): gold = json.loads(Path(gold).read_text(encoding="utf-8")) family = (gold.get("meta") or {}).get("task_family") if not family: raise ValueError("gold.meta['task_family'] is missing: cannot pick a grader") return grader_for(family).grade(run_dir, gold)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""Grader plumbing: the three ways a run's context is read back.
Every ContextBench reward is computed out of the agent's own messages, never offdisk. Three readers supply those messages, in order of preference:
1. **snapshots** -- ``context_snapshots/turn-*.json``, one per turn. This is the paper metric: an agent that parks content outside its context and surfaces a value only transiently still has that value captured in the snapshot of the turn where it appeared.2. **trajectory** -- an ATIF ``trajectory.json``: a flat list of chat messages that context edits mutate in place, so the final file is exactly the retained context. One frame, not a per-turn series.3. **final report** -- the closing text of a run whose agent cannot expose its context at all.
Which reader ran is recorded as ``graded_from`` in every reward dict, so a numberis never comparable by accident across sources."""
from __future__ import annotations
import jsonimport refrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Sequence
from ..tokens import SNAPSHOT_DIRNAME, snapshot_paths
__all__ = [ "ContextSource", "atif_messages", "Grader", "find_snapshots_dir", "find_trajectory", "messages_text", "normalize", "read_context", "read_final_report", "read_snapshots", "read_trajectory",]
#: Filenames a run may use for its closing report, most specific first.FINAL_REPORT_NAMES = ( "final_report.txt", "final_report.md", "final_report.json", "report.txt", "report.md",)
def normalize(text: str) -> str: """Collapse whitespace, so a reward never turns on reflow or indentation.""" return re.sub(r"\s+", " ", text.strip())
def _decoded_tool_json(content: str) -> str | None: """The string fields of a tool result that is one JSON object, else ``None``.
Some harnesses render a command's output as a JSON object (``{"returncode": 0, "output": "..."}``), which escapes ``<`` and ``>`` and turns newlines into ``\\n``. The model reads the decoded text; so does the grader. """ text = content.strip() if not (text.startswith("{") and text.endswith("}")): return None try: obj = json.loads(text) except Exception: return None if not isinstance(obj, dict): return None parts = [v for v in obj.values() if isinstance(v, str)] return "\n".join(parts) if parts else None
def messages_text(messages: Sequence[Any] | None) -> str: """Flatten a message list into the text the grader scans.""" texts: list[str] = [] for msg in messages or []: content = msg.get("content") if isinstance(msg, dict) else msg if isinstance(content, str): if isinstance(msg, dict) and msg.get("role") == "tool": decoded = _decoded_tool_json(content) if decoded is not None: content = decoded texts.append(content) elif isinstance(content, list): for item in content: texts.append( str(item.get("text") or item.get("content") or "") if isinstance(item, dict) else str(item) ) return "\n".join(texts)
# ----------------------------------------------------------------- locating filesdef _candidate_dirs(run_dir: Path) -> list[Path]: """``run_dir`` itself and the usual agent subdirectories, in preference order.""" return [run_dir, run_dir / "agent", run_dir / "logs", run_dir / "logs" / "agent"]
def find_snapshots_dir(run_dir: Path | str) -> Path | None: """The run's ``context_snapshots`` directory, if it has one.""" run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): if (cand / SNAPSHOT_DIRNAME).is_dir(): return cand / SNAPSHOT_DIRNAME hits = sorted(run_dir.glob(f"**/{SNAPSHOT_DIRNAME}")) return hits[0] if hits else None
def find_trajectory(run_dir: Path | str) -> Path | None: """The run's ATIF ``trajectory.json``, if it has one.""" run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): if (cand / "trajectory.json").is_file(): return cand / "trajectory.json" hits = sorted(run_dir.glob("**/trajectory.json")) return hits[0] if hits else None
# ------------------------------------------------------------------- the readers@dataclassclass ContextSource: """The messages a grader scores, and where they came from."""
graded_from: str #: One message list per turn. A trajectory or a report yields a single frame. frames: list[list[Any]] = field(default_factory=list) #: Per-turn context size, when the source records it. tokens: list[int] = field(default_factory=list) n_snapshots: int = 0
@property def final_frame(self) -> list[Any]: return self.frames[-1] if self.frames else []
def texts(self) -> list[str]: return [messages_text(frame) for frame in self.frames]
def all_text(self) -> str: return "\n".join(self.texts())
def read_snapshots(run_dir: Path | str) -> ContextSource | None: """Read ``context_snapshots/turn-*.json`` as one frame per turn.""" snap_dir = find_snapshots_dir(run_dir) if snap_dir is None: return None frames: list[list[Any]] = [] tokens: list[int] = [] n = 0 for path in snapshot_paths(snap_dir.parent): try: obj = json.loads(path.read_text(encoding="utf-8")) except Exception: continue n += 1 if isinstance(obj.get("tokens"), (int, float)): tokens.append(int(obj["tokens"])) frames.append(obj.get("messages") or []) if n == 0: return None return ContextSource("snapshots", frames, tokens, n)
def read_trajectory(run_dir: Path | str) -> ContextSource | None: """Read an ATIF ``trajectory.json`` as a single frame.""" path = find_trajectory(run_dir) if path is None: return None try: messages = json.loads(path.read_text(encoding="utf-8")) except Exception: return None if isinstance(messages, dict): if isinstance(messages.get("steps"), list): messages = atif_messages(messages["steps"]) else: messages = messages.get("messages") or messages.get("trajectory") or [] if not isinstance(messages, list): return None return ContextSource("trajectory", [messages], [], 0)
def _part_text(content: Any) -> str: if isinstance(content, str): return content if isinstance(content, list): return "\n".join( str(p.get("text") or "") if isinstance(p, dict) else str(p) for p in content ) return "" if content is None else str(content)
def atif_messages(steps: Sequence[Any]) -> list[dict[str, Any]]: """Flatten ATIF ``steps`` into chat messages.
``user`` and ``system`` steps become messages of that role; an ``agent`` step becomes an ``assistant`` message followed by one ``tool`` message per observation result. The flattening is the full history the harness recorded, which for a harness that compacts is more than it retained. """ out: list[dict[str, Any]] = [] for step in steps or []: if not isinstance(step, dict): continue source = step.get("source") text = _part_text(step.get("message")) if source in ("user", "system"): out.append({"role": source, "content": text}) continue out.append({"role": "assistant", "content": text}) observation = step.get("observation") or {} for result in observation.get("results") or []: if isinstance(result, dict) and result.get("content") is not None: out.append({"role": "tool", "content": _part_text(result["content"])}) return out
def read_final_report(run_dir: Path | str) -> str: """The run's closing report text.
A file named like ``final_report.txt`` wins; otherwise the assistant messages of a trajectory are concatenated, which is what an agent that only talks leaves behind. """ run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): for name in FINAL_REPORT_NAMES: path = cand / name if path.is_file(): return path.read_text(encoding="utf-8") source = read_trajectory(run_dir) if source is None: return "" assistant = [ m for m in source.final_frame if isinstance(m, dict) and m.get("role") == "assistant" ] return messages_text(assistant or source.final_frame)
def read_context(run_dir: Path | str) -> ContextSource: """The best available source for ``run_dir``.
Snapshots first (the paper metric), then the ATIF trajectory, then the final report. An empty :class:`ContextSource` with ``graded_from="none"`` means the run left nothing gradeable behind, which a grader reports as invalid rather than as a zero. """ for reader in (read_snapshots, read_trajectory): source = reader(run_dir) if source is not None: return source report = read_final_report(run_dir) if report: return ContextSource( "final_report", [[{"role": "assistant", "content": report}]], [], 0 ) return ContextSource("none", [], [], 0)
# ---------------------------------------------------------------------- base classclass Grader: """A ContextBench grader.
Subclasses implement :meth:`grade`, which takes a run directory and the parsed ``gold.json`` and returns a reward dict. Every returned dict carries ``graded_from`` and ``grader_valid``. """
family: str = "" #: The reward name a caller should read as "the score". primary: str = "reward"
def grade(self, run_dir: Path | str, gold: dict) -> dict: raise NotImplementedError
def grade_path(self, run_dir: Path | str, gold_path: Path | str) -> dict: gold = json.loads(Path(gold_path).read_text(encoding="utf-8")) return self.grade(run_dir, gold)
# -- helpers shared by the concrete graders -------------------------------- @staticmethod def _token_stats(tokens: list[int]) -> dict[str, float]: return { "agent_peak_tokens": float(max(tokens)) if tokens else 0.0, "agent_mean_tokens": float(sum(tokens) / len(tokens)) if tokens else 0.0, }
@staticmethod def _invalid(graded_from: str, why: str) -> dict: """A grade that could not be computed: never reported as a zero score.""" return { "reward": 0.0, "grader_valid": 0.0, "graded_from": graded_from, "grader_note": why, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Grader for *Key-Value Store*: process-graded, ANSWER-block based.
The agent answers each ``GET <key>`` by emitting an ANSWER block::
<<<ANSWER key=K00007>>> <the value it stored for K00007> <<<ANSWER END>>>
Every per-turn context frame is scanned, all ANSWER blocks are collected as``key -> {value strings the agent ever produced}``, and the score is the fractionof gold GET queries whose correct value was produced.
Reading the whole per-turn series rather than the final context is what makes themechanisms comparable on one number: an agent that parks values outside its contextand surfaces the queried one only transiently has the value in the snapshot of theGET turn, but not in its final context.
Rewards:
* ``reward`` -- fraction of GET queries answered with the correct value;* ``reward_attempted`` -- of the GETs answered at all, the fraction correct;* ``n_answered`` -- how many distinct gold GETs got any ANSWER block;* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ContextSource, Grader, messages_text, normalize, read_context
__all__ = ["KVStoreGrader", "ANSWER_RE"]
#: ``<<<ANSWER key=K00007>>> ... <<<ANSWER END>>>``; the key may carry spaces.ANSWER_RE = re.compile( r"<<<\s*ANSWER\s+key\s*=\s*([^\s>]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
class KVStoreGrader(Grader): family = "kv_store"
def grade(self, run_dir: Path | str, gold: dict) -> dict: queries = gold.get("queries") or [] total = len(queries) source = read_context(run_dir) if total == 0: return self._invalid(source.graded_from, "gold has no queries") if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report")
answers = self._collect(source) correct = 0 answered = 0 for q in queries: key = normalize(str(q["key"])) want = normalize(str(q["value"])) seen = answers.get(key) if seen: answered += 1 # Tolerate the value being embedded in a longer answer line. if want in seen or any(want in s for s in seen): correct += 1
result = { "reward": correct / total, "reward_attempted": (correct / answered) if answered else 0.0, "n_answered": float(answered), "matched": float(correct), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _collect(source: ContextSource) -> dict[str, set[str]]: """``key -> {normalized answer strings}`` across every frame.""" answers: dict[str, set[str]] = {} for frame in source.frames: for key, val in ANSWER_RE.findall(messages_text(frame)): answers.setdefault(normalize(key), set()).add(normalize(val)) return answers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Grader for *Incident Log Triage*: process-graded, ANSWER-block based.
The agent answers each ``QUERY <n>`` by emitting an ANSWER block::
<<<ANSWER qid=0>>> timeout retry connection refused #ab12cd34 (lookup) <<<ANSWER END>>>
Every per-turn context frame is scanned, all ANSWER blocks are collected as``qid -> {answer strings}``, and the score is the fraction of gold queries answeredcorrectly. Matching is per type:
* ``lookup`` -- the exact message string must appear in the agent's answer, as a whitespace-normalized substring, so adding a label does not cost a point;* ``count`` -- the integer must appear as a standalone token in the answer.
A gold message ends in a random ``#<hex>`` uniqueness tag that a model treats as anoise id and usually drops. Lookup grading measures retrieval -- did the agentsurface the right log line's message -- not whether it parrots that tag, so atrailing tag is stripped before matching.
Rewards: ``reward``, ``reward_lookup`` / ``reward_count`` per type,``reward_attempted`` over the queries answered at all, and the per-turn context size."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ContextSource, Grader, messages_text, normalize, read_context
__all__ = ["LogTriageGrader", "ANSWER_RE"]
ANSWER_RE = re.compile( r"<<<\s*ANSWER\s+qid\s*=\s*([0-9]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
#: The trailing uniqueness tag of a gold message._TAG_RE = re.compile(r"\s*#[0-9a-f]+\s*$")
def _count_correct(want: str, answers: set[str]) -> bool: """A count is correct when the integer appears as a standalone token.""" pat = re.compile(rf"(?<!\d){re.escape(want)}(?!\d)") return any(pat.search(a) for a in answers)
def _lookup_correct(want: str, answers: set[str]) -> bool: core = _TAG_RE.sub("", want).strip() if not core: return False return any(core in a for a in answers)
class LogTriageGrader(Grader): family = "log_triage"
def grade(self, run_dir: Path | str, gold: dict) -> dict: queries = gold.get("queries") or [] total = len(queries) source = read_context(run_dir) if total == 0: return self._invalid(source.graded_from, "gold has no queries") if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report")
answers = self._collect(source) correct = answered = 0 by_type_total: dict[str, int] = {"lookup": 0, "count": 0} by_type_correct: dict[str, int] = {"lookup": 0, "count": 0} for q in queries: qid = str(q["qid"]) qtype = q.get("type", "lookup") want = normalize(str(q["answer"])) by_type_total[qtype] = by_type_total.get(qtype, 0) + 1 seen = answers.get(qid) if not seen: continue answered += 1 ok = ( _count_correct(want, seen) if qtype == "count" else _lookup_correct(want, seen) ) if ok: correct += 1 by_type_correct[qtype] = by_type_correct.get(qtype, 0) + 1
def _rate(t: str) -> float: n = by_type_total.get(t, 0) return (by_type_correct.get(t, 0) / n) if n else 0.0
result = { "reward": correct / total, "reward_lookup": _rate("lookup"), "reward_count": _rate("count"), "reward_attempted": (correct / answered) if answered else 0.0, "n_answered": float(answered), "matched": float(correct), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _collect(source: ContextSource) -> dict[str, set[str]]: answers: dict[str, set[str]] = {} for frame in source.frames: for qid, val in ANSWER_RE.findall(messages_text(frame)): answers.setdefault(qid.strip(), set()).add(normalize(val)) return answers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Grader for *Needle Retention*: what is still in the context at the end.
The reward is the fraction of gold needle lines present verbatim in the agent'sfinal retained context. Two modes, and which one ran is recorded as ``mode`` and``graded_from``:
* ``final_context`` (the paper metric) -- the last per-turn snapshot, or an ATIF ``trajectory.json``, is the retained context: context edits mutate that message list in place, so the final state is exactly what the agent kept.* ``final_report`` -- for an agent that cannot expose its context at all, the kept lines are read from between ``<<<NEEDLES BEGIN>>>`` and ``<<<NEEDLES END>>>`` in its closing report. A report is a weaker witness than a context: the agent could in principle re-read the lines from somewhere else, so the two modes are not interchangeable and are never averaged together.
Rewards: ``reward``, ``matched``, ``total``, ``mode``, ``graded_from``."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ( Grader, messages_text, normalize, read_final_report, read_snapshots, read_trajectory,)
__all__ = ["NeedleRetentionGrader", "NEEDLES_BLOCK_RE", "extract_reported_needles"]
#: The block an agent without context access prints instead.NEEDLES_BLOCK_RE = re.compile( r"<<<\s*NEEDLES\s+BEGIN\s*>>>(.*?)<<<\s*NEEDLES\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
def extract_reported_needles(text: str) -> set[str]: """The normalized lines inside every ``NEEDLES`` block of ``text``.""" lines: set[str] = set() for block in NEEDLES_BLOCK_RE.findall(text or ""): for line in block.splitlines(): if line.strip(): lines.add(normalize(line)) return lines
class NeedleRetentionGrader(Grader): family = "needle_retention"
def grade(self, run_dir: Path | str, gold: dict) -> dict: gold_lines = {normalize(s) for s in gold.get("answer_lines") or []} total = len(gold_lines)
snapshots = read_snapshots(run_dir) if snapshots is not None: present = self._context_lines(messages_text(snapshots.final_frame)) return self._result( gold_lines, present, total, "final_context", "snapshots", snapshots.n_snapshots, snapshots.tokens, )
trajectory = read_trajectory(run_dir) if trajectory is not None: present = self._context_lines(messages_text(trajectory.final_frame)) return self._result( gold_lines, present, total, "final_context", "trajectory", 0, [] )
report = read_final_report(run_dir) if report: return self._result( gold_lines, extract_reported_needles(report), total, "final_report", "final_report", 0, [], ) return self._invalid("none", "no context snapshots, trajectory or report")
@staticmethod def _context_lines(text: str) -> set[str]: return {normalize(line) for line in text.splitlines() if line.strip()}
def _result( self, gold_lines: set[str], present: set[str], total: int, mode: str, graded_from: str, n_snapshots: int, tokens: list[int], ) -> dict: if total == 0: return self._invalid(graded_from, "gold has no answer_lines") matched = gold_lines & present result = { "reward": len(matched) / total, "matched": float(len(matched)), "total": float(total), "mode": mode, "n_snapshots": float(n_snapshots), "graded_from": graded_from, "grader_valid": 1.0, } result.update(self._token_stats(tokens)) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""Grader for *Sudoku Sketchpad*: versioned, process-graded.
Each move advances the sketchpad to a new version ``v`` with a correct grid ``G_v``(a cell-to-value map). The agent labels every panel it displays with a ``VERSION``line. Every versioned panel the agent ever displayed is recovered from the per-turncontext frames, and for each gold version the grader checks whether the agentdisplayed that exact grid.
This makes the styles comparable on one number. An agent that edits its context inplace bumps the version and changes the affected cells, so one panel lives incontext and stays small; each version appears transiently across the turns. Anappend-only agent writes a brand-new full panel per move, so all versionsaccumulate and the context grows by a panel per move. Both score equally oncorrectness while every version is right: the benefit of editing shows up in theper-turn context size, and in correctness holding at large horizons where anappend-only context overflows the budget.
Rewards:
* ``reward`` -- ``reward_content``, the fraction of gold versions whose exact grid the agent displayed. The cells are what "exact match of the gold sketchpad throughout the process" means; the version label is a secondary bookkeeping check.* ``reward_versioned`` -- the same, but the panel's version label must match too;* ``reward_cell`` -- mean over versions of the best per-cell accuracy seen;* ``reward_final_em`` / ``reward_final_cell`` -- the final displayed grid against the final gold grid;* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size."""
from __future__ import annotations
import refrom pathlib import Pathfrom typing import Iterator
from .base import ContextSource, Grader, messages_text, read_context
__all__ = ["SudokuSketchpadGrader", "SYMBOLS"]
#: Single-character value symbols; must match the generator.SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_TUPLE_RE = re.compile(r"\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^)]*?)\s*\)")_VERSION_RE = re.compile(r"VERSION:\s*(\d+)")
Cells = dict[str, str]Panel = tuple[tuple[str, str], ...]
def _norm_value(raw: str) -> str: raw = raw.strip() if raw in (".", ""): return "." if raw.startswith("="): return "=" + raw[1:].strip() return raw
def _parse_panel_body(body: list[str], side: int) -> Cells: """Parse one board body into ``{"rXcY": value}``.
Position-independent: every cell self-locates through its ``(r,c,v)`` tuple and a later occurrence wins, so the parse is robust to spacing and to the same tuple text appearing elsewhere in the block. """ cells: Cells = {} for m in _TUPLE_RE.finditer("\n".join(body)): r, c, v = int(m.group(1)), int(m.group(2)), m.group(3).strip() if not (1 <= r <= side and 1 <= c <= side): continue if v in (".", ""): cells[f"r{r}c{c}"] = "." elif v in SYMBOLS[:side]: cells[f"r{r}c{c}"] = f"={SYMBOLS.index(v) + 1}" return cells
def _parse_blocks(text: str, side: int) -> list[tuple[int | None, Cells]]: """Every sketchpad block in ``text`` as ``(version, cells)``.
The version comes from the block's ``VERSION:`` line, or is ``None``. """ blocks: list[tuple[int | None, Cells]] = [] buf: list[str] | None = None for line in text.splitlines(): if "SKETCHPAD BEGIN" in line: buf = [] elif "SKETCHPAD END" in line: if buf is not None: ver = None for bl in buf: m = _VERSION_RE.search(bl) if m: ver = int(m.group(1)) break cells = _parse_panel_body(buf, side) if cells: blocks.append((ver, cells)) buf = None elif buf is not None: buf.append(line) return blocks
def _cell_accuracy(gold: Cells, panel: Panel) -> float: if not gold: return 0.0 state = dict(panel) return sum(1 for k, v in gold.items() if state.get(k) == v) / len(gold)
def gold_states(gold: dict) -> Iterator[tuple[int, Cells]]: """Fold the compact per-version deltas into ``(version, full cells)`` pairs.
A ``reset`` delta replaces the whole board (a new puzzle, or version 0); an ordinary delta updates only the changed cells. Version 0, the given starting panel, is yielded too, but the scorer grades only the streamed actions. """ current: Cells = {} for d in gold.get("deltas") or []: cells = {k: _norm_value(v) for k, v in (d.get("cells") or {}).items()} if d.get("reset"): current = dict(cells) else: current.update(cells) yield d["v"], dict(current)
class SudokuSketchpadGrader(Grader): family = "sudoku_sketchpad"
def grade(self, run_dir: Path | str, gold: dict) -> dict: meta = gold.get("meta") or {} # No silent 9x9 default: a missing side in a 16x16 or 25x25 gold would grade # the board on a 9x9 assumption and look perfectly healthy while doing it. if "side" not in meta: raise ValueError( "gold.meta['side'] is missing: refusing to default to 9x9. A larger " "board graded under a silent 9x9 default would pass every check we " "have. Stamp 'side' in the instance gold.meta." ) side = int(meta["side"])
source = read_context(run_dir) if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report") obs = self._observe(source, side)
total = 0 versioned = 0 content = 0 cell_sum = 0.0 final_gold: Panel | None = None for v, cells in gold_states(gold): if v == 0: continue total += 1 panel: Panel = tuple(sorted(cells.items())) final_gold = panel if panel in obs["by_version"].get(v, ()): versioned += 1 if panel in obs["content"]: content += 1 seen = obs["by_version"].get(v) if seen: cell_sum += max( (_cell_accuracy(cells, s) for s in seen), default=0.0 )
if total == 0: return self._invalid(source.graded_from, "gold has no graded versions")
final_state: Panel | None = obs["final"] final_em = 1.0 if (final_state is not None and final_state == final_gold) else 0.0 final_cell = ( _cell_accuracy(dict(final_gold), final_state) if (final_state is not None and final_gold is not None) else 0.0 )
result = { "reward": content / total, "reward_versioned": versioned / total, "reward_content": content / total, "reward_cell": cell_sum / total, "reward_final_em": final_em, "reward_final_cell": final_cell, "matched": float(versioned), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _observe(source: ContextSource, side: int) -> dict: """Every versioned panel, deduplicated as canonical tuples.
Deduplication keeps an append-only agent that re-shows every old version from blowing up the grader's memory. """ by_version: dict[int, set[Panel]] = {} content: set[Panel] = set() final_state: Panel | None = None
for frame in source.frames: blocks = _parse_blocks(messages_text(frame), side) best: tuple[int, Panel] | None = None for ver, cells in blocks: panel: Panel = tuple(sorted(cells.items())) content.add(panel) if ver is not None: by_version.setdefault(ver, set()).add(panel) if best is None or ver >= best[0]: best = (ver, panel) # The final state is the highest-version panel of the latest frame that # has one at all. if best is not None: final_state = best[1] elif blocks: final_state = tuple(sorted(blocks[-1][1].items()))
return {"by_version": by_version, "content": content, "final": final_state}1234567891011121314151617181920212223242526272829303132"""ContextBench on Harbor: task packaging, the op stream, agents and verifiers.
``turn_source``, ``mixin`` and ``package`` import nothing from Harbor, so a task canbe built and a stream tested without it installed. ``agents``, ``wrap`` and``verifiers`` require ``harbor>=0.16`` (``pip install 'contextbench[harbor]'``)."""
from __future__ import annotations
from .mixin import CBStreamMixinfrom .turn_source import ( ENV_STREAM_COUNT, ENV_STREAM_PATH, ENV_STREAM_SHA256, STREAM_RECORD_NAME, STREAM_RELPATH, StreamIdentityError, TurnSource, canonical_sha256,)
__all__ = [ "CBStreamMixin", "ENV_STREAM_COUNT", "ENV_STREAM_PATH", "ENV_STREAM_SHA256", "STREAM_RECORD_NAME", "STREAM_RELPATH", "StreamIdentityError", "TurnSource", "canonical_sha256",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""``CBStreamMixin``: ContextBench support for any Python agent loop under Harbor.
Add the mixin to your Harbor agent and three calls to its loop::
class MyAgent(CBStreamMixin, BaseAgent): async def run(self, instruction, environment, context): await self.cb_setup(environment) # 1 messages = [system, {"role": "user", "content": instruction}] messages += self.cb_user_turns(self.cb_initial_turns()) while not self.cb_done: ... # model call messages.append(tool_result_message) messages += self.cb_user_turns( # 2 self.cb_pending(command, exit_code)) if self.cb_over_budget(messages): # 3 break
The mixin owns everything else: loading and verifying the stream (and removing itfrom the container), the readiness rule, the early-submit refusal, the terminalreason, ``interactive_stream.json`` and the ``context_snapshots/turn-NNNN.json`` thegraders read. ``cb_over_budget`` both snapshots the context you are about to sendand enforces the budget wall on it; call it right before every model call (or whereyour loop sends), and call :meth:`cb_finish` in a ``finally``."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any
from ..tokens import count_tokens, record_snapshotfrom .turn_source import TurnSource
__all__ = ["CBStreamMixin"]
class CBStreamMixin: """Stream delivery, snapshots and the budget wall for a Harbor agent loop."""
logs_dir: Path
#: Budget of record; override per instance with ``cb_setup(budget=...)``. cb_budget: int = 32768 cb_reserve: int = 2048
# ------------------------------------------------------------------ setup async def cb_setup(self, environment: Any, *, budget: int | None = None, reserve: int | None = None, **load_kwargs: Any) -> TurnSource: """Load the task's stream (verified, then removed from the container).""" if budget is not None: self.cb_budget = int(budget) if reserve is not None: self.cb_reserve = int(reserve) self.cb_source = await TurnSource.load( environment, logs_dir=self.logs_dir, **load_kwargs) self._cb_snap_step = 0 self.cb_peak_tokens = 0 return self.cb_source
@property def cb_turn_source(self) -> TurnSource | None: return getattr(self, "cb_source", None)
# --------------------------------------------------------------- delivery def cb_initial_turns(self) -> list[str]: """The user turns to append after the instruction: op 0.""" first = self.cb_source.first_turn(turn=0) return [first] if first is not None else []
def cb_pending(self, last_command: str | None, last_exit: int | None = 0, *, turn: int | None = None) -> list[str]: """The user turns to append right after the tool result of ``last_command``.""" return self.cb_source.pending(last_command, last_exit, turn=turn)
def cb_submit(self, *, trigger: str = "<submit>") -> list[str]: """The harness's own finish signal: refused (texts returned) until the drain.""" return self.cb_source.on_submit(trigger=trigger)
@property def cb_done(self) -> bool: src = self.cb_turn_source return bool(src and src.done)
@staticmethod def cb_user_turns(texts: list[str]) -> list[dict[str, str]]: return [{"role": "user", "content": t} for t in texts]
# ------------------------------------------------------ snapshots and wall def cb_snapshot(self, messages: list[Any], kind: str = "sent", extra: dict[str, Any] | None = None) -> int: """Write ``context_snapshots/turn-NNNN.json``; returns its token count.""" src = self.cb_turn_source tokens, _ = count_tokens(messages) self.cb_peak_tokens = max(getattr(self, "cb_peak_tokens", 0), tokens) step = getattr(self, "_cb_snap_step", 0) record_snapshot( self.logs_dir, step, list(messages), {"kind": kind, "n_ops_delivered": src.n_delivered if src else 0, "n_ops_total": src.n_total if src else 0, "budget": self.cb_budget, "reserve": self.cb_reserve, **(extra or {})}, ) self._cb_snap_step = step + 1 return tokens
def cb_over_budget(self, messages: list[Any]) -> bool: """Snapshot what is about to be sent; True (and ``budget_wall``) if it is over.""" if self.cb_snapshot(messages, "sent") > self.cb_budget - self.cb_reserve: self.cb_source.terminate("budget_wall") return True return False
def cb_finish(self, reason: str | None = None, messages: list[Any] | None = None) -> None: """Record a terminal reason if none was set, snapshot the final context.""" src = self.cb_turn_source if src is None: return if reason and not src.done: src.terminate(reason) if messages is not None: self.cb_snapshot(messages, "final") src.write()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Grade a Harbor trial's agent directory and write Harbor's reward files.
Shared by the two ways a ContextBench task is verified:
* in the container, by the task's own ``tests/test.sh`` (Harbor's default verifier: no flag needed), which runs ``python3 -m contextbench.harbor.reward`` against a copy of the graders vendored into ``tests/_cb/``;* on the host, by ``contextbench.harbor.verifiers:ContextBenchVerifier``, for images without ``python3``.
Harbor's reward dict must be numeric (its job-level mean sums every key), so thestring fields are encoded: ``graded_from_code`` (3 snapshots, 2 trajectory,1 final_report, 0 none) and ``terminated_by_code`` (index into``contextbench.stream.TERMINATED_BY``, -1 unknown). The unencoded result goes to``contextbench_result.json`` next to ``reward.json``.
Pure standard library: this module runs inside task containers."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Pathfrom typing import Any
from ..graders import grade_runfrom ..stream import TERMINATED_BY
__all__ = ["GRADED_FROM_CODES", "harbor_rewards", "write_rewards", "main"]
GRADED_FROM_CODES = {"snapshots": 3, "trajectory": 2, "final_report": 1, "none": 0}
STREAM_RECORD_NAME = "interactive_stream.json"
def harbor_rewards(agent_dir: Path | str, gold: dict) -> tuple[dict, dict]: """``(numeric reward dict, full result dict)`` for one agent directory.""" agent_dir = Path(agent_dir) rewards = grade_run(agent_dir, gold) stream: dict[str, Any] = {} record = agent_dir / STREAM_RECORD_NAME if record.is_file(): try: stream = json.loads(record.read_text(encoding="utf-8")) except Exception: stream = {} numeric: dict[str, float | int] = { k: v for k, v in rewards.items() if isinstance(v, (int, float)) and not isinstance(v, bool) } numeric["graded_from_code"] = GRADED_FROM_CODES.get(str(rewards.get("graded_from")), 0) terminated_by = stream.get("terminated_by") numeric["terminated_by_code"] = ( TERMINATED_BY.index(terminated_by) if terminated_by in TERMINATED_BY else -1 ) for key in ("n_ops_delivered", "n_ops_total", "n_refusals"): if isinstance(stream.get(key), int): numeric[key] = stream[key] full = { "rewards": rewards, "graded_from": rewards.get("graded_from"), "terminated_by": terminated_by, "agent_dir": str(agent_dir), "stream": {k: v for k, v in stream.items() if k != "log"}, } return numeric, full
def write_rewards(agent_dir: Path | str, gold: dict | Path | str, out_dir: Path | str) -> dict: """Grade and write ``reward.json`` + ``contextbench_result.json``; return numeric.""" if not isinstance(gold, dict): gold = json.loads(Path(gold).read_text(encoding="utf-8")) numeric, full = harbor_rewards(agent_dir, gold) out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) (out / "contextbench_result.json").write_text( json.dumps(full, indent=2, default=str) + "\n", encoding="utf-8") (out / "reward.json").write_text(json.dumps(numeric, indent=2) + "\n", encoding="utf-8") return numeric
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--agent-dir", type=Path, default=Path("/logs/agent")) ap.add_argument("--gold", type=Path, default=Path("/tests/gold.json")) ap.add_argument("--out-dir", type=Path, default=Path("/logs/verifier")) a = ap.parse_args(argv) numeric = write_rewards(a.agent_dir, a.gold, a.out_dir) print(json.dumps(numeric)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""``TurnSource``: the one place a Harbor agent gets its next ContextBench operation.
Every Harbor path (the shipped ``ContextBenchAgent``, ``Terminus2Stream``, and anymethod adapter built outside this package) consumes the stream through this class,so the delivery rules cannot drift between harnesses:
* the operations are read **once** from the container, from the ``stream/chunks.jsonl`` file Harbor uploads into the work directory, and checked against the op count and canonical body sha recorded in ``task.toml``;* the file is then **removed** from the container, so the agent cannot read ahead with its shell (the only route an op has into the context is the user turn the harness appends);* the next op is released only when the agent's last command was the standalone ``echo READY_FOR_NEXT_OP`` (see :func:`contextbench.stream.is_ready_command`);* a submit before the stream is drained is refused with :data:`contextbench.stream.REFUSE_SUBMIT_TEXT`;* ``terminated_by`` and the delivery log are written to ``<logs_dir>/interactive_stream.json`` after every change, so a run that is killed still leaves an accurate record.
The class is harness-agnostic: it never touches the message list. A harness asks:meth:`TurnSource.pending` what to append after a tool result and appends thereturned texts as ``role="user"`` messages itself."""
from __future__ import annotations
import asyncioimport hashlibimport jsonimport osimport posixpathimport shlexfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Iterable, Mapping
from .. import stream as protofrom ..stream import Op, render_op
__all__ = [ "ENV_STREAM_COUNT", "ENV_STREAM_PATH", "ENV_STREAM_SHA256", "STREAM_RECORD_NAME", "STREAM_RELPATH", "Delivery", "StreamIdentityError", "TurnSource", "canonical_sha256",]
#: Where the stream lives relative to the task's ``environment/`` directory, and#: therefore relative to the container work directory after Harbor's upload.STREAM_RELPATH = "stream/chunks.jsonl"#: Reads of the stream before giving up; each must parse and match the task identity.READ_ATTEMPTS = 4#: Seconds of back-off per retry (linear).READ_BACKOFF_SEC = 2.0
#: ``[environment.env]`` keys that ``contextbench package`` writes into task.toml.ENV_STREAM_COUNT = "CONTEXTBENCH_STREAM_COUNT"ENV_STREAM_SHA256 = "CONTEXTBENCH_STREAM_SHA256"ENV_STREAM_PATH = "CONTEXTBENCH_STREAM_PATH"
STREAM_RECORD_NAME = "interactive_stream.json"
class StreamIdentityError(RuntimeError): """The stream read from the container is not the one the task was built with."""
def canonical_sha256(records: Iterable[Mapping[str, Any]]) -> str: """sha256 over the ops as sorted-key JSON, one per line.
Canonical rather than byte-level, so re-serializing ``chunks.jsonl`` (key order, trailing newline) does not change the identity, while any change to an op does. """ canon = "\n".join(json.dumps(dict(r), sort_keys=True) for r in records) return hashlib.sha256(canon.encode("utf-8")).hexdigest()
def _parse_records(text: str) -> list[dict[str, Any]]: records: list[dict[str, Any]] = [] for line in (text or "").splitlines(): line = line.strip() if line: records.append(json.loads(line)) return records
@dataclassclass Delivery: """One entry of the delivery log."""
#: What was handed to the agent: ``op``, ``refuse_submit`` or ``explain``. kind: str #: The op index for ``kind == "op"``, else ``None``. index: int | None #: The command that triggered it (head and tail when long), or ``"<start>"``. trigger: str #: The harness's own turn counter at the time, when it passes one. turn: int | None = None #: Why it was handed over: ``start``, ``ready`` (standalone readiness command), #: ``submit`` (a submit before the drain), ``mention`` (non-standalone marker). via: str = ""
def to_dict(self) -> dict[str, Any]: return {"kind": self.kind, "index": self.index, "via": self.via, "trigger": self.trigger, "turn": self.turn}
def _excerpt(command: str, limit: int = 240) -> str: """The command as logged: whole when short, else head and tail.""" cmd = (command or "").strip() if len(cmd) <= limit: return cmd half = limit // 2 return cmd[:half] + " [...] " + cmd[-half:]
@dataclassclass TurnSource: """The operation stream of one trial, and its delivery bookkeeping."""
ops: list[Op] logs_dir: Path | None = None #: How the stream was verified: ``{"count", "sha256", "path", "removed"}``. identity: dict[str, Any] = field(default_factory=dict)
n_delivered: int = 0 terminated_by: str | None = None n_refusals: int = 0 n_explains: int = 0 log: list[Delivery] = field(default_factory=list)
# ---------------------------------------------------------------- building @classmethod def from_records( cls, records: list[Mapping[str, Any]], *, logs_dir: Path | str | None = None, expect_count: int | str | None = None, expect_sha256: str | None = None, identity: dict[str, Any] | None = None, ) -> "TurnSource": """Build from parsed ``chunks.jsonl`` records, verifying count and sha.""" got_sha = canonical_sha256(records) if expect_count is not None and str(expect_count).strip() != "": if len(records) != int(str(expect_count).strip()): raise StreamIdentityError( f"stream op count mismatch: read {len(records)}, task expects " f"{str(expect_count).strip()}" ) if expect_sha256 and got_sha != str(expect_sha256).strip(): raise StreamIdentityError( f"stream sha256 mismatch: read {got_sha[:16]}, task expects " f"{str(expect_sha256).strip()[:16]}" ) ops = [Op.from_dict(dict(r), fallback_index=i) for i, r in enumerate(records)] ident = {"count": len(records), "sha256": got_sha, "verified": bool(expect_count is not None or expect_sha256)} ident.update(identity or {}) src = cls(ops=ops, logs_dir=Path(logs_dir) if logs_dir else None, identity=ident) src.write() return src
@classmethod def from_jsonl(cls, text: str, **kwargs: Any) -> "TurnSource": return cls.from_records(_parse_records(text), **kwargs)
@classmethod async def load( cls, environment: Any, *, logs_dir: Path | str | None = None, path: str | None = None, expect_count: int | str | None = None, expect_sha256: str | None = None, remove_after_load: bool = True, require_identity: bool = True, ) -> "TurnSource": """Read the stream out of a running Harbor environment.
``path``, ``expect_count`` and ``expect_sha256`` default to the ``CONTEXTBENCH_STREAM_*`` values in the task's ``[environment.env]``, then to the host process environment. Without a path, the stream is looked up at ``<workdir>/stream/chunks.jsonl``. With ``require_identity`` (the default) a task that records no count or sha is refused: an unverified stream could be another task's. """ env_cfg = _task_env(environment)
def _setting(name: str, given: Any) -> Any: if given is not None: return given return env_cfg.get(name) or os.environ.get(name)
expect_count = _setting(ENV_STREAM_COUNT, expect_count) expect_sha256 = _setting(ENV_STREAM_SHA256, expect_sha256) path = _setting(ENV_STREAM_PATH, path) if require_identity and not (expect_count or expect_sha256): raise StreamIdentityError( f"the task records no {ENV_STREAM_COUNT} / {ENV_STREAM_SHA256}; " "refusing to deliver an unverifiable stream (rebuild the task with " "`contextbench package`)" ) if not path: workdir = getattr(getattr(environment, "task_env_config", None), "workdir", None) if not workdir: res = await environment.exec("pwd", timeout_sec=30) workdir = (getattr(res, "stdout", "") or "/").strip() or "/" path = posixpath.join(workdir, STREAM_RELPATH)
# Read, parse and verify before removing anything. Under concurrent exec # load the captured stdout can come back truncated; a verified retry # recovers it, and the file is only deleted once a read has matched. last_err: Exception | None = None records: list[dict[str, Any]] = [] for attempt in range(READ_ATTEMPTS): if attempt: await asyncio.sleep(READ_BACKOFF_SEC * attempt) res = await environment.exec(f"cat {shlex.quote(path)}", timeout_sec=120) if getattr(res, "return_code", 1) != 0: last_err = RuntimeError( f"could not read the stream at {path} in the container: " f"{(getattr(res, 'stderr', '') or getattr(res, 'stdout', ''))[:300]}" ) continue try: records = _parse_records(getattr(res, "stdout", "") or "") if not records: raise RuntimeError(f"the stream at {path} is empty") cls.from_records(records, expect_count=expect_count, expect_sha256=expect_sha256) except (json.JSONDecodeError, StreamIdentityError, RuntimeError) as err: last_err = err records = [] continue break if not records: raise StreamIdentityError( f"stream at {path} failed verification after {READ_ATTEMPTS} reads: " f"{last_err}" ) from last_err
removed = False if remove_after_load: stream_dir = posixpath.dirname(path) await environment.exec(f"rm -rf {shlex.quote(stream_dir)}", timeout_sec=60) check = await environment.exec( f"test -e {shlex.quote(path)}", timeout_sec=30 ) removed = getattr(check, "return_code", 0) != 0 if not removed: raise RuntimeError( f"could not remove {path} after loading it: the agent could read " "ahead in the stream" ) return cls.from_records( records, logs_dir=logs_dir, expect_count=expect_count, expect_sha256=expect_sha256, identity={"path": path, "removed": removed}, )
# -------------------------------------------------------------- properties @property def n_total(self) -> int: return len(self.ops)
@property def drained(self) -> bool: """True once every op has been delivered.""" return self.n_delivered >= self.n_total
@property def done(self) -> bool: """True once the run has a terminal reason; the harness should stop.""" return self.terminated_by is not None
# ----------------------------------------------------------------- delivery def _deliver(self, trigger: str, turn: int | None) -> str: index = self.n_delivered text = render_op(self.ops[index], remaining=self.n_total - (index + 1)) self.n_delivered += 1 self.log.append(Delivery("op", index, trigger, turn, "start" if trigger == "<start>" else "ready")) self.write() return text
def first_turn(self, *, turn: int | None = None) -> str | None: """Op 0, delivered with the instruction. ``None`` for an empty stream.""" if self.n_delivered: raise RuntimeError("first_turn() called after delivery started") if not self.ops: self.terminate("stream_exhausted") return None return self._deliver("<start>", turn)
def pending( self, last_command: str | None, last_exit: int | None = 0, *, turn: int | None = None, ) -> list[str]: """The user turns to append after the tool result of ``last_command``.
* standalone readiness, ops left: ``[next op]``; * standalone readiness, stream drained: ``[]`` and ``terminated_by = "stream_exhausted"`` (the harness must stop); * standalone submit, ops left: ``[REFUSE_SUBMIT_TEXT]``; * standalone submit, drained: ``[]`` and ``terminated_by = "submit"``; * the marker mentioned but not standalone: ``[EXPLAIN_NON_STANDALONE_TEXT]``; * anything else: ``[]``.
``last_exit`` is the command's exit code; ``None`` means the harness cannot observe it (a terminal multiplexer), which is treated as success. """ if self.done: return [] cmd = last_command or "" code = 0 if last_exit is None else int(last_exit) trigger = _excerpt(cmd) if proto.is_ready_command(cmd, code): if self.drained: self.terminate("stream_exhausted") return [] return [self._deliver(trigger, turn)] if proto.is_submit_command(cmd, code): return self.on_submit(trigger=trigger, turn=turn) if proto.mentions_advance_marker(cmd): self.n_explains += 1 self.log.append(Delivery("explain", None, trigger, turn, "mention")) self.write() return [proto.EXPLAIN_NON_STANDALONE_TEXT] return []
def on_submit(self, *, trigger: str = "<submit>", turn: int | None = None) -> list[str]: """The agent asked to finish (by command or by the harness's own signal).
Before the stream is drained this is refused, and the refusal text is returned for the harness to deliver; afterwards the run ends as ``submit``. """ if self.done: return [] if not self.drained: self.n_refusals += 1 self.log.append(Delivery("refuse_submit", None, _excerpt(trigger), turn, "submit")) self.write() return [proto.REFUSE_SUBMIT_TEXT] self.terminate("submit") return []
def terminate(self, reason: str) -> None: """Record the terminal reason once; later calls do not overwrite it.""" if reason not in proto.TERMINATED_BY: raise ValueError(f"unknown terminated_by {reason!r}") if self.terminated_by is None: self.terminated_by = reason self.write()
# ------------------------------------------------------------------ record def record(self) -> dict[str, Any]: return { "n_ops_delivered": self.n_delivered, "n_ops_total": self.n_total, "terminated_by": self.terminated_by, "n_refusals": self.n_refusals, "n_explains": self.n_explains, "stream": self.identity, "log": [d.to_dict() for d in self.log], }
def write(self, logs_dir: Path | str | None = None) -> Path | None: """Write ``interactive_stream.json``. Best effort: never raises.""" target = Path(logs_dir) if logs_dir else self.logs_dir if target is None: return None try: target.mkdir(parents=True, exist_ok=True) out = target / STREAM_RECORD_NAME out.write_text(json.dumps(self.record(), indent=2) + "\n", encoding="utf-8") return out except Exception: return None
def _task_env(environment: Any) -> dict[str, str]: cfg = getattr(environment, "task_env_config", None) env = getattr(cfg, "env", None) or {} try: return {str(k): str(v) for k, v in dict(env).items()} except Exception: return {}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""The pure-Python ContextBench runner.
The runner owns the turn protocol so an agent does not have to. It delivers oneoperation per user turn, advances only on a standalone readiness marker, refuses anearly submit, enforces the budget wall on the agent's own reported context,snapshots that context after every turn, and grades the run at the end.
The invariant the runner exists to hold: an operation enters the agent's context asa user message appended by the runner, before the agent can act on it. The agentcontrols only *when* the next operation arrives, never its content or its routeinto the context."""
from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Protocol, runtime_checkable
from . import stream as protofrom .graders import grade_runfrom .stream import Op, render_opfrom .tokens import count_tokens, record_snapshot
__all__ = [ "ContextAgent", "Instance", "DEFAULT_SYSTEM_PROMPT", "load_instance", "run",]
DEFAULT_SYSTEM_PROMPT = ( "You are a careful assistant working through a long stream of operations that " "does not fit in your context window. Handle each operation as it arrives, keep " "in your context exactly what later operations will need, and let go of the " "rest.\n\n" + proto.MARKER_PARAGRAPH_REPLY)
@runtime_checkableclass ContextAgent(Protocol): """What the runner needs from an agent.
``reset`` starts a fresh episode with the system prompt and the family instruction. ``on_user_turn`` receives one user message -- an operation, or a protocol message from the runner -- and returns the reply text. ``context`` returns the agent's current message list, which the runner snapshots and measures against the budget: an agent that hides its context from the runner cannot be graded on the paper metric. """
def reset(self, system: str, instruction: str) -> None: ...
def on_user_turn(self, text: str) -> str: ...
def context(self) -> list[dict]: ...
@dataclass(frozen=True)class Instance: """One generated instance on disk."""
path: Path family: str ops: list[Op] gold: dict meta: dict
@property def n_ops(self) -> int: return len(self.ops)
def load_instance(instance_dir: Path | str) -> Instance: """Read ``chunks.jsonl``, ``gold.json`` and ``meta.json`` from a directory.""" d = Path(instance_dir) meta = json.loads((d / "meta.json").read_text(encoding="utf-8")) gold = json.loads((d / "gold.json").read_text(encoding="utf-8")) ops = proto.load_ops((d / "chunks.jsonl").read_text(encoding="utf-8").splitlines()) family = meta.get("task_family") or (gold.get("meta") or {}).get("task_family") if not family: raise ValueError(f"{d}: meta.json has no task_family") return Instance(path=d, family=family, ops=ops, gold=gold, meta=meta)
def instruction_for(instance: Instance, *, delivery: str = "reply") -> str: """The instruction text for an instance's family.""" import importlib
module = importlib.import_module( f"contextbench.tasks.{instance.family}.generate" ) return module.instruction(instance.gold, delivery=delivery)
def run( agent: ContextAgent, instance_dir: Path | str, *, budget: int = 32768, reserve: int = 2048, out_dir: Path | str = "runs/latest", max_turns: int | None = None, system_prompt: str | None = None, delivery: str = "reply",) -> dict: """Run one instance end to end and return the result dict.
``budget`` and ``reserve`` set the wall: a turn whose snapshot exceeds ``budget - reserve`` tokens ends the run with ``terminated_by="budget_wall"``, because a real serving stack would have refused the next request. ``max_turns`` is a safety stop, not part of the task: leave it unset for a full horizon.
Writes ``context_snapshots/turn-NNNN.json`` per turn, ``interactive_stream.json`` and ``result.json`` into ``out_dir``, and returns the same result dict. """ instance = load_instance(instance_dir) out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) usable = budget - reserve
instruction = instruction_for(instance, delivery=delivery) agent.reset(system_prompt or DEFAULT_SYSTEM_PROMPT, instruction)
total_ops = instance.n_ops delivered = 0 step = 0 terminated_by: str | None = None peak_tokens = 0
def _deliver_op(index: int) -> str: return render_op(instance.ops[index], remaining=total_ops - (index + 1))
if total_ops == 0: terminated_by = "stream_exhausted" pending: str | None = None else: pending = _deliver_op(0) delivered = 1
while pending is not None and terminated_by is None: reply = agent.on_user_turn(pending) or "" step += 1
messages = list(agent.context() or []) tokens, _ = count_tokens(messages) peak_tokens = max(peak_tokens, tokens) record_snapshot( out, step, messages, { "n_ops_delivered": delivered, "n_ops_total": total_ops, "budget": budget, "reserve": reserve, }, )
if tokens > usable: terminated_by = "budget_wall" break
if proto.is_submit_line(reply) or proto.is_submit_command(reply): if delivered < total_ops: pending = proto.REFUSE_SUBMIT_TEXT else: terminated_by = "submit" break elif proto.is_ready_line(reply) or proto.is_ready_command(reply): if delivered < total_ops: pending = _deliver_op(delivered) delivered += 1 else: terminated_by = "stream_exhausted" break elif proto.mentions_advance_marker(reply): pending = proto.EXPLAIN_NON_STANDALONE_TEXT else: pending = proto.NO_MARKER_TEXT
if max_turns is not None and step >= max_turns: terminated_by = "max_steps" break
if terminated_by is None: terminated_by = "stream_exhausted"
stream_record = { "n_ops_delivered": delivered, "n_ops_total": total_ops, "terminated_by": terminated_by, } (out / "interactive_stream.json").write_text( json.dumps(stream_record, indent=2) + "\n", encoding="utf-8" )
rewards = grade_run(out, instance.gold) result: dict[str, Any] = { "task_family": instance.family, "instance_dir": str(instance.path), "out_dir": str(out), "budget": budget, "reserve": reserve, "n_turns": step, "peak_tokens": peak_tokens, "reward": rewards.get("reward", 0.0), "rewards": rewards, **stream_record, } (out / "result.json").write_text( json.dumps(result, indent=2, default=str) + "\n", encoding="utf-8" ) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""The ContextBench turn protocol: op rendering, readiness detection, refusals.
Pure Python. This module is the single definition of how an operation reaches theagent and how the agent asks for the next one, so the Python runner and (phase 2)the Harbor adapters cannot drift apart.
Readiness has two equivalent forms:
* ``READY_FOR_NEXT_OP`` as a **standalone line** of the reply -- for chat agents driven by :mod:`contextbench.runner`, which have no shell;* ``echo READY_FOR_NEXT_OP`` as a **standalone shell statement** -- for agents with a bash tool, where the marker is a command the harness executes.
Both are deliberately strict about "standalone": the marker must not count when itmerely appears as an argument (``grep READY_FOR_NEXT_OP file``) or inside answerdata, because a spurious advance consumes an operation that is then lost forever.A command that failed (non-zero exit) never advances either: the step did notfinish, so the op must not be handed over."""
from __future__ import annotations
import refrom dataclasses import dataclassfrom typing import Iterable
__all__ = [ "ADVANCE_MARKER", "SUBMIT_MARKER", "TERMINATED_BY", "Op", "render_op", "is_ready_line", "is_ready_command", "mentions_advance_marker", "is_submit_line", "is_submit_command", "mentions_submit_marker", "REFUSE_SUBMIT_TEXT", "EXPLAIN_NON_STANDALONE_TEXT", "NO_MARKER_TEXT", "SUBMIT_PARAGRAPH", "MARKER_PARAGRAPH", "MARKER_PARAGRAPH_REPLY",]
ADVANCE_MARKER = "READY_FOR_NEXT_OP"SUBMIT_MARKER = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
#: Every way a ContextBench run can end. ``timeout`` is produced by wall-clock#: enforcement in the container runners; the pure-Python runner produces the#: other four.TERMINATED_BY = ( "submit", "stream_exhausted", "budget_wall", "timeout", "max_steps",)
def _standalone_line_re(marker: str) -> re.Pattern[str]: """The marker alone on a line, tolerating whitespace and code-fence quoting.""" return re.compile( rf"^[ \t]*(?:`{{1,3}})?{re.escape(marker)}(?:`{{1,3}})?[ \t]*\.?[ \t]*$", re.MULTILINE, )
def _standalone_command_re(marker: str) -> re.Pattern[str]: """``echo MARKER`` as a whole shell statement (quotes optional).""" return re.compile( rf"""^\s*(?:/bin/)?echo\s+(?:['"])?{re.escape(marker)}(?:['"])?\s*$""" )
_READY_LINE_RE = _standalone_line_re(ADVANCE_MARKER)_READY_SEGMENT_RE = _standalone_command_re(ADVANCE_MARKER)_SUBMIT_LINE_RE = _standalone_line_re(SUBMIT_MARKER)_SUBMIT_SEGMENT_RE = _standalone_command_re(SUBMIT_MARKER)
#: Shell statement separators. A bundled command such as#: ``printf '<<<ANSWER ...>>>'; echo READY_FOR_NEXT_OP`` advances, because its#: last segment is a clean echo._SEPARATORS = re.compile(r";|\n|&&|\|\|")
_HEREDOC_OPEN = re.compile(r"<<(-?)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\2")_MULTILINE_QUOTED = re.compile(r"'[^']*\n[^']*'|\"(?:[^\"\\]|\\.)*\n(?:[^\"\\]|\\.)*\"")
def _strip_heredoc_bodies(command: str) -> str: """Drop the body lines of every here-document; keep the line that opens it.
A here-document body is data fed to a program, not shell statements, so an ``echo READY_FOR_NEXT_OP`` line inside it never runs and must not count. """ lines = command.split("\n") out: list[str] = [] i = 0 while i < len(lines): line = lines[i] out.append(line) pending = _HEREDOC_OPEN.findall(line) i += 1 for dash, _quote, word in pending: while i < len(lines): body_line = lines[i] i += 1 if (body_line.lstrip("\t") if dash else body_line) == word: break return "\n".join(out)
def _statements(command: str) -> list[str]: """Split a shell command into statements, ignoring here-document bodies and quoted strings that span lines (both are data, not statements).""" text = _strip_heredoc_bodies(command) text = _MULTILINE_QUOTED.sub("''", text) return _SEPARATORS.split(text)
@dataclass(frozen=True)class Op: """One streamed operation, as it is stored in ``chunks.jsonl``."""
index: int header: str body: str
@classmethod def from_dict(cls, obj: dict, *, fallback_index: int = 0) -> "Op": return cls( index=int(obj.get("index", fallback_index)), header=str(obj.get("header", "")), body=str(obj.get("body", "")), )
def render_op(op: Op, *, remaining: int) -> str: """The exact user-turn text for one operation.
``remaining`` is the number of operations that follow this one. """ return f"=== {op.header} ({remaining} op(s) remaining after this) ===\n{op.body}"
def load_ops(lines: Iterable[str]) -> list[Op]: """Parse ``chunks.jsonl`` lines into :class:`Op` objects.""" import json
ops: list[Op] = [] for line in lines: if line.strip(): ops.append(Op.from_dict(json.loads(line), fallback_index=len(ops))) return ops
# --------------------------------------------------------------------- matchingdef is_ready_line(reply: str) -> bool: """True when the reply carries the advance marker on a line of its own.""" return bool(reply) and bool(_READY_LINE_RE.search(reply))
def is_ready_command(command: str, exit_code: int = 0) -> bool: """True when ``command`` runs ``echo READY_FOR_NEXT_OP`` as a whole statement.
A failed command means the step did not finish, so it never advances. """ if not command or exit_code != 0: return False return any(_READY_SEGMENT_RE.match(seg) for seg in _statements(command))
def mentions_advance_marker(text: str) -> bool: return bool(text) and ADVANCE_MARKER in text
def is_submit_line(reply: str) -> bool: return bool(reply) and bool(_SUBMIT_LINE_RE.search(reply))
def is_submit_command(command: str, exit_code: int = 0) -> bool: if not command or exit_code != 0: return False return any(_SUBMIT_SEGMENT_RE.match(seg) for seg in _statements(command))
def mentions_submit_marker(text: str) -> bool: return bool(text) and SUBMIT_MARKER in text
# ----------------------------------------------------------- texts sent back#: Sent when the agent submits while operations are still undelivered.REFUSE_SUBMIT_TEXT = ( "There is nothing to submit in this task and the run did NOT end. " "Operations are still being delivered one at a time: run the " f"standalone command `echo {ADVANCE_MARKER}` to receive the " "next one, and keep doing that until you are told none remain.")
#: Sent when the marker appeared but not as a standalone statement. Without this#: the agent sees its command succeed, believes it advanced, and then stalls in#: empty turns with no error signal anywhere.EXPLAIN_NON_STANDALONE_TEXT = ( f"[{ADVANCE_MARKER} did NOT advance: it must be a STANDALONE " f"command -- `echo {ADVANCE_MARKER}` on its own, or as the last " f"statement after a `;`. It does not count when passed as an " f"argument to printf/cat/grep. Your command ran normally; run the " f"marker as its own statement to receive the next operation.]")
#: Sent when a reply neither handled the op nor asked for the next one.NO_MARKER_TEXT = ( f"[No {ADVANCE_MARKER} in your reply, so the stream did not advance. " f"Finish the current operation, then put {ADVANCE_MARKER} on a line of " f"its own to receive the next one.]")
#: The two closing paragraphs a system prompt can carry. The submit contract is#: wrong for a streamed task: an agent that submits before the stream is drained#: loses every operation it has not seen.SUBMIT_PARAGRAPH = ( "When you are finished, submit by running the standalone command\n" f"`echo {SUBMIT_MARKER}` (with nothing else in that command).\n" "After it runs you cannot continue.")
MARKER_PARAGRAPH = ( "This task is delivered to you one operation at a time. You do NOT submit and\n" "you do NOT decide when it is over: after handling each operation, run the\n" f"standalone command `echo {ADVANCE_MARKER}` (with nothing else in that\n" "command) to receive the next one. Do this for EVERY operation, including the\n" "one that says none remain -- that final marker is what ends the run, and the\n" "harness stops you. Submitting early discards the work you just did.")
MARKER_PARAGRAPH_REPLY = ( "This task is delivered to you one operation at a time. You do NOT decide when\n" "it is over: after handling each operation, end your reply with\n" f"{ADVANCE_MARKER} on a line of its own to receive the next one. Do this for\n" "EVERY operation, including the one that says none remain. Submitting early\n" "discards the work you just did.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Token counting and per-turn context snapshots.
Every part of ContextBench that asks "how big is this context right now?" goesthrough :func:`count_tokens`: exact ``o200k_base`` counts when ``tiktoken`` can beimported, and a ``len // 3`` character estimate otherwise, so the package workswith no optional dependency and no network.
:func:`record_snapshot` persists the full retained context after each turn. Thesnapshots are the paper metric's source of truth: an agent that offloads contentto disk and reads a value back only transiently still has that value captured inthe snapshot of the turn where it surfaced."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathfrom typing import Any, Iterator
__all__ = [ "SNAPSHOT_DIRNAME", "count_text", "count_tokens", "get_encoder", "iter_text", "record_snapshot", "snapshot_paths",]
SNAPSHOT_DIRNAME = "context_snapshots"
#: The character-per-token divisor used when tiktoken is unavailable.FALLBACK_CHARS_PER_TOKEN = 3
_ENCODER: Any = None_ENCODER_NAME: str | None = None
def get_encoder() -> Any: """A cached ``tiktoken`` encoder, or ``None`` when tiktoken is unavailable.
Defaults to ``o200k_base``; ``TIKTOKEN_ENCODING`` overrides it and ``cl100k_base`` is the second choice (its vocabulary may be cached when ``o200k_base`` is not). """ global _ENCODER, _ENCODER_NAME if _ENCODER is not None or _ENCODER_NAME == "_failed": return _ENCODER try: import tiktoken except Exception: _ENCODER_NAME = "_failed" return None for name in (os.environ.get("TIKTOKEN_ENCODING") or "o200k_base", "cl100k_base"): try: _ENCODER = tiktoken.get_encoding(name) _ENCODER_NAME = name return _ENCODER except Exception: continue # e.g. the vocabulary download is blocked offline _ENCODER_NAME = "_failed" return None
def encoder_name() -> str: """The method label that :func:`count_tokens` reports.""" get_encoder() if _ENCODER_NAME in (None, "_failed"): return f"approx_chars{FALLBACK_CHARS_PER_TOKEN}" return f"tiktoken:{_ENCODER_NAME}"
def iter_text(messages: list[Any] | None) -> Iterator[str]: """Yield every text piece of ``messages`` that reaches the model.
This includes ``tool_calls[*].function.arguments``, where a shell command lives: a tool-heavy agent keeps most of its bytes there, so counting only ``content`` would undercount the real prompt by roughly a factor of two. """ for msg in messages or []: content: Any if isinstance(msg, dict): reasoning = msg.get("reasoning_content") if isinstance(reasoning, str): yield reasoning content = msg.get("content") for call in msg.get("tool_calls") or []: fn = call.get("function") if isinstance(call, dict) else None if isinstance(fn, dict): if fn.get("name"): yield str(fn["name"]) if fn.get("arguments"): yield str(fn["arguments"]) else: content = msg if isinstance(content, str): yield content elif isinstance(content, list): for item in content: if isinstance(item, dict): yield str(item.get("text") or item.get("content") or "") else: yield str(item)
def count_text(text: str) -> int: """Token count of one string (exact with tiktoken, else ``len // 3``).""" if not text: return 0 enc = get_encoder() if enc is None: return max(1, len(text) // FALLBACK_CHARS_PER_TOKEN) return len(enc.encode(text, disallowed_special=()))
def count_tokens(messages: list[Any] | None) -> tuple[int, str]: """Token count over a message list. Returns ``(tokens, method)``.""" total = sum(count_text(piece) for piece in iter_text(messages)) return total, encoder_name()
def snapshot_paths(logs_dir: Path | str) -> list[Path]: """Every ``context_snapshots/turn-*.json`` under ``logs_dir``, in turn order.""" import re
d = Path(logs_dir) / SNAPSHOT_DIRNAME if not d.is_dir(): return []
def _turn(path: Path) -> int: m = re.search(r"turn-(\d+)", path.name) return int(m.group(1)) if m else -1
return sorted(d.glob("turn-*.json"), key=_turn)
def record_snapshot( logs_dir: Path | str, step: int, messages: list[Any], extra: dict[str, Any] | None = None,) -> Path | None: """Persist one per-turn snapshot of the full retained context.
Writes ``<logs_dir>/context_snapshots/turn-NNNN.json`` holding ``step``, ``tokens``, ``token_method``, ``n_messages``, anything in ``extra``, and the ``messages`` themselves (last, so a human reading the file sees the accounting first). Best effort: snapshotting is a logging side effect and never raises into the run. """ try: d = Path(logs_dir) / SNAPSHOT_DIRNAME d.mkdir(parents=True, exist_ok=True) tokens, method = count_tokens(messages) payload: dict[str, Any] = { "step": step, "tokens": tokens, "token_method": method, "n_messages": len(messages or []), } if extra: payload.update(extra) payload["messages"] = messages out = d / f"turn-{step:04d}.json" out.write_text( json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8" ) return out except Exception: return None1234567891011121314151617181920212223242526272829303132333435363738{ "verdict": "PASS", "feasible": true, "task_family": "kv_store", "checks": { "pressure": { "pass": true, "detail": "streamed 49676 / budget 32768 = P 1.52 (need > 1)" }, "small_ops": { "pass": true, "detail": "max op 4924 tok (cap 5529 = usable 30720 / 5 x 0.9)" }, "retained": { "pass": true, "detail": "retained 1688 tok [per-batch index 200 + answers 1488] (cap 13824 = usable / 2 x 0.9)" }, "horizon": { "pass": true, "detail": "34 ops (need >= 4)" } }, "measured": { "P": 1.516, "streamed_tokens": 49676, "max_op_tokens": 4924, "retained_tokens": 1688, "n_ops": 34 }, "budget": 32768, "reserve": 2048, "usable_tokens": 30720, "cap_op_tokens": 5529, "cap_retained_tokens": 13824, "regime": "pressure", "token_method": "tiktoken:o200k_base", "validator_sha16": "ad7a9a4d10534c47"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138{ "queries": [ { "qid": 0, "key": "K00048", "value": "kindle boulder garnet fathom cinder thistle ember pewter cinder vellum marble onyx verdant garnet spruce onyx thistle glacier cinder glacier indigo lattice willow russet #948823b5" }, { "qid": 1, "key": "K00465", "value": "harbor lattice zebra boulder willow crimson thistle pewter glacier fathom fathom copper pewter auburn zebra willow auburn cobalt meadow marble fathom onyx mistral ember #a95c5171" }, { "qid": 2, "key": "K00600", "value": "ember glacier lattice spruce kindle spruce marble copper onyx thistle marble garnet willow cedar lantern fathom thistle cobble willow meadow trellis falcon spruce trellis #b68a208a" }, { "qid": 3, "key": "K00135", "value": "pewter falcon meadow copper indigo thistle lantern orbit auburn vellum onyx harbor onyx cobble auburn copper mistral auburn thistle russet marble harbor vellum meadow #38614f46" }, { "qid": 4, "key": "K00224", "value": "onyx nimbus harbor boulder nimbus garnet lattice zebra cobalt trellis glacier lattice auburn meadow cinder meadow boulder russet quartz ember saffron verdant kindle onyx #4191f4d6" }, { "qid": 5, "key": "K00492", "value": "verdant glacier harbor lattice kindle lantern spruce onyx orbit meadow cedar fathom willow saffron cobalt nimbus vellum zebra saffron cedar fathom onyx nimbus lantern #f68ab589" }, { "qid": 6, "key": "K00798", "value": "copper quartz lattice copper pewter falcon willow harbor willow vellum marble cedar kindle nimbus lantern boulder lattice russet marble copper marble quartz marble cinder #a0f5d114" }, { "qid": 7, "key": "K00150", "value": "cobble cobalt quartz cinder cinder spruce cinder russet auburn lantern zebra mistral cedar lattice lantern glacier kindle cedar crimson lantern falcon marble copper trellis #94342d3b" }, { "qid": 8, "key": "K00603", "value": "russet indigo mistral cobalt cobalt falcon thistle garnet auburn verdant falcon russet zebra glacier trellis vellum pewter onyx thistle lantern quartz crimson fathom vellum #71fb2dea" }, { "qid": 9, "key": "K00568", "value": "harbor lattice crimson cinder trellis willow zebra garnet onyx mistral marble spruce quartz copper pewter spruce onyx onyx garnet vellum vellum auburn garnet lattice #a66280c1" }, { "qid": 10, "key": "K00147", "value": "glacier quartz crimson cobble boulder indigo onyx spruce auburn zebra cedar verdant marble mistral russet copper fathom trellis harbor nimbus boulder thistle russet quartz #0d8bf269" }, { "qid": 11, "key": "K00396", "value": "cedar cobble nimbus boulder crimson trellis harbor nimbus spruce cedar meadow willow meadow cinder falcon garnet spruce thistle kindle quartz lantern thistle auburn auburn #144b8f86" }, { "qid": 12, "key": "K00566", "value": "willow glacier orbit ember meadow onyx kindle mistral crimson harbor glacier lattice zebra willow thistle marble lantern auburn lantern orbit auburn ember marble zebra #6438087d" }, { "qid": 13, "key": "K00621", "value": "onyx trellis harbor kindle meadow marble cobalt orbit nimbus boulder russet cinder harbor falcon crimson cedar meadow meadow thistle saffron nimbus mistral ember garnet #92830246" }, { "qid": 14, "key": "K00914", "value": "cinder falcon lantern mistral marble zebra spruce glacier indigo orbit harbor copper glacier thistle marble marble quartz garnet harbor cobble nimbus mistral cobalt harbor #bebb22d5" }, { "qid": 15, "key": "K00236", "value": "quartz lantern willow willow vellum mistral boulder auburn vellum cedar pewter glacier trellis trellis cinder copper cobalt lantern fathom spruce quartz boulder orbit lattice #ebf3e4e4" }, { "qid": 16, "key": "K00229", "value": "pewter kindle trellis nimbus ember lattice zebra cedar cobalt vellum fathom crimson russet fathom willow cedar verdant russet kindle trellis glacier willow thistle kindle #ff2f10be" }, { "qid": 17, "key": "K00281", "value": "garnet zebra zebra nimbus trellis harbor cobble cinder quartz trellis auburn cobble ember cobble mistral russet russet harbor fathom orbit spruce indigo cobble auburn #6244f10d" }, { "qid": 18, "key": "K00927", "value": "cobalt harbor harbor falcon saffron cobalt boulder nimbus lantern lantern onyx spruce harbor vellum zebra quartz onyx spruce lantern indigo verdant orbit lattice cinder #0da51e66" }, { "qid": 19, "key": "K00723", "value": "fathom ember zebra pewter crimson onyx marble thistle vellum spruce saffron cobalt cobble harbor cinder kindle zebra mistral lantern kindle thistle lattice vellum thistle #bdfdd7d5" }, { "qid": 20, "key": "K00523", "value": "trellis fathom trellis glacier kindle russet thistle trellis pewter willow glacier harbor cedar spruce harbor harbor harbor glacier kindle russet onyx saffron marble indigo #76d686b6" }, { "qid": 21, "key": "K00678", "value": "zebra cedar orbit kindle pewter lattice auburn spruce cobalt crimson auburn willow garnet meadow glacier pewter thistle nimbus pewter indigo verdant copper orbit cinder #a4fdac81" }, { "qid": 22, "key": "K00952", "value": "falcon pewter glacier russet spruce fathom garnet cobble vellum nimbus lattice cinder lantern trellis ember falcon indigo kindle nimbus orbit kindle indigo falcon thistle #1629cb95" }, { "qid": 23, "key": "K00869", "value": "zebra copper vellum garnet quartz lantern saffron saffron meadow crimson orbit cobble saffron thistle pewter harbor saffron lattice falcon meadow orbit russet trellis thistle #64a082b2" } ], "meta": { "task_family": "kv_store", "seed": 42, "records": 1000, "value_words": 24, "records_per_chunk": 100, "queries": 24, "n_set": 1000, "n_get": 24, "n_batches": 10, "n_actions": 34, "approx_value_tokens": 48457, "approx_per_value_tokens": 48 }}1234567891011121314{ "task_family": "kv_store", "seed": 42, "records": 1000, "value_words": 24, "records_per_chunk": 100, "queries": 24, "n_set": 1000, "n_get": 24, "n_batches": 10, "n_actions": 34, "approx_value_tokens": 48457, "approx_per_value_tokens": 48}12345678910#!/usr/bin/env bash# Grades the agent's own messages (context snapshots, else trajectory, else final# report) with the ContextBench graders vendored next to this script. Runs after the# agent has finished; writes /logs/verifier/reward.json.set -uPY=$(command -v python3 || command -v python) || { echo "ContextBench grading needs python3 in the image; or verify on the host with" "contextbench.harbor.verifiers:ContextBenchVerifier" >&2 exit 2}PYTHONPATH=/tests/_cb "$PY" -m contextbench.harbor.reward --agent-dir /logs/agent --gold /tests/gold.json --out-dir /logs/verifier12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Key-Value Store - process graded (interactive)
Operations are delivered to you ONE AT A TIME, as messages in this conversation.You do NOT fetch them: each operation arrives automatically as the next usermessage, and you receive the following operation only after you finish thecurrent turn. The stream has two phases:
1. a long run of **SET-BATCH** blocks, each delimited by unique `<<<SET-BATCH <id> BEGIN ...>>>` / `<<<SET-BATCH <id> END>>>` sentinel lines and carrying many lines of the form `SET <key> = <value>` (each `<value>` is a random, unguessable token; each key is set exactly once), then2. a run of **GET** ops at the end: `GET <key>` - report the value you stored earlier for `<key>`.
Because every `SET` arrives before any `GET`, you cannot predict which keys willbe queried - you must be able to recall **any** value you have seen.
## Turn protocol (IMPORTANT)Each incoming message is ONE operation. Do whatever work it needs FIRST (offload,`grep`, emit an ANSWER block, ...). When you are done with the current operation,**end your turn** by running this single command with the `bash` tool to receivethe next operation:
```echo READY_FOR_NEXT_OP```
This is a multi-turn task: the harness RUNS this command and then delivers thenext operation as the next user message. You MAY bundle real work into the SAMEcommand — in fact the cleanest way to answer a GET is to pipe the stored valuestraight into an ANSWER block and emit the marker together, e.g.:
```printf '<<<ANSWER key=K00084>>>\n%s\n<<<ANSWER END>>>\n' "$val"; echo READY_FOR_NEXT_OP```
ONLY running `echo READY_FOR_NEXT_OP` advances to the next operation — a replywith no tool call does NOT advance (it just prompts you to keep going). Do NOT runthe marker until you have fully handled the current operation (offloaded thebatch, or emitted the GET ANSWER block).
## How to answer a GET
When you read a `GET <key>`, reply with an **ANSWER block** on its own lines,carrying the value **verbatim**:
```<<<ANSWER key=<key>>>><the exact value you stored for <key>><<<ANSWER END>>>```
## How you are graded
Process-graded: for every `GET`, the ANSWER block you emit must contain thecorrect value. Grading reads your **context** (the ANSWER blocks across yourturns). You MAY use the disk as scratch/storage, but FINDING a value (e.g. with`grep`) is NOT answering — only an ANSWER block that actually appears in yourcontext is scored, so you must PRINT the value inside `<<<ANSWER ...>>>` ...`<<<ANSWER END>>>`.The run ends automatically after the final operation; you do not need to submit.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#!/usr/bin/env bash# Oracle: writes every gold answer into the agent log dir as a final report.# Graded as graded_from=final_report, never comparable to a context grade.set -euo pipefailmkdir -p /logs/agentcat > /logs/agent/final_report.txt <<'CONTEXTBENCH_ORACLE_EOF'<<<ANSWER key=K00101>>>cobalt indigo willow meadow lattice zebra lattice spruce lattice russet vellum crimson trellis lattice meadow nimbus onyx cobble cobalt cedar onyx marble glacier quartz #fb248fcb<<<ANSWER END>>><<<ANSWER key=K00011>>>thistle lantern cobble russet meadow boulder thistle pewter vellum cobalt mistral cinder russet willow nimbus copper lantern cobalt indigo verdant zebra cobalt glacier nimbus #1455732a<<<ANSWER END>>><<<ANSWER key=K00313>>>quartz glacier trellis cedar copper lantern cobalt mistral indigo cobble verdant trellis fathom mistral willow falcon cobble spruce lantern onyx willow cobble cedar meadow #4fe15478<<<ANSWER END>>><<<ANSWER key=K00307>>>orbit nimbus russet trellis orbit verdant glacier pewter boulder indigo fathom auburn spruce nimbus mistral onyx boulder cinder trellis saffron lattice cobalt cinder copper #4ee12e40<<<ANSWER END>>><<<ANSWER key=K00769>>>russet zebra lantern cobble fathom fathom spruce pewter crimson falcon verdant glacier onyx spruce lattice cedar falcon nimbus spruce ember meadow mistral orbit meadow #371e4cae<<<ANSWER END>>><<<ANSWER key=K00979>>>lattice thistle cedar marble willow nimbus harbor boulder garnet cobble cobalt kindle lantern quartz copper fathom lattice cinder onyx falcon nimbus copper saffron fathom #439f0f2b<<<ANSWER END>>><<<ANSWER key=K00697>>>garnet falcon cobalt glacier cobble lantern ember cobble cedar ember quartz garnet harbor zebra glacier cobble marble trellis cinder falcon copper lattice cinder cobalt #45006b65<<<ANSWER END>>><<<ANSWER key=K00485>>>kindle pewter cedar lantern kindle falcon trellis lattice garnet pewter zebra verdant boulder fathom kindle quartz saffron indigo ember onyx copper fathom copper thistle #b2624d46<<<ANSWER END>>><<<ANSWER key=K00974>>>boulder boulder harbor thistle crimson garnet trellis cobalt cedar cinder russet cobalt zebra cedar meadow crimson crimson trellis saffron boulder orbit kindle meadow meadow #3eafa2e4<<<ANSWER END>>><<<ANSWER key=K00827>>>saffron falcon cedar kindle russet auburn kindle quartz indigo glacier kindle cobalt boulder cobble willow ember saffron cinder glacier mistral cinder harbor trellis auburn #250cfa16<<<ANSWER END>>><<<ANSWER key=K00203>>>russet willow garnet vellum lattice trellis fathom cinder harbor lantern cobble trellis fathom saffron cobble lattice spruce cedar zebra meadow meadow russet mistral garnet #9b3f786a<<<ANSWER END>>><<<ANSWER key=K00565>>>lattice ember pewter zebra cinder onyx cobble falcon copper cobalt quartz pewter auburn onyx quartz ember fathom onyx quartz boulder falcon boulder thistle meadow #f5d97b96<<<ANSWER END>>><<<ANSWER key=K00704>>>copper garnet onyx cobalt vellum fathom meadow thistle quartz copper mistral copper cobble ember cobalt orbit cobalt fathom cinder trellis meadow cobble cinder harbor #4140461e<<<ANSWER END>>><<<ANSWER key=K00358>>>verdant vellum falcon meadow thistle kindle cedar mistral crimson zebra cinder onyx pewter copper falcon nimbus meadow boulder willow kindle kindle vellum auburn meadow #e113fff3<<<ANSWER END>>><<<ANSWER key=K00665>>>cinder boulder fathom cedar zebra willow falcon lattice ember indigo boulder lattice cinder thistle crimson glacier onyx mistral marble pewter spruce garnet garnet copper #bf7d41cd<<<ANSWER END>>><<<ANSWER key=K00586>>>quartz garnet indigo fathom falcon garnet ember mistral cinder thistle meadow copper orbit lattice marble ember harbor fathom marble cinder russet kindle onyx thistle #b3bb03d6<<<ANSWER END>>><<<ANSWER key=K00867>>>spruce orbit pewter marble glacier harbor copper russet indigo vellum boulder cobalt thistle cedar orbit onyx cinder boulder cobble nimbus verdant cedar cobalt auburn #113644f8<<<ANSWER END>>><<<ANSWER key=K00879>>>saffron cobble verdant russet russet glacier boulder saffron orbit thistle cedar harbor cobalt meadow falcon nimbus crimson russet verdant harbor kindle nimbus lattice saffron #afdce33c<<<ANSWER END>>><<<ANSWER key=K00091>>>russet russet meadow onyx onyx marble onyx cedar kindle copper indigo lantern orbit orbit cobble cinder nimbus falcon harbor spruce onyx vellum spruce verdant #572d466b<<<ANSWER END>>><<<ANSWER key=K00989>>>vellum ember garnet cinder cedar auburn lantern verdant lantern meadow pewter auburn quartz mistral onyx cedar mistral thistle lattice willow orbit zebra saffron kindle #9a393c5a<<<ANSWER END>>><<<ANSWER key=K00265>>>zebra mistral zebra copper orbit quartz orbit falcon trellis kindle cedar ember kindle trellis trellis marble zebra vellum marble saffron quartz orbit auburn willow #267f7a97<<<ANSWER END>>><<<ANSWER key=K00207>>>saffron russet cobalt cinder falcon lantern boulder auburn meadow indigo kindle marble saffron willow onyx glacier thistle quartz ember kindle spruce garnet fathom saffron #2fca0dfc<<<ANSWER END>>><<<ANSWER key=K00930>>>indigo fathom cedar harbor ember russet verdant nimbus boulder thistle glacier trellis nimbus verdant orbit cedar harbor cobble spruce cobble verdant cinder cobble cinder #8165442b<<<ANSWER END>>><<<ANSWER key=K00031>>>falcon garnet zebra lantern saffron russet ember lantern verdant cedar pewter vellum glacier harbor fathom crimson fathom boulder fathom thistle fathom auburn russet trellis #5283b3f0<<<ANSWER END>>>CONTEXTBENCH_ORACLE_EOF1234567891011121314151617181920212223242526272829303132333435363738394041424344[metadata]author_name = "contextbench"difficulty = "medium"category = "context-management"tags = ["context-management", "contextbench", "kv-store", "storage-offloading"]contextbench_family = "kv_store"contextbench_budget_tokens = 32768contextbench_reserve_tokens = 2048contextbench_pressure = 1.517contextbench_feasible = truecontextbench_regime = "pressure"contextbench_stream_count = 34contextbench_stream_sha256 = "65ab71cafbc320b63832d42b20144faa366754e1ec9535b00056c14b30075e59"instance_approx_per_value_tokens = 48instance_approx_value_tokens = 48428instance_n_actions = 34instance_n_batches = 10instance_n_get = 24instance_n_set = 1000instance_queries = 24instance_records = 1000instance_records_per_chunk = 100instance_seed = 43instance_task_family = "kv_store"instance_value_words = 24
[verifier]timeout_sec = 600.0
[agent]timeout_sec = 14400.0
[environment]docker_image = "python:3.12-slim"workdir = "/app"build_timeout_sec = 600.0cpus = 1memory_mb = 2048storage_mb = 4096
[environment.env]CONTEXTBENCH_STREAM_COUNT = "34"CONTEXTBENCH_STREAM_SHA256 = "65ab71cafbc320b63832d42b20144faa366754e1ec9535b00056c14b30075e59"CONTEXTBENCH_STREAM_PATH = "/app/stream/chunks.jsonl"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""ContextBench: benchmarking what an agent keeps, updates, and offloads.
Four task families stream more input than fits in an agent's context window andgrade what survived. Everything the agent has to do is expressed as ordinary userturns, so any chat agent can be evaluated.
Quickstart::
from contextbench import run from contextbench.oracle import OracleAgent # task self-check only, not a baseline
result = run(OracleAgent(instance_dir), instance_dir, budget=32768, reserve=2048, out_dir="runs/kv-R1000-seed42") print(result["reward"], result["terminated_by"])
The core imports nothing outside the standard library: ``tiktoken`` and``harbor`` are optional extras and never required to generate, run or grade."""
from __future__ import annotations
from .graders import grade_run, grader_forfrom .runner import ( DEFAULT_SYSTEM_PROMPT, ContextAgent, Instance, instruction_for, load_instance, run,)from .stream import ADVANCE_MARKER, SUBMIT_MARKER, TERMINATED_BY, Op, render_opfrom .tokens import count_tokens, record_snapshot
__version__ = "0.1.0"
FAMILIES = ("kv_store", "log_triage", "needle_retention", "sudoku_sketchpad")
__all__ = [ "ADVANCE_MARKER", "ContextAgent", "DEFAULT_SYSTEM_PROMPT", "FAMILIES", "Instance", "Op", "SUBMIT_MARKER", "TERMINATED_BY", "__version__", "count_tokens", "grade_run", "grader_for", "instruction_for", "load_instance", "record_snapshot", "render_op", "run",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""ContextBench graders: one per task family, plus the shared context readers.
Every grader takes a run directory and the parsed ``gold.json`` and returns areward dict carrying ``graded_from`` -- the context source it actually read."""
from __future__ import annotations
import jsonfrom pathlib import Path
from .base import ( ContextSource, Grader, read_context, read_final_report, read_snapshots, read_trajectory,)from .kv import KVStoreGraderfrom .log import LogTriageGraderfrom .needle import NeedleRetentionGraderfrom .sudoku import SudokuSketchpadGrader
__all__ = [ "ContextSource", "Grader", "GRADERS", "KVStoreGrader", "LogTriageGrader", "NeedleRetentionGrader", "SudokuSketchpadGrader", "grade_run", "grader_for", "read_context", "read_final_report", "read_snapshots", "read_trajectory",]
GRADERS: dict[str, type[Grader]] = { "kv_store": KVStoreGrader, "log_triage": LogTriageGrader, "needle_retention": NeedleRetentionGrader, "sudoku_sketchpad": SudokuSketchpadGrader,}
def grader_for(family: str) -> Grader: """The grader instance for one family.""" try: return GRADERS[family]() except KeyError: raise KeyError( f"no grader for family {family!r}; known: {', '.join(sorted(GRADERS))}" ) from None
def grade_run(run_dir: Path | str, gold: dict | Path | str) -> dict: """Grade a run directory against a gold object or a ``gold.json`` path.
The family comes from ``gold["meta"]["task_family"]``, so a grader can never be pointed at the wrong family's instance by accident. """ if not isinstance(gold, dict): gold = json.loads(Path(gold).read_text(encoding="utf-8")) family = (gold.get("meta") or {}).get("task_family") if not family: raise ValueError("gold.meta['task_family'] is missing: cannot pick a grader") return grader_for(family).grade(run_dir, gold)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""Grader plumbing: the three ways a run's context is read back.
Every ContextBench reward is computed out of the agent's own messages, never offdisk. Three readers supply those messages, in order of preference:
1. **snapshots** -- ``context_snapshots/turn-*.json``, one per turn. This is the paper metric: an agent that parks content outside its context and surfaces a value only transiently still has that value captured in the snapshot of the turn where it appeared.2. **trajectory** -- an ATIF ``trajectory.json``: a flat list of chat messages that context edits mutate in place, so the final file is exactly the retained context. One frame, not a per-turn series.3. **final report** -- the closing text of a run whose agent cannot expose its context at all.
Which reader ran is recorded as ``graded_from`` in every reward dict, so a numberis never comparable by accident across sources."""
from __future__ import annotations
import jsonimport refrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Sequence
from ..tokens import SNAPSHOT_DIRNAME, snapshot_paths
__all__ = [ "ContextSource", "atif_messages", "Grader", "find_snapshots_dir", "find_trajectory", "messages_text", "normalize", "read_context", "read_final_report", "read_snapshots", "read_trajectory",]
#: Filenames a run may use for its closing report, most specific first.FINAL_REPORT_NAMES = ( "final_report.txt", "final_report.md", "final_report.json", "report.txt", "report.md",)
def normalize(text: str) -> str: """Collapse whitespace, so a reward never turns on reflow or indentation.""" return re.sub(r"\s+", " ", text.strip())
def _decoded_tool_json(content: str) -> str | None: """The string fields of a tool result that is one JSON object, else ``None``.
Some harnesses render a command's output as a JSON object (``{"returncode": 0, "output": "..."}``), which escapes ``<`` and ``>`` and turns newlines into ``\\n``. The model reads the decoded text; so does the grader. """ text = content.strip() if not (text.startswith("{") and text.endswith("}")): return None try: obj = json.loads(text) except Exception: return None if not isinstance(obj, dict): return None parts = [v for v in obj.values() if isinstance(v, str)] return "\n".join(parts) if parts else None
def messages_text(messages: Sequence[Any] | None) -> str: """Flatten a message list into the text the grader scans.""" texts: list[str] = [] for msg in messages or []: content = msg.get("content") if isinstance(msg, dict) else msg if isinstance(content, str): if isinstance(msg, dict) and msg.get("role") == "tool": decoded = _decoded_tool_json(content) if decoded is not None: content = decoded texts.append(content) elif isinstance(content, list): for item in content: texts.append( str(item.get("text") or item.get("content") or "") if isinstance(item, dict) else str(item) ) return "\n".join(texts)
# ----------------------------------------------------------------- locating filesdef _candidate_dirs(run_dir: Path) -> list[Path]: """``run_dir`` itself and the usual agent subdirectories, in preference order.""" return [run_dir, run_dir / "agent", run_dir / "logs", run_dir / "logs" / "agent"]
def find_snapshots_dir(run_dir: Path | str) -> Path | None: """The run's ``context_snapshots`` directory, if it has one.""" run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): if (cand / SNAPSHOT_DIRNAME).is_dir(): return cand / SNAPSHOT_DIRNAME hits = sorted(run_dir.glob(f"**/{SNAPSHOT_DIRNAME}")) return hits[0] if hits else None
def find_trajectory(run_dir: Path | str) -> Path | None: """The run's ATIF ``trajectory.json``, if it has one.""" run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): if (cand / "trajectory.json").is_file(): return cand / "trajectory.json" hits = sorted(run_dir.glob("**/trajectory.json")) return hits[0] if hits else None
# ------------------------------------------------------------------- the readers@dataclassclass ContextSource: """The messages a grader scores, and where they came from."""
graded_from: str #: One message list per turn. A trajectory or a report yields a single frame. frames: list[list[Any]] = field(default_factory=list) #: Per-turn context size, when the source records it. tokens: list[int] = field(default_factory=list) n_snapshots: int = 0
@property def final_frame(self) -> list[Any]: return self.frames[-1] if self.frames else []
def texts(self) -> list[str]: return [messages_text(frame) for frame in self.frames]
def all_text(self) -> str: return "\n".join(self.texts())
def read_snapshots(run_dir: Path | str) -> ContextSource | None: """Read ``context_snapshots/turn-*.json`` as one frame per turn.""" snap_dir = find_snapshots_dir(run_dir) if snap_dir is None: return None frames: list[list[Any]] = [] tokens: list[int] = [] n = 0 for path in snapshot_paths(snap_dir.parent): try: obj = json.loads(path.read_text(encoding="utf-8")) except Exception: continue n += 1 if isinstance(obj.get("tokens"), (int, float)): tokens.append(int(obj["tokens"])) frames.append(obj.get("messages") or []) if n == 0: return None return ContextSource("snapshots", frames, tokens, n)
def read_trajectory(run_dir: Path | str) -> ContextSource | None: """Read an ATIF ``trajectory.json`` as a single frame.""" path = find_trajectory(run_dir) if path is None: return None try: messages = json.loads(path.read_text(encoding="utf-8")) except Exception: return None if isinstance(messages, dict): if isinstance(messages.get("steps"), list): messages = atif_messages(messages["steps"]) else: messages = messages.get("messages") or messages.get("trajectory") or [] if not isinstance(messages, list): return None return ContextSource("trajectory", [messages], [], 0)
def _part_text(content: Any) -> str: if isinstance(content, str): return content if isinstance(content, list): return "\n".join( str(p.get("text") or "") if isinstance(p, dict) else str(p) for p in content ) return "" if content is None else str(content)
def atif_messages(steps: Sequence[Any]) -> list[dict[str, Any]]: """Flatten ATIF ``steps`` into chat messages.
``user`` and ``system`` steps become messages of that role; an ``agent`` step becomes an ``assistant`` message followed by one ``tool`` message per observation result. The flattening is the full history the harness recorded, which for a harness that compacts is more than it retained. """ out: list[dict[str, Any]] = [] for step in steps or []: if not isinstance(step, dict): continue source = step.get("source") text = _part_text(step.get("message")) if source in ("user", "system"): out.append({"role": source, "content": text}) continue out.append({"role": "assistant", "content": text}) observation = step.get("observation") or {} for result in observation.get("results") or []: if isinstance(result, dict) and result.get("content") is not None: out.append({"role": "tool", "content": _part_text(result["content"])}) return out
def read_final_report(run_dir: Path | str) -> str: """The run's closing report text.
A file named like ``final_report.txt`` wins; otherwise the assistant messages of a trajectory are concatenated, which is what an agent that only talks leaves behind. """ run_dir = Path(run_dir) for cand in _candidate_dirs(run_dir): for name in FINAL_REPORT_NAMES: path = cand / name if path.is_file(): return path.read_text(encoding="utf-8") source = read_trajectory(run_dir) if source is None: return "" assistant = [ m for m in source.final_frame if isinstance(m, dict) and m.get("role") == "assistant" ] return messages_text(assistant or source.final_frame)
def read_context(run_dir: Path | str) -> ContextSource: """The best available source for ``run_dir``.
Snapshots first (the paper metric), then the ATIF trajectory, then the final report. An empty :class:`ContextSource` with ``graded_from="none"`` means the run left nothing gradeable behind, which a grader reports as invalid rather than as a zero. """ for reader in (read_snapshots, read_trajectory): source = reader(run_dir) if source is not None: return source report = read_final_report(run_dir) if report: return ContextSource( "final_report", [[{"role": "assistant", "content": report}]], [], 0 ) return ContextSource("none", [], [], 0)
# ---------------------------------------------------------------------- base classclass Grader: """A ContextBench grader.
Subclasses implement :meth:`grade`, which takes a run directory and the parsed ``gold.json`` and returns a reward dict. Every returned dict carries ``graded_from`` and ``grader_valid``. """
family: str = "" #: The reward name a caller should read as "the score". primary: str = "reward"
def grade(self, run_dir: Path | str, gold: dict) -> dict: raise NotImplementedError
def grade_path(self, run_dir: Path | str, gold_path: Path | str) -> dict: gold = json.loads(Path(gold_path).read_text(encoding="utf-8")) return self.grade(run_dir, gold)
# -- helpers shared by the concrete graders -------------------------------- @staticmethod def _token_stats(tokens: list[int]) -> dict[str, float]: return { "agent_peak_tokens": float(max(tokens)) if tokens else 0.0, "agent_mean_tokens": float(sum(tokens) / len(tokens)) if tokens else 0.0, }
@staticmethod def _invalid(graded_from: str, why: str) -> dict: """A grade that could not be computed: never reported as a zero score.""" return { "reward": 0.0, "grader_valid": 0.0, "graded_from": graded_from, "grader_note": why, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687"""Grader for *Key-Value Store*: process-graded, ANSWER-block based.
The agent answers each ``GET <key>`` by emitting an ANSWER block::
<<<ANSWER key=K00007>>> <the value it stored for K00007> <<<ANSWER END>>>
Every per-turn context frame is scanned, all ANSWER blocks are collected as``key -> {value strings the agent ever produced}``, and the score is the fractionof gold GET queries whose correct value was produced.
Reading the whole per-turn series rather than the final context is what makes themechanisms comparable on one number: an agent that parks values outside its contextand surfaces the queried one only transiently has the value in the snapshot of theGET turn, but not in its final context.
Rewards:
* ``reward`` -- fraction of GET queries answered with the correct value;* ``reward_attempted`` -- of the GETs answered at all, the fraction correct;* ``n_answered`` -- how many distinct gold GETs got any ANSWER block;* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ContextSource, Grader, messages_text, normalize, read_context
__all__ = ["KVStoreGrader", "ANSWER_RE"]
#: ``<<<ANSWER key=K00007>>> ... <<<ANSWER END>>>``; the key may carry spaces.ANSWER_RE = re.compile( r"<<<\s*ANSWER\s+key\s*=\s*([^\s>]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
class KVStoreGrader(Grader): family = "kv_store"
def grade(self, run_dir: Path | str, gold: dict) -> dict: queries = gold.get("queries") or [] total = len(queries) source = read_context(run_dir) if total == 0: return self._invalid(source.graded_from, "gold has no queries") if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report")
answers = self._collect(source) correct = 0 answered = 0 for q in queries: key = normalize(str(q["key"])) want = normalize(str(q["value"])) seen = answers.get(key) if seen: answered += 1 # Tolerate the value being embedded in a longer answer line. if want in seen or any(want in s for s in seen): correct += 1
result = { "reward": correct / total, "reward_attempted": (correct / answered) if answered else 0.0, "n_answered": float(answered), "matched": float(correct), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _collect(source: ContextSource) -> dict[str, set[str]]: """``key -> {normalized answer strings}`` across every frame.""" answers: dict[str, set[str]] = {} for frame in source.frames: for key, val in ANSWER_RE.findall(messages_text(frame)): answers.setdefault(normalize(key), set()).add(normalize(val)) return answers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Grader for *Incident Log Triage*: process-graded, ANSWER-block based.
The agent answers each ``QUERY <n>`` by emitting an ANSWER block::
<<<ANSWER qid=0>>> timeout retry connection refused #ab12cd34 (lookup) <<<ANSWER END>>>
Every per-turn context frame is scanned, all ANSWER blocks are collected as``qid -> {answer strings}``, and the score is the fraction of gold queries answeredcorrectly. Matching is per type:
* ``lookup`` -- the exact message string must appear in the agent's answer, as a whitespace-normalized substring, so adding a label does not cost a point;* ``count`` -- the integer must appear as a standalone token in the answer.
A gold message ends in a random ``#<hex>`` uniqueness tag that a model treats as anoise id and usually drops. Lookup grading measures retrieval -- did the agentsurface the right log line's message -- not whether it parrots that tag, so atrailing tag is stripped before matching.
Rewards: ``reward``, ``reward_lookup`` / ``reward_count`` per type,``reward_attempted`` over the queries answered at all, and the per-turn context size."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ContextSource, Grader, messages_text, normalize, read_context
__all__ = ["LogTriageGrader", "ANSWER_RE"]
ANSWER_RE = re.compile( r"<<<\s*ANSWER\s+qid\s*=\s*([0-9]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
#: The trailing uniqueness tag of a gold message._TAG_RE = re.compile(r"\s*#[0-9a-f]+\s*$")
def _count_correct(want: str, answers: set[str]) -> bool: """A count is correct when the integer appears as a standalone token.""" pat = re.compile(rf"(?<!\d){re.escape(want)}(?!\d)") return any(pat.search(a) for a in answers)
def _lookup_correct(want: str, answers: set[str]) -> bool: core = _TAG_RE.sub("", want).strip() if not core: return False return any(core in a for a in answers)
class LogTriageGrader(Grader): family = "log_triage"
def grade(self, run_dir: Path | str, gold: dict) -> dict: queries = gold.get("queries") or [] total = len(queries) source = read_context(run_dir) if total == 0: return self._invalid(source.graded_from, "gold has no queries") if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report")
answers = self._collect(source) correct = answered = 0 by_type_total: dict[str, int] = {"lookup": 0, "count": 0} by_type_correct: dict[str, int] = {"lookup": 0, "count": 0} for q in queries: qid = str(q["qid"]) qtype = q.get("type", "lookup") want = normalize(str(q["answer"])) by_type_total[qtype] = by_type_total.get(qtype, 0) + 1 seen = answers.get(qid) if not seen: continue answered += 1 ok = ( _count_correct(want, seen) if qtype == "count" else _lookup_correct(want, seen) ) if ok: correct += 1 by_type_correct[qtype] = by_type_correct.get(qtype, 0) + 1
def _rate(t: str) -> float: n = by_type_total.get(t, 0) return (by_type_correct.get(t, 0) / n) if n else 0.0
result = { "reward": correct / total, "reward_lookup": _rate("lookup"), "reward_count": _rate("count"), "reward_attempted": (correct / answered) if answered else 0.0, "n_answered": float(answered), "matched": float(correct), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _collect(source: ContextSource) -> dict[str, set[str]]: answers: dict[str, set[str]] = {} for frame in source.frames: for qid, val in ANSWER_RE.findall(messages_text(frame)): answers.setdefault(qid.strip(), set()).add(normalize(val)) return answers123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Grader for *Needle Retention*: what is still in the context at the end.
The reward is the fraction of gold needle lines present verbatim in the agent'sfinal retained context. Two modes, and which one ran is recorded as ``mode`` and``graded_from``:
* ``final_context`` (the paper metric) -- the last per-turn snapshot, or an ATIF ``trajectory.json``, is the retained context: context edits mutate that message list in place, so the final state is exactly what the agent kept.* ``final_report`` -- for an agent that cannot expose its context at all, the kept lines are read from between ``<<<NEEDLES BEGIN>>>`` and ``<<<NEEDLES END>>>`` in its closing report. A report is a weaker witness than a context: the agent could in principle re-read the lines from somewhere else, so the two modes are not interchangeable and are never averaged together.
Rewards: ``reward``, ``matched``, ``total``, ``mode``, ``graded_from``."""
from __future__ import annotations
import refrom pathlib import Path
from .base import ( Grader, messages_text, normalize, read_final_report, read_snapshots, read_trajectory,)
__all__ = ["NeedleRetentionGrader", "NEEDLES_BLOCK_RE", "extract_reported_needles"]
#: The block an agent without context access prints instead.NEEDLES_BLOCK_RE = re.compile( r"<<<\s*NEEDLES\s+BEGIN\s*>>>(.*?)<<<\s*NEEDLES\s+END\s*>>>", re.DOTALL | re.IGNORECASE,)
def extract_reported_needles(text: str) -> set[str]: """The normalized lines inside every ``NEEDLES`` block of ``text``.""" lines: set[str] = set() for block in NEEDLES_BLOCK_RE.findall(text or ""): for line in block.splitlines(): if line.strip(): lines.add(normalize(line)) return lines
class NeedleRetentionGrader(Grader): family = "needle_retention"
def grade(self, run_dir: Path | str, gold: dict) -> dict: gold_lines = {normalize(s) for s in gold.get("answer_lines") or []} total = len(gold_lines)
snapshots = read_snapshots(run_dir) if snapshots is not None: present = self._context_lines(messages_text(snapshots.final_frame)) return self._result( gold_lines, present, total, "final_context", "snapshots", snapshots.n_snapshots, snapshots.tokens, )
trajectory = read_trajectory(run_dir) if trajectory is not None: present = self._context_lines(messages_text(trajectory.final_frame)) return self._result( gold_lines, present, total, "final_context", "trajectory", 0, [] )
report = read_final_report(run_dir) if report: return self._result( gold_lines, extract_reported_needles(report), total, "final_report", "final_report", 0, [], ) return self._invalid("none", "no context snapshots, trajectory or report")
@staticmethod def _context_lines(text: str) -> set[str]: return {normalize(line) for line in text.splitlines() if line.strip()}
def _result( self, gold_lines: set[str], present: set[str], total: int, mode: str, graded_from: str, n_snapshots: int, tokens: list[int], ) -> dict: if total == 0: return self._invalid(graded_from, "gold has no answer_lines") matched = gold_lines & present result = { "reward": len(matched) / total, "matched": float(len(matched)), "total": float(total), "mode": mode, "n_snapshots": float(n_snapshots), "graded_from": graded_from, "grader_valid": 1.0, } result.update(self._token_stats(tokens)) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225"""Grader for *Sudoku Sketchpad*: versioned, process-graded.
Each move advances the sketchpad to a new version ``v`` with a correct grid ``G_v``(a cell-to-value map). The agent labels every panel it displays with a ``VERSION``line. Every versioned panel the agent ever displayed is recovered from the per-turncontext frames, and for each gold version the grader checks whether the agentdisplayed that exact grid.
This makes the styles comparable on one number. An agent that edits its context inplace bumps the version and changes the affected cells, so one panel lives incontext and stays small; each version appears transiently across the turns. Anappend-only agent writes a brand-new full panel per move, so all versionsaccumulate and the context grows by a panel per move. Both score equally oncorrectness while every version is right: the benefit of editing shows up in theper-turn context size, and in correctness holding at large horizons where anappend-only context overflows the budget.
Rewards:
* ``reward`` -- ``reward_content``, the fraction of gold versions whose exact grid the agent displayed. The cells are what "exact match of the gold sketchpad throughout the process" means; the version label is a secondary bookkeeping check.* ``reward_versioned`` -- the same, but the panel's version label must match too;* ``reward_cell`` -- mean over versions of the best per-cell accuracy seen;* ``reward_final_em`` / ``reward_final_cell`` -- the final displayed grid against the final gold grid;* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size."""
from __future__ import annotations
import refrom pathlib import Pathfrom typing import Iterator
from .base import ContextSource, Grader, messages_text, read_context
__all__ = ["SudokuSketchpadGrader", "SYMBOLS"]
#: Single-character value symbols; must match the generator.SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
_TUPLE_RE = re.compile(r"\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^)]*?)\s*\)")_VERSION_RE = re.compile(r"VERSION:\s*(\d+)")
Cells = dict[str, str]Panel = tuple[tuple[str, str], ...]
def _norm_value(raw: str) -> str: raw = raw.strip() if raw in (".", ""): return "." if raw.startswith("="): return "=" + raw[1:].strip() return raw
def _parse_panel_body(body: list[str], side: int) -> Cells: """Parse one board body into ``{"rXcY": value}``.
Position-independent: every cell self-locates through its ``(r,c,v)`` tuple and a later occurrence wins, so the parse is robust to spacing and to the same tuple text appearing elsewhere in the block. """ cells: Cells = {} for m in _TUPLE_RE.finditer("\n".join(body)): r, c, v = int(m.group(1)), int(m.group(2)), m.group(3).strip() if not (1 <= r <= side and 1 <= c <= side): continue if v in (".", ""): cells[f"r{r}c{c}"] = "." elif v in SYMBOLS[:side]: cells[f"r{r}c{c}"] = f"={SYMBOLS.index(v) + 1}" return cells
def _parse_blocks(text: str, side: int) -> list[tuple[int | None, Cells]]: """Every sketchpad block in ``text`` as ``(version, cells)``.
The version comes from the block's ``VERSION:`` line, or is ``None``. """ blocks: list[tuple[int | None, Cells]] = [] buf: list[str] | None = None for line in text.splitlines(): if "SKETCHPAD BEGIN" in line: buf = [] elif "SKETCHPAD END" in line: if buf is not None: ver = None for bl in buf: m = _VERSION_RE.search(bl) if m: ver = int(m.group(1)) break cells = _parse_panel_body(buf, side) if cells: blocks.append((ver, cells)) buf = None elif buf is not None: buf.append(line) return blocks
def _cell_accuracy(gold: Cells, panel: Panel) -> float: if not gold: return 0.0 state = dict(panel) return sum(1 for k, v in gold.items() if state.get(k) == v) / len(gold)
def gold_states(gold: dict) -> Iterator[tuple[int, Cells]]: """Fold the compact per-version deltas into ``(version, full cells)`` pairs.
A ``reset`` delta replaces the whole board (a new puzzle, or version 0); an ordinary delta updates only the changed cells. Version 0, the given starting panel, is yielded too, but the scorer grades only the streamed actions. """ current: Cells = {} for d in gold.get("deltas") or []: cells = {k: _norm_value(v) for k, v in (d.get("cells") or {}).items()} if d.get("reset"): current = dict(cells) else: current.update(cells) yield d["v"], dict(current)
class SudokuSketchpadGrader(Grader): family = "sudoku_sketchpad"
def grade(self, run_dir: Path | str, gold: dict) -> dict: meta = gold.get("meta") or {} # No silent 9x9 default: a missing side in a 16x16 or 25x25 gold would grade # the board on a 9x9 assumption and look perfectly healthy while doing it. if "side" not in meta: raise ValueError( "gold.meta['side'] is missing: refusing to default to 9x9. A larger " "board graded under a silent 9x9 default would pass every check we " "have. Stamp 'side' in the instance gold.meta." ) side = int(meta["side"])
source = read_context(run_dir) if source.graded_from == "none": return self._invalid("none", "no context snapshots, trajectory or report") obs = self._observe(source, side)
total = 0 versioned = 0 content = 0 cell_sum = 0.0 final_gold: Panel | None = None for v, cells in gold_states(gold): if v == 0: continue total += 1 panel: Panel = tuple(sorted(cells.items())) final_gold = panel if panel in obs["by_version"].get(v, ()): versioned += 1 if panel in obs["content"]: content += 1 seen = obs["by_version"].get(v) if seen: cell_sum += max( (_cell_accuracy(cells, s) for s in seen), default=0.0 )
if total == 0: return self._invalid(source.graded_from, "gold has no graded versions")
final_state: Panel | None = obs["final"] final_em = 1.0 if (final_state is not None and final_state == final_gold) else 0.0 final_cell = ( _cell_accuracy(dict(final_gold), final_state) if (final_state is not None and final_gold is not None) else 0.0 )
result = { "reward": content / total, "reward_versioned": versioned / total, "reward_content": content / total, "reward_cell": cell_sum / total, "reward_final_em": final_em, "reward_final_cell": final_cell, "matched": float(versioned), "total": float(total), "n_snapshots": float(source.n_snapshots), "graded_from": source.graded_from, "grader_valid": 1.0, } result.update(self._token_stats(source.tokens)) return result
@staticmethod def _observe(source: ContextSource, side: int) -> dict: """Every versioned panel, deduplicated as canonical tuples.
Deduplication keeps an append-only agent that re-shows every old version from blowing up the grader's memory. """ by_version: dict[int, set[Panel]] = {} content: set[Panel] = set() final_state: Panel | None = None
for frame in source.frames: blocks = _parse_blocks(messages_text(frame), side) best: tuple[int, Panel] | None = None for ver, cells in blocks: panel: Panel = tuple(sorted(cells.items())) content.add(panel) if ver is not None: by_version.setdefault(ver, set()).add(panel) if best is None or ver >= best[0]: best = (ver, panel) # The final state is the highest-version panel of the latest frame that # has one at all. if best is not None: final_state = best[1] elif blocks: final_state = tuple(sorted(blocks[-1][1].items()))
return {"by_version": by_version, "content": content, "final": final_state}1234567891011121314151617181920212223242526272829303132"""ContextBench on Harbor: task packaging, the op stream, agents and verifiers.
``turn_source``, ``mixin`` and ``package`` import nothing from Harbor, so a task canbe built and a stream tested without it installed. ``agents``, ``wrap`` and``verifiers`` require ``harbor>=0.16`` (``pip install 'contextbench[harbor]'``)."""
from __future__ import annotations
from .mixin import CBStreamMixinfrom .turn_source import ( ENV_STREAM_COUNT, ENV_STREAM_PATH, ENV_STREAM_SHA256, STREAM_RECORD_NAME, STREAM_RELPATH, StreamIdentityError, TurnSource, canonical_sha256,)
__all__ = [ "CBStreamMixin", "ENV_STREAM_COUNT", "ENV_STREAM_PATH", "ENV_STREAM_SHA256", "STREAM_RECORD_NAME", "STREAM_RELPATH", "StreamIdentityError", "TurnSource", "canonical_sha256",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""``CBStreamMixin``: ContextBench support for any Python agent loop under Harbor.
Add the mixin to your Harbor agent and three calls to its loop::
class MyAgent(CBStreamMixin, BaseAgent): async def run(self, instruction, environment, context): await self.cb_setup(environment) # 1 messages = [system, {"role": "user", "content": instruction}] messages += self.cb_user_turns(self.cb_initial_turns()) while not self.cb_done: ... # model call messages.append(tool_result_message) messages += self.cb_user_turns( # 2 self.cb_pending(command, exit_code)) if self.cb_over_budget(messages): # 3 break
The mixin owns everything else: loading and verifying the stream (and removing itfrom the container), the readiness rule, the early-submit refusal, the terminalreason, ``interactive_stream.json`` and the ``context_snapshots/turn-NNNN.json`` thegraders read. ``cb_over_budget`` both snapshots the context you are about to sendand enforces the budget wall on it; call it right before every model call (or whereyour loop sends), and call :meth:`cb_finish` in a ``finally``."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any
from ..tokens import count_tokens, record_snapshotfrom .turn_source import TurnSource
__all__ = ["CBStreamMixin"]
class CBStreamMixin: """Stream delivery, snapshots and the budget wall for a Harbor agent loop."""
logs_dir: Path
#: Budget of record; override per instance with ``cb_setup(budget=...)``. cb_budget: int = 32768 cb_reserve: int = 2048
# ------------------------------------------------------------------ setup async def cb_setup(self, environment: Any, *, budget: int | None = None, reserve: int | None = None, **load_kwargs: Any) -> TurnSource: """Load the task's stream (verified, then removed from the container).""" if budget is not None: self.cb_budget = int(budget) if reserve is not None: self.cb_reserve = int(reserve) self.cb_source = await TurnSource.load( environment, logs_dir=self.logs_dir, **load_kwargs) self._cb_snap_step = 0 self.cb_peak_tokens = 0 return self.cb_source
@property def cb_turn_source(self) -> TurnSource | None: return getattr(self, "cb_source", None)
# --------------------------------------------------------------- delivery def cb_initial_turns(self) -> list[str]: """The user turns to append after the instruction: op 0.""" first = self.cb_source.first_turn(turn=0) return [first] if first is not None else []
def cb_pending(self, last_command: str | None, last_exit: int | None = 0, *, turn: int | None = None) -> list[str]: """The user turns to append right after the tool result of ``last_command``.""" return self.cb_source.pending(last_command, last_exit, turn=turn)
def cb_submit(self, *, trigger: str = "<submit>") -> list[str]: """The harness's own finish signal: refused (texts returned) until the drain.""" return self.cb_source.on_submit(trigger=trigger)
@property def cb_done(self) -> bool: src = self.cb_turn_source return bool(src and src.done)
@staticmethod def cb_user_turns(texts: list[str]) -> list[dict[str, str]]: return [{"role": "user", "content": t} for t in texts]
# ------------------------------------------------------ snapshots and wall def cb_snapshot(self, messages: list[Any], kind: str = "sent", extra: dict[str, Any] | None = None) -> int: """Write ``context_snapshots/turn-NNNN.json``; returns its token count.""" src = self.cb_turn_source tokens, _ = count_tokens(messages) self.cb_peak_tokens = max(getattr(self, "cb_peak_tokens", 0), tokens) step = getattr(self, "_cb_snap_step", 0) record_snapshot( self.logs_dir, step, list(messages), {"kind": kind, "n_ops_delivered": src.n_delivered if src else 0, "n_ops_total": src.n_total if src else 0, "budget": self.cb_budget, "reserve": self.cb_reserve, **(extra or {})}, ) self._cb_snap_step = step + 1 return tokens
def cb_over_budget(self, messages: list[Any]) -> bool: """Snapshot what is about to be sent; True (and ``budget_wall``) if it is over.""" if self.cb_snapshot(messages, "sent") > self.cb_budget - self.cb_reserve: self.cb_source.terminate("budget_wall") return True return False
def cb_finish(self, reason: str | None = None, messages: list[Any] | None = None) -> None: """Record a terminal reason if none was set, snapshot the final context.""" src = self.cb_turn_source if src is None: return if reason and not src.done: src.terminate(reason) if messages is not None: self.cb_snapshot(messages, "final") src.write()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Grade a Harbor trial's agent directory and write Harbor's reward files.
Shared by the two ways a ContextBench task is verified:
* in the container, by the task's own ``tests/test.sh`` (Harbor's default verifier: no flag needed), which runs ``python3 -m contextbench.harbor.reward`` against a copy of the graders vendored into ``tests/_cb/``;* on the host, by ``contextbench.harbor.verifiers:ContextBenchVerifier``, for images without ``python3``.
Harbor's reward dict must be numeric (its job-level mean sums every key), so thestring fields are encoded: ``graded_from_code`` (3 snapshots, 2 trajectory,1 final_report, 0 none) and ``terminated_by_code`` (index into``contextbench.stream.TERMINATED_BY``, -1 unknown). The unencoded result goes to``contextbench_result.json`` next to ``reward.json``.
Pure standard library: this module runs inside task containers."""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Pathfrom typing import Any
from ..graders import grade_runfrom ..stream import TERMINATED_BY
__all__ = ["GRADED_FROM_CODES", "harbor_rewards", "write_rewards", "main"]
GRADED_FROM_CODES = {"snapshots": 3, "trajectory": 2, "final_report": 1, "none": 0}
STREAM_RECORD_NAME = "interactive_stream.json"
def harbor_rewards(agent_dir: Path | str, gold: dict) -> tuple[dict, dict]: """``(numeric reward dict, full result dict)`` for one agent directory.""" agent_dir = Path(agent_dir) rewards = grade_run(agent_dir, gold) stream: dict[str, Any] = {} record = agent_dir / STREAM_RECORD_NAME if record.is_file(): try: stream = json.loads(record.read_text(encoding="utf-8")) except Exception: stream = {} numeric: dict[str, float | int] = { k: v for k, v in rewards.items() if isinstance(v, (int, float)) and not isinstance(v, bool) } numeric["graded_from_code"] = GRADED_FROM_CODES.get(str(rewards.get("graded_from")), 0) terminated_by = stream.get("terminated_by") numeric["terminated_by_code"] = ( TERMINATED_BY.index(terminated_by) if terminated_by in TERMINATED_BY else -1 ) for key in ("n_ops_delivered", "n_ops_total", "n_refusals"): if isinstance(stream.get(key), int): numeric[key] = stream[key] full = { "rewards": rewards, "graded_from": rewards.get("graded_from"), "terminated_by": terminated_by, "agent_dir": str(agent_dir), "stream": {k: v for k, v in stream.items() if k != "log"}, } return numeric, full
def write_rewards(agent_dir: Path | str, gold: dict | Path | str, out_dir: Path | str) -> dict: """Grade and write ``reward.json`` + ``contextbench_result.json``; return numeric.""" if not isinstance(gold, dict): gold = json.loads(Path(gold).read_text(encoding="utf-8")) numeric, full = harbor_rewards(agent_dir, gold) out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) (out / "contextbench_result.json").write_text( json.dumps(full, indent=2, default=str) + "\n", encoding="utf-8") (out / "reward.json").write_text(json.dumps(numeric, indent=2) + "\n", encoding="utf-8") return numeric
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--agent-dir", type=Path, default=Path("/logs/agent")) ap.add_argument("--gold", type=Path, default=Path("/tests/gold.json")) ap.add_argument("--out-dir", type=Path, default=Path("/logs/verifier")) a = ap.parse_args(argv) numeric = write_rewards(a.agent_dir, a.gold, a.out_dir) print(json.dumps(numeric)) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""``TurnSource``: the one place a Harbor agent gets its next ContextBench operation.
Every Harbor path (the shipped ``ContextBenchAgent``, ``Terminus2Stream``, and anymethod adapter built outside this package) consumes the stream through this class,so the delivery rules cannot drift between harnesses:
* the operations are read **once** from the container, from the ``stream/chunks.jsonl`` file Harbor uploads into the work directory, and checked against the op count and canonical body sha recorded in ``task.toml``;* the file is then **removed** from the container, so the agent cannot read ahead with its shell (the only route an op has into the context is the user turn the harness appends);* the next op is released only when the agent's last command was the standalone ``echo READY_FOR_NEXT_OP`` (see :func:`contextbench.stream.is_ready_command`);* a submit before the stream is drained is refused with :data:`contextbench.stream.REFUSE_SUBMIT_TEXT`;* ``terminated_by`` and the delivery log are written to ``<logs_dir>/interactive_stream.json`` after every change, so a run that is killed still leaves an accurate record.
The class is harness-agnostic: it never touches the message list. A harness asks:meth:`TurnSource.pending` what to append after a tool result and appends thereturned texts as ``role="user"`` messages itself."""
from __future__ import annotations
import asyncioimport hashlibimport jsonimport osimport posixpathimport shlexfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Iterable, Mapping
from .. import stream as protofrom ..stream import Op, render_op
__all__ = [ "ENV_STREAM_COUNT", "ENV_STREAM_PATH", "ENV_STREAM_SHA256", "STREAM_RECORD_NAME", "STREAM_RELPATH", "Delivery", "StreamIdentityError", "TurnSource", "canonical_sha256",]
#: Where the stream lives relative to the task's ``environment/`` directory, and#: therefore relative to the container work directory after Harbor's upload.STREAM_RELPATH = "stream/chunks.jsonl"#: Reads of the stream before giving up; each must parse and match the task identity.READ_ATTEMPTS = 4#: Seconds of back-off per retry (linear).READ_BACKOFF_SEC = 2.0
#: ``[environment.env]`` keys that ``contextbench package`` writes into task.toml.ENV_STREAM_COUNT = "CONTEXTBENCH_STREAM_COUNT"ENV_STREAM_SHA256 = "CONTEXTBENCH_STREAM_SHA256"ENV_STREAM_PATH = "CONTEXTBENCH_STREAM_PATH"
STREAM_RECORD_NAME = "interactive_stream.json"
class StreamIdentityError(RuntimeError): """The stream read from the container is not the one the task was built with."""
def canonical_sha256(records: Iterable[Mapping[str, Any]]) -> str: """sha256 over the ops as sorted-key JSON, one per line.
Canonical rather than byte-level, so re-serializing ``chunks.jsonl`` (key order, trailing newline) does not change the identity, while any change to an op does. """ canon = "\n".join(json.dumps(dict(r), sort_keys=True) for r in records) return hashlib.sha256(canon.encode("utf-8")).hexdigest()
def _parse_records(text: str) -> list[dict[str, Any]]: records: list[dict[str, Any]] = [] for line in (text or "").splitlines(): line = line.strip() if line: records.append(json.loads(line)) return records
@dataclassclass Delivery: """One entry of the delivery log."""
#: What was handed to the agent: ``op``, ``refuse_submit`` or ``explain``. kind: str #: The op index for ``kind == "op"``, else ``None``. index: int | None #: The command that triggered it (head and tail when long), or ``"<start>"``. trigger: str #: The harness's own turn counter at the time, when it passes one. turn: int | None = None #: Why it was handed over: ``start``, ``ready`` (standalone readiness command), #: ``submit`` (a submit before the drain), ``mention`` (non-standalone marker). via: str = ""
def to_dict(self) -> dict[str, Any]: return {"kind": self.kind, "index": self.index, "via": self.via, "trigger": self.trigger, "turn": self.turn}
def _excerpt(command: str, limit: int = 240) -> str: """The command as logged: whole when short, else head and tail.""" cmd = (command or "").strip() if len(cmd) <= limit: return cmd half = limit // 2 return cmd[:half] + " [...] " + cmd[-half:]
@dataclassclass TurnSource: """The operation stream of one trial, and its delivery bookkeeping."""
ops: list[Op] logs_dir: Path | None = None #: How the stream was verified: ``{"count", "sha256", "path", "removed"}``. identity: dict[str, Any] = field(default_factory=dict)
n_delivered: int = 0 terminated_by: str | None = None n_refusals: int = 0 n_explains: int = 0 log: list[Delivery] = field(default_factory=list)
# ---------------------------------------------------------------- building @classmethod def from_records( cls, records: list[Mapping[str, Any]], *, logs_dir: Path | str | None = None, expect_count: int | str | None = None, expect_sha256: str | None = None, identity: dict[str, Any] | None = None, ) -> "TurnSource": """Build from parsed ``chunks.jsonl`` records, verifying count and sha.""" got_sha = canonical_sha256(records) if expect_count is not None and str(expect_count).strip() != "": if len(records) != int(str(expect_count).strip()): raise StreamIdentityError( f"stream op count mismatch: read {len(records)}, task expects " f"{str(expect_count).strip()}" ) if expect_sha256 and got_sha != str(expect_sha256).strip(): raise StreamIdentityError( f"stream sha256 mismatch: read {got_sha[:16]}, task expects " f"{str(expect_sha256).strip()[:16]}" ) ops = [Op.from_dict(dict(r), fallback_index=i) for i, r in enumerate(records)] ident = {"count": len(records), "sha256": got_sha, "verified": bool(expect_count is not None or expect_sha256)} ident.update(identity or {}) src = cls(ops=ops, logs_dir=Path(logs_dir) if logs_dir else None, identity=ident) src.write() return src
@classmethod def from_jsonl(cls, text: str, **kwargs: Any) -> "TurnSource": return cls.from_records(_parse_records(text), **kwargs)
@classmethod async def load( cls, environment: Any, *, logs_dir: Path | str | None = None, path: str | None = None, expect_count: int | str | None = None, expect_sha256: str | None = None, remove_after_load: bool = True, require_identity: bool = True, ) -> "TurnSource": """Read the stream out of a running Harbor environment.
``path``, ``expect_count`` and ``expect_sha256`` default to the ``CONTEXTBENCH_STREAM_*`` values in the task's ``[environment.env]``, then to the host process environment. Without a path, the stream is looked up at ``<workdir>/stream/chunks.jsonl``. With ``require_identity`` (the default) a task that records no count or sha is refused: an unverified stream could be another task's. """ env_cfg = _task_env(environment)
def _setting(name: str, given: Any) -> Any: if given is not None: return given return env_cfg.get(name) or os.environ.get(name)
expect_count = _setting(ENV_STREAM_COUNT, expect_count) expect_sha256 = _setting(ENV_STREAM_SHA256, expect_sha256) path = _setting(ENV_STREAM_PATH, path) if require_identity and not (expect_count or expect_sha256): raise StreamIdentityError( f"the task records no {ENV_STREAM_COUNT} / {ENV_STREAM_SHA256}; " "refusing to deliver an unverifiable stream (rebuild the task with " "`contextbench package`)" ) if not path: workdir = getattr(getattr(environment, "task_env_config", None), "workdir", None) if not workdir: res = await environment.exec("pwd", timeout_sec=30) workdir = (getattr(res, "stdout", "") or "/").strip() or "/" path = posixpath.join(workdir, STREAM_RELPATH)
# Read, parse and verify before removing anything. Under concurrent exec # load the captured stdout can come back truncated; a verified retry # recovers it, and the file is only deleted once a read has matched. last_err: Exception | None = None records: list[dict[str, Any]] = [] for attempt in range(READ_ATTEMPTS): if attempt: await asyncio.sleep(READ_BACKOFF_SEC * attempt) res = await environment.exec(f"cat {shlex.quote(path)}", timeout_sec=120) if getattr(res, "return_code", 1) != 0: last_err = RuntimeError( f"could not read the stream at {path} in the container: " f"{(getattr(res, 'stderr', '') or getattr(res, 'stdout', ''))[:300]}" ) continue try: records = _parse_records(getattr(res, "stdout", "") or "") if not records: raise RuntimeError(f"the stream at {path} is empty") cls.from_records(records, expect_count=expect_count, expect_sha256=expect_sha256) except (json.JSONDecodeError, StreamIdentityError, RuntimeError) as err: last_err = err records = [] continue break if not records: raise StreamIdentityError( f"stream at {path} failed verification after {READ_ATTEMPTS} reads: " f"{last_err}" ) from last_err
removed = False if remove_after_load: stream_dir = posixpath.dirname(path) await environment.exec(f"rm -rf {shlex.quote(stream_dir)}", timeout_sec=60) check = await environment.exec( f"test -e {shlex.quote(path)}", timeout_sec=30 ) removed = getattr(check, "return_code", 0) != 0 if not removed: raise RuntimeError( f"could not remove {path} after loading it: the agent could read " "ahead in the stream" ) return cls.from_records( records, logs_dir=logs_dir, expect_count=expect_count, expect_sha256=expect_sha256, identity={"path": path, "removed": removed}, )
# -------------------------------------------------------------- properties @property def n_total(self) -> int: return len(self.ops)
@property def drained(self) -> bool: """True once every op has been delivered.""" return self.n_delivered >= self.n_total
@property def done(self) -> bool: """True once the run has a terminal reason; the harness should stop.""" return self.terminated_by is not None
# ----------------------------------------------------------------- delivery def _deliver(self, trigger: str, turn: int | None) -> str: index = self.n_delivered text = render_op(self.ops[index], remaining=self.n_total - (index + 1)) self.n_delivered += 1 self.log.append(Delivery("op", index, trigger, turn, "start" if trigger == "<start>" else "ready")) self.write() return text
def first_turn(self, *, turn: int | None = None) -> str | None: """Op 0, delivered with the instruction. ``None`` for an empty stream.""" if self.n_delivered: raise RuntimeError("first_turn() called after delivery started") if not self.ops: self.terminate("stream_exhausted") return None return self._deliver("<start>", turn)
def pending( self, last_command: str | None, last_exit: int | None = 0, *, turn: int | None = None, ) -> list[str]: """The user turns to append after the tool result of ``last_command``.
* standalone readiness, ops left: ``[next op]``; * standalone readiness, stream drained: ``[]`` and ``terminated_by = "stream_exhausted"`` (the harness must stop); * standalone submit, ops left: ``[REFUSE_SUBMIT_TEXT]``; * standalone submit, drained: ``[]`` and ``terminated_by = "submit"``; * the marker mentioned but not standalone: ``[EXPLAIN_NON_STANDALONE_TEXT]``; * anything else: ``[]``.
``last_exit`` is the command's exit code; ``None`` means the harness cannot observe it (a terminal multiplexer), which is treated as success. """ if self.done: return [] cmd = last_command or "" code = 0 if last_exit is None else int(last_exit) trigger = _excerpt(cmd) if proto.is_ready_command(cmd, code): if self.drained: self.terminate("stream_exhausted") return [] return [self._deliver(trigger, turn)] if proto.is_submit_command(cmd, code): return self.on_submit(trigger=trigger, turn=turn) if proto.mentions_advance_marker(cmd): self.n_explains += 1 self.log.append(Delivery("explain", None, trigger, turn, "mention")) self.write() return [proto.EXPLAIN_NON_STANDALONE_TEXT] return []
def on_submit(self, *, trigger: str = "<submit>", turn: int | None = None) -> list[str]: """The agent asked to finish (by command or by the harness's own signal).
Before the stream is drained this is refused, and the refusal text is returned for the harness to deliver; afterwards the run ends as ``submit``. """ if self.done: return [] if not self.drained: self.n_refusals += 1 self.log.append(Delivery("refuse_submit", None, _excerpt(trigger), turn, "submit")) self.write() return [proto.REFUSE_SUBMIT_TEXT] self.terminate("submit") return []
def terminate(self, reason: str) -> None: """Record the terminal reason once; later calls do not overwrite it.""" if reason not in proto.TERMINATED_BY: raise ValueError(f"unknown terminated_by {reason!r}") if self.terminated_by is None: self.terminated_by = reason self.write()
# ------------------------------------------------------------------ record def record(self) -> dict[str, Any]: return { "n_ops_delivered": self.n_delivered, "n_ops_total": self.n_total, "terminated_by": self.terminated_by, "n_refusals": self.n_refusals, "n_explains": self.n_explains, "stream": self.identity, "log": [d.to_dict() for d in self.log], }
def write(self, logs_dir: Path | str | None = None) -> Path | None: """Write ``interactive_stream.json``. Best effort: never raises.""" target = Path(logs_dir) if logs_dir else self.logs_dir if target is None: return None try: target.mkdir(parents=True, exist_ok=True) out = target / STREAM_RECORD_NAME out.write_text(json.dumps(self.record(), indent=2) + "\n", encoding="utf-8") return out except Exception: return None
def _task_env(environment: Any) -> dict[str, str]: cfg = getattr(environment, "task_env_config", None) env = getattr(cfg, "env", None) or {} try: return {str(k): str(v) for k, v in dict(env).items()} except Exception: return {}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""The pure-Python ContextBench runner.
The runner owns the turn protocol so an agent does not have to. It delivers oneoperation per user turn, advances only on a standalone readiness marker, refuses anearly submit, enforces the budget wall on the agent's own reported context,snapshots that context after every turn, and grades the run at the end.
The invariant the runner exists to hold: an operation enters the agent's context asa user message appended by the runner, before the agent can act on it. The agentcontrols only *when* the next operation arrives, never its content or its routeinto the context."""
from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Protocol, runtime_checkable
from . import stream as protofrom .graders import grade_runfrom .stream import Op, render_opfrom .tokens import count_tokens, record_snapshot
__all__ = [ "ContextAgent", "Instance", "DEFAULT_SYSTEM_PROMPT", "load_instance", "run",]
DEFAULT_SYSTEM_PROMPT = ( "You are a careful assistant working through a long stream of operations that " "does not fit in your context window. Handle each operation as it arrives, keep " "in your context exactly what later operations will need, and let go of the " "rest.\n\n" + proto.MARKER_PARAGRAPH_REPLY)
@runtime_checkableclass ContextAgent(Protocol): """What the runner needs from an agent.
``reset`` starts a fresh episode with the system prompt and the family instruction. ``on_user_turn`` receives one user message -- an operation, or a protocol message from the runner -- and returns the reply text. ``context`` returns the agent's current message list, which the runner snapshots and measures against the budget: an agent that hides its context from the runner cannot be graded on the paper metric. """
def reset(self, system: str, instruction: str) -> None: ...
def on_user_turn(self, text: str) -> str: ...
def context(self) -> list[dict]: ...
@dataclass(frozen=True)class Instance: """One generated instance on disk."""
path: Path family: str ops: list[Op] gold: dict meta: dict
@property def n_ops(self) -> int: return len(self.ops)
def load_instance(instance_dir: Path | str) -> Instance: """Read ``chunks.jsonl``, ``gold.json`` and ``meta.json`` from a directory.""" d = Path(instance_dir) meta = json.loads((d / "meta.json").read_text(encoding="utf-8")) gold = json.loads((d / "gold.json").read_text(encoding="utf-8")) ops = proto.load_ops((d / "chunks.jsonl").read_text(encoding="utf-8").splitlines()) family = meta.get("task_family") or (gold.get("meta") or {}).get("task_family") if not family: raise ValueError(f"{d}: meta.json has no task_family") return Instance(path=d, family=family, ops=ops, gold=gold, meta=meta)
def instruction_for(instance: Instance, *, delivery: str = "reply") -> str: """The instruction text for an instance's family.""" import importlib
module = importlib.import_module( f"contextbench.tasks.{instance.family}.generate" ) return module.instruction(instance.gold, delivery=delivery)
def run( agent: ContextAgent, instance_dir: Path | str, *, budget: int = 32768, reserve: int = 2048, out_dir: Path | str = "runs/latest", max_turns: int | None = None, system_prompt: str | None = None, delivery: str = "reply",) -> dict: """Run one instance end to end and return the result dict.
``budget`` and ``reserve`` set the wall: a turn whose snapshot exceeds ``budget - reserve`` tokens ends the run with ``terminated_by="budget_wall"``, because a real serving stack would have refused the next request. ``max_turns`` is a safety stop, not part of the task: leave it unset for a full horizon.
Writes ``context_snapshots/turn-NNNN.json`` per turn, ``interactive_stream.json`` and ``result.json`` into ``out_dir``, and returns the same result dict. """ instance = load_instance(instance_dir) out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) usable = budget - reserve
instruction = instruction_for(instance, delivery=delivery) agent.reset(system_prompt or DEFAULT_SYSTEM_PROMPT, instruction)
total_ops = instance.n_ops delivered = 0 step = 0 terminated_by: str | None = None peak_tokens = 0
def _deliver_op(index: int) -> str: return render_op(instance.ops[index], remaining=total_ops - (index + 1))
if total_ops == 0: terminated_by = "stream_exhausted" pending: str | None = None else: pending = _deliver_op(0) delivered = 1
while pending is not None and terminated_by is None: reply = agent.on_user_turn(pending) or "" step += 1
messages = list(agent.context() or []) tokens, _ = count_tokens(messages) peak_tokens = max(peak_tokens, tokens) record_snapshot( out, step, messages, { "n_ops_delivered": delivered, "n_ops_total": total_ops, "budget": budget, "reserve": reserve, }, )
if tokens > usable: terminated_by = "budget_wall" break
if proto.is_submit_line(reply) or proto.is_submit_command(reply): if delivered < total_ops: pending = proto.REFUSE_SUBMIT_TEXT else: terminated_by = "submit" break elif proto.is_ready_line(reply) or proto.is_ready_command(reply): if delivered < total_ops: pending = _deliver_op(delivered) delivered += 1 else: terminated_by = "stream_exhausted" break elif proto.mentions_advance_marker(reply): pending = proto.EXPLAIN_NON_STANDALONE_TEXT else: pending = proto.NO_MARKER_TEXT
if max_turns is not None and step >= max_turns: terminated_by = "max_steps" break
if terminated_by is None: terminated_by = "stream_exhausted"
stream_record = { "n_ops_delivered": delivered, "n_ops_total": total_ops, "terminated_by": terminated_by, } (out / "interactive_stream.json").write_text( json.dumps(stream_record, indent=2) + "\n", encoding="utf-8" )
rewards = grade_run(out, instance.gold) result: dict[str, Any] = { "task_family": instance.family, "instance_dir": str(instance.path), "out_dir": str(out), "budget": budget, "reserve": reserve, "n_turns": step, "peak_tokens": peak_tokens, "reward": rewards.get("reward", 0.0), "rewards": rewards, **stream_record, } (out / "result.json").write_text( json.dumps(result, indent=2, default=str) + "\n", encoding="utf-8" ) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""The ContextBench turn protocol: op rendering, readiness detection, refusals.
Pure Python. This module is the single definition of how an operation reaches theagent and how the agent asks for the next one, so the Python runner and (phase 2)the Harbor adapters cannot drift apart.
Readiness has two equivalent forms:
* ``READY_FOR_NEXT_OP`` as a **standalone line** of the reply -- for chat agents driven by :mod:`contextbench.runner`, which have no shell;* ``echo READY_FOR_NEXT_OP`` as a **standalone shell statement** -- for agents with a bash tool, where the marker is a command the harness executes.
Both are deliberately strict about "standalone": the marker must not count when itmerely appears as an argument (``grep READY_FOR_NEXT_OP file``) or inside answerdata, because a spurious advance consumes an operation that is then lost forever.A command that failed (non-zero exit) never advances either: the step did notfinish, so the op must not be handed over."""
from __future__ import annotations
import refrom dataclasses import dataclassfrom typing import Iterable
__all__ = [ "ADVANCE_MARKER", "SUBMIT_MARKER", "TERMINATED_BY", "Op", "render_op", "is_ready_line", "is_ready_command", "mentions_advance_marker", "is_submit_line", "is_submit_command", "mentions_submit_marker", "REFUSE_SUBMIT_TEXT", "EXPLAIN_NON_STANDALONE_TEXT", "NO_MARKER_TEXT", "SUBMIT_PARAGRAPH", "MARKER_PARAGRAPH", "MARKER_PARAGRAPH_REPLY",]
ADVANCE_MARKER = "READY_FOR_NEXT_OP"SUBMIT_MARKER = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
#: Every way a ContextBench run can end. ``timeout`` is produced by wall-clock#: enforcement in the container runners; the pure-Python runner produces the#: other four.TERMINATED_BY = ( "submit", "stream_exhausted", "budget_wall", "timeout", "max_steps",)
def _standalone_line_re(marker: str) -> re.Pattern[str]: """The marker alone on a line, tolerating whitespace and code-fence quoting.""" return re.compile( rf"^[ \t]*(?:`{{1,3}})?{re.escape(marker)}(?:`{{1,3}})?[ \t]*\.?[ \t]*$", re.MULTILINE, )
def _standalone_command_re(marker: str) -> re.Pattern[str]: """``echo MARKER`` as a whole shell statement (quotes optional).""" return re.compile( rf"""^\s*(?:/bin/)?echo\s+(?:['"])?{re.escape(marker)}(?:['"])?\s*$""" )
_READY_LINE_RE = _standalone_line_re(ADVANCE_MARKER)_READY_SEGMENT_RE = _standalone_command_re(ADVANCE_MARKER)_SUBMIT_LINE_RE = _standalone_line_re(SUBMIT_MARKER)_SUBMIT_SEGMENT_RE = _standalone_command_re(SUBMIT_MARKER)
#: Shell statement separators. A bundled command such as#: ``printf '<<<ANSWER ...>>>'; echo READY_FOR_NEXT_OP`` advances, because its#: last segment is a clean echo._SEPARATORS = re.compile(r";|\n|&&|\|\|")
_HEREDOC_OPEN = re.compile(r"<<(-?)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\2")_MULTILINE_QUOTED = re.compile(r"'[^']*\n[^']*'|\"(?:[^\"\\]|\\.)*\n(?:[^\"\\]|\\.)*\"")
def _strip_heredoc_bodies(command: str) -> str: """Drop the body lines of every here-document; keep the line that opens it.
A here-document body is data fed to a program, not shell statements, so an ``echo READY_FOR_NEXT_OP`` line inside it never runs and must not count. """ lines = command.split("\n") out: list[str] = [] i = 0 while i < len(lines): line = lines[i] out.append(line) pending = _HEREDOC_OPEN.findall(line) i += 1 for dash, _quote, word in pending: while i < len(lines): body_line = lines[i] i += 1 if (body_line.lstrip("\t") if dash else body_line) == word: break return "\n".join(out)
def _statements(command: str) -> list[str]: """Split a shell command into statements, ignoring here-document bodies and quoted strings that span lines (both are data, not statements).""" text = _strip_heredoc_bodies(command) text = _MULTILINE_QUOTED.sub("''", text) return _SEPARATORS.split(text)
@dataclass(frozen=True)class Op: """One streamed operation, as it is stored in ``chunks.jsonl``."""
index: int header: str body: str
@classmethod def from_dict(cls, obj: dict, *, fallback_index: int = 0) -> "Op": return cls( index=int(obj.get("index", fallback_index)), header=str(obj.get("header", "")), body=str(obj.get("body", "")), )
def render_op(op: Op, *, remaining: int) -> str: """The exact user-turn text for one operation.
``remaining`` is the number of operations that follow this one. """ return f"=== {op.header} ({remaining} op(s) remaining after this) ===\n{op.body}"
def load_ops(lines: Iterable[str]) -> list[Op]: """Parse ``chunks.jsonl`` lines into :class:`Op` objects.""" import json
ops: list[Op] = [] for line in lines: if line.strip(): ops.append(Op.from_dict(json.loads(line), fallback_index=len(ops))) return ops
# --------------------------------------------------------------------- matchingdef is_ready_line(reply: str) -> bool: """True when the reply carries the advance marker on a line of its own.""" return bool(reply) and bool(_READY_LINE_RE.search(reply))
def is_ready_command(command: str, exit_code: int = 0) -> bool: """True when ``command`` runs ``echo READY_FOR_NEXT_OP`` as a whole statement.
A failed command means the step did not finish, so it never advances. """ if not command or exit_code != 0: return False return any(_READY_SEGMENT_RE.match(seg) for seg in _statements(command))
def mentions_advance_marker(text: str) -> bool: return bool(text) and ADVANCE_MARKER in text
def is_submit_line(reply: str) -> bool: return bool(reply) and bool(_SUBMIT_LINE_RE.search(reply))
def is_submit_command(command: str, exit_code: int = 0) -> bool: if not command or exit_code != 0: return False return any(_SUBMIT_SEGMENT_RE.match(seg) for seg in _statements(command))
def mentions_submit_marker(text: str) -> bool: return bool(text) and SUBMIT_MARKER in text
# ----------------------------------------------------------- texts sent back#: Sent when the agent submits while operations are still undelivered.REFUSE_SUBMIT_TEXT = ( "There is nothing to submit in this task and the run did NOT end. " "Operations are still being delivered one at a time: run the " f"standalone command `echo {ADVANCE_MARKER}` to receive the " "next one, and keep doing that until you are told none remain.")
#: Sent when the marker appeared but not as a standalone statement. Without this#: the agent sees its command succeed, believes it advanced, and then stalls in#: empty turns with no error signal anywhere.EXPLAIN_NON_STANDALONE_TEXT = ( f"[{ADVANCE_MARKER} did NOT advance: it must be a STANDALONE " f"command -- `echo {ADVANCE_MARKER}` on its own, or as the last " f"statement after a `;`. It does not count when passed as an " f"argument to printf/cat/grep. Your command ran normally; run the " f"marker as its own statement to receive the next operation.]")
#: Sent when a reply neither handled the op nor asked for the next one.NO_MARKER_TEXT = ( f"[No {ADVANCE_MARKER} in your reply, so the stream did not advance. " f"Finish the current operation, then put {ADVANCE_MARKER} on a line of " f"its own to receive the next one.]")
#: The two closing paragraphs a system prompt can carry. The submit contract is#: wrong for a streamed task: an agent that submits before the stream is drained#: loses every operation it has not seen.SUBMIT_PARAGRAPH = ( "When you are finished, submit by running the standalone command\n" f"`echo {SUBMIT_MARKER}` (with nothing else in that command).\n" "After it runs you cannot continue.")
MARKER_PARAGRAPH = ( "This task is delivered to you one operation at a time. You do NOT submit and\n" "you do NOT decide when it is over: after handling each operation, run the\n" f"standalone command `echo {ADVANCE_MARKER}` (with nothing else in that\n" "command) to receive the next one. Do this for EVERY operation, including the\n" "one that says none remain -- that final marker is what ends the run, and the\n" "harness stops you. Submitting early discards the work you just did.")
MARKER_PARAGRAPH_REPLY = ( "This task is delivered to you one operation at a time. You do NOT decide when\n" "it is over: after handling each operation, end your reply with\n" f"{ADVANCE_MARKER} on a line of its own to receive the next one. Do this for\n" "EVERY operation, including the one that says none remain. Submitting early\n" "discards the work you just did.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Token counting and per-turn context snapshots.
Every part of ContextBench that asks "how big is this context right now?" goesthrough :func:`count_tokens`: exact ``o200k_base`` counts when ``tiktoken`` can beimported, and a ``len // 3`` character estimate otherwise, so the package workswith no optional dependency and no network.
:func:`record_snapshot` persists the full retained context after each turn. Thesnapshots are the paper metric's source of truth: an agent that offloads contentto disk and reads a value back only transiently still has that value captured inthe snapshot of the turn where it surfaced."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathfrom typing import Any, Iterator
__all__ = [ "SNAPSHOT_DIRNAME", "count_text", "count_tokens", "get_encoder", "iter_text", "record_snapshot", "snapshot_paths",]
SNAPSHOT_DIRNAME = "context_snapshots"
#: The character-per-token divisor used when tiktoken is unavailable.FALLBACK_CHARS_PER_TOKEN = 3
_ENCODER: Any = None_ENCODER_NAME: str | None = None
def get_encoder() -> Any: """A cached ``tiktoken`` encoder, or ``None`` when tiktoken is unavailable.
Defaults to ``o200k_base``; ``TIKTOKEN_ENCODING`` overrides it and ``cl100k_base`` is the second choice (its vocabulary may be cached when ``o200k_base`` is not). """ global _ENCODER, _ENCODER_NAME if _ENCODER is not None or _ENCODER_NAME == "_failed": return _ENCODER try: import tiktoken except Exception: _ENCODER_NAME = "_failed" return None for name in (os.environ.get("TIKTOKEN_ENCODING") or "o200k_base", "cl100k_base"): try: _ENCODER = tiktoken.get_encoding(name) _ENCODER_NAME = name return _ENCODER except Exception: continue # e.g. the vocabulary download is blocked offline _ENCODER_NAME = "_failed" return None
def encoder_name() -> str: """The method label that :func:`count_tokens` reports.""" get_encoder() if _ENCODER_NAME in (None, "_failed"): return f"approx_chars{FALLBACK_CHARS_PER_TOKEN}" return f"tiktoken:{_ENCODER_NAME}"
def iter_text(messages: list[Any] | None) -> Iterator[str]: """Yield every text piece of ``messages`` that reaches the model.
This includes ``tool_calls[*].function.arguments``, where a shell command lives: a tool-heavy agent keeps most of its bytes there, so counting only ``content`` would undercount the real prompt by roughly a factor of two. """ for msg in messages or []: content: Any if isinstance(msg, dict): reasoning = msg.get("reasoning_content") if isinstance(reasoning, str): yield reasoning content = msg.get("content") for call in msg.get("tool_calls") or []: fn = call.get("function") if isinstance(call, dict) else None if isinstance(fn, dict): if fn.get("name"): yield str(fn["name"]) if fn.get("arguments"): yield str(fn["arguments"]) else: content = msg if isinstance(content, str): yield content elif isinstance(content, list): for item in content: if isinstance(item, dict): yield str(item.get("text") or item.get("content") or "") else: yield str(item)
def count_text(text: str) -> int: """Token count of one string (exact with tiktoken, else ``len // 3``).""" if not text: return 0 enc = get_encoder() if enc is None: return max(1, len(text) // FALLBACK_CHARS_PER_TOKEN) return len(enc.encode(text, disallowed_special=()))
def count_tokens(messages: list[Any] | None) -> tuple[int, str]: """Token count over a message list. Returns ``(tokens, method)``.""" total = sum(count_text(piece) for piece in iter_text(messages)) return total, encoder_name()
def snapshot_paths(logs_dir: Path | str) -> list[Path]: """Every ``context_snapshots/turn-*.json`` under ``logs_dir``, in turn order.""" import re
d = Path(logs_dir) / SNAPSHOT_DIRNAME if not d.is_dir(): return []
def _turn(path: Path) -> int: m = re.search(r"turn-(\d+)", path.name) return int(m.group(1)) if m else -1
return sorted(d.glob("turn-*.json"), key=_turn)
def record_snapshot( logs_dir: Path | str, step: int, messages: list[Any], extra: dict[str, Any] | None = None,) -> Path | None: """Persist one per-turn snapshot of the full retained context.
Writes ``<logs_dir>/context_snapshots/turn-NNNN.json`` holding ``step``, ``tokens``, ``token_method``, ``n_messages``, anything in ``extra``, and the ``messages`` themselves (last, so a human reading the file sees the accounting first). Best effort: snapshotting is a logging side effect and never raises into the run. """ try: d = Path(logs_dir) / SNAPSHOT_DIRNAME d.mkdir(parents=True, exist_ok=True) tokens, method = count_tokens(messages) payload: dict[str, Any] = { "step": step, "tokens": tokens, "token_method": method, "n_messages": len(messages or []), } if extra: payload.update(extra) payload["messages"] = messages out = d / f"turn-{step:04d}.json" out.write_text( json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8" ) return out except Exception: return None1234567891011121314151617181920212223242526272829303132333435363738{ "verdict": "PASS", "feasible": true, "task_family": "kv_store", "checks": { "pressure": { "pass": true, "detail": "streamed 49717 / budget 32768 = P 1.52 (need > 1)" }, "small_ops": { "pass": true, "detail": "max op 4909 tok (cap 5529 = usable 30720 / 5 x 0.9)" }, "retained": { "pass": true, "detail": "retained 1688 tok [per-batch index 200 + answers 1488] (cap 13824 = usable / 2 x 0.9)" }, "horizon": { "pass": true, "detail": "34 ops (need >= 4)" } }, "measured": { "P": 1.517, "streamed_tokens": 49717, "max_op_tokens": 4909, "retained_tokens": 1688, "n_ops": 34 }, "budget": 32768, "reserve": 2048, "usable_tokens": 30720, "cap_op_tokens": 5529, "cap_retained_tokens": 13824, "regime": "pressure", "token_method": "tiktoken:o200k_base", "validator_sha16": "ad7a9a4d10534c47"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138{ "queries": [ { "qid": 0, "key": "K00101", "value": "cobalt indigo willow meadow lattice zebra lattice spruce lattice russet vellum crimson trellis lattice meadow nimbus onyx cobble cobalt cedar onyx marble glacier quartz #fb248fcb" }, { "qid": 1, "key": "K00011", "value": "thistle lantern cobble russet meadow boulder thistle pewter vellum cobalt mistral cinder russet willow nimbus copper lantern cobalt indigo verdant zebra cobalt glacier nimbus #1455732a" }, { "qid": 2, "key": "K00313", "value": "quartz glacier trellis cedar copper lantern cobalt mistral indigo cobble verdant trellis fathom mistral willow falcon cobble spruce lantern onyx willow cobble cedar meadow #4fe15478" }, { "qid": 3, "key": "K00307", "value": "orbit nimbus russet trellis orbit verdant glacier pewter boulder indigo fathom auburn spruce nimbus mistral onyx boulder cinder trellis saffron lattice cobalt cinder copper #4ee12e40" }, { "qid": 4, "key": "K00769", "value": "russet zebra lantern cobble fathom fathom spruce pewter crimson falcon verdant glacier onyx spruce lattice cedar falcon nimbus spruce ember meadow mistral orbit meadow #371e4cae" }, { "qid": 5, "key": "K00979", "value": "lattice thistle cedar marble willow nimbus harbor boulder garnet cobble cobalt kindle lantern quartz copper fathom lattice cinder onyx falcon nimbus copper saffron fathom #439f0f2b" }, { "qid": 6, "key": "K00697", "value": "garnet falcon cobalt glacier cobble lantern ember cobble cedar ember quartz garnet harbor zebra glacier cobble marble trellis cinder falcon copper lattice cinder cobalt #45006b65" }, { "qid": 7, "key": "K00485", "value": "kindle pewter cedar lantern kindle falcon trellis lattice garnet pewter zebra verdant boulder fathom kindle quartz saffron indigo ember onyx copper fathom copper thistle #b2624d46" }, { "qid": 8, "key": "K00974", "value": "boulder boulder harbor thistle crimson garnet trellis cobalt cedar cinder russet cobalt zebra cedar meadow crimson crimson trellis saffron boulder orbit kindle meadow meadow #3eafa2e4" }, { "qid": 9, "key": "K00827", "value": "saffron falcon cedar kindle russet auburn kindle quartz indigo glacier kindle cobalt boulder cobble willow ember saffron cinder glacier mistral cinder harbor trellis auburn #250cfa16" }, { "qid": 10, "key": "K00203", "value": "russet willow garnet vellum lattice trellis fathom cinder harbor lantern cobble trellis fathom saffron cobble lattice spruce cedar zebra meadow meadow russet mistral garnet #9b3f786a" }, { "qid": 11, "key": "K00565", "value": "lattice ember pewter zebra cinder onyx cobble falcon copper cobalt quartz pewter auburn onyx quartz ember fathom onyx quartz boulder falcon boulder thistle meadow #f5d97b96" }, { "qid": 12, "key": "K00704", "value": "copper garnet onyx cobalt vellum fathom meadow thistle quartz copper mistral copper cobble ember cobalt orbit cobalt fathom cinder trellis meadow cobble cinder harbor #4140461e" }, { "qid": 13, "key": "K00358", "value": "verdant vellum falcon meadow thistle kindle cedar mistral crimson zebra cinder onyx pewter copper falcon nimbus meadow boulder willow kindle kindle vellum auburn meadow #e113fff3" }, { "qid": 14, "key": "K00665", "value": "cinder boulder fathom cedar zebra willow falcon lattice ember indigo boulder lattice cinder thistle crimson glacier onyx mistral marble pewter spruce garnet garnet copper #bf7d41cd" }, { "qid": 15, "key": "K00586", "value": "quartz garnet indigo fathom falcon garnet ember mistral cinder thistle meadow copper orbit lattice marble ember harbor fathom marble cinder russet kindle onyx thistle #b3bb03d6" }, { "qid": 16, "key": "K00867", "value": "spruce orbit pewter marble glacier harbor copper russet indigo vellum boulder cobalt thistle cedar orbit onyx cinder boulder cobble nimbus verdant cedar cobalt auburn #113644f8" }, { "qid": 17, "key": "K00879", "value": "saffron cobble verdant russet russet glacier boulder saffron orbit thistle cedar harbor cobalt meadow falcon nimbus crimson russet verdant harbor kindle nimbus lattice saffron #afdce33c" }, { "qid": 18, "key": "K00091", "value": "russet russet meadow onyx onyx marble onyx cedar kindle copper indigo lantern orbit orbit cobble cinder nimbus falcon harbor spruce onyx vellum spruce verdant #572d466b" }, { "qid": 19, "key": "K00989", "value": "vellum ember garnet cinder cedar auburn lantern verdant lantern meadow pewter auburn quartz mistral onyx cedar mistral thistle lattice willow orbit zebra saffron kindle #9a393c5a" }, { "qid": 20, "key": "K00265", "value": "zebra mistral zebra copper orbit quartz orbit falcon trellis kindle cedar ember kindle trellis trellis marble zebra vellum marble saffron quartz orbit auburn willow #267f7a97" }, { "qid": 21, "key": "K00207", "value": "saffron russet cobalt cinder falcon lantern boulder auburn meadow indigo kindle marble saffron willow onyx glacier thistle quartz ember kindle spruce garnet fathom saffron #2fca0dfc" }, { "qid": 22, "key": "K00930", "value": "indigo fathom cedar harbor ember russet verdant nimbus boulder thistle glacier trellis nimbus verdant orbit cedar harbor cobble spruce cobble verdant cinder cobble cinder #8165442b" }, { "qid": 23, "key": "K00031", "value": "falcon garnet zebra lantern saffron russet ember lantern verdant cedar pewter vellum glacier harbor fathom crimson fathom boulder fathom thistle fathom auburn russet trellis #5283b3f0" } ], "meta": { "task_family": "kv_store", "seed": 43, "records": 1000, "value_words": 24, "records_per_chunk": 100, "queries": 24, "n_set": 1000, "n_get": 24, "n_batches": 10, "n_actions": 34, "approx_value_tokens": 48428, "approx_per_value_tokens": 48 }}1234567891011121314{ "task_family": "kv_store", "seed": 43, "records": 1000, "value_words": 24, "records_per_chunk": 100, "queries": 24, "n_set": 1000, "n_get": 24, "n_batches": 10, "n_actions": 34, "approx_value_tokens": 48428, "approx_per_value_tokens": 48}12345678910#!/usr/bin/env bash# Grades the agent's own messages (context snapshots, else trajectory, else final# report) with the ContextBench graders vendored next to this script. Runs after the# agent has finished; writes /logs/verifier/reward.json.set -uPY=$(command -v python3 || command -v python) || { echo "ContextBench grading needs python3 in the image; or verify on the host with" "contextbench.harbor.verifiers:ContextBenchVerifier" >&2 exit 2}PYTHONPATH=/tests/_cb "$PY" -m contextbench.harbor.reward --agent-dir /logs/agent --gold /tests/gold.json --out-dir /logs/verifierREADME.mdAdded+132
data/kv_store.parquetAdded+3
data/log_triage.parquetAdded+3
data/needle_retention.parquetAdded+3
data/sudoku_sketchpad.parquetAdded+3
harbor/kv-store-R1000-seed42/environment/stream/chunks.jsonlAdded
harbor/kv-store-R1000-seed42/instruction.mdAdded+61
harbor/kv-store-R1000-seed42/solution/solve.shAdded+79
harbor/kv-store-R1000-seed42/task.tomlAdded+44
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/__init__.pyAdded+56
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/__init__.pyAdded+70
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/base.pyAdded+305
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/kv.pyAdded+87
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/log.pyAdded+116
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/needle.pyAdded+109
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/sudoku.pyAdded+225
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/__init__.pyAdded+32
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/mixin.pyAdded+122
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/reward.pyAdded+98
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/turn_source.pyAdded+399
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/runner.pyAdded+216
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/stream.pyAdded+244
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/tokens.pyAdded+171
harbor/kv-store-R1000-seed42/tests/feasibility_receipt.jsonAdded+38
harbor/kv-store-R1000-seed42/tests/gold.jsonAdded+138
harbor/kv-store-R1000-seed42/tests/meta.jsonAdded+14
harbor/kv-store-R1000-seed42/tests/test.shAdded+10
harbor/kv-store-R1000-seed43/environment/stream/chunks.jsonlAdded
harbor/kv-store-R1000-seed43/instruction.mdAdded+61
harbor/kv-store-R1000-seed43/solution/solve.shAdded+79
harbor/kv-store-R1000-seed43/task.tomlAdded+44
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/__init__.pyAdded+56
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/__init__.pyAdded+70
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/base.pyAdded+305
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/kv.pyAdded+87
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/log.pyAdded+116
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/needle.pyAdded+109
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/sudoku.pyAdded+225
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/__init__.pyAdded+32
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/mixin.pyAdded+122
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/reward.pyAdded+98
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/turn_source.pyAdded+399
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/runner.pyAdded+216
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/stream.pyAdded+244
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/tokens.pyAdded+171
harbor/kv-store-R1000-seed43/tests/feasibility_receipt.jsonAdded+38
harbor/kv-store-R1000-seed43/tests/gold.jsonAdded+138
harbor/kv-store-R1000-seed43/tests/meta.jsonAdded+14
harbor/kv-store-R1000-seed43/tests/test.shAdded+10
harbor/kv-store-R1000-seed44/environment/stream/chunks.jsonlAdded