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
- README.md +132 -0
- data/kv_store.parquet +3 -0
- data/log_triage.parquet +3 -0
- data/needle_retention.parquet +3 -0
- data/sudoku_sketchpad.parquet +3 -0
- harbor/kv-store-R1000-seed42/environment/stream/chunks.jsonl +0 -0
- harbor/kv-store-R1000-seed42/instruction.md +61 -0
- harbor/kv-store-R1000-seed42/solution/solve.sh +79 -0
- harbor/kv-store-R1000-seed42/task.toml +44 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/__init__.py +56 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/__init__.py +70 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/base.py +305 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/kv.py +87 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/log.py +116 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/needle.py +109 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/sudoku.py +225 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/__init__.py +32 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/mixin.py +122 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/reward.py +98 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/turn_source.py +399 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/runner.py +216 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/stream.py +244 -0
- harbor/kv-store-R1000-seed42/tests/_cb/contextbench/tokens.py +171 -0
- harbor/kv-store-R1000-seed42/tests/feasibility_receipt.json +38 -0
- harbor/kv-store-R1000-seed42/tests/gold.json +138 -0
- harbor/kv-store-R1000-seed42/tests/meta.json +14 -0
- harbor/kv-store-R1000-seed42/tests/test.sh +10 -0
- harbor/kv-store-R1000-seed43/environment/stream/chunks.jsonl +0 -0
- harbor/kv-store-R1000-seed43/instruction.md +61 -0
- harbor/kv-store-R1000-seed43/solution/solve.sh +79 -0
- harbor/kv-store-R1000-seed43/task.toml +44 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/__init__.py +56 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/__init__.py +70 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/base.py +305 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/kv.py +87 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/log.py +116 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/needle.py +109 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/sudoku.py +225 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/__init__.py +32 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/mixin.py +122 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/reward.py +98 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/turn_source.py +399 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/runner.py +216 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/stream.py +244 -0
- harbor/kv-store-R1000-seed43/tests/_cb/contextbench/tokens.py +171 -0
- harbor/kv-store-R1000-seed43/tests/feasibility_receipt.json +38 -0
- harbor/kv-store-R1000-seed43/tests/gold.json +138 -0
- harbor/kv-store-R1000-seed43/tests/meta.json +14 -0
- harbor/kv-store-R1000-seed43/tests/test.sh +10 -0
- harbor/kv-store-R1000-seed44/environment/stream/chunks.jsonl +0 -0
README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
pretty_name: ContextBench
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
tags:
|
| 7 |
+
- agents
|
| 8 |
+
- long-context
|
| 9 |
+
- context-management
|
| 10 |
+
- benchmark
|
| 11 |
+
size_categories:
|
| 12 |
+
- n<1K
|
| 13 |
+
configs:
|
| 14 |
+
- config_name: all
|
| 15 |
+
default: true
|
| 16 |
+
data_files:
|
| 17 |
+
- split: test
|
| 18 |
+
path: data/*.parquet
|
| 19 |
+
- config_name: kv_store
|
| 20 |
+
data_files:
|
| 21 |
+
- split: test
|
| 22 |
+
path: data/kv_store.parquet
|
| 23 |
+
- config_name: log_triage
|
| 24 |
+
data_files:
|
| 25 |
+
- split: test
|
| 26 |
+
path: data/log_triage.parquet
|
| 27 |
+
- config_name: needle_retention
|
| 28 |
+
data_files:
|
| 29 |
+
- split: test
|
| 30 |
+
path: data/needle_retention.parquet
|
| 31 |
+
- config_name: sudoku_sketchpad
|
| 32 |
+
data_files:
|
| 33 |
+
- split: test
|
| 34 |
+
path: data/sudoku_sketchpad.parquet
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
# ContextBench
|
| 38 |
+
|
| 39 |
+
ContextBench measures what an agent keeps, updates, and offloads when its input does
|
| 40 |
+
not fit in its context window. Each task streams a sequence of operations as ordinary
|
| 41 |
+
user turns, more than the context budget holds, and the reward is read from the
|
| 42 |
+
agent's own messages: what survived in its context, not what it wrote to disk.
|
| 43 |
+
|
| 44 |
+
Paper: [https://huggingface.co/papers/2609.37725](https://huggingface.co/papers/2609.37725)
|
| 45 |
+
|
| 46 |
+
## Families
|
| 47 |
+
|
| 48 |
+
| config | task | reward |
|
| 49 |
+
|---|---|---|
|
| 50 |
+
| `kv_store` | batches of `SET key = value`, then `GET key` queries | fraction of GETs answered with the right value |
|
| 51 |
+
| `log_triage` | batches of service log lines, then count and lookup questions | fraction of questions answered correctly |
|
| 52 |
+
| `needle_retention` | chunks with a few needle lines inside a large filler block | fraction of needle lines still present verbatim |
|
| 53 |
+
| `sudoku_sketchpad` | one fully specified move per turn on a 16x16 board | fraction of gold board versions the agent displayed |
|
| 54 |
+
|
| 55 |
+
The `all` config holds every instance. This release has 256 instances:
|
| 56 |
+
64 `kv_store`, 56 `log_triage`, 80 `needle_retention`, 56 `sudoku_sketchpad` (32 levels, seeds 42-49), with a context budget of 32768 tokens
|
| 57 |
+
and a reserve of 2048.
|
| 58 |
+
|
| 59 |
+
## Columns
|
| 60 |
+
|
| 61 |
+
| column | type | meaning |
|
| 62 |
+
|---|---|---|
|
| 63 |
+
| `task_id` | string | `<family>-<level>-seed<seed>`, also the Harbor task directory name |
|
| 64 |
+
| `family` | string | task family |
|
| 65 |
+
| `level` | string | difficulty level |
|
| 66 |
+
| `seed` | int | generator seed |
|
| 67 |
+
| `budget` | int | context budget in tokens |
|
| 68 |
+
| `reserve` | int | tokens reserved for the reply; the agent may use `budget - reserve` |
|
| 69 |
+
| `n_ops` | int | number of streamed operations |
|
| 70 |
+
| `streamed_tokens` | int | tokens streamed over the episode (`o200k_base`) |
|
| 71 |
+
| `pressure` | float | `streamed_tokens / budget` |
|
| 72 |
+
| `chunks` | list of `{index, header, body}` | the operations, one user turn each |
|
| 73 |
+
| `gold` | string (JSON) | the answers the graders score against |
|
| 74 |
+
| `meta` | string (JSON) | generator settings and instance statistics |
|
| 75 |
+
|
| 76 |
+
Each operation is shown to the agent as
|
| 77 |
+
`=== {header} ({remaining} op(s) remaining after this) ===` followed by its body.
|
| 78 |
+
|
| 79 |
+
## Usage
|
| 80 |
+
|
| 81 |
+
### With `datasets`
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
import json
|
| 85 |
+
from datasets import load_dataset
|
| 86 |
+
|
| 87 |
+
ds = load_dataset("context-language-model/ContextBench", "kv_store", split="test") # or "all"
|
| 88 |
+
row = ds[0]
|
| 89 |
+
ops = row["chunks"] # list of {"index", "header", "body"}
|
| 90 |
+
gold = json.loads(row["gold"])
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
To evaluate an agent from Python, install the `contextbench` package, write an
|
| 94 |
+
instance to disk, and pass your agent to `contextbench.run`:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
from pathlib import Path
|
| 98 |
+
from contextbench import run
|
| 99 |
+
|
| 100 |
+
inst = Path("instances") / row["task_id"]
|
| 101 |
+
inst.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
(inst / "chunks.jsonl").write_text(
|
| 103 |
+
"".join(json.dumps(c) + "\n" for c in row["chunks"]))
|
| 104 |
+
(inst / "gold.json").write_text(row["gold"])
|
| 105 |
+
(inst / "meta.json").write_text(row["meta"])
|
| 106 |
+
|
| 107 |
+
result = run(my_agent, inst, budget=row["budget"], reserve=row["reserve"],
|
| 108 |
+
out_dir=Path("runs") / row["task_id"])
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
### With Harbor
|
| 112 |
+
|
| 113 |
+
The `harbor/` directory holds one Harbor task per instance, and `registry.json`
|
| 114 |
+
lists the datasets `contextbench` (every task) and `contextbench-<family>`
|
| 115 |
+
(for example `contextbench-kv-store`). Download the repository, then run Harbor
|
| 116 |
+
from inside it:
|
| 117 |
+
|
| 118 |
+
```bash
|
| 119 |
+
hf download context-language-model/ContextBench --repo-type dataset --local-dir contextbench-hf
|
| 120 |
+
cd contextbench-hf
|
| 121 |
+
harbor jobs start --registry-path registry.json -d contextbench \
|
| 122 |
+
-a contextbench.harbor.agents:Terminus2Stream -m <model>
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
Use `-d contextbench-sudoku-sketchpad` for one family, `-i <task_id>` for one task,
|
| 126 |
+
`-p harbor/` to run the directory without the registry, or `-a oracle` to check a
|
| 127 |
+
task with its reference solution. Agents that deliver operations into a running
|
| 128 |
+
conversation ship with the `contextbench` package (`contextbench.harbor.agents`).
|
| 129 |
+
|
| 130 |
+
## License
|
| 131 |
+
|
| 132 |
+
Apache-2.0.
|
data/kv_store.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7cf5f19812143495fdec73e097d67ba6a36b3ebe98cb63dcacdae4cab5440e11
|
| 3 |
+
size 11894440
|
data/log_triage.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:99ba1f0f479c5cc4780c61572323db642e90a50b45736c9459c9c97cc12bc3ba
|
| 3 |
+
size 5891832
|
data/needle_retention.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4676617211f8beb029303629922630cb27458c9254794093a06eef3ff0ec2bfe
|
| 3 |
+
size 40076404
|
data/sudoku_sketchpad.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5130d8cd005f47dbe7f0ffaedf0ec5b56b4d9429ed1a777b8835e3e70aece9d2
|
| 3 |
+
size 144182
|
harbor/kv-store-R1000-seed42/environment/stream/chunks.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
harbor/kv-store-R1000-seed42/instruction.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Key-Value Store - process graded (interactive)
|
| 2 |
+
|
| 3 |
+
Operations are delivered to you ONE AT A TIME, as messages in this conversation.
|
| 4 |
+
You do NOT fetch them: each operation arrives automatically as the next user
|
| 5 |
+
message, and you receive the following operation only after you finish the
|
| 6 |
+
current turn. The stream has two phases:
|
| 7 |
+
|
| 8 |
+
1. a long run of **SET-BATCH** blocks, each delimited by unique
|
| 9 |
+
`<<<SET-BATCH <id> BEGIN ...>>>` / `<<<SET-BATCH <id> END>>>` sentinel lines and
|
| 10 |
+
carrying many lines of the form `SET <key> = <value>` (each `<value>` is a
|
| 11 |
+
random, unguessable token; each key is set exactly once), then
|
| 12 |
+
2. a run of **GET** ops at the end: `GET <key>` - report the value you stored
|
| 13 |
+
earlier for `<key>`.
|
| 14 |
+
|
| 15 |
+
Because every `SET` arrives before any `GET`, you cannot predict which keys will
|
| 16 |
+
be queried - you must be able to recall **any** value you have seen.
|
| 17 |
+
|
| 18 |
+
## Turn protocol (IMPORTANT)
|
| 19 |
+
Each incoming message is ONE operation. Do whatever work it needs FIRST (offload,
|
| 20 |
+
`grep`, emit an ANSWER block, ...). When you are done with the current operation,
|
| 21 |
+
**end your turn** by running this single command with the `bash` tool to receive
|
| 22 |
+
the next operation:
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
echo READY_FOR_NEXT_OP
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
This is a multi-turn task: the harness RUNS this command and then delivers the
|
| 29 |
+
next operation as the next user message. You MAY bundle real work into the SAME
|
| 30 |
+
command — in fact the cleanest way to answer a GET is to pipe the stored value
|
| 31 |
+
straight into an ANSWER block and emit the marker together, e.g.:
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
printf '<<<ANSWER key=K00084>>>\n%s\n<<<ANSWER END>>>\n' "$val"; echo READY_FOR_NEXT_OP
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
ONLY running `echo READY_FOR_NEXT_OP` advances to the next operation — a reply
|
| 38 |
+
with no tool call does NOT advance (it just prompts you to keep going). Do NOT run
|
| 39 |
+
the marker until you have fully handled the current operation (offloaded the
|
| 40 |
+
batch, or emitted the GET ANSWER block).
|
| 41 |
+
|
| 42 |
+
## How to answer a GET
|
| 43 |
+
|
| 44 |
+
When you read a `GET <key>`, reply with an **ANSWER block** on its own lines,
|
| 45 |
+
carrying the value **verbatim**:
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
<<<ANSWER key=<key>>>>
|
| 49 |
+
<the exact value you stored for <key>>
|
| 50 |
+
<<<ANSWER END>>>
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## How you are graded
|
| 54 |
+
|
| 55 |
+
Process-graded: for every `GET`, the ANSWER block you emit must contain the
|
| 56 |
+
correct value. Grading reads your **context** (the ANSWER blocks across your
|
| 57 |
+
turns). You MAY use the disk as scratch/storage, but FINDING a value (e.g. with
|
| 58 |
+
`grep`) is NOT answering — only an ANSWER block that actually appears in your
|
| 59 |
+
context is scored, so you must PRINT the value inside `<<<ANSWER ...>>>` ...
|
| 60 |
+
`<<<ANSWER END>>>`.
|
| 61 |
+
The run ends automatically after the final operation; you do not need to submit.
|
harbor/kv-store-R1000-seed42/solution/solve.sh
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Oracle: writes every gold answer into the agent log dir as a final report.
|
| 3 |
+
# Graded as graded_from=final_report, never comparable to a context grade.
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
mkdir -p /logs/agent
|
| 6 |
+
cat > /logs/agent/final_report.txt <<'CONTEXTBENCH_ORACLE_EOF'
|
| 7 |
+
<<<ANSWER key=K00048>>>
|
| 8 |
+
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
|
| 9 |
+
<<<ANSWER END>>>
|
| 10 |
+
<<<ANSWER key=K00465>>>
|
| 11 |
+
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
|
| 12 |
+
<<<ANSWER END>>>
|
| 13 |
+
<<<ANSWER key=K00600>>>
|
| 14 |
+
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
|
| 15 |
+
<<<ANSWER END>>>
|
| 16 |
+
<<<ANSWER key=K00135>>>
|
| 17 |
+
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
|
| 18 |
+
<<<ANSWER END>>>
|
| 19 |
+
<<<ANSWER key=K00224>>>
|
| 20 |
+
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
|
| 21 |
+
<<<ANSWER END>>>
|
| 22 |
+
<<<ANSWER key=K00492>>>
|
| 23 |
+
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
|
| 24 |
+
<<<ANSWER END>>>
|
| 25 |
+
<<<ANSWER key=K00798>>>
|
| 26 |
+
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
|
| 27 |
+
<<<ANSWER END>>>
|
| 28 |
+
<<<ANSWER key=K00150>>>
|
| 29 |
+
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
|
| 30 |
+
<<<ANSWER END>>>
|
| 31 |
+
<<<ANSWER key=K00603>>>
|
| 32 |
+
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
|
| 33 |
+
<<<ANSWER END>>>
|
| 34 |
+
<<<ANSWER key=K00568>>>
|
| 35 |
+
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
|
| 36 |
+
<<<ANSWER END>>>
|
| 37 |
+
<<<ANSWER key=K00147>>>
|
| 38 |
+
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
|
| 39 |
+
<<<ANSWER END>>>
|
| 40 |
+
<<<ANSWER key=K00396>>>
|
| 41 |
+
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
|
| 42 |
+
<<<ANSWER END>>>
|
| 43 |
+
<<<ANSWER key=K00566>>>
|
| 44 |
+
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
|
| 45 |
+
<<<ANSWER END>>>
|
| 46 |
+
<<<ANSWER key=K00621>>>
|
| 47 |
+
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
|
| 48 |
+
<<<ANSWER END>>>
|
| 49 |
+
<<<ANSWER key=K00914>>>
|
| 50 |
+
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
|
| 51 |
+
<<<ANSWER END>>>
|
| 52 |
+
<<<ANSWER key=K00236>>>
|
| 53 |
+
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
|
| 54 |
+
<<<ANSWER END>>>
|
| 55 |
+
<<<ANSWER key=K00229>>>
|
| 56 |
+
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
|
| 57 |
+
<<<ANSWER END>>>
|
| 58 |
+
<<<ANSWER key=K00281>>>
|
| 59 |
+
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
|
| 60 |
+
<<<ANSWER END>>>
|
| 61 |
+
<<<ANSWER key=K00927>>>
|
| 62 |
+
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
|
| 63 |
+
<<<ANSWER END>>>
|
| 64 |
+
<<<ANSWER key=K00723>>>
|
| 65 |
+
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
|
| 66 |
+
<<<ANSWER END>>>
|
| 67 |
+
<<<ANSWER key=K00523>>>
|
| 68 |
+
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
|
| 69 |
+
<<<ANSWER END>>>
|
| 70 |
+
<<<ANSWER key=K00678>>>
|
| 71 |
+
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
|
| 72 |
+
<<<ANSWER END>>>
|
| 73 |
+
<<<ANSWER key=K00952>>>
|
| 74 |
+
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
|
| 75 |
+
<<<ANSWER END>>>
|
| 76 |
+
<<<ANSWER key=K00869>>>
|
| 77 |
+
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
|
| 78 |
+
<<<ANSWER END>>>
|
| 79 |
+
CONTEXTBENCH_ORACLE_EOF
|
harbor/kv-store-R1000-seed42/task.toml
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[metadata]
|
| 2 |
+
author_name = "contextbench"
|
| 3 |
+
difficulty = "medium"
|
| 4 |
+
category = "context-management"
|
| 5 |
+
tags = ["context-management", "contextbench", "kv-store", "storage-offloading"]
|
| 6 |
+
contextbench_family = "kv_store"
|
| 7 |
+
contextbench_budget_tokens = 32768
|
| 8 |
+
contextbench_reserve_tokens = 2048
|
| 9 |
+
contextbench_pressure = 1.516
|
| 10 |
+
contextbench_feasible = true
|
| 11 |
+
contextbench_regime = "pressure"
|
| 12 |
+
contextbench_stream_count = 34
|
| 13 |
+
contextbench_stream_sha256 = "5f0799fab3470cf468bf2936f0a487da6f85e2c1ff6e8f5aa55af259c210cc9c"
|
| 14 |
+
instance_approx_per_value_tokens = 48
|
| 15 |
+
instance_approx_value_tokens = 48457
|
| 16 |
+
instance_n_actions = 34
|
| 17 |
+
instance_n_batches = 10
|
| 18 |
+
instance_n_get = 24
|
| 19 |
+
instance_n_set = 1000
|
| 20 |
+
instance_queries = 24
|
| 21 |
+
instance_records = 1000
|
| 22 |
+
instance_records_per_chunk = 100
|
| 23 |
+
instance_seed = 42
|
| 24 |
+
instance_task_family = "kv_store"
|
| 25 |
+
instance_value_words = 24
|
| 26 |
+
|
| 27 |
+
[verifier]
|
| 28 |
+
timeout_sec = 600.0
|
| 29 |
+
|
| 30 |
+
[agent]
|
| 31 |
+
timeout_sec = 14400.0
|
| 32 |
+
|
| 33 |
+
[environment]
|
| 34 |
+
docker_image = "python:3.12-slim"
|
| 35 |
+
workdir = "/app"
|
| 36 |
+
build_timeout_sec = 600.0
|
| 37 |
+
cpus = 1
|
| 38 |
+
memory_mb = 2048
|
| 39 |
+
storage_mb = 4096
|
| 40 |
+
|
| 41 |
+
[environment.env]
|
| 42 |
+
CONTEXTBENCH_STREAM_COUNT = "34"
|
| 43 |
+
CONTEXTBENCH_STREAM_SHA256 = "5f0799fab3470cf468bf2936f0a487da6f85e2c1ff6e8f5aa55af259c210cc9c"
|
| 44 |
+
CONTEXTBENCH_STREAM_PATH = "/app/stream/chunks.jsonl"
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench: benchmarking what an agent keeps, updates, and offloads.
|
| 2 |
+
|
| 3 |
+
Four task families stream more input than fits in an agent's context window and
|
| 4 |
+
grade what survived. Everything the agent has to do is expressed as ordinary user
|
| 5 |
+
turns, so any chat agent can be evaluated.
|
| 6 |
+
|
| 7 |
+
Quickstart::
|
| 8 |
+
|
| 9 |
+
from contextbench import run
|
| 10 |
+
from contextbench.oracle import OracleAgent # task self-check only, not a baseline
|
| 11 |
+
|
| 12 |
+
result = run(OracleAgent(instance_dir), instance_dir, budget=32768,
|
| 13 |
+
reserve=2048, out_dir="runs/kv-R1000-seed42")
|
| 14 |
+
print(result["reward"], result["terminated_by"])
|
| 15 |
+
|
| 16 |
+
The core imports nothing outside the standard library: ``tiktoken`` and
|
| 17 |
+
``harbor`` are optional extras and never required to generate, run or grade.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from .graders import grade_run, grader_for
|
| 23 |
+
from .runner import (
|
| 24 |
+
DEFAULT_SYSTEM_PROMPT,
|
| 25 |
+
ContextAgent,
|
| 26 |
+
Instance,
|
| 27 |
+
instruction_for,
|
| 28 |
+
load_instance,
|
| 29 |
+
run,
|
| 30 |
+
)
|
| 31 |
+
from .stream import ADVANCE_MARKER, SUBMIT_MARKER, TERMINATED_BY, Op, render_op
|
| 32 |
+
from .tokens import count_tokens, record_snapshot
|
| 33 |
+
|
| 34 |
+
__version__ = "0.1.0"
|
| 35 |
+
|
| 36 |
+
FAMILIES = ("kv_store", "log_triage", "needle_retention", "sudoku_sketchpad")
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"ADVANCE_MARKER",
|
| 40 |
+
"ContextAgent",
|
| 41 |
+
"DEFAULT_SYSTEM_PROMPT",
|
| 42 |
+
"FAMILIES",
|
| 43 |
+
"Instance",
|
| 44 |
+
"Op",
|
| 45 |
+
"SUBMIT_MARKER",
|
| 46 |
+
"TERMINATED_BY",
|
| 47 |
+
"__version__",
|
| 48 |
+
"count_tokens",
|
| 49 |
+
"grade_run",
|
| 50 |
+
"grader_for",
|
| 51 |
+
"instruction_for",
|
| 52 |
+
"load_instance",
|
| 53 |
+
"record_snapshot",
|
| 54 |
+
"render_op",
|
| 55 |
+
"run",
|
| 56 |
+
]
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/__init__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench graders: one per task family, plus the shared context readers.
|
| 2 |
+
|
| 3 |
+
Every grader takes a run directory and the parsed ``gold.json`` and returns a
|
| 4 |
+
reward dict carrying ``graded_from`` -- the context source it actually read.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .base import (
|
| 13 |
+
ContextSource,
|
| 14 |
+
Grader,
|
| 15 |
+
read_context,
|
| 16 |
+
read_final_report,
|
| 17 |
+
read_snapshots,
|
| 18 |
+
read_trajectory,
|
| 19 |
+
)
|
| 20 |
+
from .kv import KVStoreGrader
|
| 21 |
+
from .log import LogTriageGrader
|
| 22 |
+
from .needle import NeedleRetentionGrader
|
| 23 |
+
from .sudoku import SudokuSketchpadGrader
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"ContextSource",
|
| 27 |
+
"Grader",
|
| 28 |
+
"GRADERS",
|
| 29 |
+
"KVStoreGrader",
|
| 30 |
+
"LogTriageGrader",
|
| 31 |
+
"NeedleRetentionGrader",
|
| 32 |
+
"SudokuSketchpadGrader",
|
| 33 |
+
"grade_run",
|
| 34 |
+
"grader_for",
|
| 35 |
+
"read_context",
|
| 36 |
+
"read_final_report",
|
| 37 |
+
"read_snapshots",
|
| 38 |
+
"read_trajectory",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
GRADERS: dict[str, type[Grader]] = {
|
| 42 |
+
"kv_store": KVStoreGrader,
|
| 43 |
+
"log_triage": LogTriageGrader,
|
| 44 |
+
"needle_retention": NeedleRetentionGrader,
|
| 45 |
+
"sudoku_sketchpad": SudokuSketchpadGrader,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def grader_for(family: str) -> Grader:
|
| 50 |
+
"""The grader instance for one family."""
|
| 51 |
+
try:
|
| 52 |
+
return GRADERS[family]()
|
| 53 |
+
except KeyError:
|
| 54 |
+
raise KeyError(
|
| 55 |
+
f"no grader for family {family!r}; known: {', '.join(sorted(GRADERS))}"
|
| 56 |
+
) from None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def grade_run(run_dir: Path | str, gold: dict | Path | str) -> dict:
|
| 60 |
+
"""Grade a run directory against a gold object or a ``gold.json`` path.
|
| 61 |
+
|
| 62 |
+
The family comes from ``gold["meta"]["task_family"]``, so a grader can never be
|
| 63 |
+
pointed at the wrong family's instance by accident.
|
| 64 |
+
"""
|
| 65 |
+
if not isinstance(gold, dict):
|
| 66 |
+
gold = json.loads(Path(gold).read_text(encoding="utf-8"))
|
| 67 |
+
family = (gold.get("meta") or {}).get("task_family")
|
| 68 |
+
if not family:
|
| 69 |
+
raise ValueError("gold.meta['task_family'] is missing: cannot pick a grader")
|
| 70 |
+
return grader_for(family).grade(run_dir, gold)
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/base.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader plumbing: the three ways a run's context is read back.
|
| 2 |
+
|
| 3 |
+
Every ContextBench reward is computed out of the agent's own messages, never off
|
| 4 |
+
disk. Three readers supply those messages, in order of preference:
|
| 5 |
+
|
| 6 |
+
1. **snapshots** -- ``context_snapshots/turn-*.json``, one per turn. This is the
|
| 7 |
+
paper metric: an agent that parks content outside its context and surfaces a
|
| 8 |
+
value only transiently still has that value captured in the snapshot of the turn
|
| 9 |
+
where it appeared.
|
| 10 |
+
2. **trajectory** -- an ATIF ``trajectory.json``: a flat list of chat messages that
|
| 11 |
+
context edits mutate in place, so the final file is exactly the retained
|
| 12 |
+
context. One frame, not a per-turn series.
|
| 13 |
+
3. **final report** -- the closing text of a run whose agent cannot expose its
|
| 14 |
+
context at all.
|
| 15 |
+
|
| 16 |
+
Which reader ran is recorded as ``graded_from`` in every reward dict, so a number
|
| 17 |
+
is never comparable by accident across sources.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Sequence
|
| 27 |
+
|
| 28 |
+
from ..tokens import SNAPSHOT_DIRNAME, snapshot_paths
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"ContextSource",
|
| 32 |
+
"atif_messages",
|
| 33 |
+
"Grader",
|
| 34 |
+
"find_snapshots_dir",
|
| 35 |
+
"find_trajectory",
|
| 36 |
+
"messages_text",
|
| 37 |
+
"normalize",
|
| 38 |
+
"read_context",
|
| 39 |
+
"read_final_report",
|
| 40 |
+
"read_snapshots",
|
| 41 |
+
"read_trajectory",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
#: Filenames a run may use for its closing report, most specific first.
|
| 45 |
+
FINAL_REPORT_NAMES = (
|
| 46 |
+
"final_report.txt",
|
| 47 |
+
"final_report.md",
|
| 48 |
+
"final_report.json",
|
| 49 |
+
"report.txt",
|
| 50 |
+
"report.md",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def normalize(text: str) -> str:
|
| 55 |
+
"""Collapse whitespace, so a reward never turns on reflow or indentation."""
|
| 56 |
+
return re.sub(r"\s+", " ", text.strip())
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _decoded_tool_json(content: str) -> str | None:
|
| 60 |
+
"""The string fields of a tool result that is one JSON object, else ``None``.
|
| 61 |
+
|
| 62 |
+
Some harnesses render a command's output as a JSON object (``{"returncode": 0,
|
| 63 |
+
"output": "..."}``), which escapes ``<`` and ``>`` and turns newlines into
|
| 64 |
+
``\\n``. The model reads the decoded text; so does the grader.
|
| 65 |
+
"""
|
| 66 |
+
text = content.strip()
|
| 67 |
+
if not (text.startswith("{") and text.endswith("}")):
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
obj = json.loads(text)
|
| 71 |
+
except Exception:
|
| 72 |
+
return None
|
| 73 |
+
if not isinstance(obj, dict):
|
| 74 |
+
return None
|
| 75 |
+
parts = [v for v in obj.values() if isinstance(v, str)]
|
| 76 |
+
return "\n".join(parts) if parts else None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def messages_text(messages: Sequence[Any] | None) -> str:
|
| 80 |
+
"""Flatten a message list into the text the grader scans."""
|
| 81 |
+
texts: list[str] = []
|
| 82 |
+
for msg in messages or []:
|
| 83 |
+
content = msg.get("content") if isinstance(msg, dict) else msg
|
| 84 |
+
if isinstance(content, str):
|
| 85 |
+
if isinstance(msg, dict) and msg.get("role") == "tool":
|
| 86 |
+
decoded = _decoded_tool_json(content)
|
| 87 |
+
if decoded is not None:
|
| 88 |
+
content = decoded
|
| 89 |
+
texts.append(content)
|
| 90 |
+
elif isinstance(content, list):
|
| 91 |
+
for item in content:
|
| 92 |
+
texts.append(
|
| 93 |
+
str(item.get("text") or item.get("content") or "")
|
| 94 |
+
if isinstance(item, dict)
|
| 95 |
+
else str(item)
|
| 96 |
+
)
|
| 97 |
+
return "\n".join(texts)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ----------------------------------------------------------------- locating files
|
| 101 |
+
def _candidate_dirs(run_dir: Path) -> list[Path]:
|
| 102 |
+
"""``run_dir`` itself and the usual agent subdirectories, in preference order."""
|
| 103 |
+
return [run_dir, run_dir / "agent", run_dir / "logs", run_dir / "logs" / "agent"]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def find_snapshots_dir(run_dir: Path | str) -> Path | None:
|
| 107 |
+
"""The run's ``context_snapshots`` directory, if it has one."""
|
| 108 |
+
run_dir = Path(run_dir)
|
| 109 |
+
for cand in _candidate_dirs(run_dir):
|
| 110 |
+
if (cand / SNAPSHOT_DIRNAME).is_dir():
|
| 111 |
+
return cand / SNAPSHOT_DIRNAME
|
| 112 |
+
hits = sorted(run_dir.glob(f"**/{SNAPSHOT_DIRNAME}"))
|
| 113 |
+
return hits[0] if hits else None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def find_trajectory(run_dir: Path | str) -> Path | None:
|
| 117 |
+
"""The run's ATIF ``trajectory.json``, if it has one."""
|
| 118 |
+
run_dir = Path(run_dir)
|
| 119 |
+
for cand in _candidate_dirs(run_dir):
|
| 120 |
+
if (cand / "trajectory.json").is_file():
|
| 121 |
+
return cand / "trajectory.json"
|
| 122 |
+
hits = sorted(run_dir.glob("**/trajectory.json"))
|
| 123 |
+
return hits[0] if hits else None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ------------------------------------------------------------------- the readers
|
| 127 |
+
@dataclass
|
| 128 |
+
class ContextSource:
|
| 129 |
+
"""The messages a grader scores, and where they came from."""
|
| 130 |
+
|
| 131 |
+
graded_from: str
|
| 132 |
+
#: One message list per turn. A trajectory or a report yields a single frame.
|
| 133 |
+
frames: list[list[Any]] = field(default_factory=list)
|
| 134 |
+
#: Per-turn context size, when the source records it.
|
| 135 |
+
tokens: list[int] = field(default_factory=list)
|
| 136 |
+
n_snapshots: int = 0
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def final_frame(self) -> list[Any]:
|
| 140 |
+
return self.frames[-1] if self.frames else []
|
| 141 |
+
|
| 142 |
+
def texts(self) -> list[str]:
|
| 143 |
+
return [messages_text(frame) for frame in self.frames]
|
| 144 |
+
|
| 145 |
+
def all_text(self) -> str:
|
| 146 |
+
return "\n".join(self.texts())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def read_snapshots(run_dir: Path | str) -> ContextSource | None:
|
| 150 |
+
"""Read ``context_snapshots/turn-*.json`` as one frame per turn."""
|
| 151 |
+
snap_dir = find_snapshots_dir(run_dir)
|
| 152 |
+
if snap_dir is None:
|
| 153 |
+
return None
|
| 154 |
+
frames: list[list[Any]] = []
|
| 155 |
+
tokens: list[int] = []
|
| 156 |
+
n = 0
|
| 157 |
+
for path in snapshot_paths(snap_dir.parent):
|
| 158 |
+
try:
|
| 159 |
+
obj = json.loads(path.read_text(encoding="utf-8"))
|
| 160 |
+
except Exception:
|
| 161 |
+
continue
|
| 162 |
+
n += 1
|
| 163 |
+
if isinstance(obj.get("tokens"), (int, float)):
|
| 164 |
+
tokens.append(int(obj["tokens"]))
|
| 165 |
+
frames.append(obj.get("messages") or [])
|
| 166 |
+
if n == 0:
|
| 167 |
+
return None
|
| 168 |
+
return ContextSource("snapshots", frames, tokens, n)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def read_trajectory(run_dir: Path | str) -> ContextSource | None:
|
| 172 |
+
"""Read an ATIF ``trajectory.json`` as a single frame."""
|
| 173 |
+
path = find_trajectory(run_dir)
|
| 174 |
+
if path is None:
|
| 175 |
+
return None
|
| 176 |
+
try:
|
| 177 |
+
messages = json.loads(path.read_text(encoding="utf-8"))
|
| 178 |
+
except Exception:
|
| 179 |
+
return None
|
| 180 |
+
if isinstance(messages, dict):
|
| 181 |
+
if isinstance(messages.get("steps"), list):
|
| 182 |
+
messages = atif_messages(messages["steps"])
|
| 183 |
+
else:
|
| 184 |
+
messages = messages.get("messages") or messages.get("trajectory") or []
|
| 185 |
+
if not isinstance(messages, list):
|
| 186 |
+
return None
|
| 187 |
+
return ContextSource("trajectory", [messages], [], 0)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _part_text(content: Any) -> str:
|
| 191 |
+
if isinstance(content, str):
|
| 192 |
+
return content
|
| 193 |
+
if isinstance(content, list):
|
| 194 |
+
return "\n".join(
|
| 195 |
+
str(p.get("text") or "") if isinstance(p, dict) else str(p) for p in content
|
| 196 |
+
)
|
| 197 |
+
return "" if content is None else str(content)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def atif_messages(steps: Sequence[Any]) -> list[dict[str, Any]]:
|
| 201 |
+
"""Flatten ATIF ``steps`` into chat messages.
|
| 202 |
+
|
| 203 |
+
``user`` and ``system`` steps become messages of that role; an ``agent`` step
|
| 204 |
+
becomes an ``assistant`` message followed by one ``tool`` message per
|
| 205 |
+
observation result. The flattening is the full history the harness recorded,
|
| 206 |
+
which for a harness that compacts is more than it retained.
|
| 207 |
+
"""
|
| 208 |
+
out: list[dict[str, Any]] = []
|
| 209 |
+
for step in steps or []:
|
| 210 |
+
if not isinstance(step, dict):
|
| 211 |
+
continue
|
| 212 |
+
source = step.get("source")
|
| 213 |
+
text = _part_text(step.get("message"))
|
| 214 |
+
if source in ("user", "system"):
|
| 215 |
+
out.append({"role": source, "content": text})
|
| 216 |
+
continue
|
| 217 |
+
out.append({"role": "assistant", "content": text})
|
| 218 |
+
observation = step.get("observation") or {}
|
| 219 |
+
for result in observation.get("results") or []:
|
| 220 |
+
if isinstance(result, dict) and result.get("content") is not None:
|
| 221 |
+
out.append({"role": "tool", "content": _part_text(result["content"])})
|
| 222 |
+
return out
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def read_final_report(run_dir: Path | str) -> str:
|
| 226 |
+
"""The run's closing report text.
|
| 227 |
+
|
| 228 |
+
A file named like ``final_report.txt`` wins; otherwise the assistant messages
|
| 229 |
+
of a trajectory are concatenated, which is what an agent that only talks leaves
|
| 230 |
+
behind.
|
| 231 |
+
"""
|
| 232 |
+
run_dir = Path(run_dir)
|
| 233 |
+
for cand in _candidate_dirs(run_dir):
|
| 234 |
+
for name in FINAL_REPORT_NAMES:
|
| 235 |
+
path = cand / name
|
| 236 |
+
if path.is_file():
|
| 237 |
+
return path.read_text(encoding="utf-8")
|
| 238 |
+
source = read_trajectory(run_dir)
|
| 239 |
+
if source is None:
|
| 240 |
+
return ""
|
| 241 |
+
assistant = [
|
| 242 |
+
m
|
| 243 |
+
for m in source.final_frame
|
| 244 |
+
if isinstance(m, dict) and m.get("role") == "assistant"
|
| 245 |
+
]
|
| 246 |
+
return messages_text(assistant or source.final_frame)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def read_context(run_dir: Path | str) -> ContextSource:
|
| 250 |
+
"""The best available source for ``run_dir``.
|
| 251 |
+
|
| 252 |
+
Snapshots first (the paper metric), then the ATIF trajectory, then the final
|
| 253 |
+
report. An empty :class:`ContextSource` with ``graded_from="none"`` means the
|
| 254 |
+
run left nothing gradeable behind, which a grader reports as invalid rather
|
| 255 |
+
than as a zero.
|
| 256 |
+
"""
|
| 257 |
+
for reader in (read_snapshots, read_trajectory):
|
| 258 |
+
source = reader(run_dir)
|
| 259 |
+
if source is not None:
|
| 260 |
+
return source
|
| 261 |
+
report = read_final_report(run_dir)
|
| 262 |
+
if report:
|
| 263 |
+
return ContextSource(
|
| 264 |
+
"final_report", [[{"role": "assistant", "content": report}]], [], 0
|
| 265 |
+
)
|
| 266 |
+
return ContextSource("none", [], [], 0)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ---------------------------------------------------------------------- base class
|
| 270 |
+
class Grader:
|
| 271 |
+
"""A ContextBench grader.
|
| 272 |
+
|
| 273 |
+
Subclasses implement :meth:`grade`, which takes a run directory and the parsed
|
| 274 |
+
``gold.json`` and returns a reward dict. Every returned dict carries
|
| 275 |
+
``graded_from`` and ``grader_valid``.
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
family: str = ""
|
| 279 |
+
#: The reward name a caller should read as "the score".
|
| 280 |
+
primary: str = "reward"
|
| 281 |
+
|
| 282 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 283 |
+
raise NotImplementedError
|
| 284 |
+
|
| 285 |
+
def grade_path(self, run_dir: Path | str, gold_path: Path | str) -> dict:
|
| 286 |
+
gold = json.loads(Path(gold_path).read_text(encoding="utf-8"))
|
| 287 |
+
return self.grade(run_dir, gold)
|
| 288 |
+
|
| 289 |
+
# -- helpers shared by the concrete graders --------------------------------
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _token_stats(tokens: list[int]) -> dict[str, float]:
|
| 292 |
+
return {
|
| 293 |
+
"agent_peak_tokens": float(max(tokens)) if tokens else 0.0,
|
| 294 |
+
"agent_mean_tokens": float(sum(tokens) / len(tokens)) if tokens else 0.0,
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
@staticmethod
|
| 298 |
+
def _invalid(graded_from: str, why: str) -> dict:
|
| 299 |
+
"""A grade that could not be computed: never reported as a zero score."""
|
| 300 |
+
return {
|
| 301 |
+
"reward": 0.0,
|
| 302 |
+
"grader_valid": 0.0,
|
| 303 |
+
"graded_from": graded_from,
|
| 304 |
+
"grader_note": why,
|
| 305 |
+
}
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/kv.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Key-Value Store*: process-graded, ANSWER-block based.
|
| 2 |
+
|
| 3 |
+
The agent answers each ``GET <key>`` by emitting an ANSWER block::
|
| 4 |
+
|
| 5 |
+
<<<ANSWER key=K00007>>>
|
| 6 |
+
<the value it stored for K00007>
|
| 7 |
+
<<<ANSWER END>>>
|
| 8 |
+
|
| 9 |
+
Every per-turn context frame is scanned, all ANSWER blocks are collected as
|
| 10 |
+
``key -> {value strings the agent ever produced}``, and the score is the fraction
|
| 11 |
+
of gold GET queries whose correct value was produced.
|
| 12 |
+
|
| 13 |
+
Reading the whole per-turn series rather than the final context is what makes the
|
| 14 |
+
mechanisms comparable on one number: an agent that parks values outside its context
|
| 15 |
+
and surfaces the queried one only transiently has the value in the snapshot of the
|
| 16 |
+
GET turn, but not in its final context.
|
| 17 |
+
|
| 18 |
+
Rewards:
|
| 19 |
+
|
| 20 |
+
* ``reward`` -- fraction of GET queries answered with the correct value;
|
| 21 |
+
* ``reward_attempted`` -- of the GETs answered at all, the fraction correct;
|
| 22 |
+
* ``n_answered`` -- how many distinct gold GETs got any ANSWER block;
|
| 23 |
+
* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import re
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
from .base import ContextSource, Grader, messages_text, normalize, read_context
|
| 32 |
+
|
| 33 |
+
__all__ = ["KVStoreGrader", "ANSWER_RE"]
|
| 34 |
+
|
| 35 |
+
#: ``<<<ANSWER key=K00007>>> ... <<<ANSWER END>>>``; the key may carry spaces.
|
| 36 |
+
ANSWER_RE = re.compile(
|
| 37 |
+
r"<<<\s*ANSWER\s+key\s*=\s*([^\s>]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>",
|
| 38 |
+
re.DOTALL | re.IGNORECASE,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class KVStoreGrader(Grader):
|
| 43 |
+
family = "kv_store"
|
| 44 |
+
|
| 45 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 46 |
+
queries = gold.get("queries") or []
|
| 47 |
+
total = len(queries)
|
| 48 |
+
source = read_context(run_dir)
|
| 49 |
+
if total == 0:
|
| 50 |
+
return self._invalid(source.graded_from, "gold has no queries")
|
| 51 |
+
if source.graded_from == "none":
|
| 52 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 53 |
+
|
| 54 |
+
answers = self._collect(source)
|
| 55 |
+
correct = 0
|
| 56 |
+
answered = 0
|
| 57 |
+
for q in queries:
|
| 58 |
+
key = normalize(str(q["key"]))
|
| 59 |
+
want = normalize(str(q["value"]))
|
| 60 |
+
seen = answers.get(key)
|
| 61 |
+
if seen:
|
| 62 |
+
answered += 1
|
| 63 |
+
# Tolerate the value being embedded in a longer answer line.
|
| 64 |
+
if want in seen or any(want in s for s in seen):
|
| 65 |
+
correct += 1
|
| 66 |
+
|
| 67 |
+
result = {
|
| 68 |
+
"reward": correct / total,
|
| 69 |
+
"reward_attempted": (correct / answered) if answered else 0.0,
|
| 70 |
+
"n_answered": float(answered),
|
| 71 |
+
"matched": float(correct),
|
| 72 |
+
"total": float(total),
|
| 73 |
+
"n_snapshots": float(source.n_snapshots),
|
| 74 |
+
"graded_from": source.graded_from,
|
| 75 |
+
"grader_valid": 1.0,
|
| 76 |
+
}
|
| 77 |
+
result.update(self._token_stats(source.tokens))
|
| 78 |
+
return result
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _collect(source: ContextSource) -> dict[str, set[str]]:
|
| 82 |
+
"""``key -> {normalized answer strings}`` across every frame."""
|
| 83 |
+
answers: dict[str, set[str]] = {}
|
| 84 |
+
for frame in source.frames:
|
| 85 |
+
for key, val in ANSWER_RE.findall(messages_text(frame)):
|
| 86 |
+
answers.setdefault(normalize(key), set()).add(normalize(val))
|
| 87 |
+
return answers
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/log.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Incident Log Triage*: process-graded, ANSWER-block based.
|
| 2 |
+
|
| 3 |
+
The agent answers each ``QUERY <n>`` by emitting an ANSWER block::
|
| 4 |
+
|
| 5 |
+
<<<ANSWER qid=0>>>
|
| 6 |
+
timeout retry connection refused #ab12cd34 (lookup)
|
| 7 |
+
<<<ANSWER END>>>
|
| 8 |
+
|
| 9 |
+
Every per-turn context frame is scanned, all ANSWER blocks are collected as
|
| 10 |
+
``qid -> {answer strings}``, and the score is the fraction of gold queries answered
|
| 11 |
+
correctly. Matching is per type:
|
| 12 |
+
|
| 13 |
+
* ``lookup`` -- the exact message string must appear in the agent's answer, as a
|
| 14 |
+
whitespace-normalized substring, so adding a label does not cost a point;
|
| 15 |
+
* ``count`` -- the integer must appear as a standalone token in the answer.
|
| 16 |
+
|
| 17 |
+
A gold message ends in a random ``#<hex>`` uniqueness tag that a model treats as a
|
| 18 |
+
noise id and usually drops. Lookup grading measures retrieval -- did the agent
|
| 19 |
+
surface the right log line's message -- not whether it parrots that tag, so a
|
| 20 |
+
trailing tag is stripped before matching.
|
| 21 |
+
|
| 22 |
+
Rewards: ``reward``, ``reward_lookup`` / ``reward_count`` per type,
|
| 23 |
+
``reward_attempted`` over the queries answered at all, and the per-turn context size.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import re
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
from .base import ContextSource, Grader, messages_text, normalize, read_context
|
| 32 |
+
|
| 33 |
+
__all__ = ["LogTriageGrader", "ANSWER_RE"]
|
| 34 |
+
|
| 35 |
+
ANSWER_RE = re.compile(
|
| 36 |
+
r"<<<\s*ANSWER\s+qid\s*=\s*([0-9]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>",
|
| 37 |
+
re.DOTALL | re.IGNORECASE,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
#: The trailing uniqueness tag of a gold message.
|
| 41 |
+
_TAG_RE = re.compile(r"\s*#[0-9a-f]+\s*$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _count_correct(want: str, answers: set[str]) -> bool:
|
| 45 |
+
"""A count is correct when the integer appears as a standalone token."""
|
| 46 |
+
pat = re.compile(rf"(?<!\d){re.escape(want)}(?!\d)")
|
| 47 |
+
return any(pat.search(a) for a in answers)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _lookup_correct(want: str, answers: set[str]) -> bool:
|
| 51 |
+
core = _TAG_RE.sub("", want).strip()
|
| 52 |
+
if not core:
|
| 53 |
+
return False
|
| 54 |
+
return any(core in a for a in answers)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class LogTriageGrader(Grader):
|
| 58 |
+
family = "log_triage"
|
| 59 |
+
|
| 60 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 61 |
+
queries = gold.get("queries") or []
|
| 62 |
+
total = len(queries)
|
| 63 |
+
source = read_context(run_dir)
|
| 64 |
+
if total == 0:
|
| 65 |
+
return self._invalid(source.graded_from, "gold has no queries")
|
| 66 |
+
if source.graded_from == "none":
|
| 67 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 68 |
+
|
| 69 |
+
answers = self._collect(source)
|
| 70 |
+
correct = answered = 0
|
| 71 |
+
by_type_total: dict[str, int] = {"lookup": 0, "count": 0}
|
| 72 |
+
by_type_correct: dict[str, int] = {"lookup": 0, "count": 0}
|
| 73 |
+
for q in queries:
|
| 74 |
+
qid = str(q["qid"])
|
| 75 |
+
qtype = q.get("type", "lookup")
|
| 76 |
+
want = normalize(str(q["answer"]))
|
| 77 |
+
by_type_total[qtype] = by_type_total.get(qtype, 0) + 1
|
| 78 |
+
seen = answers.get(qid)
|
| 79 |
+
if not seen:
|
| 80 |
+
continue
|
| 81 |
+
answered += 1
|
| 82 |
+
ok = (
|
| 83 |
+
_count_correct(want, seen)
|
| 84 |
+
if qtype == "count"
|
| 85 |
+
else _lookup_correct(want, seen)
|
| 86 |
+
)
|
| 87 |
+
if ok:
|
| 88 |
+
correct += 1
|
| 89 |
+
by_type_correct[qtype] = by_type_correct.get(qtype, 0) + 1
|
| 90 |
+
|
| 91 |
+
def _rate(t: str) -> float:
|
| 92 |
+
n = by_type_total.get(t, 0)
|
| 93 |
+
return (by_type_correct.get(t, 0) / n) if n else 0.0
|
| 94 |
+
|
| 95 |
+
result = {
|
| 96 |
+
"reward": correct / total,
|
| 97 |
+
"reward_lookup": _rate("lookup"),
|
| 98 |
+
"reward_count": _rate("count"),
|
| 99 |
+
"reward_attempted": (correct / answered) if answered else 0.0,
|
| 100 |
+
"n_answered": float(answered),
|
| 101 |
+
"matched": float(correct),
|
| 102 |
+
"total": float(total),
|
| 103 |
+
"n_snapshots": float(source.n_snapshots),
|
| 104 |
+
"graded_from": source.graded_from,
|
| 105 |
+
"grader_valid": 1.0,
|
| 106 |
+
}
|
| 107 |
+
result.update(self._token_stats(source.tokens))
|
| 108 |
+
return result
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def _collect(source: ContextSource) -> dict[str, set[str]]:
|
| 112 |
+
answers: dict[str, set[str]] = {}
|
| 113 |
+
for frame in source.frames:
|
| 114 |
+
for qid, val in ANSWER_RE.findall(messages_text(frame)):
|
| 115 |
+
answers.setdefault(qid.strip(), set()).add(normalize(val))
|
| 116 |
+
return answers
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/needle.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Needle Retention*: what is still in the context at the end.
|
| 2 |
+
|
| 3 |
+
The reward is the fraction of gold needle lines present verbatim in the agent's
|
| 4 |
+
final retained context. Two modes, and which one ran is recorded as ``mode`` and
|
| 5 |
+
``graded_from``:
|
| 6 |
+
|
| 7 |
+
* ``final_context`` (the paper metric) -- the last per-turn snapshot, or an ATIF
|
| 8 |
+
``trajectory.json``, is the retained context: context edits mutate that message
|
| 9 |
+
list in place, so the final state is exactly what the agent kept.
|
| 10 |
+
* ``final_report`` -- for an agent that cannot expose its context at all, the kept
|
| 11 |
+
lines are read from between ``<<<NEEDLES BEGIN>>>`` and ``<<<NEEDLES END>>>`` in
|
| 12 |
+
its closing report. A report is a weaker witness than a context: the agent could
|
| 13 |
+
in principle re-read the lines from somewhere else, so the two modes are not
|
| 14 |
+
interchangeable and are never averaged together.
|
| 15 |
+
|
| 16 |
+
Rewards: ``reward``, ``matched``, ``total``, ``mode``, ``graded_from``.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import re
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
from .base import (
|
| 25 |
+
Grader,
|
| 26 |
+
messages_text,
|
| 27 |
+
normalize,
|
| 28 |
+
read_final_report,
|
| 29 |
+
read_snapshots,
|
| 30 |
+
read_trajectory,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
__all__ = ["NeedleRetentionGrader", "NEEDLES_BLOCK_RE", "extract_reported_needles"]
|
| 34 |
+
|
| 35 |
+
#: The block an agent without context access prints instead.
|
| 36 |
+
NEEDLES_BLOCK_RE = re.compile(
|
| 37 |
+
r"<<<\s*NEEDLES\s+BEGIN\s*>>>(.*?)<<<\s*NEEDLES\s+END\s*>>>",
|
| 38 |
+
re.DOTALL | re.IGNORECASE,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def extract_reported_needles(text: str) -> set[str]:
|
| 43 |
+
"""The normalized lines inside every ``NEEDLES`` block of ``text``."""
|
| 44 |
+
lines: set[str] = set()
|
| 45 |
+
for block in NEEDLES_BLOCK_RE.findall(text or ""):
|
| 46 |
+
for line in block.splitlines():
|
| 47 |
+
if line.strip():
|
| 48 |
+
lines.add(normalize(line))
|
| 49 |
+
return lines
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class NeedleRetentionGrader(Grader):
|
| 53 |
+
family = "needle_retention"
|
| 54 |
+
|
| 55 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 56 |
+
gold_lines = {normalize(s) for s in gold.get("answer_lines") or []}
|
| 57 |
+
total = len(gold_lines)
|
| 58 |
+
|
| 59 |
+
snapshots = read_snapshots(run_dir)
|
| 60 |
+
if snapshots is not None:
|
| 61 |
+
present = self._context_lines(messages_text(snapshots.final_frame))
|
| 62 |
+
return self._result(
|
| 63 |
+
gold_lines, present, total, "final_context", "snapshots",
|
| 64 |
+
snapshots.n_snapshots, snapshots.tokens,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
trajectory = read_trajectory(run_dir)
|
| 68 |
+
if trajectory is not None:
|
| 69 |
+
present = self._context_lines(messages_text(trajectory.final_frame))
|
| 70 |
+
return self._result(
|
| 71 |
+
gold_lines, present, total, "final_context", "trajectory", 0, []
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
report = read_final_report(run_dir)
|
| 75 |
+
if report:
|
| 76 |
+
return self._result(
|
| 77 |
+
gold_lines, extract_reported_needles(report), total,
|
| 78 |
+
"final_report", "final_report", 0, [],
|
| 79 |
+
)
|
| 80 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
def _context_lines(text: str) -> set[str]:
|
| 84 |
+
return {normalize(line) for line in text.splitlines() if line.strip()}
|
| 85 |
+
|
| 86 |
+
def _result(
|
| 87 |
+
self,
|
| 88 |
+
gold_lines: set[str],
|
| 89 |
+
present: set[str],
|
| 90 |
+
total: int,
|
| 91 |
+
mode: str,
|
| 92 |
+
graded_from: str,
|
| 93 |
+
n_snapshots: int,
|
| 94 |
+
tokens: list[int],
|
| 95 |
+
) -> dict:
|
| 96 |
+
if total == 0:
|
| 97 |
+
return self._invalid(graded_from, "gold has no answer_lines")
|
| 98 |
+
matched = gold_lines & present
|
| 99 |
+
result = {
|
| 100 |
+
"reward": len(matched) / total,
|
| 101 |
+
"matched": float(len(matched)),
|
| 102 |
+
"total": float(total),
|
| 103 |
+
"mode": mode,
|
| 104 |
+
"n_snapshots": float(n_snapshots),
|
| 105 |
+
"graded_from": graded_from,
|
| 106 |
+
"grader_valid": 1.0,
|
| 107 |
+
}
|
| 108 |
+
result.update(self._token_stats(tokens))
|
| 109 |
+
return result
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/graders/sudoku.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Sudoku Sketchpad*: versioned, process-graded.
|
| 2 |
+
|
| 3 |
+
Each move advances the sketchpad to a new version ``v`` with a correct grid ``G_v``
|
| 4 |
+
(a cell-to-value map). The agent labels every panel it displays with a ``VERSION``
|
| 5 |
+
line. Every versioned panel the agent ever displayed is recovered from the per-turn
|
| 6 |
+
context frames, and for each gold version the grader checks whether the agent
|
| 7 |
+
displayed that exact grid.
|
| 8 |
+
|
| 9 |
+
This makes the styles comparable on one number. An agent that edits its context in
|
| 10 |
+
place bumps the version and changes the affected cells, so one panel lives in
|
| 11 |
+
context and stays small; each version appears transiently across the turns. An
|
| 12 |
+
append-only agent writes a brand-new full panel per move, so all versions
|
| 13 |
+
accumulate and the context grows by a panel per move. Both score equally on
|
| 14 |
+
correctness while every version is right: the benefit of editing shows up in the
|
| 15 |
+
per-turn context size, and in correctness holding at large horizons where an
|
| 16 |
+
append-only context overflows the budget.
|
| 17 |
+
|
| 18 |
+
Rewards:
|
| 19 |
+
|
| 20 |
+
* ``reward`` -- ``reward_content``, the fraction of gold versions whose exact grid
|
| 21 |
+
the agent displayed. The cells are what "exact match of the gold sketchpad
|
| 22 |
+
throughout the process" means; the version label is a secondary bookkeeping check.
|
| 23 |
+
* ``reward_versioned`` -- the same, but the panel's version label must match too;
|
| 24 |
+
* ``reward_cell`` -- mean over versions of the best per-cell accuracy seen;
|
| 25 |
+
* ``reward_final_em`` / ``reward_final_cell`` -- the final displayed grid against
|
| 26 |
+
the final gold grid;
|
| 27 |
+
* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import re
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Iterator
|
| 35 |
+
|
| 36 |
+
from .base import ContextSource, Grader, messages_text, read_context
|
| 37 |
+
|
| 38 |
+
__all__ = ["SudokuSketchpadGrader", "SYMBOLS"]
|
| 39 |
+
|
| 40 |
+
#: Single-character value symbols; must match the generator.
|
| 41 |
+
SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
| 42 |
+
|
| 43 |
+
_TUPLE_RE = re.compile(r"\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^)]*?)\s*\)")
|
| 44 |
+
_VERSION_RE = re.compile(r"VERSION:\s*(\d+)")
|
| 45 |
+
|
| 46 |
+
Cells = dict[str, str]
|
| 47 |
+
Panel = tuple[tuple[str, str], ...]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _norm_value(raw: str) -> str:
|
| 51 |
+
raw = raw.strip()
|
| 52 |
+
if raw in (".", ""):
|
| 53 |
+
return "."
|
| 54 |
+
if raw.startswith("="):
|
| 55 |
+
return "=" + raw[1:].strip()
|
| 56 |
+
return raw
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _parse_panel_body(body: list[str], side: int) -> Cells:
|
| 60 |
+
"""Parse one board body into ``{"rXcY": value}``.
|
| 61 |
+
|
| 62 |
+
Position-independent: every cell self-locates through its ``(r,c,v)`` tuple and
|
| 63 |
+
a later occurrence wins, so the parse is robust to spacing and to the same tuple
|
| 64 |
+
text appearing elsewhere in the block.
|
| 65 |
+
"""
|
| 66 |
+
cells: Cells = {}
|
| 67 |
+
for m in _TUPLE_RE.finditer("\n".join(body)):
|
| 68 |
+
r, c, v = int(m.group(1)), int(m.group(2)), m.group(3).strip()
|
| 69 |
+
if not (1 <= r <= side and 1 <= c <= side):
|
| 70 |
+
continue
|
| 71 |
+
if v in (".", ""):
|
| 72 |
+
cells[f"r{r}c{c}"] = "."
|
| 73 |
+
elif v in SYMBOLS[:side]:
|
| 74 |
+
cells[f"r{r}c{c}"] = f"={SYMBOLS.index(v) + 1}"
|
| 75 |
+
return cells
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _parse_blocks(text: str, side: int) -> list[tuple[int | None, Cells]]:
|
| 79 |
+
"""Every sketchpad block in ``text`` as ``(version, cells)``.
|
| 80 |
+
|
| 81 |
+
The version comes from the block's ``VERSION:`` line, or is ``None``.
|
| 82 |
+
"""
|
| 83 |
+
blocks: list[tuple[int | None, Cells]] = []
|
| 84 |
+
buf: list[str] | None = None
|
| 85 |
+
for line in text.splitlines():
|
| 86 |
+
if "SKETCHPAD BEGIN" in line:
|
| 87 |
+
buf = []
|
| 88 |
+
elif "SKETCHPAD END" in line:
|
| 89 |
+
if buf is not None:
|
| 90 |
+
ver = None
|
| 91 |
+
for bl in buf:
|
| 92 |
+
m = _VERSION_RE.search(bl)
|
| 93 |
+
if m:
|
| 94 |
+
ver = int(m.group(1))
|
| 95 |
+
break
|
| 96 |
+
cells = _parse_panel_body(buf, side)
|
| 97 |
+
if cells:
|
| 98 |
+
blocks.append((ver, cells))
|
| 99 |
+
buf = None
|
| 100 |
+
elif buf is not None:
|
| 101 |
+
buf.append(line)
|
| 102 |
+
return blocks
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _cell_accuracy(gold: Cells, panel: Panel) -> float:
|
| 106 |
+
if not gold:
|
| 107 |
+
return 0.0
|
| 108 |
+
state = dict(panel)
|
| 109 |
+
return sum(1 for k, v in gold.items() if state.get(k) == v) / len(gold)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def gold_states(gold: dict) -> Iterator[tuple[int, Cells]]:
|
| 113 |
+
"""Fold the compact per-version deltas into ``(version, full cells)`` pairs.
|
| 114 |
+
|
| 115 |
+
A ``reset`` delta replaces the whole board (a new puzzle, or version 0); an
|
| 116 |
+
ordinary delta updates only the changed cells. Version 0, the given starting
|
| 117 |
+
panel, is yielded too, but the scorer grades only the streamed actions.
|
| 118 |
+
"""
|
| 119 |
+
current: Cells = {}
|
| 120 |
+
for d in gold.get("deltas") or []:
|
| 121 |
+
cells = {k: _norm_value(v) for k, v in (d.get("cells") or {}).items()}
|
| 122 |
+
if d.get("reset"):
|
| 123 |
+
current = dict(cells)
|
| 124 |
+
else:
|
| 125 |
+
current.update(cells)
|
| 126 |
+
yield d["v"], dict(current)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class SudokuSketchpadGrader(Grader):
|
| 130 |
+
family = "sudoku_sketchpad"
|
| 131 |
+
|
| 132 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 133 |
+
meta = gold.get("meta") or {}
|
| 134 |
+
# No silent 9x9 default: a missing side in a 16x16 or 25x25 gold would grade
|
| 135 |
+
# the board on a 9x9 assumption and look perfectly healthy while doing it.
|
| 136 |
+
if "side" not in meta:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"gold.meta['side'] is missing: refusing to default to 9x9. A larger "
|
| 139 |
+
"board graded under a silent 9x9 default would pass every check we "
|
| 140 |
+
"have. Stamp 'side' in the instance gold.meta."
|
| 141 |
+
)
|
| 142 |
+
side = int(meta["side"])
|
| 143 |
+
|
| 144 |
+
source = read_context(run_dir)
|
| 145 |
+
if source.graded_from == "none":
|
| 146 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 147 |
+
obs = self._observe(source, side)
|
| 148 |
+
|
| 149 |
+
total = 0
|
| 150 |
+
versioned = 0
|
| 151 |
+
content = 0
|
| 152 |
+
cell_sum = 0.0
|
| 153 |
+
final_gold: Panel | None = None
|
| 154 |
+
for v, cells in gold_states(gold):
|
| 155 |
+
if v == 0:
|
| 156 |
+
continue
|
| 157 |
+
total += 1
|
| 158 |
+
panel: Panel = tuple(sorted(cells.items()))
|
| 159 |
+
final_gold = panel
|
| 160 |
+
if panel in obs["by_version"].get(v, ()):
|
| 161 |
+
versioned += 1
|
| 162 |
+
if panel in obs["content"]:
|
| 163 |
+
content += 1
|
| 164 |
+
seen = obs["by_version"].get(v)
|
| 165 |
+
if seen:
|
| 166 |
+
cell_sum += max(
|
| 167 |
+
(_cell_accuracy(cells, s) for s in seen), default=0.0
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if total == 0:
|
| 171 |
+
return self._invalid(source.graded_from, "gold has no graded versions")
|
| 172 |
+
|
| 173 |
+
final_state: Panel | None = obs["final"]
|
| 174 |
+
final_em = 1.0 if (final_state is not None and final_state == final_gold) else 0.0
|
| 175 |
+
final_cell = (
|
| 176 |
+
_cell_accuracy(dict(final_gold), final_state)
|
| 177 |
+
if (final_state is not None and final_gold is not None)
|
| 178 |
+
else 0.0
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
result = {
|
| 182 |
+
"reward": content / total,
|
| 183 |
+
"reward_versioned": versioned / total,
|
| 184 |
+
"reward_content": content / total,
|
| 185 |
+
"reward_cell": cell_sum / total,
|
| 186 |
+
"reward_final_em": final_em,
|
| 187 |
+
"reward_final_cell": final_cell,
|
| 188 |
+
"matched": float(versioned),
|
| 189 |
+
"total": float(total),
|
| 190 |
+
"n_snapshots": float(source.n_snapshots),
|
| 191 |
+
"graded_from": source.graded_from,
|
| 192 |
+
"grader_valid": 1.0,
|
| 193 |
+
}
|
| 194 |
+
result.update(self._token_stats(source.tokens))
|
| 195 |
+
return result
|
| 196 |
+
|
| 197 |
+
@staticmethod
|
| 198 |
+
def _observe(source: ContextSource, side: int) -> dict:
|
| 199 |
+
"""Every versioned panel, deduplicated as canonical tuples.
|
| 200 |
+
|
| 201 |
+
Deduplication keeps an append-only agent that re-shows every old version
|
| 202 |
+
from blowing up the grader's memory.
|
| 203 |
+
"""
|
| 204 |
+
by_version: dict[int, set[Panel]] = {}
|
| 205 |
+
content: set[Panel] = set()
|
| 206 |
+
final_state: Panel | None = None
|
| 207 |
+
|
| 208 |
+
for frame in source.frames:
|
| 209 |
+
blocks = _parse_blocks(messages_text(frame), side)
|
| 210 |
+
best: tuple[int, Panel] | None = None
|
| 211 |
+
for ver, cells in blocks:
|
| 212 |
+
panel: Panel = tuple(sorted(cells.items()))
|
| 213 |
+
content.add(panel)
|
| 214 |
+
if ver is not None:
|
| 215 |
+
by_version.setdefault(ver, set()).add(panel)
|
| 216 |
+
if best is None or ver >= best[0]:
|
| 217 |
+
best = (ver, panel)
|
| 218 |
+
# The final state is the highest-version panel of the latest frame that
|
| 219 |
+
# has one at all.
|
| 220 |
+
if best is not None:
|
| 221 |
+
final_state = best[1]
|
| 222 |
+
elif blocks:
|
| 223 |
+
final_state = tuple(sorted(blocks[-1][1].items()))
|
| 224 |
+
|
| 225 |
+
return {"by_version": by_version, "content": content, "final": final_state}
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench on Harbor: task packaging, the op stream, agents and verifiers.
|
| 2 |
+
|
| 3 |
+
``turn_source``, ``mixin`` and ``package`` import nothing from Harbor, so a task can
|
| 4 |
+
be built and a stream tested without it installed. ``agents``, ``wrap`` and
|
| 5 |
+
``verifiers`` require ``harbor>=0.16`` (``pip install 'contextbench[harbor]'``).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from .mixin import CBStreamMixin
|
| 11 |
+
from .turn_source import (
|
| 12 |
+
ENV_STREAM_COUNT,
|
| 13 |
+
ENV_STREAM_PATH,
|
| 14 |
+
ENV_STREAM_SHA256,
|
| 15 |
+
STREAM_RECORD_NAME,
|
| 16 |
+
STREAM_RELPATH,
|
| 17 |
+
StreamIdentityError,
|
| 18 |
+
TurnSource,
|
| 19 |
+
canonical_sha256,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"CBStreamMixin",
|
| 24 |
+
"ENV_STREAM_COUNT",
|
| 25 |
+
"ENV_STREAM_PATH",
|
| 26 |
+
"ENV_STREAM_SHA256",
|
| 27 |
+
"STREAM_RECORD_NAME",
|
| 28 |
+
"STREAM_RELPATH",
|
| 29 |
+
"StreamIdentityError",
|
| 30 |
+
"TurnSource",
|
| 31 |
+
"canonical_sha256",
|
| 32 |
+
]
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/mixin.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""``CBStreamMixin``: ContextBench support for any Python agent loop under Harbor.
|
| 2 |
+
|
| 3 |
+
Add the mixin to your Harbor agent and three calls to its loop::
|
| 4 |
+
|
| 5 |
+
class MyAgent(CBStreamMixin, BaseAgent):
|
| 6 |
+
async def run(self, instruction, environment, context):
|
| 7 |
+
await self.cb_setup(environment) # 1
|
| 8 |
+
messages = [system, {"role": "user", "content": instruction}]
|
| 9 |
+
messages += self.cb_user_turns(self.cb_initial_turns())
|
| 10 |
+
while not self.cb_done:
|
| 11 |
+
... # model call
|
| 12 |
+
messages.append(tool_result_message)
|
| 13 |
+
messages += self.cb_user_turns( # 2
|
| 14 |
+
self.cb_pending(command, exit_code))
|
| 15 |
+
if self.cb_over_budget(messages): # 3
|
| 16 |
+
break
|
| 17 |
+
|
| 18 |
+
The mixin owns everything else: loading and verifying the stream (and removing it
|
| 19 |
+
from the container), the readiness rule, the early-submit refusal, the terminal
|
| 20 |
+
reason, ``interactive_stream.json`` and the ``context_snapshots/turn-NNNN.json`` the
|
| 21 |
+
graders read. ``cb_over_budget`` both snapshots the context you are about to send
|
| 22 |
+
and enforces the budget wall on it; call it right before every model call (or where
|
| 23 |
+
your loop sends), and call :meth:`cb_finish` in a ``finally``.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
from ..tokens import count_tokens, record_snapshot
|
| 32 |
+
from .turn_source import TurnSource
|
| 33 |
+
|
| 34 |
+
__all__ = ["CBStreamMixin"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CBStreamMixin:
|
| 38 |
+
"""Stream delivery, snapshots and the budget wall for a Harbor agent loop."""
|
| 39 |
+
|
| 40 |
+
logs_dir: Path
|
| 41 |
+
|
| 42 |
+
#: Budget of record; override per instance with ``cb_setup(budget=...)``.
|
| 43 |
+
cb_budget: int = 32768
|
| 44 |
+
cb_reserve: int = 2048
|
| 45 |
+
|
| 46 |
+
# ------------------------------------------------------------------ setup
|
| 47 |
+
async def cb_setup(self, environment: Any, *, budget: int | None = None,
|
| 48 |
+
reserve: int | None = None, **load_kwargs: Any) -> TurnSource:
|
| 49 |
+
"""Load the task's stream (verified, then removed from the container)."""
|
| 50 |
+
if budget is not None:
|
| 51 |
+
self.cb_budget = int(budget)
|
| 52 |
+
if reserve is not None:
|
| 53 |
+
self.cb_reserve = int(reserve)
|
| 54 |
+
self.cb_source = await TurnSource.load(
|
| 55 |
+
environment, logs_dir=self.logs_dir, **load_kwargs)
|
| 56 |
+
self._cb_snap_step = 0
|
| 57 |
+
self.cb_peak_tokens = 0
|
| 58 |
+
return self.cb_source
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def cb_turn_source(self) -> TurnSource | None:
|
| 62 |
+
return getattr(self, "cb_source", None)
|
| 63 |
+
|
| 64 |
+
# --------------------------------------------------------------- delivery
|
| 65 |
+
def cb_initial_turns(self) -> list[str]:
|
| 66 |
+
"""The user turns to append after the instruction: op 0."""
|
| 67 |
+
first = self.cb_source.first_turn(turn=0)
|
| 68 |
+
return [first] if first is not None else []
|
| 69 |
+
|
| 70 |
+
def cb_pending(self, last_command: str | None, last_exit: int | None = 0, *,
|
| 71 |
+
turn: int | None = None) -> list[str]:
|
| 72 |
+
"""The user turns to append right after the tool result of ``last_command``."""
|
| 73 |
+
return self.cb_source.pending(last_command, last_exit, turn=turn)
|
| 74 |
+
|
| 75 |
+
def cb_submit(self, *, trigger: str = "<submit>") -> list[str]:
|
| 76 |
+
"""The harness's own finish signal: refused (texts returned) until the drain."""
|
| 77 |
+
return self.cb_source.on_submit(trigger=trigger)
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def cb_done(self) -> bool:
|
| 81 |
+
src = self.cb_turn_source
|
| 82 |
+
return bool(src and src.done)
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def cb_user_turns(texts: list[str]) -> list[dict[str, str]]:
|
| 86 |
+
return [{"role": "user", "content": t} for t in texts]
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------ snapshots and wall
|
| 89 |
+
def cb_snapshot(self, messages: list[Any], kind: str = "sent",
|
| 90 |
+
extra: dict[str, Any] | None = None) -> int:
|
| 91 |
+
"""Write ``context_snapshots/turn-NNNN.json``; returns its token count."""
|
| 92 |
+
src = self.cb_turn_source
|
| 93 |
+
tokens, _ = count_tokens(messages)
|
| 94 |
+
self.cb_peak_tokens = max(getattr(self, "cb_peak_tokens", 0), tokens)
|
| 95 |
+
step = getattr(self, "_cb_snap_step", 0)
|
| 96 |
+
record_snapshot(
|
| 97 |
+
self.logs_dir, step, list(messages),
|
| 98 |
+
{"kind": kind, "n_ops_delivered": src.n_delivered if src else 0,
|
| 99 |
+
"n_ops_total": src.n_total if src else 0,
|
| 100 |
+
"budget": self.cb_budget, "reserve": self.cb_reserve, **(extra or {})},
|
| 101 |
+
)
|
| 102 |
+
self._cb_snap_step = step + 1
|
| 103 |
+
return tokens
|
| 104 |
+
|
| 105 |
+
def cb_over_budget(self, messages: list[Any]) -> bool:
|
| 106 |
+
"""Snapshot what is about to be sent; True (and ``budget_wall``) if it is over."""
|
| 107 |
+
if self.cb_snapshot(messages, "sent") > self.cb_budget - self.cb_reserve:
|
| 108 |
+
self.cb_source.terminate("budget_wall")
|
| 109 |
+
return True
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
def cb_finish(self, reason: str | None = None,
|
| 113 |
+
messages: list[Any] | None = None) -> None:
|
| 114 |
+
"""Record a terminal reason if none was set, snapshot the final context."""
|
| 115 |
+
src = self.cb_turn_source
|
| 116 |
+
if src is None:
|
| 117 |
+
return
|
| 118 |
+
if reason and not src.done:
|
| 119 |
+
src.terminate(reason)
|
| 120 |
+
if messages is not None:
|
| 121 |
+
self.cb_snapshot(messages, "final")
|
| 122 |
+
src.write()
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/reward.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grade a Harbor trial's agent directory and write Harbor's reward files.
|
| 2 |
+
|
| 3 |
+
Shared by the two ways a ContextBench task is verified:
|
| 4 |
+
|
| 5 |
+
* in the container, by the task's own ``tests/test.sh`` (Harbor's default verifier:
|
| 6 |
+
no flag needed), which runs ``python3 -m contextbench.harbor.reward`` against a
|
| 7 |
+
copy of the graders vendored into ``tests/_cb/``;
|
| 8 |
+
* on the host, by ``contextbench.harbor.verifiers:ContextBenchVerifier``, for images
|
| 9 |
+
without ``python3``.
|
| 10 |
+
|
| 11 |
+
Harbor's reward dict must be numeric (its job-level mean sums every key), so the
|
| 12 |
+
string fields are encoded: ``graded_from_code`` (3 snapshots, 2 trajectory,
|
| 13 |
+
1 final_report, 0 none) and ``terminated_by_code`` (index into
|
| 14 |
+
``contextbench.stream.TERMINATED_BY``, -1 unknown). The unencoded result goes to
|
| 15 |
+
``contextbench_result.json`` next to ``reward.json``.
|
| 16 |
+
|
| 17 |
+
Pure standard library: this module runs inside task containers.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
from ..graders import grade_run
|
| 29 |
+
from ..stream import TERMINATED_BY
|
| 30 |
+
|
| 31 |
+
__all__ = ["GRADED_FROM_CODES", "harbor_rewards", "write_rewards", "main"]
|
| 32 |
+
|
| 33 |
+
GRADED_FROM_CODES = {"snapshots": 3, "trajectory": 2, "final_report": 1, "none": 0}
|
| 34 |
+
|
| 35 |
+
STREAM_RECORD_NAME = "interactive_stream.json"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def harbor_rewards(agent_dir: Path | str, gold: dict) -> tuple[dict, dict]:
|
| 39 |
+
"""``(numeric reward dict, full result dict)`` for one agent directory."""
|
| 40 |
+
agent_dir = Path(agent_dir)
|
| 41 |
+
rewards = grade_run(agent_dir, gold)
|
| 42 |
+
stream: dict[str, Any] = {}
|
| 43 |
+
record = agent_dir / STREAM_RECORD_NAME
|
| 44 |
+
if record.is_file():
|
| 45 |
+
try:
|
| 46 |
+
stream = json.loads(record.read_text(encoding="utf-8"))
|
| 47 |
+
except Exception:
|
| 48 |
+
stream = {}
|
| 49 |
+
numeric: dict[str, float | int] = {
|
| 50 |
+
k: v for k, v in rewards.items()
|
| 51 |
+
if isinstance(v, (int, float)) and not isinstance(v, bool)
|
| 52 |
+
}
|
| 53 |
+
numeric["graded_from_code"] = GRADED_FROM_CODES.get(str(rewards.get("graded_from")), 0)
|
| 54 |
+
terminated_by = stream.get("terminated_by")
|
| 55 |
+
numeric["terminated_by_code"] = (
|
| 56 |
+
TERMINATED_BY.index(terminated_by) if terminated_by in TERMINATED_BY else -1
|
| 57 |
+
)
|
| 58 |
+
for key in ("n_ops_delivered", "n_ops_total", "n_refusals"):
|
| 59 |
+
if isinstance(stream.get(key), int):
|
| 60 |
+
numeric[key] = stream[key]
|
| 61 |
+
full = {
|
| 62 |
+
"rewards": rewards,
|
| 63 |
+
"graded_from": rewards.get("graded_from"),
|
| 64 |
+
"terminated_by": terminated_by,
|
| 65 |
+
"agent_dir": str(agent_dir),
|
| 66 |
+
"stream": {k: v for k, v in stream.items() if k != "log"},
|
| 67 |
+
}
|
| 68 |
+
return numeric, full
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def write_rewards(agent_dir: Path | str, gold: dict | Path | str,
|
| 72 |
+
out_dir: Path | str) -> dict:
|
| 73 |
+
"""Grade and write ``reward.json`` + ``contextbench_result.json``; return numeric."""
|
| 74 |
+
if not isinstance(gold, dict):
|
| 75 |
+
gold = json.loads(Path(gold).read_text(encoding="utf-8"))
|
| 76 |
+
numeric, full = harbor_rewards(agent_dir, gold)
|
| 77 |
+
out = Path(out_dir)
|
| 78 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
(out / "contextbench_result.json").write_text(
|
| 80 |
+
json.dumps(full, indent=2, default=str) + "\n", encoding="utf-8")
|
| 81 |
+
(out / "reward.json").write_text(json.dumps(numeric, indent=2) + "\n",
|
| 82 |
+
encoding="utf-8")
|
| 83 |
+
return numeric
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main(argv: list[str] | None = None) -> int:
|
| 87 |
+
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 88 |
+
ap.add_argument("--agent-dir", type=Path, default=Path("/logs/agent"))
|
| 89 |
+
ap.add_argument("--gold", type=Path, default=Path("/tests/gold.json"))
|
| 90 |
+
ap.add_argument("--out-dir", type=Path, default=Path("/logs/verifier"))
|
| 91 |
+
a = ap.parse_args(argv)
|
| 92 |
+
numeric = write_rewards(a.agent_dir, a.gold, a.out_dir)
|
| 93 |
+
print(json.dumps(numeric))
|
| 94 |
+
return 0
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
sys.exit(main())
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/harbor/turn_source.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""``TurnSource``: the one place a Harbor agent gets its next ContextBench operation.
|
| 2 |
+
|
| 3 |
+
Every Harbor path (the shipped ``ContextBenchAgent``, ``Terminus2Stream``, and any
|
| 4 |
+
method adapter built outside this package) consumes the stream through this class,
|
| 5 |
+
so the delivery rules cannot drift between harnesses:
|
| 6 |
+
|
| 7 |
+
* the operations are read **once** from the container, from the
|
| 8 |
+
``stream/chunks.jsonl`` file Harbor uploads into the work directory, and checked
|
| 9 |
+
against the op count and canonical body sha recorded in ``task.toml``;
|
| 10 |
+
* the file is then **removed** from the container, so the agent cannot read ahead
|
| 11 |
+
with its shell (the only route an op has into the context is the user turn the
|
| 12 |
+
harness appends);
|
| 13 |
+
* the next op is released only when the agent's last command was the standalone
|
| 14 |
+
``echo READY_FOR_NEXT_OP`` (see :func:`contextbench.stream.is_ready_command`);
|
| 15 |
+
* a submit before the stream is drained is refused with
|
| 16 |
+
:data:`contextbench.stream.REFUSE_SUBMIT_TEXT`;
|
| 17 |
+
* ``terminated_by`` and the delivery log are written to
|
| 18 |
+
``<logs_dir>/interactive_stream.json`` after every change, so a run that is
|
| 19 |
+
killed still leaves an accurate record.
|
| 20 |
+
|
| 21 |
+
The class is harness-agnostic: it never touches the message list. A harness asks
|
| 22 |
+
:meth:`TurnSource.pending` what to append after a tool result and appends the
|
| 23 |
+
returned texts as ``role="user"`` messages itself.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import asyncio
|
| 29 |
+
import hashlib
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import posixpath
|
| 33 |
+
import shlex
|
| 34 |
+
from dataclasses import dataclass, field
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Any, Iterable, Mapping
|
| 37 |
+
|
| 38 |
+
from .. import stream as proto
|
| 39 |
+
from ..stream import Op, render_op
|
| 40 |
+
|
| 41 |
+
__all__ = [
|
| 42 |
+
"ENV_STREAM_COUNT",
|
| 43 |
+
"ENV_STREAM_PATH",
|
| 44 |
+
"ENV_STREAM_SHA256",
|
| 45 |
+
"STREAM_RECORD_NAME",
|
| 46 |
+
"STREAM_RELPATH",
|
| 47 |
+
"Delivery",
|
| 48 |
+
"StreamIdentityError",
|
| 49 |
+
"TurnSource",
|
| 50 |
+
"canonical_sha256",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
#: Where the stream lives relative to the task's ``environment/`` directory, and
|
| 54 |
+
#: therefore relative to the container work directory after Harbor's upload.
|
| 55 |
+
STREAM_RELPATH = "stream/chunks.jsonl"
|
| 56 |
+
#: Reads of the stream before giving up; each must parse and match the task identity.
|
| 57 |
+
READ_ATTEMPTS = 4
|
| 58 |
+
#: Seconds of back-off per retry (linear).
|
| 59 |
+
READ_BACKOFF_SEC = 2.0
|
| 60 |
+
|
| 61 |
+
#: ``[environment.env]`` keys that ``contextbench package`` writes into task.toml.
|
| 62 |
+
ENV_STREAM_COUNT = "CONTEXTBENCH_STREAM_COUNT"
|
| 63 |
+
ENV_STREAM_SHA256 = "CONTEXTBENCH_STREAM_SHA256"
|
| 64 |
+
ENV_STREAM_PATH = "CONTEXTBENCH_STREAM_PATH"
|
| 65 |
+
|
| 66 |
+
STREAM_RECORD_NAME = "interactive_stream.json"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class StreamIdentityError(RuntimeError):
|
| 70 |
+
"""The stream read from the container is not the one the task was built with."""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def canonical_sha256(records: Iterable[Mapping[str, Any]]) -> str:
|
| 74 |
+
"""sha256 over the ops as sorted-key JSON, one per line.
|
| 75 |
+
|
| 76 |
+
Canonical rather than byte-level, so re-serializing ``chunks.jsonl`` (key order,
|
| 77 |
+
trailing newline) does not change the identity, while any change to an op does.
|
| 78 |
+
"""
|
| 79 |
+
canon = "\n".join(json.dumps(dict(r), sort_keys=True) for r in records)
|
| 80 |
+
return hashlib.sha256(canon.encode("utf-8")).hexdigest()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _parse_records(text: str) -> list[dict[str, Any]]:
|
| 84 |
+
records: list[dict[str, Any]] = []
|
| 85 |
+
for line in (text or "").splitlines():
|
| 86 |
+
line = line.strip()
|
| 87 |
+
if line:
|
| 88 |
+
records.append(json.loads(line))
|
| 89 |
+
return records
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass
|
| 93 |
+
class Delivery:
|
| 94 |
+
"""One entry of the delivery log."""
|
| 95 |
+
|
| 96 |
+
#: What was handed to the agent: ``op``, ``refuse_submit`` or ``explain``.
|
| 97 |
+
kind: str
|
| 98 |
+
#: The op index for ``kind == "op"``, else ``None``.
|
| 99 |
+
index: int | None
|
| 100 |
+
#: The command that triggered it (head and tail when long), or ``"<start>"``.
|
| 101 |
+
trigger: str
|
| 102 |
+
#: The harness's own turn counter at the time, when it passes one.
|
| 103 |
+
turn: int | None = None
|
| 104 |
+
#: Why it was handed over: ``start``, ``ready`` (standalone readiness command),
|
| 105 |
+
#: ``submit`` (a submit before the drain), ``mention`` (non-standalone marker).
|
| 106 |
+
via: str = ""
|
| 107 |
+
|
| 108 |
+
def to_dict(self) -> dict[str, Any]:
|
| 109 |
+
return {"kind": self.kind, "index": self.index, "via": self.via,
|
| 110 |
+
"trigger": self.trigger, "turn": self.turn}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _excerpt(command: str, limit: int = 240) -> str:
|
| 114 |
+
"""The command as logged: whole when short, else head and tail."""
|
| 115 |
+
cmd = (command or "").strip()
|
| 116 |
+
if len(cmd) <= limit:
|
| 117 |
+
return cmd
|
| 118 |
+
half = limit // 2
|
| 119 |
+
return cmd[:half] + " [...] " + cmd[-half:]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class TurnSource:
|
| 124 |
+
"""The operation stream of one trial, and its delivery bookkeeping."""
|
| 125 |
+
|
| 126 |
+
ops: list[Op]
|
| 127 |
+
logs_dir: Path | None = None
|
| 128 |
+
#: How the stream was verified: ``{"count", "sha256", "path", "removed"}``.
|
| 129 |
+
identity: dict[str, Any] = field(default_factory=dict)
|
| 130 |
+
|
| 131 |
+
n_delivered: int = 0
|
| 132 |
+
terminated_by: str | None = None
|
| 133 |
+
n_refusals: int = 0
|
| 134 |
+
n_explains: int = 0
|
| 135 |
+
log: list[Delivery] = field(default_factory=list)
|
| 136 |
+
|
| 137 |
+
# ---------------------------------------------------------------- building
|
| 138 |
+
@classmethod
|
| 139 |
+
def from_records(
|
| 140 |
+
cls,
|
| 141 |
+
records: list[Mapping[str, Any]],
|
| 142 |
+
*,
|
| 143 |
+
logs_dir: Path | str | None = None,
|
| 144 |
+
expect_count: int | str | None = None,
|
| 145 |
+
expect_sha256: str | None = None,
|
| 146 |
+
identity: dict[str, Any] | None = None,
|
| 147 |
+
) -> "TurnSource":
|
| 148 |
+
"""Build from parsed ``chunks.jsonl`` records, verifying count and sha."""
|
| 149 |
+
got_sha = canonical_sha256(records)
|
| 150 |
+
if expect_count is not None and str(expect_count).strip() != "":
|
| 151 |
+
if len(records) != int(str(expect_count).strip()):
|
| 152 |
+
raise StreamIdentityError(
|
| 153 |
+
f"stream op count mismatch: read {len(records)}, task expects "
|
| 154 |
+
f"{str(expect_count).strip()}"
|
| 155 |
+
)
|
| 156 |
+
if expect_sha256 and got_sha != str(expect_sha256).strip():
|
| 157 |
+
raise StreamIdentityError(
|
| 158 |
+
f"stream sha256 mismatch: read {got_sha[:16]}, task expects "
|
| 159 |
+
f"{str(expect_sha256).strip()[:16]}"
|
| 160 |
+
)
|
| 161 |
+
ops = [Op.from_dict(dict(r), fallback_index=i) for i, r in enumerate(records)]
|
| 162 |
+
ident = {"count": len(records), "sha256": got_sha,
|
| 163 |
+
"verified": bool(expect_count is not None or expect_sha256)}
|
| 164 |
+
ident.update(identity or {})
|
| 165 |
+
src = cls(ops=ops, logs_dir=Path(logs_dir) if logs_dir else None,
|
| 166 |
+
identity=ident)
|
| 167 |
+
src.write()
|
| 168 |
+
return src
|
| 169 |
+
|
| 170 |
+
@classmethod
|
| 171 |
+
def from_jsonl(cls, text: str, **kwargs: Any) -> "TurnSource":
|
| 172 |
+
return cls.from_records(_parse_records(text), **kwargs)
|
| 173 |
+
|
| 174 |
+
@classmethod
|
| 175 |
+
async def load(
|
| 176 |
+
cls,
|
| 177 |
+
environment: Any,
|
| 178 |
+
*,
|
| 179 |
+
logs_dir: Path | str | None = None,
|
| 180 |
+
path: str | None = None,
|
| 181 |
+
expect_count: int | str | None = None,
|
| 182 |
+
expect_sha256: str | None = None,
|
| 183 |
+
remove_after_load: bool = True,
|
| 184 |
+
require_identity: bool = True,
|
| 185 |
+
) -> "TurnSource":
|
| 186 |
+
"""Read the stream out of a running Harbor environment.
|
| 187 |
+
|
| 188 |
+
``path``, ``expect_count`` and ``expect_sha256`` default to the
|
| 189 |
+
``CONTEXTBENCH_STREAM_*`` values in the task's ``[environment.env]``, then
|
| 190 |
+
to the host process environment. Without a path, the stream is looked up
|
| 191 |
+
at ``<workdir>/stream/chunks.jsonl``. With ``require_identity`` (the
|
| 192 |
+
default) a task that records no count or sha is refused: an unverified
|
| 193 |
+
stream could be another task's.
|
| 194 |
+
"""
|
| 195 |
+
env_cfg = _task_env(environment)
|
| 196 |
+
|
| 197 |
+
def _setting(name: str, given: Any) -> Any:
|
| 198 |
+
if given is not None:
|
| 199 |
+
return given
|
| 200 |
+
return env_cfg.get(name) or os.environ.get(name)
|
| 201 |
+
|
| 202 |
+
expect_count = _setting(ENV_STREAM_COUNT, expect_count)
|
| 203 |
+
expect_sha256 = _setting(ENV_STREAM_SHA256, expect_sha256)
|
| 204 |
+
path = _setting(ENV_STREAM_PATH, path)
|
| 205 |
+
if require_identity and not (expect_count or expect_sha256):
|
| 206 |
+
raise StreamIdentityError(
|
| 207 |
+
f"the task records no {ENV_STREAM_COUNT} / {ENV_STREAM_SHA256}; "
|
| 208 |
+
"refusing to deliver an unverifiable stream (rebuild the task with "
|
| 209 |
+
"`contextbench package`)"
|
| 210 |
+
)
|
| 211 |
+
if not path:
|
| 212 |
+
workdir = getattr(getattr(environment, "task_env_config", None),
|
| 213 |
+
"workdir", None)
|
| 214 |
+
if not workdir:
|
| 215 |
+
res = await environment.exec("pwd", timeout_sec=30)
|
| 216 |
+
workdir = (getattr(res, "stdout", "") or "/").strip() or "/"
|
| 217 |
+
path = posixpath.join(workdir, STREAM_RELPATH)
|
| 218 |
+
|
| 219 |
+
# Read, parse and verify before removing anything. Under concurrent exec
|
| 220 |
+
# load the captured stdout can come back truncated; a verified retry
|
| 221 |
+
# recovers it, and the file is only deleted once a read has matched.
|
| 222 |
+
last_err: Exception | None = None
|
| 223 |
+
records: list[dict[str, Any]] = []
|
| 224 |
+
for attempt in range(READ_ATTEMPTS):
|
| 225 |
+
if attempt:
|
| 226 |
+
await asyncio.sleep(READ_BACKOFF_SEC * attempt)
|
| 227 |
+
res = await environment.exec(f"cat {shlex.quote(path)}", timeout_sec=120)
|
| 228 |
+
if getattr(res, "return_code", 1) != 0:
|
| 229 |
+
last_err = RuntimeError(
|
| 230 |
+
f"could not read the stream at {path} in the container: "
|
| 231 |
+
f"{(getattr(res, 'stderr', '') or getattr(res, 'stdout', ''))[:300]}"
|
| 232 |
+
)
|
| 233 |
+
continue
|
| 234 |
+
try:
|
| 235 |
+
records = _parse_records(getattr(res, "stdout", "") or "")
|
| 236 |
+
if not records:
|
| 237 |
+
raise RuntimeError(f"the stream at {path} is empty")
|
| 238 |
+
cls.from_records(records, expect_count=expect_count,
|
| 239 |
+
expect_sha256=expect_sha256)
|
| 240 |
+
except (json.JSONDecodeError, StreamIdentityError, RuntimeError) as err:
|
| 241 |
+
last_err = err
|
| 242 |
+
records = []
|
| 243 |
+
continue
|
| 244 |
+
break
|
| 245 |
+
if not records:
|
| 246 |
+
raise StreamIdentityError(
|
| 247 |
+
f"stream at {path} failed verification after {READ_ATTEMPTS} reads: "
|
| 248 |
+
f"{last_err}"
|
| 249 |
+
) from last_err
|
| 250 |
+
|
| 251 |
+
removed = False
|
| 252 |
+
if remove_after_load:
|
| 253 |
+
stream_dir = posixpath.dirname(path)
|
| 254 |
+
await environment.exec(f"rm -rf {shlex.quote(stream_dir)}", timeout_sec=60)
|
| 255 |
+
check = await environment.exec(
|
| 256 |
+
f"test -e {shlex.quote(path)}", timeout_sec=30
|
| 257 |
+
)
|
| 258 |
+
removed = getattr(check, "return_code", 0) != 0
|
| 259 |
+
if not removed:
|
| 260 |
+
raise RuntimeError(
|
| 261 |
+
f"could not remove {path} after loading it: the agent could read "
|
| 262 |
+
"ahead in the stream"
|
| 263 |
+
)
|
| 264 |
+
return cls.from_records(
|
| 265 |
+
records,
|
| 266 |
+
logs_dir=logs_dir,
|
| 267 |
+
expect_count=expect_count,
|
| 268 |
+
expect_sha256=expect_sha256,
|
| 269 |
+
identity={"path": path, "removed": removed},
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# -------------------------------------------------------------- properties
|
| 273 |
+
@property
|
| 274 |
+
def n_total(self) -> int:
|
| 275 |
+
return len(self.ops)
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def drained(self) -> bool:
|
| 279 |
+
"""True once every op has been delivered."""
|
| 280 |
+
return self.n_delivered >= self.n_total
|
| 281 |
+
|
| 282 |
+
@property
|
| 283 |
+
def done(self) -> bool:
|
| 284 |
+
"""True once the run has a terminal reason; the harness should stop."""
|
| 285 |
+
return self.terminated_by is not None
|
| 286 |
+
|
| 287 |
+
# ----------------------------------------------------------------- delivery
|
| 288 |
+
def _deliver(self, trigger: str, turn: int | None) -> str:
|
| 289 |
+
index = self.n_delivered
|
| 290 |
+
text = render_op(self.ops[index], remaining=self.n_total - (index + 1))
|
| 291 |
+
self.n_delivered += 1
|
| 292 |
+
self.log.append(Delivery("op", index, trigger, turn,
|
| 293 |
+
"start" if trigger == "<start>" else "ready"))
|
| 294 |
+
self.write()
|
| 295 |
+
return text
|
| 296 |
+
|
| 297 |
+
def first_turn(self, *, turn: int | None = None) -> str | None:
|
| 298 |
+
"""Op 0, delivered with the instruction. ``None`` for an empty stream."""
|
| 299 |
+
if self.n_delivered:
|
| 300 |
+
raise RuntimeError("first_turn() called after delivery started")
|
| 301 |
+
if not self.ops:
|
| 302 |
+
self.terminate("stream_exhausted")
|
| 303 |
+
return None
|
| 304 |
+
return self._deliver("<start>", turn)
|
| 305 |
+
|
| 306 |
+
def pending(
|
| 307 |
+
self, last_command: str | None, last_exit: int | None = 0, *,
|
| 308 |
+
turn: int | None = None,
|
| 309 |
+
) -> list[str]:
|
| 310 |
+
"""The user turns to append after the tool result of ``last_command``.
|
| 311 |
+
|
| 312 |
+
* standalone readiness, ops left: ``[next op]``;
|
| 313 |
+
* standalone readiness, stream drained: ``[]`` and ``terminated_by =
|
| 314 |
+
"stream_exhausted"`` (the harness must stop);
|
| 315 |
+
* standalone submit, ops left: ``[REFUSE_SUBMIT_TEXT]``;
|
| 316 |
+
* standalone submit, drained: ``[]`` and ``terminated_by = "submit"``;
|
| 317 |
+
* the marker mentioned but not standalone: ``[EXPLAIN_NON_STANDALONE_TEXT]``;
|
| 318 |
+
* anything else: ``[]``.
|
| 319 |
+
|
| 320 |
+
``last_exit`` is the command's exit code; ``None`` means the harness cannot
|
| 321 |
+
observe it (a terminal multiplexer), which is treated as success.
|
| 322 |
+
"""
|
| 323 |
+
if self.done:
|
| 324 |
+
return []
|
| 325 |
+
cmd = last_command or ""
|
| 326 |
+
code = 0 if last_exit is None else int(last_exit)
|
| 327 |
+
trigger = _excerpt(cmd)
|
| 328 |
+
if proto.is_ready_command(cmd, code):
|
| 329 |
+
if self.drained:
|
| 330 |
+
self.terminate("stream_exhausted")
|
| 331 |
+
return []
|
| 332 |
+
return [self._deliver(trigger, turn)]
|
| 333 |
+
if proto.is_submit_command(cmd, code):
|
| 334 |
+
return self.on_submit(trigger=trigger, turn=turn)
|
| 335 |
+
if proto.mentions_advance_marker(cmd):
|
| 336 |
+
self.n_explains += 1
|
| 337 |
+
self.log.append(Delivery("explain", None, trigger, turn, "mention"))
|
| 338 |
+
self.write()
|
| 339 |
+
return [proto.EXPLAIN_NON_STANDALONE_TEXT]
|
| 340 |
+
return []
|
| 341 |
+
|
| 342 |
+
def on_submit(self, *, trigger: str = "<submit>", turn: int | None = None) -> list[str]:
|
| 343 |
+
"""The agent asked to finish (by command or by the harness's own signal).
|
| 344 |
+
|
| 345 |
+
Before the stream is drained this is refused, and the refusal text is
|
| 346 |
+
returned for the harness to deliver; afterwards the run ends as ``submit``.
|
| 347 |
+
"""
|
| 348 |
+
if self.done:
|
| 349 |
+
return []
|
| 350 |
+
if not self.drained:
|
| 351 |
+
self.n_refusals += 1
|
| 352 |
+
self.log.append(Delivery("refuse_submit", None, _excerpt(trigger), turn,
|
| 353 |
+
"submit"))
|
| 354 |
+
self.write()
|
| 355 |
+
return [proto.REFUSE_SUBMIT_TEXT]
|
| 356 |
+
self.terminate("submit")
|
| 357 |
+
return []
|
| 358 |
+
|
| 359 |
+
def terminate(self, reason: str) -> None:
|
| 360 |
+
"""Record the terminal reason once; later calls do not overwrite it."""
|
| 361 |
+
if reason not in proto.TERMINATED_BY:
|
| 362 |
+
raise ValueError(f"unknown terminated_by {reason!r}")
|
| 363 |
+
if self.terminated_by is None:
|
| 364 |
+
self.terminated_by = reason
|
| 365 |
+
self.write()
|
| 366 |
+
|
| 367 |
+
# ------------------------------------------------------------------ record
|
| 368 |
+
def record(self) -> dict[str, Any]:
|
| 369 |
+
return {
|
| 370 |
+
"n_ops_delivered": self.n_delivered,
|
| 371 |
+
"n_ops_total": self.n_total,
|
| 372 |
+
"terminated_by": self.terminated_by,
|
| 373 |
+
"n_refusals": self.n_refusals,
|
| 374 |
+
"n_explains": self.n_explains,
|
| 375 |
+
"stream": self.identity,
|
| 376 |
+
"log": [d.to_dict() for d in self.log],
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
def write(self, logs_dir: Path | str | None = None) -> Path | None:
|
| 380 |
+
"""Write ``interactive_stream.json``. Best effort: never raises."""
|
| 381 |
+
target = Path(logs_dir) if logs_dir else self.logs_dir
|
| 382 |
+
if target is None:
|
| 383 |
+
return None
|
| 384 |
+
try:
|
| 385 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 386 |
+
out = target / STREAM_RECORD_NAME
|
| 387 |
+
out.write_text(json.dumps(self.record(), indent=2) + "\n", encoding="utf-8")
|
| 388 |
+
return out
|
| 389 |
+
except Exception:
|
| 390 |
+
return None
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _task_env(environment: Any) -> dict[str, str]:
|
| 394 |
+
cfg = getattr(environment, "task_env_config", None)
|
| 395 |
+
env = getattr(cfg, "env", None) or {}
|
| 396 |
+
try:
|
| 397 |
+
return {str(k): str(v) for k, v in dict(env).items()}
|
| 398 |
+
except Exception:
|
| 399 |
+
return {}
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/runner.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The pure-Python ContextBench runner.
|
| 2 |
+
|
| 3 |
+
The runner owns the turn protocol so an agent does not have to. It delivers one
|
| 4 |
+
operation per user turn, advances only on a standalone readiness marker, refuses an
|
| 5 |
+
early submit, enforces the budget wall on the agent's own reported context,
|
| 6 |
+
snapshots that context after every turn, and grades the run at the end.
|
| 7 |
+
|
| 8 |
+
The invariant the runner exists to hold: an operation enters the agent's context as
|
| 9 |
+
a user message appended by the runner, before the agent can act on it. The agent
|
| 10 |
+
controls only *when* the next operation arrives, never its content or its route
|
| 11 |
+
into the context.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Protocol, runtime_checkable
|
| 20 |
+
|
| 21 |
+
from . import stream as proto
|
| 22 |
+
from .graders import grade_run
|
| 23 |
+
from .stream import Op, render_op
|
| 24 |
+
from .tokens import count_tokens, record_snapshot
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"ContextAgent",
|
| 28 |
+
"Instance",
|
| 29 |
+
"DEFAULT_SYSTEM_PROMPT",
|
| 30 |
+
"load_instance",
|
| 31 |
+
"run",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
DEFAULT_SYSTEM_PROMPT = (
|
| 35 |
+
"You are a careful assistant working through a long stream of operations that "
|
| 36 |
+
"does not fit in your context window. Handle each operation as it arrives, keep "
|
| 37 |
+
"in your context exactly what later operations will need, and let go of the "
|
| 38 |
+
"rest.\n\n" + proto.MARKER_PARAGRAPH_REPLY
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@runtime_checkable
|
| 43 |
+
class ContextAgent(Protocol):
|
| 44 |
+
"""What the runner needs from an agent.
|
| 45 |
+
|
| 46 |
+
``reset`` starts a fresh episode with the system prompt and the family
|
| 47 |
+
instruction. ``on_user_turn`` receives one user message -- an operation, or a
|
| 48 |
+
protocol message from the runner -- and returns the reply text. ``context``
|
| 49 |
+
returns the agent's current message list, which the runner snapshots and
|
| 50 |
+
measures against the budget: an agent that hides its context from the runner
|
| 51 |
+
cannot be graded on the paper metric.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def reset(self, system: str, instruction: str) -> None: ...
|
| 55 |
+
|
| 56 |
+
def on_user_turn(self, text: str) -> str: ...
|
| 57 |
+
|
| 58 |
+
def context(self) -> list[dict]: ...
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class Instance:
|
| 63 |
+
"""One generated instance on disk."""
|
| 64 |
+
|
| 65 |
+
path: Path
|
| 66 |
+
family: str
|
| 67 |
+
ops: list[Op]
|
| 68 |
+
gold: dict
|
| 69 |
+
meta: dict
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def n_ops(self) -> int:
|
| 73 |
+
return len(self.ops)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_instance(instance_dir: Path | str) -> Instance:
|
| 77 |
+
"""Read ``chunks.jsonl``, ``gold.json`` and ``meta.json`` from a directory."""
|
| 78 |
+
d = Path(instance_dir)
|
| 79 |
+
meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
|
| 80 |
+
gold = json.loads((d / "gold.json").read_text(encoding="utf-8"))
|
| 81 |
+
ops = proto.load_ops((d / "chunks.jsonl").read_text(encoding="utf-8").splitlines())
|
| 82 |
+
family = meta.get("task_family") or (gold.get("meta") or {}).get("task_family")
|
| 83 |
+
if not family:
|
| 84 |
+
raise ValueError(f"{d}: meta.json has no task_family")
|
| 85 |
+
return Instance(path=d, family=family, ops=ops, gold=gold, meta=meta)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def instruction_for(instance: Instance, *, delivery: str = "reply") -> str:
|
| 89 |
+
"""The instruction text for an instance's family."""
|
| 90 |
+
import importlib
|
| 91 |
+
|
| 92 |
+
module = importlib.import_module(
|
| 93 |
+
f"contextbench.tasks.{instance.family}.generate"
|
| 94 |
+
)
|
| 95 |
+
return module.instruction(instance.gold, delivery=delivery)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run(
|
| 99 |
+
agent: ContextAgent,
|
| 100 |
+
instance_dir: Path | str,
|
| 101 |
+
*,
|
| 102 |
+
budget: int = 32768,
|
| 103 |
+
reserve: int = 2048,
|
| 104 |
+
out_dir: Path | str = "runs/latest",
|
| 105 |
+
max_turns: int | None = None,
|
| 106 |
+
system_prompt: str | None = None,
|
| 107 |
+
delivery: str = "reply",
|
| 108 |
+
) -> dict:
|
| 109 |
+
"""Run one instance end to end and return the result dict.
|
| 110 |
+
|
| 111 |
+
``budget`` and ``reserve`` set the wall: a turn whose snapshot exceeds
|
| 112 |
+
``budget - reserve`` tokens ends the run with ``terminated_by="budget_wall"``,
|
| 113 |
+
because a real serving stack would have refused the next request. ``max_turns``
|
| 114 |
+
is a safety stop, not part of the task: leave it unset for a full horizon.
|
| 115 |
+
|
| 116 |
+
Writes ``context_snapshots/turn-NNNN.json`` per turn, ``interactive_stream.json``
|
| 117 |
+
and ``result.json`` into ``out_dir``, and returns the same result dict.
|
| 118 |
+
"""
|
| 119 |
+
instance = load_instance(instance_dir)
|
| 120 |
+
out = Path(out_dir)
|
| 121 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
usable = budget - reserve
|
| 123 |
+
|
| 124 |
+
instruction = instruction_for(instance, delivery=delivery)
|
| 125 |
+
agent.reset(system_prompt or DEFAULT_SYSTEM_PROMPT, instruction)
|
| 126 |
+
|
| 127 |
+
total_ops = instance.n_ops
|
| 128 |
+
delivered = 0
|
| 129 |
+
step = 0
|
| 130 |
+
terminated_by: str | None = None
|
| 131 |
+
peak_tokens = 0
|
| 132 |
+
|
| 133 |
+
def _deliver_op(index: int) -> str:
|
| 134 |
+
return render_op(instance.ops[index], remaining=total_ops - (index + 1))
|
| 135 |
+
|
| 136 |
+
if total_ops == 0:
|
| 137 |
+
terminated_by = "stream_exhausted"
|
| 138 |
+
pending: str | None = None
|
| 139 |
+
else:
|
| 140 |
+
pending = _deliver_op(0)
|
| 141 |
+
delivered = 1
|
| 142 |
+
|
| 143 |
+
while pending is not None and terminated_by is None:
|
| 144 |
+
reply = agent.on_user_turn(pending) or ""
|
| 145 |
+
step += 1
|
| 146 |
+
|
| 147 |
+
messages = list(agent.context() or [])
|
| 148 |
+
tokens, _ = count_tokens(messages)
|
| 149 |
+
peak_tokens = max(peak_tokens, tokens)
|
| 150 |
+
record_snapshot(
|
| 151 |
+
out,
|
| 152 |
+
step,
|
| 153 |
+
messages,
|
| 154 |
+
{
|
| 155 |
+
"n_ops_delivered": delivered,
|
| 156 |
+
"n_ops_total": total_ops,
|
| 157 |
+
"budget": budget,
|
| 158 |
+
"reserve": reserve,
|
| 159 |
+
},
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if tokens > usable:
|
| 163 |
+
terminated_by = "budget_wall"
|
| 164 |
+
break
|
| 165 |
+
|
| 166 |
+
if proto.is_submit_line(reply) or proto.is_submit_command(reply):
|
| 167 |
+
if delivered < total_ops:
|
| 168 |
+
pending = proto.REFUSE_SUBMIT_TEXT
|
| 169 |
+
else:
|
| 170 |
+
terminated_by = "submit"
|
| 171 |
+
break
|
| 172 |
+
elif proto.is_ready_line(reply) or proto.is_ready_command(reply):
|
| 173 |
+
if delivered < total_ops:
|
| 174 |
+
pending = _deliver_op(delivered)
|
| 175 |
+
delivered += 1
|
| 176 |
+
else:
|
| 177 |
+
terminated_by = "stream_exhausted"
|
| 178 |
+
break
|
| 179 |
+
elif proto.mentions_advance_marker(reply):
|
| 180 |
+
pending = proto.EXPLAIN_NON_STANDALONE_TEXT
|
| 181 |
+
else:
|
| 182 |
+
pending = proto.NO_MARKER_TEXT
|
| 183 |
+
|
| 184 |
+
if max_turns is not None and step >= max_turns:
|
| 185 |
+
terminated_by = "max_steps"
|
| 186 |
+
break
|
| 187 |
+
|
| 188 |
+
if terminated_by is None:
|
| 189 |
+
terminated_by = "stream_exhausted"
|
| 190 |
+
|
| 191 |
+
stream_record = {
|
| 192 |
+
"n_ops_delivered": delivered,
|
| 193 |
+
"n_ops_total": total_ops,
|
| 194 |
+
"terminated_by": terminated_by,
|
| 195 |
+
}
|
| 196 |
+
(out / "interactive_stream.json").write_text(
|
| 197 |
+
json.dumps(stream_record, indent=2) + "\n", encoding="utf-8"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
rewards = grade_run(out, instance.gold)
|
| 201 |
+
result: dict[str, Any] = {
|
| 202 |
+
"task_family": instance.family,
|
| 203 |
+
"instance_dir": str(instance.path),
|
| 204 |
+
"out_dir": str(out),
|
| 205 |
+
"budget": budget,
|
| 206 |
+
"reserve": reserve,
|
| 207 |
+
"n_turns": step,
|
| 208 |
+
"peak_tokens": peak_tokens,
|
| 209 |
+
"reward": rewards.get("reward", 0.0),
|
| 210 |
+
"rewards": rewards,
|
| 211 |
+
**stream_record,
|
| 212 |
+
}
|
| 213 |
+
(out / "result.json").write_text(
|
| 214 |
+
json.dumps(result, indent=2, default=str) + "\n", encoding="utf-8"
|
| 215 |
+
)
|
| 216 |
+
return result
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/stream.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The ContextBench turn protocol: op rendering, readiness detection, refusals.
|
| 2 |
+
|
| 3 |
+
Pure Python. This module is the single definition of how an operation reaches the
|
| 4 |
+
agent and how the agent asks for the next one, so the Python runner and (phase 2)
|
| 5 |
+
the Harbor adapters cannot drift apart.
|
| 6 |
+
|
| 7 |
+
Readiness has two equivalent forms:
|
| 8 |
+
|
| 9 |
+
* ``READY_FOR_NEXT_OP`` as a **standalone line** of the reply -- for chat agents
|
| 10 |
+
driven by :mod:`contextbench.runner`, which have no shell;
|
| 11 |
+
* ``echo READY_FOR_NEXT_OP`` as a **standalone shell statement** -- for agents
|
| 12 |
+
with a bash tool, where the marker is a command the harness executes.
|
| 13 |
+
|
| 14 |
+
Both are deliberately strict about "standalone": the marker must not count when it
|
| 15 |
+
merely appears as an argument (``grep READY_FOR_NEXT_OP file``) or inside answer
|
| 16 |
+
data, because a spurious advance consumes an operation that is then lost forever.
|
| 17 |
+
A command that failed (non-zero exit) never advances either: the step did not
|
| 18 |
+
finish, so the op must not be handed over.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from typing import Iterable
|
| 26 |
+
|
| 27 |
+
__all__ = [
|
| 28 |
+
"ADVANCE_MARKER",
|
| 29 |
+
"SUBMIT_MARKER",
|
| 30 |
+
"TERMINATED_BY",
|
| 31 |
+
"Op",
|
| 32 |
+
"render_op",
|
| 33 |
+
"is_ready_line",
|
| 34 |
+
"is_ready_command",
|
| 35 |
+
"mentions_advance_marker",
|
| 36 |
+
"is_submit_line",
|
| 37 |
+
"is_submit_command",
|
| 38 |
+
"mentions_submit_marker",
|
| 39 |
+
"REFUSE_SUBMIT_TEXT",
|
| 40 |
+
"EXPLAIN_NON_STANDALONE_TEXT",
|
| 41 |
+
"NO_MARKER_TEXT",
|
| 42 |
+
"SUBMIT_PARAGRAPH",
|
| 43 |
+
"MARKER_PARAGRAPH",
|
| 44 |
+
"MARKER_PARAGRAPH_REPLY",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
ADVANCE_MARKER = "READY_FOR_NEXT_OP"
|
| 48 |
+
SUBMIT_MARKER = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
|
| 49 |
+
|
| 50 |
+
#: Every way a ContextBench run can end. ``timeout`` is produced by wall-clock
|
| 51 |
+
#: enforcement in the container runners; the pure-Python runner produces the
|
| 52 |
+
#: other four.
|
| 53 |
+
TERMINATED_BY = (
|
| 54 |
+
"submit",
|
| 55 |
+
"stream_exhausted",
|
| 56 |
+
"budget_wall",
|
| 57 |
+
"timeout",
|
| 58 |
+
"max_steps",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _standalone_line_re(marker: str) -> re.Pattern[str]:
|
| 63 |
+
"""The marker alone on a line, tolerating whitespace and code-fence quoting."""
|
| 64 |
+
return re.compile(
|
| 65 |
+
rf"^[ \t]*(?:`{{1,3}})?{re.escape(marker)}(?:`{{1,3}})?[ \t]*\.?[ \t]*$",
|
| 66 |
+
re.MULTILINE,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _standalone_command_re(marker: str) -> re.Pattern[str]:
|
| 71 |
+
"""``echo MARKER`` as a whole shell statement (quotes optional)."""
|
| 72 |
+
return re.compile(
|
| 73 |
+
rf"""^\s*(?:/bin/)?echo\s+(?:['"])?{re.escape(marker)}(?:['"])?\s*$"""
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_READY_LINE_RE = _standalone_line_re(ADVANCE_MARKER)
|
| 78 |
+
_READY_SEGMENT_RE = _standalone_command_re(ADVANCE_MARKER)
|
| 79 |
+
_SUBMIT_LINE_RE = _standalone_line_re(SUBMIT_MARKER)
|
| 80 |
+
_SUBMIT_SEGMENT_RE = _standalone_command_re(SUBMIT_MARKER)
|
| 81 |
+
|
| 82 |
+
#: Shell statement separators. A bundled command such as
|
| 83 |
+
#: ``printf '<<<ANSWER ...>>>'; echo READY_FOR_NEXT_OP`` advances, because its
|
| 84 |
+
#: last segment is a clean echo.
|
| 85 |
+
_SEPARATORS = re.compile(r";|\n|&&|\|\|")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_HEREDOC_OPEN = re.compile(r"<<(-?)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\2")
|
| 89 |
+
_MULTILINE_QUOTED = re.compile(r"'[^']*\n[^']*'|\"(?:[^\"\\]|\\.)*\n(?:[^\"\\]|\\.)*\"")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _strip_heredoc_bodies(command: str) -> str:
|
| 93 |
+
"""Drop the body lines of every here-document; keep the line that opens it.
|
| 94 |
+
|
| 95 |
+
A here-document body is data fed to a program, not shell statements, so an
|
| 96 |
+
``echo READY_FOR_NEXT_OP`` line inside it never runs and must not count.
|
| 97 |
+
"""
|
| 98 |
+
lines = command.split("\n")
|
| 99 |
+
out: list[str] = []
|
| 100 |
+
i = 0
|
| 101 |
+
while i < len(lines):
|
| 102 |
+
line = lines[i]
|
| 103 |
+
out.append(line)
|
| 104 |
+
pending = _HEREDOC_OPEN.findall(line)
|
| 105 |
+
i += 1
|
| 106 |
+
for dash, _quote, word in pending:
|
| 107 |
+
while i < len(lines):
|
| 108 |
+
body_line = lines[i]
|
| 109 |
+
i += 1
|
| 110 |
+
if (body_line.lstrip("\t") if dash else body_line) == word:
|
| 111 |
+
break
|
| 112 |
+
return "\n".join(out)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _statements(command: str) -> list[str]:
|
| 116 |
+
"""Split a shell command into statements, ignoring here-document bodies and
|
| 117 |
+
quoted strings that span lines (both are data, not statements)."""
|
| 118 |
+
text = _strip_heredoc_bodies(command)
|
| 119 |
+
text = _MULTILINE_QUOTED.sub("''", text)
|
| 120 |
+
return _SEPARATORS.split(text)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass(frozen=True)
|
| 124 |
+
class Op:
|
| 125 |
+
"""One streamed operation, as it is stored in ``chunks.jsonl``."""
|
| 126 |
+
|
| 127 |
+
index: int
|
| 128 |
+
header: str
|
| 129 |
+
body: str
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def from_dict(cls, obj: dict, *, fallback_index: int = 0) -> "Op":
|
| 133 |
+
return cls(
|
| 134 |
+
index=int(obj.get("index", fallback_index)),
|
| 135 |
+
header=str(obj.get("header", "")),
|
| 136 |
+
body=str(obj.get("body", "")),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def render_op(op: Op, *, remaining: int) -> str:
|
| 141 |
+
"""The exact user-turn text for one operation.
|
| 142 |
+
|
| 143 |
+
``remaining`` is the number of operations that follow this one.
|
| 144 |
+
"""
|
| 145 |
+
return f"=== {op.header} ({remaining} op(s) remaining after this) ===\n{op.body}"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def load_ops(lines: Iterable[str]) -> list[Op]:
|
| 149 |
+
"""Parse ``chunks.jsonl`` lines into :class:`Op` objects."""
|
| 150 |
+
import json
|
| 151 |
+
|
| 152 |
+
ops: list[Op] = []
|
| 153 |
+
for line in lines:
|
| 154 |
+
if line.strip():
|
| 155 |
+
ops.append(Op.from_dict(json.loads(line), fallback_index=len(ops)))
|
| 156 |
+
return ops
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# --------------------------------------------------------------------- matching
|
| 160 |
+
def is_ready_line(reply: str) -> bool:
|
| 161 |
+
"""True when the reply carries the advance marker on a line of its own."""
|
| 162 |
+
return bool(reply) and bool(_READY_LINE_RE.search(reply))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def is_ready_command(command: str, exit_code: int = 0) -> bool:
|
| 166 |
+
"""True when ``command`` runs ``echo READY_FOR_NEXT_OP`` as a whole statement.
|
| 167 |
+
|
| 168 |
+
A failed command means the step did not finish, so it never advances.
|
| 169 |
+
"""
|
| 170 |
+
if not command or exit_code != 0:
|
| 171 |
+
return False
|
| 172 |
+
return any(_READY_SEGMENT_RE.match(seg) for seg in _statements(command))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def mentions_advance_marker(text: str) -> bool:
|
| 176 |
+
return bool(text) and ADVANCE_MARKER in text
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def is_submit_line(reply: str) -> bool:
|
| 180 |
+
return bool(reply) and bool(_SUBMIT_LINE_RE.search(reply))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def is_submit_command(command: str, exit_code: int = 0) -> bool:
|
| 184 |
+
if not command or exit_code != 0:
|
| 185 |
+
return False
|
| 186 |
+
return any(_SUBMIT_SEGMENT_RE.match(seg) for seg in _statements(command))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def mentions_submit_marker(text: str) -> bool:
|
| 190 |
+
return bool(text) and SUBMIT_MARKER in text
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ----------------------------------------------------------- texts sent back
|
| 194 |
+
#: Sent when the agent submits while operations are still undelivered.
|
| 195 |
+
REFUSE_SUBMIT_TEXT = (
|
| 196 |
+
"There is nothing to submit in this task and the run did NOT end. "
|
| 197 |
+
"Operations are still being delivered one at a time: run the "
|
| 198 |
+
f"standalone command `echo {ADVANCE_MARKER}` to receive the "
|
| 199 |
+
"next one, and keep doing that until you are told none remain."
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
#: Sent when the marker appeared but not as a standalone statement. Without this
|
| 203 |
+
#: the agent sees its command succeed, believes it advanced, and then stalls in
|
| 204 |
+
#: empty turns with no error signal anywhere.
|
| 205 |
+
EXPLAIN_NON_STANDALONE_TEXT = (
|
| 206 |
+
f"[{ADVANCE_MARKER} did NOT advance: it must be a STANDALONE "
|
| 207 |
+
f"command -- `echo {ADVANCE_MARKER}` on its own, or as the last "
|
| 208 |
+
f"statement after a `;`. It does not count when passed as an "
|
| 209 |
+
f"argument to printf/cat/grep. Your command ran normally; run the "
|
| 210 |
+
f"marker as its own statement to receive the next operation.]"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
#: Sent when a reply neither handled the op nor asked for the next one.
|
| 214 |
+
NO_MARKER_TEXT = (
|
| 215 |
+
f"[No {ADVANCE_MARKER} in your reply, so the stream did not advance. "
|
| 216 |
+
f"Finish the current operation, then put {ADVANCE_MARKER} on a line of "
|
| 217 |
+
f"its own to receive the next one.]"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
#: The two closing paragraphs a system prompt can carry. The submit contract is
|
| 221 |
+
#: wrong for a streamed task: an agent that submits before the stream is drained
|
| 222 |
+
#: loses every operation it has not seen.
|
| 223 |
+
SUBMIT_PARAGRAPH = (
|
| 224 |
+
"When you are finished, submit by running the standalone command\n"
|
| 225 |
+
f"`echo {SUBMIT_MARKER}` (with nothing else in that command).\n"
|
| 226 |
+
"After it runs you cannot continue."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
MARKER_PARAGRAPH = (
|
| 230 |
+
"This task is delivered to you one operation at a time. You do NOT submit and\n"
|
| 231 |
+
"you do NOT decide when it is over: after handling each operation, run the\n"
|
| 232 |
+
f"standalone command `echo {ADVANCE_MARKER}` (with nothing else in that\n"
|
| 233 |
+
"command) to receive the next one. Do this for EVERY operation, including the\n"
|
| 234 |
+
"one that says none remain -- that final marker is what ends the run, and the\n"
|
| 235 |
+
"harness stops you. Submitting early discards the work you just did."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
MARKER_PARAGRAPH_REPLY = (
|
| 239 |
+
"This task is delivered to you one operation at a time. You do NOT decide when\n"
|
| 240 |
+
"it is over: after handling each operation, end your reply with\n"
|
| 241 |
+
f"{ADVANCE_MARKER} on a line of its own to receive the next one. Do this for\n"
|
| 242 |
+
"EVERY operation, including the one that says none remain. Submitting early\n"
|
| 243 |
+
"discards the work you just did."
|
| 244 |
+
)
|
harbor/kv-store-R1000-seed42/tests/_cb/contextbench/tokens.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token counting and per-turn context snapshots.
|
| 2 |
+
|
| 3 |
+
Every part of ContextBench that asks "how big is this context right now?" goes
|
| 4 |
+
through :func:`count_tokens`: exact ``o200k_base`` counts when ``tiktoken`` can be
|
| 5 |
+
imported, and a ``len // 3`` character estimate otherwise, so the package works
|
| 6 |
+
with no optional dependency and no network.
|
| 7 |
+
|
| 8 |
+
:func:`record_snapshot` persists the full retained context after each turn. The
|
| 9 |
+
snapshots are the paper metric's source of truth: an agent that offloads content
|
| 10 |
+
to disk and reads a value back only transiently still has that value captured in
|
| 11 |
+
the snapshot of the turn where it surfaced.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Iterator
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"SNAPSHOT_DIRNAME",
|
| 23 |
+
"count_text",
|
| 24 |
+
"count_tokens",
|
| 25 |
+
"get_encoder",
|
| 26 |
+
"iter_text",
|
| 27 |
+
"record_snapshot",
|
| 28 |
+
"snapshot_paths",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
SNAPSHOT_DIRNAME = "context_snapshots"
|
| 32 |
+
|
| 33 |
+
#: The character-per-token divisor used when tiktoken is unavailable.
|
| 34 |
+
FALLBACK_CHARS_PER_TOKEN = 3
|
| 35 |
+
|
| 36 |
+
_ENCODER: Any = None
|
| 37 |
+
_ENCODER_NAME: str | None = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_encoder() -> Any:
|
| 41 |
+
"""A cached ``tiktoken`` encoder, or ``None`` when tiktoken is unavailable.
|
| 42 |
+
|
| 43 |
+
Defaults to ``o200k_base``; ``TIKTOKEN_ENCODING`` overrides it and
|
| 44 |
+
``cl100k_base`` is the second choice (its vocabulary may be cached when
|
| 45 |
+
``o200k_base`` is not).
|
| 46 |
+
"""
|
| 47 |
+
global _ENCODER, _ENCODER_NAME
|
| 48 |
+
if _ENCODER is not None or _ENCODER_NAME == "_failed":
|
| 49 |
+
return _ENCODER
|
| 50 |
+
try:
|
| 51 |
+
import tiktoken
|
| 52 |
+
except Exception:
|
| 53 |
+
_ENCODER_NAME = "_failed"
|
| 54 |
+
return None
|
| 55 |
+
for name in (os.environ.get("TIKTOKEN_ENCODING") or "o200k_base", "cl100k_base"):
|
| 56 |
+
try:
|
| 57 |
+
_ENCODER = tiktoken.get_encoding(name)
|
| 58 |
+
_ENCODER_NAME = name
|
| 59 |
+
return _ENCODER
|
| 60 |
+
except Exception:
|
| 61 |
+
continue # e.g. the vocabulary download is blocked offline
|
| 62 |
+
_ENCODER_NAME = "_failed"
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def encoder_name() -> str:
|
| 67 |
+
"""The method label that :func:`count_tokens` reports."""
|
| 68 |
+
get_encoder()
|
| 69 |
+
if _ENCODER_NAME in (None, "_failed"):
|
| 70 |
+
return f"approx_chars{FALLBACK_CHARS_PER_TOKEN}"
|
| 71 |
+
return f"tiktoken:{_ENCODER_NAME}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def iter_text(messages: list[Any] | None) -> Iterator[str]:
|
| 75 |
+
"""Yield every text piece of ``messages`` that reaches the model.
|
| 76 |
+
|
| 77 |
+
This includes ``tool_calls[*].function.arguments``, where a shell command
|
| 78 |
+
lives: a tool-heavy agent keeps most of its bytes there, so counting only
|
| 79 |
+
``content`` would undercount the real prompt by roughly a factor of two.
|
| 80 |
+
"""
|
| 81 |
+
for msg in messages or []:
|
| 82 |
+
content: Any
|
| 83 |
+
if isinstance(msg, dict):
|
| 84 |
+
reasoning = msg.get("reasoning_content")
|
| 85 |
+
if isinstance(reasoning, str):
|
| 86 |
+
yield reasoning
|
| 87 |
+
content = msg.get("content")
|
| 88 |
+
for call in msg.get("tool_calls") or []:
|
| 89 |
+
fn = call.get("function") if isinstance(call, dict) else None
|
| 90 |
+
if isinstance(fn, dict):
|
| 91 |
+
if fn.get("name"):
|
| 92 |
+
yield str(fn["name"])
|
| 93 |
+
if fn.get("arguments"):
|
| 94 |
+
yield str(fn["arguments"])
|
| 95 |
+
else:
|
| 96 |
+
content = msg
|
| 97 |
+
if isinstance(content, str):
|
| 98 |
+
yield content
|
| 99 |
+
elif isinstance(content, list):
|
| 100 |
+
for item in content:
|
| 101 |
+
if isinstance(item, dict):
|
| 102 |
+
yield str(item.get("text") or item.get("content") or "")
|
| 103 |
+
else:
|
| 104 |
+
yield str(item)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def count_text(text: str) -> int:
|
| 108 |
+
"""Token count of one string (exact with tiktoken, else ``len // 3``)."""
|
| 109 |
+
if not text:
|
| 110 |
+
return 0
|
| 111 |
+
enc = get_encoder()
|
| 112 |
+
if enc is None:
|
| 113 |
+
return max(1, len(text) // FALLBACK_CHARS_PER_TOKEN)
|
| 114 |
+
return len(enc.encode(text, disallowed_special=()))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def count_tokens(messages: list[Any] | None) -> tuple[int, str]:
|
| 118 |
+
"""Token count over a message list. Returns ``(tokens, method)``."""
|
| 119 |
+
total = sum(count_text(piece) for piece in iter_text(messages))
|
| 120 |
+
return total, encoder_name()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def snapshot_paths(logs_dir: Path | str) -> list[Path]:
|
| 124 |
+
"""Every ``context_snapshots/turn-*.json`` under ``logs_dir``, in turn order."""
|
| 125 |
+
import re
|
| 126 |
+
|
| 127 |
+
d = Path(logs_dir) / SNAPSHOT_DIRNAME
|
| 128 |
+
if not d.is_dir():
|
| 129 |
+
return []
|
| 130 |
+
|
| 131 |
+
def _turn(path: Path) -> int:
|
| 132 |
+
m = re.search(r"turn-(\d+)", path.name)
|
| 133 |
+
return int(m.group(1)) if m else -1
|
| 134 |
+
|
| 135 |
+
return sorted(d.glob("turn-*.json"), key=_turn)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def record_snapshot(
|
| 139 |
+
logs_dir: Path | str,
|
| 140 |
+
step: int,
|
| 141 |
+
messages: list[Any],
|
| 142 |
+
extra: dict[str, Any] | None = None,
|
| 143 |
+
) -> Path | None:
|
| 144 |
+
"""Persist one per-turn snapshot of the full retained context.
|
| 145 |
+
|
| 146 |
+
Writes ``<logs_dir>/context_snapshots/turn-NNNN.json`` holding ``step``,
|
| 147 |
+
``tokens``, ``token_method``, ``n_messages``, anything in ``extra``, and the
|
| 148 |
+
``messages`` themselves (last, so a human reading the file sees the
|
| 149 |
+
accounting first). Best effort: snapshotting is a logging side effect and
|
| 150 |
+
never raises into the run.
|
| 151 |
+
"""
|
| 152 |
+
try:
|
| 153 |
+
d = Path(logs_dir) / SNAPSHOT_DIRNAME
|
| 154 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 155 |
+
tokens, method = count_tokens(messages)
|
| 156 |
+
payload: dict[str, Any] = {
|
| 157 |
+
"step": step,
|
| 158 |
+
"tokens": tokens,
|
| 159 |
+
"token_method": method,
|
| 160 |
+
"n_messages": len(messages or []),
|
| 161 |
+
}
|
| 162 |
+
if extra:
|
| 163 |
+
payload.update(extra)
|
| 164 |
+
payload["messages"] = messages
|
| 165 |
+
out = d / f"turn-{step:04d}.json"
|
| 166 |
+
out.write_text(
|
| 167 |
+
json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8"
|
| 168 |
+
)
|
| 169 |
+
return out
|
| 170 |
+
except Exception:
|
| 171 |
+
return None
|
harbor/kv-store-R1000-seed42/tests/feasibility_receipt.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"verdict": "PASS",
|
| 3 |
+
"feasible": true,
|
| 4 |
+
"task_family": "kv_store",
|
| 5 |
+
"checks": {
|
| 6 |
+
"pressure": {
|
| 7 |
+
"pass": true,
|
| 8 |
+
"detail": "streamed 49676 / budget 32768 = P 1.52 (need > 1)"
|
| 9 |
+
},
|
| 10 |
+
"small_ops": {
|
| 11 |
+
"pass": true,
|
| 12 |
+
"detail": "max op 4924 tok (cap 5529 = usable 30720 / 5 x 0.9)"
|
| 13 |
+
},
|
| 14 |
+
"retained": {
|
| 15 |
+
"pass": true,
|
| 16 |
+
"detail": "retained 1688 tok [per-batch index 200 + answers 1488] (cap 13824 = usable / 2 x 0.9)"
|
| 17 |
+
},
|
| 18 |
+
"horizon": {
|
| 19 |
+
"pass": true,
|
| 20 |
+
"detail": "34 ops (need >= 4)"
|
| 21 |
+
}
|
| 22 |
+
},
|
| 23 |
+
"measured": {
|
| 24 |
+
"P": 1.516,
|
| 25 |
+
"streamed_tokens": 49676,
|
| 26 |
+
"max_op_tokens": 4924,
|
| 27 |
+
"retained_tokens": 1688,
|
| 28 |
+
"n_ops": 34
|
| 29 |
+
},
|
| 30 |
+
"budget": 32768,
|
| 31 |
+
"reserve": 2048,
|
| 32 |
+
"usable_tokens": 30720,
|
| 33 |
+
"cap_op_tokens": 5529,
|
| 34 |
+
"cap_retained_tokens": 13824,
|
| 35 |
+
"regime": "pressure",
|
| 36 |
+
"token_method": "tiktoken:o200k_base",
|
| 37 |
+
"validator_sha16": "ad7a9a4d10534c47"
|
| 38 |
+
}
|
harbor/kv-store-R1000-seed42/tests/gold.json
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"queries": [
|
| 3 |
+
{
|
| 4 |
+
"qid": 0,
|
| 5 |
+
"key": "K00048",
|
| 6 |
+
"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"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"qid": 1,
|
| 10 |
+
"key": "K00465",
|
| 11 |
+
"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"
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"qid": 2,
|
| 15 |
+
"key": "K00600",
|
| 16 |
+
"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"
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"qid": 3,
|
| 20 |
+
"key": "K00135",
|
| 21 |
+
"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"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"qid": 4,
|
| 25 |
+
"key": "K00224",
|
| 26 |
+
"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"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"qid": 5,
|
| 30 |
+
"key": "K00492",
|
| 31 |
+
"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"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"qid": 6,
|
| 35 |
+
"key": "K00798",
|
| 36 |
+
"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"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"qid": 7,
|
| 40 |
+
"key": "K00150",
|
| 41 |
+
"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"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"qid": 8,
|
| 45 |
+
"key": "K00603",
|
| 46 |
+
"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"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"qid": 9,
|
| 50 |
+
"key": "K00568",
|
| 51 |
+
"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"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"qid": 10,
|
| 55 |
+
"key": "K00147",
|
| 56 |
+
"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"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"qid": 11,
|
| 60 |
+
"key": "K00396",
|
| 61 |
+
"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"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"qid": 12,
|
| 65 |
+
"key": "K00566",
|
| 66 |
+
"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"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"qid": 13,
|
| 70 |
+
"key": "K00621",
|
| 71 |
+
"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"
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"qid": 14,
|
| 75 |
+
"key": "K00914",
|
| 76 |
+
"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"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"qid": 15,
|
| 80 |
+
"key": "K00236",
|
| 81 |
+
"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"
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"qid": 16,
|
| 85 |
+
"key": "K00229",
|
| 86 |
+
"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"
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"qid": 17,
|
| 90 |
+
"key": "K00281",
|
| 91 |
+
"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"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"qid": 18,
|
| 95 |
+
"key": "K00927",
|
| 96 |
+
"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"
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"qid": 19,
|
| 100 |
+
"key": "K00723",
|
| 101 |
+
"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"
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"qid": 20,
|
| 105 |
+
"key": "K00523",
|
| 106 |
+
"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"
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"qid": 21,
|
| 110 |
+
"key": "K00678",
|
| 111 |
+
"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"
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"qid": 22,
|
| 115 |
+
"key": "K00952",
|
| 116 |
+
"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"
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"qid": 23,
|
| 120 |
+
"key": "K00869",
|
| 121 |
+
"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"
|
| 122 |
+
}
|
| 123 |
+
],
|
| 124 |
+
"meta": {
|
| 125 |
+
"task_family": "kv_store",
|
| 126 |
+
"seed": 42,
|
| 127 |
+
"records": 1000,
|
| 128 |
+
"value_words": 24,
|
| 129 |
+
"records_per_chunk": 100,
|
| 130 |
+
"queries": 24,
|
| 131 |
+
"n_set": 1000,
|
| 132 |
+
"n_get": 24,
|
| 133 |
+
"n_batches": 10,
|
| 134 |
+
"n_actions": 34,
|
| 135 |
+
"approx_value_tokens": 48457,
|
| 136 |
+
"approx_per_value_tokens": 48
|
| 137 |
+
}
|
| 138 |
+
}
|
harbor/kv-store-R1000-seed42/tests/meta.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task_family": "kv_store",
|
| 3 |
+
"seed": 42,
|
| 4 |
+
"records": 1000,
|
| 5 |
+
"value_words": 24,
|
| 6 |
+
"records_per_chunk": 100,
|
| 7 |
+
"queries": 24,
|
| 8 |
+
"n_set": 1000,
|
| 9 |
+
"n_get": 24,
|
| 10 |
+
"n_batches": 10,
|
| 11 |
+
"n_actions": 34,
|
| 12 |
+
"approx_value_tokens": 48457,
|
| 13 |
+
"approx_per_value_tokens": 48
|
| 14 |
+
}
|
harbor/kv-store-R1000-seed42/tests/test.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Grades the agent's own messages (context snapshots, else trajectory, else final
|
| 3 |
+
# report) with the ContextBench graders vendored next to this script. Runs after the
|
| 4 |
+
# agent has finished; writes /logs/verifier/reward.json.
|
| 5 |
+
set -u
|
| 6 |
+
PY=$(command -v python3 || command -v python) || {
|
| 7 |
+
echo "ContextBench grading needs python3 in the image; or verify on the host with" "contextbench.harbor.verifiers:ContextBenchVerifier" >&2
|
| 8 |
+
exit 2
|
| 9 |
+
}
|
| 10 |
+
PYTHONPATH=/tests/_cb "$PY" -m contextbench.harbor.reward --agent-dir /logs/agent --gold /tests/gold.json --out-dir /logs/verifier
|
harbor/kv-store-R1000-seed43/environment/stream/chunks.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
harbor/kv-store-R1000-seed43/instruction.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Key-Value Store - process graded (interactive)
|
| 2 |
+
|
| 3 |
+
Operations are delivered to you ONE AT A TIME, as messages in this conversation.
|
| 4 |
+
You do NOT fetch them: each operation arrives automatically as the next user
|
| 5 |
+
message, and you receive the following operation only after you finish the
|
| 6 |
+
current turn. The stream has two phases:
|
| 7 |
+
|
| 8 |
+
1. a long run of **SET-BATCH** blocks, each delimited by unique
|
| 9 |
+
`<<<SET-BATCH <id> BEGIN ...>>>` / `<<<SET-BATCH <id> END>>>` sentinel lines and
|
| 10 |
+
carrying many lines of the form `SET <key> = <value>` (each `<value>` is a
|
| 11 |
+
random, unguessable token; each key is set exactly once), then
|
| 12 |
+
2. a run of **GET** ops at the end: `GET <key>` - report the value you stored
|
| 13 |
+
earlier for `<key>`.
|
| 14 |
+
|
| 15 |
+
Because every `SET` arrives before any `GET`, you cannot predict which keys will
|
| 16 |
+
be queried - you must be able to recall **any** value you have seen.
|
| 17 |
+
|
| 18 |
+
## Turn protocol (IMPORTANT)
|
| 19 |
+
Each incoming message is ONE operation. Do whatever work it needs FIRST (offload,
|
| 20 |
+
`grep`, emit an ANSWER block, ...). When you are done with the current operation,
|
| 21 |
+
**end your turn** by running this single command with the `bash` tool to receive
|
| 22 |
+
the next operation:
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
echo READY_FOR_NEXT_OP
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
This is a multi-turn task: the harness RUNS this command and then delivers the
|
| 29 |
+
next operation as the next user message. You MAY bundle real work into the SAME
|
| 30 |
+
command — in fact the cleanest way to answer a GET is to pipe the stored value
|
| 31 |
+
straight into an ANSWER block and emit the marker together, e.g.:
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
printf '<<<ANSWER key=K00084>>>\n%s\n<<<ANSWER END>>>\n' "$val"; echo READY_FOR_NEXT_OP
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
ONLY running `echo READY_FOR_NEXT_OP` advances to the next operation — a reply
|
| 38 |
+
with no tool call does NOT advance (it just prompts you to keep going). Do NOT run
|
| 39 |
+
the marker until you have fully handled the current operation (offloaded the
|
| 40 |
+
batch, or emitted the GET ANSWER block).
|
| 41 |
+
|
| 42 |
+
## How to answer a GET
|
| 43 |
+
|
| 44 |
+
When you read a `GET <key>`, reply with an **ANSWER block** on its own lines,
|
| 45 |
+
carrying the value **verbatim**:
|
| 46 |
+
|
| 47 |
+
```
|
| 48 |
+
<<<ANSWER key=<key>>>>
|
| 49 |
+
<the exact value you stored for <key>>
|
| 50 |
+
<<<ANSWER END>>>
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## How you are graded
|
| 54 |
+
|
| 55 |
+
Process-graded: for every `GET`, the ANSWER block you emit must contain the
|
| 56 |
+
correct value. Grading reads your **context** (the ANSWER blocks across your
|
| 57 |
+
turns). You MAY use the disk as scratch/storage, but FINDING a value (e.g. with
|
| 58 |
+
`grep`) is NOT answering — only an ANSWER block that actually appears in your
|
| 59 |
+
context is scored, so you must PRINT the value inside `<<<ANSWER ...>>>` ...
|
| 60 |
+
`<<<ANSWER END>>>`.
|
| 61 |
+
The run ends automatically after the final operation; you do not need to submit.
|
harbor/kv-store-R1000-seed43/solution/solve.sh
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Oracle: writes every gold answer into the agent log dir as a final report.
|
| 3 |
+
# Graded as graded_from=final_report, never comparable to a context grade.
|
| 4 |
+
set -euo pipefail
|
| 5 |
+
mkdir -p /logs/agent
|
| 6 |
+
cat > /logs/agent/final_report.txt <<'CONTEXTBENCH_ORACLE_EOF'
|
| 7 |
+
<<<ANSWER key=K00101>>>
|
| 8 |
+
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
|
| 9 |
+
<<<ANSWER END>>>
|
| 10 |
+
<<<ANSWER key=K00011>>>
|
| 11 |
+
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
|
| 12 |
+
<<<ANSWER END>>>
|
| 13 |
+
<<<ANSWER key=K00313>>>
|
| 14 |
+
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
|
| 15 |
+
<<<ANSWER END>>>
|
| 16 |
+
<<<ANSWER key=K00307>>>
|
| 17 |
+
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
|
| 18 |
+
<<<ANSWER END>>>
|
| 19 |
+
<<<ANSWER key=K00769>>>
|
| 20 |
+
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
|
| 21 |
+
<<<ANSWER END>>>
|
| 22 |
+
<<<ANSWER key=K00979>>>
|
| 23 |
+
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
|
| 24 |
+
<<<ANSWER END>>>
|
| 25 |
+
<<<ANSWER key=K00697>>>
|
| 26 |
+
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
|
| 27 |
+
<<<ANSWER END>>>
|
| 28 |
+
<<<ANSWER key=K00485>>>
|
| 29 |
+
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
|
| 30 |
+
<<<ANSWER END>>>
|
| 31 |
+
<<<ANSWER key=K00974>>>
|
| 32 |
+
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
|
| 33 |
+
<<<ANSWER END>>>
|
| 34 |
+
<<<ANSWER key=K00827>>>
|
| 35 |
+
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
|
| 36 |
+
<<<ANSWER END>>>
|
| 37 |
+
<<<ANSWER key=K00203>>>
|
| 38 |
+
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
|
| 39 |
+
<<<ANSWER END>>>
|
| 40 |
+
<<<ANSWER key=K00565>>>
|
| 41 |
+
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
|
| 42 |
+
<<<ANSWER END>>>
|
| 43 |
+
<<<ANSWER key=K00704>>>
|
| 44 |
+
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
|
| 45 |
+
<<<ANSWER END>>>
|
| 46 |
+
<<<ANSWER key=K00358>>>
|
| 47 |
+
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
|
| 48 |
+
<<<ANSWER END>>>
|
| 49 |
+
<<<ANSWER key=K00665>>>
|
| 50 |
+
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
|
| 51 |
+
<<<ANSWER END>>>
|
| 52 |
+
<<<ANSWER key=K00586>>>
|
| 53 |
+
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
|
| 54 |
+
<<<ANSWER END>>>
|
| 55 |
+
<<<ANSWER key=K00867>>>
|
| 56 |
+
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
|
| 57 |
+
<<<ANSWER END>>>
|
| 58 |
+
<<<ANSWER key=K00879>>>
|
| 59 |
+
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
|
| 60 |
+
<<<ANSWER END>>>
|
| 61 |
+
<<<ANSWER key=K00091>>>
|
| 62 |
+
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
|
| 63 |
+
<<<ANSWER END>>>
|
| 64 |
+
<<<ANSWER key=K00989>>>
|
| 65 |
+
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
|
| 66 |
+
<<<ANSWER END>>>
|
| 67 |
+
<<<ANSWER key=K00265>>>
|
| 68 |
+
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
|
| 69 |
+
<<<ANSWER END>>>
|
| 70 |
+
<<<ANSWER key=K00207>>>
|
| 71 |
+
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
|
| 72 |
+
<<<ANSWER END>>>
|
| 73 |
+
<<<ANSWER key=K00930>>>
|
| 74 |
+
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
|
| 75 |
+
<<<ANSWER END>>>
|
| 76 |
+
<<<ANSWER key=K00031>>>
|
| 77 |
+
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
|
| 78 |
+
<<<ANSWER END>>>
|
| 79 |
+
CONTEXTBENCH_ORACLE_EOF
|
harbor/kv-store-R1000-seed43/task.toml
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[metadata]
|
| 2 |
+
author_name = "contextbench"
|
| 3 |
+
difficulty = "medium"
|
| 4 |
+
category = "context-management"
|
| 5 |
+
tags = ["context-management", "contextbench", "kv-store", "storage-offloading"]
|
| 6 |
+
contextbench_family = "kv_store"
|
| 7 |
+
contextbench_budget_tokens = 32768
|
| 8 |
+
contextbench_reserve_tokens = 2048
|
| 9 |
+
contextbench_pressure = 1.517
|
| 10 |
+
contextbench_feasible = true
|
| 11 |
+
contextbench_regime = "pressure"
|
| 12 |
+
contextbench_stream_count = 34
|
| 13 |
+
contextbench_stream_sha256 = "65ab71cafbc320b63832d42b20144faa366754e1ec9535b00056c14b30075e59"
|
| 14 |
+
instance_approx_per_value_tokens = 48
|
| 15 |
+
instance_approx_value_tokens = 48428
|
| 16 |
+
instance_n_actions = 34
|
| 17 |
+
instance_n_batches = 10
|
| 18 |
+
instance_n_get = 24
|
| 19 |
+
instance_n_set = 1000
|
| 20 |
+
instance_queries = 24
|
| 21 |
+
instance_records = 1000
|
| 22 |
+
instance_records_per_chunk = 100
|
| 23 |
+
instance_seed = 43
|
| 24 |
+
instance_task_family = "kv_store"
|
| 25 |
+
instance_value_words = 24
|
| 26 |
+
|
| 27 |
+
[verifier]
|
| 28 |
+
timeout_sec = 600.0
|
| 29 |
+
|
| 30 |
+
[agent]
|
| 31 |
+
timeout_sec = 14400.0
|
| 32 |
+
|
| 33 |
+
[environment]
|
| 34 |
+
docker_image = "python:3.12-slim"
|
| 35 |
+
workdir = "/app"
|
| 36 |
+
build_timeout_sec = 600.0
|
| 37 |
+
cpus = 1
|
| 38 |
+
memory_mb = 2048
|
| 39 |
+
storage_mb = 4096
|
| 40 |
+
|
| 41 |
+
[environment.env]
|
| 42 |
+
CONTEXTBENCH_STREAM_COUNT = "34"
|
| 43 |
+
CONTEXTBENCH_STREAM_SHA256 = "65ab71cafbc320b63832d42b20144faa366754e1ec9535b00056c14b30075e59"
|
| 44 |
+
CONTEXTBENCH_STREAM_PATH = "/app/stream/chunks.jsonl"
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench: benchmarking what an agent keeps, updates, and offloads.
|
| 2 |
+
|
| 3 |
+
Four task families stream more input than fits in an agent's context window and
|
| 4 |
+
grade what survived. Everything the agent has to do is expressed as ordinary user
|
| 5 |
+
turns, so any chat agent can be evaluated.
|
| 6 |
+
|
| 7 |
+
Quickstart::
|
| 8 |
+
|
| 9 |
+
from contextbench import run
|
| 10 |
+
from contextbench.oracle import OracleAgent # task self-check only, not a baseline
|
| 11 |
+
|
| 12 |
+
result = run(OracleAgent(instance_dir), instance_dir, budget=32768,
|
| 13 |
+
reserve=2048, out_dir="runs/kv-R1000-seed42")
|
| 14 |
+
print(result["reward"], result["terminated_by"])
|
| 15 |
+
|
| 16 |
+
The core imports nothing outside the standard library: ``tiktoken`` and
|
| 17 |
+
``harbor`` are optional extras and never required to generate, run or grade.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from .graders import grade_run, grader_for
|
| 23 |
+
from .runner import (
|
| 24 |
+
DEFAULT_SYSTEM_PROMPT,
|
| 25 |
+
ContextAgent,
|
| 26 |
+
Instance,
|
| 27 |
+
instruction_for,
|
| 28 |
+
load_instance,
|
| 29 |
+
run,
|
| 30 |
+
)
|
| 31 |
+
from .stream import ADVANCE_MARKER, SUBMIT_MARKER, TERMINATED_BY, Op, render_op
|
| 32 |
+
from .tokens import count_tokens, record_snapshot
|
| 33 |
+
|
| 34 |
+
__version__ = "0.1.0"
|
| 35 |
+
|
| 36 |
+
FAMILIES = ("kv_store", "log_triage", "needle_retention", "sudoku_sketchpad")
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"ADVANCE_MARKER",
|
| 40 |
+
"ContextAgent",
|
| 41 |
+
"DEFAULT_SYSTEM_PROMPT",
|
| 42 |
+
"FAMILIES",
|
| 43 |
+
"Instance",
|
| 44 |
+
"Op",
|
| 45 |
+
"SUBMIT_MARKER",
|
| 46 |
+
"TERMINATED_BY",
|
| 47 |
+
"__version__",
|
| 48 |
+
"count_tokens",
|
| 49 |
+
"grade_run",
|
| 50 |
+
"grader_for",
|
| 51 |
+
"instruction_for",
|
| 52 |
+
"load_instance",
|
| 53 |
+
"record_snapshot",
|
| 54 |
+
"render_op",
|
| 55 |
+
"run",
|
| 56 |
+
]
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/__init__.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench graders: one per task family, plus the shared context readers.
|
| 2 |
+
|
| 3 |
+
Every grader takes a run directory and the parsed ``gold.json`` and returns a
|
| 4 |
+
reward dict carrying ``graded_from`` -- the context source it actually read.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from .base import (
|
| 13 |
+
ContextSource,
|
| 14 |
+
Grader,
|
| 15 |
+
read_context,
|
| 16 |
+
read_final_report,
|
| 17 |
+
read_snapshots,
|
| 18 |
+
read_trajectory,
|
| 19 |
+
)
|
| 20 |
+
from .kv import KVStoreGrader
|
| 21 |
+
from .log import LogTriageGrader
|
| 22 |
+
from .needle import NeedleRetentionGrader
|
| 23 |
+
from .sudoku import SudokuSketchpadGrader
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"ContextSource",
|
| 27 |
+
"Grader",
|
| 28 |
+
"GRADERS",
|
| 29 |
+
"KVStoreGrader",
|
| 30 |
+
"LogTriageGrader",
|
| 31 |
+
"NeedleRetentionGrader",
|
| 32 |
+
"SudokuSketchpadGrader",
|
| 33 |
+
"grade_run",
|
| 34 |
+
"grader_for",
|
| 35 |
+
"read_context",
|
| 36 |
+
"read_final_report",
|
| 37 |
+
"read_snapshots",
|
| 38 |
+
"read_trajectory",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
GRADERS: dict[str, type[Grader]] = {
|
| 42 |
+
"kv_store": KVStoreGrader,
|
| 43 |
+
"log_triage": LogTriageGrader,
|
| 44 |
+
"needle_retention": NeedleRetentionGrader,
|
| 45 |
+
"sudoku_sketchpad": SudokuSketchpadGrader,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def grader_for(family: str) -> Grader:
|
| 50 |
+
"""The grader instance for one family."""
|
| 51 |
+
try:
|
| 52 |
+
return GRADERS[family]()
|
| 53 |
+
except KeyError:
|
| 54 |
+
raise KeyError(
|
| 55 |
+
f"no grader for family {family!r}; known: {', '.join(sorted(GRADERS))}"
|
| 56 |
+
) from None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def grade_run(run_dir: Path | str, gold: dict | Path | str) -> dict:
|
| 60 |
+
"""Grade a run directory against a gold object or a ``gold.json`` path.
|
| 61 |
+
|
| 62 |
+
The family comes from ``gold["meta"]["task_family"]``, so a grader can never be
|
| 63 |
+
pointed at the wrong family's instance by accident.
|
| 64 |
+
"""
|
| 65 |
+
if not isinstance(gold, dict):
|
| 66 |
+
gold = json.loads(Path(gold).read_text(encoding="utf-8"))
|
| 67 |
+
family = (gold.get("meta") or {}).get("task_family")
|
| 68 |
+
if not family:
|
| 69 |
+
raise ValueError("gold.meta['task_family'] is missing: cannot pick a grader")
|
| 70 |
+
return grader_for(family).grade(run_dir, gold)
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/base.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader plumbing: the three ways a run's context is read back.
|
| 2 |
+
|
| 3 |
+
Every ContextBench reward is computed out of the agent's own messages, never off
|
| 4 |
+
disk. Three readers supply those messages, in order of preference:
|
| 5 |
+
|
| 6 |
+
1. **snapshots** -- ``context_snapshots/turn-*.json``, one per turn. This is the
|
| 7 |
+
paper metric: an agent that parks content outside its context and surfaces a
|
| 8 |
+
value only transiently still has that value captured in the snapshot of the turn
|
| 9 |
+
where it appeared.
|
| 10 |
+
2. **trajectory** -- an ATIF ``trajectory.json``: a flat list of chat messages that
|
| 11 |
+
context edits mutate in place, so the final file is exactly the retained
|
| 12 |
+
context. One frame, not a per-turn series.
|
| 13 |
+
3. **final report** -- the closing text of a run whose agent cannot expose its
|
| 14 |
+
context at all.
|
| 15 |
+
|
| 16 |
+
Which reader ran is recorded as ``graded_from`` in every reward dict, so a number
|
| 17 |
+
is never comparable by accident across sources.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import re
|
| 24 |
+
from dataclasses import dataclass, field
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Sequence
|
| 27 |
+
|
| 28 |
+
from ..tokens import SNAPSHOT_DIRNAME, snapshot_paths
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"ContextSource",
|
| 32 |
+
"atif_messages",
|
| 33 |
+
"Grader",
|
| 34 |
+
"find_snapshots_dir",
|
| 35 |
+
"find_trajectory",
|
| 36 |
+
"messages_text",
|
| 37 |
+
"normalize",
|
| 38 |
+
"read_context",
|
| 39 |
+
"read_final_report",
|
| 40 |
+
"read_snapshots",
|
| 41 |
+
"read_trajectory",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
#: Filenames a run may use for its closing report, most specific first.
|
| 45 |
+
FINAL_REPORT_NAMES = (
|
| 46 |
+
"final_report.txt",
|
| 47 |
+
"final_report.md",
|
| 48 |
+
"final_report.json",
|
| 49 |
+
"report.txt",
|
| 50 |
+
"report.md",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def normalize(text: str) -> str:
|
| 55 |
+
"""Collapse whitespace, so a reward never turns on reflow or indentation."""
|
| 56 |
+
return re.sub(r"\s+", " ", text.strip())
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _decoded_tool_json(content: str) -> str | None:
|
| 60 |
+
"""The string fields of a tool result that is one JSON object, else ``None``.
|
| 61 |
+
|
| 62 |
+
Some harnesses render a command's output as a JSON object (``{"returncode": 0,
|
| 63 |
+
"output": "..."}``), which escapes ``<`` and ``>`` and turns newlines into
|
| 64 |
+
``\\n``. The model reads the decoded text; so does the grader.
|
| 65 |
+
"""
|
| 66 |
+
text = content.strip()
|
| 67 |
+
if not (text.startswith("{") and text.endswith("}")):
|
| 68 |
+
return None
|
| 69 |
+
try:
|
| 70 |
+
obj = json.loads(text)
|
| 71 |
+
except Exception:
|
| 72 |
+
return None
|
| 73 |
+
if not isinstance(obj, dict):
|
| 74 |
+
return None
|
| 75 |
+
parts = [v for v in obj.values() if isinstance(v, str)]
|
| 76 |
+
return "\n".join(parts) if parts else None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def messages_text(messages: Sequence[Any] | None) -> str:
|
| 80 |
+
"""Flatten a message list into the text the grader scans."""
|
| 81 |
+
texts: list[str] = []
|
| 82 |
+
for msg in messages or []:
|
| 83 |
+
content = msg.get("content") if isinstance(msg, dict) else msg
|
| 84 |
+
if isinstance(content, str):
|
| 85 |
+
if isinstance(msg, dict) and msg.get("role") == "tool":
|
| 86 |
+
decoded = _decoded_tool_json(content)
|
| 87 |
+
if decoded is not None:
|
| 88 |
+
content = decoded
|
| 89 |
+
texts.append(content)
|
| 90 |
+
elif isinstance(content, list):
|
| 91 |
+
for item in content:
|
| 92 |
+
texts.append(
|
| 93 |
+
str(item.get("text") or item.get("content") or "")
|
| 94 |
+
if isinstance(item, dict)
|
| 95 |
+
else str(item)
|
| 96 |
+
)
|
| 97 |
+
return "\n".join(texts)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ----------------------------------------------------------------- locating files
|
| 101 |
+
def _candidate_dirs(run_dir: Path) -> list[Path]:
|
| 102 |
+
"""``run_dir`` itself and the usual agent subdirectories, in preference order."""
|
| 103 |
+
return [run_dir, run_dir / "agent", run_dir / "logs", run_dir / "logs" / "agent"]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def find_snapshots_dir(run_dir: Path | str) -> Path | None:
|
| 107 |
+
"""The run's ``context_snapshots`` directory, if it has one."""
|
| 108 |
+
run_dir = Path(run_dir)
|
| 109 |
+
for cand in _candidate_dirs(run_dir):
|
| 110 |
+
if (cand / SNAPSHOT_DIRNAME).is_dir():
|
| 111 |
+
return cand / SNAPSHOT_DIRNAME
|
| 112 |
+
hits = sorted(run_dir.glob(f"**/{SNAPSHOT_DIRNAME}"))
|
| 113 |
+
return hits[0] if hits else None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def find_trajectory(run_dir: Path | str) -> Path | None:
|
| 117 |
+
"""The run's ATIF ``trajectory.json``, if it has one."""
|
| 118 |
+
run_dir = Path(run_dir)
|
| 119 |
+
for cand in _candidate_dirs(run_dir):
|
| 120 |
+
if (cand / "trajectory.json").is_file():
|
| 121 |
+
return cand / "trajectory.json"
|
| 122 |
+
hits = sorted(run_dir.glob("**/trajectory.json"))
|
| 123 |
+
return hits[0] if hits else None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ------------------------------------------------------------------- the readers
|
| 127 |
+
@dataclass
|
| 128 |
+
class ContextSource:
|
| 129 |
+
"""The messages a grader scores, and where they came from."""
|
| 130 |
+
|
| 131 |
+
graded_from: str
|
| 132 |
+
#: One message list per turn. A trajectory or a report yields a single frame.
|
| 133 |
+
frames: list[list[Any]] = field(default_factory=list)
|
| 134 |
+
#: Per-turn context size, when the source records it.
|
| 135 |
+
tokens: list[int] = field(default_factory=list)
|
| 136 |
+
n_snapshots: int = 0
|
| 137 |
+
|
| 138 |
+
@property
|
| 139 |
+
def final_frame(self) -> list[Any]:
|
| 140 |
+
return self.frames[-1] if self.frames else []
|
| 141 |
+
|
| 142 |
+
def texts(self) -> list[str]:
|
| 143 |
+
return [messages_text(frame) for frame in self.frames]
|
| 144 |
+
|
| 145 |
+
def all_text(self) -> str:
|
| 146 |
+
return "\n".join(self.texts())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def read_snapshots(run_dir: Path | str) -> ContextSource | None:
|
| 150 |
+
"""Read ``context_snapshots/turn-*.json`` as one frame per turn."""
|
| 151 |
+
snap_dir = find_snapshots_dir(run_dir)
|
| 152 |
+
if snap_dir is None:
|
| 153 |
+
return None
|
| 154 |
+
frames: list[list[Any]] = []
|
| 155 |
+
tokens: list[int] = []
|
| 156 |
+
n = 0
|
| 157 |
+
for path in snapshot_paths(snap_dir.parent):
|
| 158 |
+
try:
|
| 159 |
+
obj = json.loads(path.read_text(encoding="utf-8"))
|
| 160 |
+
except Exception:
|
| 161 |
+
continue
|
| 162 |
+
n += 1
|
| 163 |
+
if isinstance(obj.get("tokens"), (int, float)):
|
| 164 |
+
tokens.append(int(obj["tokens"]))
|
| 165 |
+
frames.append(obj.get("messages") or [])
|
| 166 |
+
if n == 0:
|
| 167 |
+
return None
|
| 168 |
+
return ContextSource("snapshots", frames, tokens, n)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def read_trajectory(run_dir: Path | str) -> ContextSource | None:
|
| 172 |
+
"""Read an ATIF ``trajectory.json`` as a single frame."""
|
| 173 |
+
path = find_trajectory(run_dir)
|
| 174 |
+
if path is None:
|
| 175 |
+
return None
|
| 176 |
+
try:
|
| 177 |
+
messages = json.loads(path.read_text(encoding="utf-8"))
|
| 178 |
+
except Exception:
|
| 179 |
+
return None
|
| 180 |
+
if isinstance(messages, dict):
|
| 181 |
+
if isinstance(messages.get("steps"), list):
|
| 182 |
+
messages = atif_messages(messages["steps"])
|
| 183 |
+
else:
|
| 184 |
+
messages = messages.get("messages") or messages.get("trajectory") or []
|
| 185 |
+
if not isinstance(messages, list):
|
| 186 |
+
return None
|
| 187 |
+
return ContextSource("trajectory", [messages], [], 0)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _part_text(content: Any) -> str:
|
| 191 |
+
if isinstance(content, str):
|
| 192 |
+
return content
|
| 193 |
+
if isinstance(content, list):
|
| 194 |
+
return "\n".join(
|
| 195 |
+
str(p.get("text") or "") if isinstance(p, dict) else str(p) for p in content
|
| 196 |
+
)
|
| 197 |
+
return "" if content is None else str(content)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def atif_messages(steps: Sequence[Any]) -> list[dict[str, Any]]:
|
| 201 |
+
"""Flatten ATIF ``steps`` into chat messages.
|
| 202 |
+
|
| 203 |
+
``user`` and ``system`` steps become messages of that role; an ``agent`` step
|
| 204 |
+
becomes an ``assistant`` message followed by one ``tool`` message per
|
| 205 |
+
observation result. The flattening is the full history the harness recorded,
|
| 206 |
+
which for a harness that compacts is more than it retained.
|
| 207 |
+
"""
|
| 208 |
+
out: list[dict[str, Any]] = []
|
| 209 |
+
for step in steps or []:
|
| 210 |
+
if not isinstance(step, dict):
|
| 211 |
+
continue
|
| 212 |
+
source = step.get("source")
|
| 213 |
+
text = _part_text(step.get("message"))
|
| 214 |
+
if source in ("user", "system"):
|
| 215 |
+
out.append({"role": source, "content": text})
|
| 216 |
+
continue
|
| 217 |
+
out.append({"role": "assistant", "content": text})
|
| 218 |
+
observation = step.get("observation") or {}
|
| 219 |
+
for result in observation.get("results") or []:
|
| 220 |
+
if isinstance(result, dict) and result.get("content") is not None:
|
| 221 |
+
out.append({"role": "tool", "content": _part_text(result["content"])})
|
| 222 |
+
return out
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def read_final_report(run_dir: Path | str) -> str:
|
| 226 |
+
"""The run's closing report text.
|
| 227 |
+
|
| 228 |
+
A file named like ``final_report.txt`` wins; otherwise the assistant messages
|
| 229 |
+
of a trajectory are concatenated, which is what an agent that only talks leaves
|
| 230 |
+
behind.
|
| 231 |
+
"""
|
| 232 |
+
run_dir = Path(run_dir)
|
| 233 |
+
for cand in _candidate_dirs(run_dir):
|
| 234 |
+
for name in FINAL_REPORT_NAMES:
|
| 235 |
+
path = cand / name
|
| 236 |
+
if path.is_file():
|
| 237 |
+
return path.read_text(encoding="utf-8")
|
| 238 |
+
source = read_trajectory(run_dir)
|
| 239 |
+
if source is None:
|
| 240 |
+
return ""
|
| 241 |
+
assistant = [
|
| 242 |
+
m
|
| 243 |
+
for m in source.final_frame
|
| 244 |
+
if isinstance(m, dict) and m.get("role") == "assistant"
|
| 245 |
+
]
|
| 246 |
+
return messages_text(assistant or source.final_frame)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def read_context(run_dir: Path | str) -> ContextSource:
|
| 250 |
+
"""The best available source for ``run_dir``.
|
| 251 |
+
|
| 252 |
+
Snapshots first (the paper metric), then the ATIF trajectory, then the final
|
| 253 |
+
report. An empty :class:`ContextSource` with ``graded_from="none"`` means the
|
| 254 |
+
run left nothing gradeable behind, which a grader reports as invalid rather
|
| 255 |
+
than as a zero.
|
| 256 |
+
"""
|
| 257 |
+
for reader in (read_snapshots, read_trajectory):
|
| 258 |
+
source = reader(run_dir)
|
| 259 |
+
if source is not None:
|
| 260 |
+
return source
|
| 261 |
+
report = read_final_report(run_dir)
|
| 262 |
+
if report:
|
| 263 |
+
return ContextSource(
|
| 264 |
+
"final_report", [[{"role": "assistant", "content": report}]], [], 0
|
| 265 |
+
)
|
| 266 |
+
return ContextSource("none", [], [], 0)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ---------------------------------------------------------------------- base class
|
| 270 |
+
class Grader:
|
| 271 |
+
"""A ContextBench grader.
|
| 272 |
+
|
| 273 |
+
Subclasses implement :meth:`grade`, which takes a run directory and the parsed
|
| 274 |
+
``gold.json`` and returns a reward dict. Every returned dict carries
|
| 275 |
+
``graded_from`` and ``grader_valid``.
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
family: str = ""
|
| 279 |
+
#: The reward name a caller should read as "the score".
|
| 280 |
+
primary: str = "reward"
|
| 281 |
+
|
| 282 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 283 |
+
raise NotImplementedError
|
| 284 |
+
|
| 285 |
+
def grade_path(self, run_dir: Path | str, gold_path: Path | str) -> dict:
|
| 286 |
+
gold = json.loads(Path(gold_path).read_text(encoding="utf-8"))
|
| 287 |
+
return self.grade(run_dir, gold)
|
| 288 |
+
|
| 289 |
+
# -- helpers shared by the concrete graders --------------------------------
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _token_stats(tokens: list[int]) -> dict[str, float]:
|
| 292 |
+
return {
|
| 293 |
+
"agent_peak_tokens": float(max(tokens)) if tokens else 0.0,
|
| 294 |
+
"agent_mean_tokens": float(sum(tokens) / len(tokens)) if tokens else 0.0,
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
@staticmethod
|
| 298 |
+
def _invalid(graded_from: str, why: str) -> dict:
|
| 299 |
+
"""A grade that could not be computed: never reported as a zero score."""
|
| 300 |
+
return {
|
| 301 |
+
"reward": 0.0,
|
| 302 |
+
"grader_valid": 0.0,
|
| 303 |
+
"graded_from": graded_from,
|
| 304 |
+
"grader_note": why,
|
| 305 |
+
}
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/kv.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Key-Value Store*: process-graded, ANSWER-block based.
|
| 2 |
+
|
| 3 |
+
The agent answers each ``GET <key>`` by emitting an ANSWER block::
|
| 4 |
+
|
| 5 |
+
<<<ANSWER key=K00007>>>
|
| 6 |
+
<the value it stored for K00007>
|
| 7 |
+
<<<ANSWER END>>>
|
| 8 |
+
|
| 9 |
+
Every per-turn context frame is scanned, all ANSWER blocks are collected as
|
| 10 |
+
``key -> {value strings the agent ever produced}``, and the score is the fraction
|
| 11 |
+
of gold GET queries whose correct value was produced.
|
| 12 |
+
|
| 13 |
+
Reading the whole per-turn series rather than the final context is what makes the
|
| 14 |
+
mechanisms comparable on one number: an agent that parks values outside its context
|
| 15 |
+
and surfaces the queried one only transiently has the value in the snapshot of the
|
| 16 |
+
GET turn, but not in its final context.
|
| 17 |
+
|
| 18 |
+
Rewards:
|
| 19 |
+
|
| 20 |
+
* ``reward`` -- fraction of GET queries answered with the correct value;
|
| 21 |
+
* ``reward_attempted`` -- of the GETs answered at all, the fraction correct;
|
| 22 |
+
* ``n_answered`` -- how many distinct gold GETs got any ANSWER block;
|
| 23 |
+
* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import re
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
from .base import ContextSource, Grader, messages_text, normalize, read_context
|
| 32 |
+
|
| 33 |
+
__all__ = ["KVStoreGrader", "ANSWER_RE"]
|
| 34 |
+
|
| 35 |
+
#: ``<<<ANSWER key=K00007>>> ... <<<ANSWER END>>>``; the key may carry spaces.
|
| 36 |
+
ANSWER_RE = re.compile(
|
| 37 |
+
r"<<<\s*ANSWER\s+key\s*=\s*([^\s>]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>",
|
| 38 |
+
re.DOTALL | re.IGNORECASE,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class KVStoreGrader(Grader):
|
| 43 |
+
family = "kv_store"
|
| 44 |
+
|
| 45 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 46 |
+
queries = gold.get("queries") or []
|
| 47 |
+
total = len(queries)
|
| 48 |
+
source = read_context(run_dir)
|
| 49 |
+
if total == 0:
|
| 50 |
+
return self._invalid(source.graded_from, "gold has no queries")
|
| 51 |
+
if source.graded_from == "none":
|
| 52 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 53 |
+
|
| 54 |
+
answers = self._collect(source)
|
| 55 |
+
correct = 0
|
| 56 |
+
answered = 0
|
| 57 |
+
for q in queries:
|
| 58 |
+
key = normalize(str(q["key"]))
|
| 59 |
+
want = normalize(str(q["value"]))
|
| 60 |
+
seen = answers.get(key)
|
| 61 |
+
if seen:
|
| 62 |
+
answered += 1
|
| 63 |
+
# Tolerate the value being embedded in a longer answer line.
|
| 64 |
+
if want in seen or any(want in s for s in seen):
|
| 65 |
+
correct += 1
|
| 66 |
+
|
| 67 |
+
result = {
|
| 68 |
+
"reward": correct / total,
|
| 69 |
+
"reward_attempted": (correct / answered) if answered else 0.0,
|
| 70 |
+
"n_answered": float(answered),
|
| 71 |
+
"matched": float(correct),
|
| 72 |
+
"total": float(total),
|
| 73 |
+
"n_snapshots": float(source.n_snapshots),
|
| 74 |
+
"graded_from": source.graded_from,
|
| 75 |
+
"grader_valid": 1.0,
|
| 76 |
+
}
|
| 77 |
+
result.update(self._token_stats(source.tokens))
|
| 78 |
+
return result
|
| 79 |
+
|
| 80 |
+
@staticmethod
|
| 81 |
+
def _collect(source: ContextSource) -> dict[str, set[str]]:
|
| 82 |
+
"""``key -> {normalized answer strings}`` across every frame."""
|
| 83 |
+
answers: dict[str, set[str]] = {}
|
| 84 |
+
for frame in source.frames:
|
| 85 |
+
for key, val in ANSWER_RE.findall(messages_text(frame)):
|
| 86 |
+
answers.setdefault(normalize(key), set()).add(normalize(val))
|
| 87 |
+
return answers
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/log.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Incident Log Triage*: process-graded, ANSWER-block based.
|
| 2 |
+
|
| 3 |
+
The agent answers each ``QUERY <n>`` by emitting an ANSWER block::
|
| 4 |
+
|
| 5 |
+
<<<ANSWER qid=0>>>
|
| 6 |
+
timeout retry connection refused #ab12cd34 (lookup)
|
| 7 |
+
<<<ANSWER END>>>
|
| 8 |
+
|
| 9 |
+
Every per-turn context frame is scanned, all ANSWER blocks are collected as
|
| 10 |
+
``qid -> {answer strings}``, and the score is the fraction of gold queries answered
|
| 11 |
+
correctly. Matching is per type:
|
| 12 |
+
|
| 13 |
+
* ``lookup`` -- the exact message string must appear in the agent's answer, as a
|
| 14 |
+
whitespace-normalized substring, so adding a label does not cost a point;
|
| 15 |
+
* ``count`` -- the integer must appear as a standalone token in the answer.
|
| 16 |
+
|
| 17 |
+
A gold message ends in a random ``#<hex>`` uniqueness tag that a model treats as a
|
| 18 |
+
noise id and usually drops. Lookup grading measures retrieval -- did the agent
|
| 19 |
+
surface the right log line's message -- not whether it parrots that tag, so a
|
| 20 |
+
trailing tag is stripped before matching.
|
| 21 |
+
|
| 22 |
+
Rewards: ``reward``, ``reward_lookup`` / ``reward_count`` per type,
|
| 23 |
+
``reward_attempted`` over the queries answered at all, and the per-turn context size.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import re
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
from .base import ContextSource, Grader, messages_text, normalize, read_context
|
| 32 |
+
|
| 33 |
+
__all__ = ["LogTriageGrader", "ANSWER_RE"]
|
| 34 |
+
|
| 35 |
+
ANSWER_RE = re.compile(
|
| 36 |
+
r"<<<\s*ANSWER\s+qid\s*=\s*([0-9]+)\s*>>>(.*?)<<<\s*ANSWER\s+END\s*>>>",
|
| 37 |
+
re.DOTALL | re.IGNORECASE,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
#: The trailing uniqueness tag of a gold message.
|
| 41 |
+
_TAG_RE = re.compile(r"\s*#[0-9a-f]+\s*$")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _count_correct(want: str, answers: set[str]) -> bool:
|
| 45 |
+
"""A count is correct when the integer appears as a standalone token."""
|
| 46 |
+
pat = re.compile(rf"(?<!\d){re.escape(want)}(?!\d)")
|
| 47 |
+
return any(pat.search(a) for a in answers)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _lookup_correct(want: str, answers: set[str]) -> bool:
|
| 51 |
+
core = _TAG_RE.sub("", want).strip()
|
| 52 |
+
if not core:
|
| 53 |
+
return False
|
| 54 |
+
return any(core in a for a in answers)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class LogTriageGrader(Grader):
|
| 58 |
+
family = "log_triage"
|
| 59 |
+
|
| 60 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 61 |
+
queries = gold.get("queries") or []
|
| 62 |
+
total = len(queries)
|
| 63 |
+
source = read_context(run_dir)
|
| 64 |
+
if total == 0:
|
| 65 |
+
return self._invalid(source.graded_from, "gold has no queries")
|
| 66 |
+
if source.graded_from == "none":
|
| 67 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 68 |
+
|
| 69 |
+
answers = self._collect(source)
|
| 70 |
+
correct = answered = 0
|
| 71 |
+
by_type_total: dict[str, int] = {"lookup": 0, "count": 0}
|
| 72 |
+
by_type_correct: dict[str, int] = {"lookup": 0, "count": 0}
|
| 73 |
+
for q in queries:
|
| 74 |
+
qid = str(q["qid"])
|
| 75 |
+
qtype = q.get("type", "lookup")
|
| 76 |
+
want = normalize(str(q["answer"]))
|
| 77 |
+
by_type_total[qtype] = by_type_total.get(qtype, 0) + 1
|
| 78 |
+
seen = answers.get(qid)
|
| 79 |
+
if not seen:
|
| 80 |
+
continue
|
| 81 |
+
answered += 1
|
| 82 |
+
ok = (
|
| 83 |
+
_count_correct(want, seen)
|
| 84 |
+
if qtype == "count"
|
| 85 |
+
else _lookup_correct(want, seen)
|
| 86 |
+
)
|
| 87 |
+
if ok:
|
| 88 |
+
correct += 1
|
| 89 |
+
by_type_correct[qtype] = by_type_correct.get(qtype, 0) + 1
|
| 90 |
+
|
| 91 |
+
def _rate(t: str) -> float:
|
| 92 |
+
n = by_type_total.get(t, 0)
|
| 93 |
+
return (by_type_correct.get(t, 0) / n) if n else 0.0
|
| 94 |
+
|
| 95 |
+
result = {
|
| 96 |
+
"reward": correct / total,
|
| 97 |
+
"reward_lookup": _rate("lookup"),
|
| 98 |
+
"reward_count": _rate("count"),
|
| 99 |
+
"reward_attempted": (correct / answered) if answered else 0.0,
|
| 100 |
+
"n_answered": float(answered),
|
| 101 |
+
"matched": float(correct),
|
| 102 |
+
"total": float(total),
|
| 103 |
+
"n_snapshots": float(source.n_snapshots),
|
| 104 |
+
"graded_from": source.graded_from,
|
| 105 |
+
"grader_valid": 1.0,
|
| 106 |
+
}
|
| 107 |
+
result.update(self._token_stats(source.tokens))
|
| 108 |
+
return result
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def _collect(source: ContextSource) -> dict[str, set[str]]:
|
| 112 |
+
answers: dict[str, set[str]] = {}
|
| 113 |
+
for frame in source.frames:
|
| 114 |
+
for qid, val in ANSWER_RE.findall(messages_text(frame)):
|
| 115 |
+
answers.setdefault(qid.strip(), set()).add(normalize(val))
|
| 116 |
+
return answers
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/needle.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Needle Retention*: what is still in the context at the end.
|
| 2 |
+
|
| 3 |
+
The reward is the fraction of gold needle lines present verbatim in the agent's
|
| 4 |
+
final retained context. Two modes, and which one ran is recorded as ``mode`` and
|
| 5 |
+
``graded_from``:
|
| 6 |
+
|
| 7 |
+
* ``final_context`` (the paper metric) -- the last per-turn snapshot, or an ATIF
|
| 8 |
+
``trajectory.json``, is the retained context: context edits mutate that message
|
| 9 |
+
list in place, so the final state is exactly what the agent kept.
|
| 10 |
+
* ``final_report`` -- for an agent that cannot expose its context at all, the kept
|
| 11 |
+
lines are read from between ``<<<NEEDLES BEGIN>>>`` and ``<<<NEEDLES END>>>`` in
|
| 12 |
+
its closing report. A report is a weaker witness than a context: the agent could
|
| 13 |
+
in principle re-read the lines from somewhere else, so the two modes are not
|
| 14 |
+
interchangeable and are never averaged together.
|
| 15 |
+
|
| 16 |
+
Rewards: ``reward``, ``matched``, ``total``, ``mode``, ``graded_from``.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import re
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
from .base import (
|
| 25 |
+
Grader,
|
| 26 |
+
messages_text,
|
| 27 |
+
normalize,
|
| 28 |
+
read_final_report,
|
| 29 |
+
read_snapshots,
|
| 30 |
+
read_trajectory,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
__all__ = ["NeedleRetentionGrader", "NEEDLES_BLOCK_RE", "extract_reported_needles"]
|
| 34 |
+
|
| 35 |
+
#: The block an agent without context access prints instead.
|
| 36 |
+
NEEDLES_BLOCK_RE = re.compile(
|
| 37 |
+
r"<<<\s*NEEDLES\s+BEGIN\s*>>>(.*?)<<<\s*NEEDLES\s+END\s*>>>",
|
| 38 |
+
re.DOTALL | re.IGNORECASE,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def extract_reported_needles(text: str) -> set[str]:
|
| 43 |
+
"""The normalized lines inside every ``NEEDLES`` block of ``text``."""
|
| 44 |
+
lines: set[str] = set()
|
| 45 |
+
for block in NEEDLES_BLOCK_RE.findall(text or ""):
|
| 46 |
+
for line in block.splitlines():
|
| 47 |
+
if line.strip():
|
| 48 |
+
lines.add(normalize(line))
|
| 49 |
+
return lines
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class NeedleRetentionGrader(Grader):
|
| 53 |
+
family = "needle_retention"
|
| 54 |
+
|
| 55 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 56 |
+
gold_lines = {normalize(s) for s in gold.get("answer_lines") or []}
|
| 57 |
+
total = len(gold_lines)
|
| 58 |
+
|
| 59 |
+
snapshots = read_snapshots(run_dir)
|
| 60 |
+
if snapshots is not None:
|
| 61 |
+
present = self._context_lines(messages_text(snapshots.final_frame))
|
| 62 |
+
return self._result(
|
| 63 |
+
gold_lines, present, total, "final_context", "snapshots",
|
| 64 |
+
snapshots.n_snapshots, snapshots.tokens,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
trajectory = read_trajectory(run_dir)
|
| 68 |
+
if trajectory is not None:
|
| 69 |
+
present = self._context_lines(messages_text(trajectory.final_frame))
|
| 70 |
+
return self._result(
|
| 71 |
+
gold_lines, present, total, "final_context", "trajectory", 0, []
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
report = read_final_report(run_dir)
|
| 75 |
+
if report:
|
| 76 |
+
return self._result(
|
| 77 |
+
gold_lines, extract_reported_needles(report), total,
|
| 78 |
+
"final_report", "final_report", 0, [],
|
| 79 |
+
)
|
| 80 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 81 |
+
|
| 82 |
+
@staticmethod
|
| 83 |
+
def _context_lines(text: str) -> set[str]:
|
| 84 |
+
return {normalize(line) for line in text.splitlines() if line.strip()}
|
| 85 |
+
|
| 86 |
+
def _result(
|
| 87 |
+
self,
|
| 88 |
+
gold_lines: set[str],
|
| 89 |
+
present: set[str],
|
| 90 |
+
total: int,
|
| 91 |
+
mode: str,
|
| 92 |
+
graded_from: str,
|
| 93 |
+
n_snapshots: int,
|
| 94 |
+
tokens: list[int],
|
| 95 |
+
) -> dict:
|
| 96 |
+
if total == 0:
|
| 97 |
+
return self._invalid(graded_from, "gold has no answer_lines")
|
| 98 |
+
matched = gold_lines & present
|
| 99 |
+
result = {
|
| 100 |
+
"reward": len(matched) / total,
|
| 101 |
+
"matched": float(len(matched)),
|
| 102 |
+
"total": float(total),
|
| 103 |
+
"mode": mode,
|
| 104 |
+
"n_snapshots": float(n_snapshots),
|
| 105 |
+
"graded_from": graded_from,
|
| 106 |
+
"grader_valid": 1.0,
|
| 107 |
+
}
|
| 108 |
+
result.update(self._token_stats(tokens))
|
| 109 |
+
return result
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/graders/sudoku.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grader for *Sudoku Sketchpad*: versioned, process-graded.
|
| 2 |
+
|
| 3 |
+
Each move advances the sketchpad to a new version ``v`` with a correct grid ``G_v``
|
| 4 |
+
(a cell-to-value map). The agent labels every panel it displays with a ``VERSION``
|
| 5 |
+
line. Every versioned panel the agent ever displayed is recovered from the per-turn
|
| 6 |
+
context frames, and for each gold version the grader checks whether the agent
|
| 7 |
+
displayed that exact grid.
|
| 8 |
+
|
| 9 |
+
This makes the styles comparable on one number. An agent that edits its context in
|
| 10 |
+
place bumps the version and changes the affected cells, so one panel lives in
|
| 11 |
+
context and stays small; each version appears transiently across the turns. An
|
| 12 |
+
append-only agent writes a brand-new full panel per move, so all versions
|
| 13 |
+
accumulate and the context grows by a panel per move. Both score equally on
|
| 14 |
+
correctness while every version is right: the benefit of editing shows up in the
|
| 15 |
+
per-turn context size, and in correctness holding at large horizons where an
|
| 16 |
+
append-only context overflows the budget.
|
| 17 |
+
|
| 18 |
+
Rewards:
|
| 19 |
+
|
| 20 |
+
* ``reward`` -- ``reward_content``, the fraction of gold versions whose exact grid
|
| 21 |
+
the agent displayed. The cells are what "exact match of the gold sketchpad
|
| 22 |
+
throughout the process" means; the version label is a secondary bookkeeping check.
|
| 23 |
+
* ``reward_versioned`` -- the same, but the panel's version label must match too;
|
| 24 |
+
* ``reward_cell`` -- mean over versions of the best per-cell accuracy seen;
|
| 25 |
+
* ``reward_final_em`` / ``reward_final_cell`` -- the final displayed grid against
|
| 26 |
+
the final gold grid;
|
| 27 |
+
* ``agent_peak_tokens`` / ``agent_mean_tokens`` -- per-turn context size.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import re
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Iterator
|
| 35 |
+
|
| 36 |
+
from .base import ContextSource, Grader, messages_text, read_context
|
| 37 |
+
|
| 38 |
+
__all__ = ["SudokuSketchpadGrader", "SYMBOLS"]
|
| 39 |
+
|
| 40 |
+
#: Single-character value symbols; must match the generator.
|
| 41 |
+
SYMBOLS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
| 42 |
+
|
| 43 |
+
_TUPLE_RE = re.compile(r"\(\s*(\d+)\s*,\s*(\d+)\s*,\s*([^)]*?)\s*\)")
|
| 44 |
+
_VERSION_RE = re.compile(r"VERSION:\s*(\d+)")
|
| 45 |
+
|
| 46 |
+
Cells = dict[str, str]
|
| 47 |
+
Panel = tuple[tuple[str, str], ...]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _norm_value(raw: str) -> str:
|
| 51 |
+
raw = raw.strip()
|
| 52 |
+
if raw in (".", ""):
|
| 53 |
+
return "."
|
| 54 |
+
if raw.startswith("="):
|
| 55 |
+
return "=" + raw[1:].strip()
|
| 56 |
+
return raw
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _parse_panel_body(body: list[str], side: int) -> Cells:
|
| 60 |
+
"""Parse one board body into ``{"rXcY": value}``.
|
| 61 |
+
|
| 62 |
+
Position-independent: every cell self-locates through its ``(r,c,v)`` tuple and
|
| 63 |
+
a later occurrence wins, so the parse is robust to spacing and to the same tuple
|
| 64 |
+
text appearing elsewhere in the block.
|
| 65 |
+
"""
|
| 66 |
+
cells: Cells = {}
|
| 67 |
+
for m in _TUPLE_RE.finditer("\n".join(body)):
|
| 68 |
+
r, c, v = int(m.group(1)), int(m.group(2)), m.group(3).strip()
|
| 69 |
+
if not (1 <= r <= side and 1 <= c <= side):
|
| 70 |
+
continue
|
| 71 |
+
if v in (".", ""):
|
| 72 |
+
cells[f"r{r}c{c}"] = "."
|
| 73 |
+
elif v in SYMBOLS[:side]:
|
| 74 |
+
cells[f"r{r}c{c}"] = f"={SYMBOLS.index(v) + 1}"
|
| 75 |
+
return cells
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _parse_blocks(text: str, side: int) -> list[tuple[int | None, Cells]]:
|
| 79 |
+
"""Every sketchpad block in ``text`` as ``(version, cells)``.
|
| 80 |
+
|
| 81 |
+
The version comes from the block's ``VERSION:`` line, or is ``None``.
|
| 82 |
+
"""
|
| 83 |
+
blocks: list[tuple[int | None, Cells]] = []
|
| 84 |
+
buf: list[str] | None = None
|
| 85 |
+
for line in text.splitlines():
|
| 86 |
+
if "SKETCHPAD BEGIN" in line:
|
| 87 |
+
buf = []
|
| 88 |
+
elif "SKETCHPAD END" in line:
|
| 89 |
+
if buf is not None:
|
| 90 |
+
ver = None
|
| 91 |
+
for bl in buf:
|
| 92 |
+
m = _VERSION_RE.search(bl)
|
| 93 |
+
if m:
|
| 94 |
+
ver = int(m.group(1))
|
| 95 |
+
break
|
| 96 |
+
cells = _parse_panel_body(buf, side)
|
| 97 |
+
if cells:
|
| 98 |
+
blocks.append((ver, cells))
|
| 99 |
+
buf = None
|
| 100 |
+
elif buf is not None:
|
| 101 |
+
buf.append(line)
|
| 102 |
+
return blocks
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _cell_accuracy(gold: Cells, panel: Panel) -> float:
|
| 106 |
+
if not gold:
|
| 107 |
+
return 0.0
|
| 108 |
+
state = dict(panel)
|
| 109 |
+
return sum(1 for k, v in gold.items() if state.get(k) == v) / len(gold)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def gold_states(gold: dict) -> Iterator[tuple[int, Cells]]:
|
| 113 |
+
"""Fold the compact per-version deltas into ``(version, full cells)`` pairs.
|
| 114 |
+
|
| 115 |
+
A ``reset`` delta replaces the whole board (a new puzzle, or version 0); an
|
| 116 |
+
ordinary delta updates only the changed cells. Version 0, the given starting
|
| 117 |
+
panel, is yielded too, but the scorer grades only the streamed actions.
|
| 118 |
+
"""
|
| 119 |
+
current: Cells = {}
|
| 120 |
+
for d in gold.get("deltas") or []:
|
| 121 |
+
cells = {k: _norm_value(v) for k, v in (d.get("cells") or {}).items()}
|
| 122 |
+
if d.get("reset"):
|
| 123 |
+
current = dict(cells)
|
| 124 |
+
else:
|
| 125 |
+
current.update(cells)
|
| 126 |
+
yield d["v"], dict(current)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class SudokuSketchpadGrader(Grader):
|
| 130 |
+
family = "sudoku_sketchpad"
|
| 131 |
+
|
| 132 |
+
def grade(self, run_dir: Path | str, gold: dict) -> dict:
|
| 133 |
+
meta = gold.get("meta") or {}
|
| 134 |
+
# No silent 9x9 default: a missing side in a 16x16 or 25x25 gold would grade
|
| 135 |
+
# the board on a 9x9 assumption and look perfectly healthy while doing it.
|
| 136 |
+
if "side" not in meta:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"gold.meta['side'] is missing: refusing to default to 9x9. A larger "
|
| 139 |
+
"board graded under a silent 9x9 default would pass every check we "
|
| 140 |
+
"have. Stamp 'side' in the instance gold.meta."
|
| 141 |
+
)
|
| 142 |
+
side = int(meta["side"])
|
| 143 |
+
|
| 144 |
+
source = read_context(run_dir)
|
| 145 |
+
if source.graded_from == "none":
|
| 146 |
+
return self._invalid("none", "no context snapshots, trajectory or report")
|
| 147 |
+
obs = self._observe(source, side)
|
| 148 |
+
|
| 149 |
+
total = 0
|
| 150 |
+
versioned = 0
|
| 151 |
+
content = 0
|
| 152 |
+
cell_sum = 0.0
|
| 153 |
+
final_gold: Panel | None = None
|
| 154 |
+
for v, cells in gold_states(gold):
|
| 155 |
+
if v == 0:
|
| 156 |
+
continue
|
| 157 |
+
total += 1
|
| 158 |
+
panel: Panel = tuple(sorted(cells.items()))
|
| 159 |
+
final_gold = panel
|
| 160 |
+
if panel in obs["by_version"].get(v, ()):
|
| 161 |
+
versioned += 1
|
| 162 |
+
if panel in obs["content"]:
|
| 163 |
+
content += 1
|
| 164 |
+
seen = obs["by_version"].get(v)
|
| 165 |
+
if seen:
|
| 166 |
+
cell_sum += max(
|
| 167 |
+
(_cell_accuracy(cells, s) for s in seen), default=0.0
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if total == 0:
|
| 171 |
+
return self._invalid(source.graded_from, "gold has no graded versions")
|
| 172 |
+
|
| 173 |
+
final_state: Panel | None = obs["final"]
|
| 174 |
+
final_em = 1.0 if (final_state is not None and final_state == final_gold) else 0.0
|
| 175 |
+
final_cell = (
|
| 176 |
+
_cell_accuracy(dict(final_gold), final_state)
|
| 177 |
+
if (final_state is not None and final_gold is not None)
|
| 178 |
+
else 0.0
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
result = {
|
| 182 |
+
"reward": content / total,
|
| 183 |
+
"reward_versioned": versioned / total,
|
| 184 |
+
"reward_content": content / total,
|
| 185 |
+
"reward_cell": cell_sum / total,
|
| 186 |
+
"reward_final_em": final_em,
|
| 187 |
+
"reward_final_cell": final_cell,
|
| 188 |
+
"matched": float(versioned),
|
| 189 |
+
"total": float(total),
|
| 190 |
+
"n_snapshots": float(source.n_snapshots),
|
| 191 |
+
"graded_from": source.graded_from,
|
| 192 |
+
"grader_valid": 1.0,
|
| 193 |
+
}
|
| 194 |
+
result.update(self._token_stats(source.tokens))
|
| 195 |
+
return result
|
| 196 |
+
|
| 197 |
+
@staticmethod
|
| 198 |
+
def _observe(source: ContextSource, side: int) -> dict:
|
| 199 |
+
"""Every versioned panel, deduplicated as canonical tuples.
|
| 200 |
+
|
| 201 |
+
Deduplication keeps an append-only agent that re-shows every old version
|
| 202 |
+
from blowing up the grader's memory.
|
| 203 |
+
"""
|
| 204 |
+
by_version: dict[int, set[Panel]] = {}
|
| 205 |
+
content: set[Panel] = set()
|
| 206 |
+
final_state: Panel | None = None
|
| 207 |
+
|
| 208 |
+
for frame in source.frames:
|
| 209 |
+
blocks = _parse_blocks(messages_text(frame), side)
|
| 210 |
+
best: tuple[int, Panel] | None = None
|
| 211 |
+
for ver, cells in blocks:
|
| 212 |
+
panel: Panel = tuple(sorted(cells.items()))
|
| 213 |
+
content.add(panel)
|
| 214 |
+
if ver is not None:
|
| 215 |
+
by_version.setdefault(ver, set()).add(panel)
|
| 216 |
+
if best is None or ver >= best[0]:
|
| 217 |
+
best = (ver, panel)
|
| 218 |
+
# The final state is the highest-version panel of the latest frame that
|
| 219 |
+
# has one at all.
|
| 220 |
+
if best is not None:
|
| 221 |
+
final_state = best[1]
|
| 222 |
+
elif blocks:
|
| 223 |
+
final_state = tuple(sorted(blocks[-1][1].items()))
|
| 224 |
+
|
| 225 |
+
return {"by_version": by_version, "content": content, "final": final_state}
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ContextBench on Harbor: task packaging, the op stream, agents and verifiers.
|
| 2 |
+
|
| 3 |
+
``turn_source``, ``mixin`` and ``package`` import nothing from Harbor, so a task can
|
| 4 |
+
be built and a stream tested without it installed. ``agents``, ``wrap`` and
|
| 5 |
+
``verifiers`` require ``harbor>=0.16`` (``pip install 'contextbench[harbor]'``).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from .mixin import CBStreamMixin
|
| 11 |
+
from .turn_source import (
|
| 12 |
+
ENV_STREAM_COUNT,
|
| 13 |
+
ENV_STREAM_PATH,
|
| 14 |
+
ENV_STREAM_SHA256,
|
| 15 |
+
STREAM_RECORD_NAME,
|
| 16 |
+
STREAM_RELPATH,
|
| 17 |
+
StreamIdentityError,
|
| 18 |
+
TurnSource,
|
| 19 |
+
canonical_sha256,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"CBStreamMixin",
|
| 24 |
+
"ENV_STREAM_COUNT",
|
| 25 |
+
"ENV_STREAM_PATH",
|
| 26 |
+
"ENV_STREAM_SHA256",
|
| 27 |
+
"STREAM_RECORD_NAME",
|
| 28 |
+
"STREAM_RELPATH",
|
| 29 |
+
"StreamIdentityError",
|
| 30 |
+
"TurnSource",
|
| 31 |
+
"canonical_sha256",
|
| 32 |
+
]
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/mixin.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""``CBStreamMixin``: ContextBench support for any Python agent loop under Harbor.
|
| 2 |
+
|
| 3 |
+
Add the mixin to your Harbor agent and three calls to its loop::
|
| 4 |
+
|
| 5 |
+
class MyAgent(CBStreamMixin, BaseAgent):
|
| 6 |
+
async def run(self, instruction, environment, context):
|
| 7 |
+
await self.cb_setup(environment) # 1
|
| 8 |
+
messages = [system, {"role": "user", "content": instruction}]
|
| 9 |
+
messages += self.cb_user_turns(self.cb_initial_turns())
|
| 10 |
+
while not self.cb_done:
|
| 11 |
+
... # model call
|
| 12 |
+
messages.append(tool_result_message)
|
| 13 |
+
messages += self.cb_user_turns( # 2
|
| 14 |
+
self.cb_pending(command, exit_code))
|
| 15 |
+
if self.cb_over_budget(messages): # 3
|
| 16 |
+
break
|
| 17 |
+
|
| 18 |
+
The mixin owns everything else: loading and verifying the stream (and removing it
|
| 19 |
+
from the container), the readiness rule, the early-submit refusal, the terminal
|
| 20 |
+
reason, ``interactive_stream.json`` and the ``context_snapshots/turn-NNNN.json`` the
|
| 21 |
+
graders read. ``cb_over_budget`` both snapshots the context you are about to send
|
| 22 |
+
and enforces the budget wall on it; call it right before every model call (or where
|
| 23 |
+
your loop sends), and call :meth:`cb_finish` in a ``finally``.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
from ..tokens import count_tokens, record_snapshot
|
| 32 |
+
from .turn_source import TurnSource
|
| 33 |
+
|
| 34 |
+
__all__ = ["CBStreamMixin"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CBStreamMixin:
|
| 38 |
+
"""Stream delivery, snapshots and the budget wall for a Harbor agent loop."""
|
| 39 |
+
|
| 40 |
+
logs_dir: Path
|
| 41 |
+
|
| 42 |
+
#: Budget of record; override per instance with ``cb_setup(budget=...)``.
|
| 43 |
+
cb_budget: int = 32768
|
| 44 |
+
cb_reserve: int = 2048
|
| 45 |
+
|
| 46 |
+
# ------------------------------------------------------------------ setup
|
| 47 |
+
async def cb_setup(self, environment: Any, *, budget: int | None = None,
|
| 48 |
+
reserve: int | None = None, **load_kwargs: Any) -> TurnSource:
|
| 49 |
+
"""Load the task's stream (verified, then removed from the container)."""
|
| 50 |
+
if budget is not None:
|
| 51 |
+
self.cb_budget = int(budget)
|
| 52 |
+
if reserve is not None:
|
| 53 |
+
self.cb_reserve = int(reserve)
|
| 54 |
+
self.cb_source = await TurnSource.load(
|
| 55 |
+
environment, logs_dir=self.logs_dir, **load_kwargs)
|
| 56 |
+
self._cb_snap_step = 0
|
| 57 |
+
self.cb_peak_tokens = 0
|
| 58 |
+
return self.cb_source
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def cb_turn_source(self) -> TurnSource | None:
|
| 62 |
+
return getattr(self, "cb_source", None)
|
| 63 |
+
|
| 64 |
+
# --------------------------------------------------------------- delivery
|
| 65 |
+
def cb_initial_turns(self) -> list[str]:
|
| 66 |
+
"""The user turns to append after the instruction: op 0."""
|
| 67 |
+
first = self.cb_source.first_turn(turn=0)
|
| 68 |
+
return [first] if first is not None else []
|
| 69 |
+
|
| 70 |
+
def cb_pending(self, last_command: str | None, last_exit: int | None = 0, *,
|
| 71 |
+
turn: int | None = None) -> list[str]:
|
| 72 |
+
"""The user turns to append right after the tool result of ``last_command``."""
|
| 73 |
+
return self.cb_source.pending(last_command, last_exit, turn=turn)
|
| 74 |
+
|
| 75 |
+
def cb_submit(self, *, trigger: str = "<submit>") -> list[str]:
|
| 76 |
+
"""The harness's own finish signal: refused (texts returned) until the drain."""
|
| 77 |
+
return self.cb_source.on_submit(trigger=trigger)
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def cb_done(self) -> bool:
|
| 81 |
+
src = self.cb_turn_source
|
| 82 |
+
return bool(src and src.done)
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def cb_user_turns(texts: list[str]) -> list[dict[str, str]]:
|
| 86 |
+
return [{"role": "user", "content": t} for t in texts]
|
| 87 |
+
|
| 88 |
+
# ------------------------------------------------------ snapshots and wall
|
| 89 |
+
def cb_snapshot(self, messages: list[Any], kind: str = "sent",
|
| 90 |
+
extra: dict[str, Any] | None = None) -> int:
|
| 91 |
+
"""Write ``context_snapshots/turn-NNNN.json``; returns its token count."""
|
| 92 |
+
src = self.cb_turn_source
|
| 93 |
+
tokens, _ = count_tokens(messages)
|
| 94 |
+
self.cb_peak_tokens = max(getattr(self, "cb_peak_tokens", 0), tokens)
|
| 95 |
+
step = getattr(self, "_cb_snap_step", 0)
|
| 96 |
+
record_snapshot(
|
| 97 |
+
self.logs_dir, step, list(messages),
|
| 98 |
+
{"kind": kind, "n_ops_delivered": src.n_delivered if src else 0,
|
| 99 |
+
"n_ops_total": src.n_total if src else 0,
|
| 100 |
+
"budget": self.cb_budget, "reserve": self.cb_reserve, **(extra or {})},
|
| 101 |
+
)
|
| 102 |
+
self._cb_snap_step = step + 1
|
| 103 |
+
return tokens
|
| 104 |
+
|
| 105 |
+
def cb_over_budget(self, messages: list[Any]) -> bool:
|
| 106 |
+
"""Snapshot what is about to be sent; True (and ``budget_wall``) if it is over."""
|
| 107 |
+
if self.cb_snapshot(messages, "sent") > self.cb_budget - self.cb_reserve:
|
| 108 |
+
self.cb_source.terminate("budget_wall")
|
| 109 |
+
return True
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
def cb_finish(self, reason: str | None = None,
|
| 113 |
+
messages: list[Any] | None = None) -> None:
|
| 114 |
+
"""Record a terminal reason if none was set, snapshot the final context."""
|
| 115 |
+
src = self.cb_turn_source
|
| 116 |
+
if src is None:
|
| 117 |
+
return
|
| 118 |
+
if reason and not src.done:
|
| 119 |
+
src.terminate(reason)
|
| 120 |
+
if messages is not None:
|
| 121 |
+
self.cb_snapshot(messages, "final")
|
| 122 |
+
src.write()
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/reward.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Grade a Harbor trial's agent directory and write Harbor's reward files.
|
| 2 |
+
|
| 3 |
+
Shared by the two ways a ContextBench task is verified:
|
| 4 |
+
|
| 5 |
+
* in the container, by the task's own ``tests/test.sh`` (Harbor's default verifier:
|
| 6 |
+
no flag needed), which runs ``python3 -m contextbench.harbor.reward`` against a
|
| 7 |
+
copy of the graders vendored into ``tests/_cb/``;
|
| 8 |
+
* on the host, by ``contextbench.harbor.verifiers:ContextBenchVerifier``, for images
|
| 9 |
+
without ``python3``.
|
| 10 |
+
|
| 11 |
+
Harbor's reward dict must be numeric (its job-level mean sums every key), so the
|
| 12 |
+
string fields are encoded: ``graded_from_code`` (3 snapshots, 2 trajectory,
|
| 13 |
+
1 final_report, 0 none) and ``terminated_by_code`` (index into
|
| 14 |
+
``contextbench.stream.TERMINATED_BY``, -1 unknown). The unencoded result goes to
|
| 15 |
+
``contextbench_result.json`` next to ``reward.json``.
|
| 16 |
+
|
| 17 |
+
Pure standard library: this module runs inside task containers.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
from ..graders import grade_run
|
| 29 |
+
from ..stream import TERMINATED_BY
|
| 30 |
+
|
| 31 |
+
__all__ = ["GRADED_FROM_CODES", "harbor_rewards", "write_rewards", "main"]
|
| 32 |
+
|
| 33 |
+
GRADED_FROM_CODES = {"snapshots": 3, "trajectory": 2, "final_report": 1, "none": 0}
|
| 34 |
+
|
| 35 |
+
STREAM_RECORD_NAME = "interactive_stream.json"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def harbor_rewards(agent_dir: Path | str, gold: dict) -> tuple[dict, dict]:
|
| 39 |
+
"""``(numeric reward dict, full result dict)`` for one agent directory."""
|
| 40 |
+
agent_dir = Path(agent_dir)
|
| 41 |
+
rewards = grade_run(agent_dir, gold)
|
| 42 |
+
stream: dict[str, Any] = {}
|
| 43 |
+
record = agent_dir / STREAM_RECORD_NAME
|
| 44 |
+
if record.is_file():
|
| 45 |
+
try:
|
| 46 |
+
stream = json.loads(record.read_text(encoding="utf-8"))
|
| 47 |
+
except Exception:
|
| 48 |
+
stream = {}
|
| 49 |
+
numeric: dict[str, float | int] = {
|
| 50 |
+
k: v for k, v in rewards.items()
|
| 51 |
+
if isinstance(v, (int, float)) and not isinstance(v, bool)
|
| 52 |
+
}
|
| 53 |
+
numeric["graded_from_code"] = GRADED_FROM_CODES.get(str(rewards.get("graded_from")), 0)
|
| 54 |
+
terminated_by = stream.get("terminated_by")
|
| 55 |
+
numeric["terminated_by_code"] = (
|
| 56 |
+
TERMINATED_BY.index(terminated_by) if terminated_by in TERMINATED_BY else -1
|
| 57 |
+
)
|
| 58 |
+
for key in ("n_ops_delivered", "n_ops_total", "n_refusals"):
|
| 59 |
+
if isinstance(stream.get(key), int):
|
| 60 |
+
numeric[key] = stream[key]
|
| 61 |
+
full = {
|
| 62 |
+
"rewards": rewards,
|
| 63 |
+
"graded_from": rewards.get("graded_from"),
|
| 64 |
+
"terminated_by": terminated_by,
|
| 65 |
+
"agent_dir": str(agent_dir),
|
| 66 |
+
"stream": {k: v for k, v in stream.items() if k != "log"},
|
| 67 |
+
}
|
| 68 |
+
return numeric, full
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def write_rewards(agent_dir: Path | str, gold: dict | Path | str,
|
| 72 |
+
out_dir: Path | str) -> dict:
|
| 73 |
+
"""Grade and write ``reward.json`` + ``contextbench_result.json``; return numeric."""
|
| 74 |
+
if not isinstance(gold, dict):
|
| 75 |
+
gold = json.loads(Path(gold).read_text(encoding="utf-8"))
|
| 76 |
+
numeric, full = harbor_rewards(agent_dir, gold)
|
| 77 |
+
out = Path(out_dir)
|
| 78 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
(out / "contextbench_result.json").write_text(
|
| 80 |
+
json.dumps(full, indent=2, default=str) + "\n", encoding="utf-8")
|
| 81 |
+
(out / "reward.json").write_text(json.dumps(numeric, indent=2) + "\n",
|
| 82 |
+
encoding="utf-8")
|
| 83 |
+
return numeric
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main(argv: list[str] | None = None) -> int:
|
| 87 |
+
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 88 |
+
ap.add_argument("--agent-dir", type=Path, default=Path("/logs/agent"))
|
| 89 |
+
ap.add_argument("--gold", type=Path, default=Path("/tests/gold.json"))
|
| 90 |
+
ap.add_argument("--out-dir", type=Path, default=Path("/logs/verifier"))
|
| 91 |
+
a = ap.parse_args(argv)
|
| 92 |
+
numeric = write_rewards(a.agent_dir, a.gold, a.out_dir)
|
| 93 |
+
print(json.dumps(numeric))
|
| 94 |
+
return 0
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
sys.exit(main())
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/harbor/turn_source.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""``TurnSource``: the one place a Harbor agent gets its next ContextBench operation.
|
| 2 |
+
|
| 3 |
+
Every Harbor path (the shipped ``ContextBenchAgent``, ``Terminus2Stream``, and any
|
| 4 |
+
method adapter built outside this package) consumes the stream through this class,
|
| 5 |
+
so the delivery rules cannot drift between harnesses:
|
| 6 |
+
|
| 7 |
+
* the operations are read **once** from the container, from the
|
| 8 |
+
``stream/chunks.jsonl`` file Harbor uploads into the work directory, and checked
|
| 9 |
+
against the op count and canonical body sha recorded in ``task.toml``;
|
| 10 |
+
* the file is then **removed** from the container, so the agent cannot read ahead
|
| 11 |
+
with its shell (the only route an op has into the context is the user turn the
|
| 12 |
+
harness appends);
|
| 13 |
+
* the next op is released only when the agent's last command was the standalone
|
| 14 |
+
``echo READY_FOR_NEXT_OP`` (see :func:`contextbench.stream.is_ready_command`);
|
| 15 |
+
* a submit before the stream is drained is refused with
|
| 16 |
+
:data:`contextbench.stream.REFUSE_SUBMIT_TEXT`;
|
| 17 |
+
* ``terminated_by`` and the delivery log are written to
|
| 18 |
+
``<logs_dir>/interactive_stream.json`` after every change, so a run that is
|
| 19 |
+
killed still leaves an accurate record.
|
| 20 |
+
|
| 21 |
+
The class is harness-agnostic: it never touches the message list. A harness asks
|
| 22 |
+
:meth:`TurnSource.pending` what to append after a tool result and appends the
|
| 23 |
+
returned texts as ``role="user"`` messages itself.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import asyncio
|
| 29 |
+
import hashlib
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import posixpath
|
| 33 |
+
import shlex
|
| 34 |
+
from dataclasses import dataclass, field
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Any, Iterable, Mapping
|
| 37 |
+
|
| 38 |
+
from .. import stream as proto
|
| 39 |
+
from ..stream import Op, render_op
|
| 40 |
+
|
| 41 |
+
__all__ = [
|
| 42 |
+
"ENV_STREAM_COUNT",
|
| 43 |
+
"ENV_STREAM_PATH",
|
| 44 |
+
"ENV_STREAM_SHA256",
|
| 45 |
+
"STREAM_RECORD_NAME",
|
| 46 |
+
"STREAM_RELPATH",
|
| 47 |
+
"Delivery",
|
| 48 |
+
"StreamIdentityError",
|
| 49 |
+
"TurnSource",
|
| 50 |
+
"canonical_sha256",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
#: Where the stream lives relative to the task's ``environment/`` directory, and
|
| 54 |
+
#: therefore relative to the container work directory after Harbor's upload.
|
| 55 |
+
STREAM_RELPATH = "stream/chunks.jsonl"
|
| 56 |
+
#: Reads of the stream before giving up; each must parse and match the task identity.
|
| 57 |
+
READ_ATTEMPTS = 4
|
| 58 |
+
#: Seconds of back-off per retry (linear).
|
| 59 |
+
READ_BACKOFF_SEC = 2.0
|
| 60 |
+
|
| 61 |
+
#: ``[environment.env]`` keys that ``contextbench package`` writes into task.toml.
|
| 62 |
+
ENV_STREAM_COUNT = "CONTEXTBENCH_STREAM_COUNT"
|
| 63 |
+
ENV_STREAM_SHA256 = "CONTEXTBENCH_STREAM_SHA256"
|
| 64 |
+
ENV_STREAM_PATH = "CONTEXTBENCH_STREAM_PATH"
|
| 65 |
+
|
| 66 |
+
STREAM_RECORD_NAME = "interactive_stream.json"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class StreamIdentityError(RuntimeError):
|
| 70 |
+
"""The stream read from the container is not the one the task was built with."""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def canonical_sha256(records: Iterable[Mapping[str, Any]]) -> str:
|
| 74 |
+
"""sha256 over the ops as sorted-key JSON, one per line.
|
| 75 |
+
|
| 76 |
+
Canonical rather than byte-level, so re-serializing ``chunks.jsonl`` (key order,
|
| 77 |
+
trailing newline) does not change the identity, while any change to an op does.
|
| 78 |
+
"""
|
| 79 |
+
canon = "\n".join(json.dumps(dict(r), sort_keys=True) for r in records)
|
| 80 |
+
return hashlib.sha256(canon.encode("utf-8")).hexdigest()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _parse_records(text: str) -> list[dict[str, Any]]:
|
| 84 |
+
records: list[dict[str, Any]] = []
|
| 85 |
+
for line in (text or "").splitlines():
|
| 86 |
+
line = line.strip()
|
| 87 |
+
if line:
|
| 88 |
+
records.append(json.loads(line))
|
| 89 |
+
return records
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass
|
| 93 |
+
class Delivery:
|
| 94 |
+
"""One entry of the delivery log."""
|
| 95 |
+
|
| 96 |
+
#: What was handed to the agent: ``op``, ``refuse_submit`` or ``explain``.
|
| 97 |
+
kind: str
|
| 98 |
+
#: The op index for ``kind == "op"``, else ``None``.
|
| 99 |
+
index: int | None
|
| 100 |
+
#: The command that triggered it (head and tail when long), or ``"<start>"``.
|
| 101 |
+
trigger: str
|
| 102 |
+
#: The harness's own turn counter at the time, when it passes one.
|
| 103 |
+
turn: int | None = None
|
| 104 |
+
#: Why it was handed over: ``start``, ``ready`` (standalone readiness command),
|
| 105 |
+
#: ``submit`` (a submit before the drain), ``mention`` (non-standalone marker).
|
| 106 |
+
via: str = ""
|
| 107 |
+
|
| 108 |
+
def to_dict(self) -> dict[str, Any]:
|
| 109 |
+
return {"kind": self.kind, "index": self.index, "via": self.via,
|
| 110 |
+
"trigger": self.trigger, "turn": self.turn}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _excerpt(command: str, limit: int = 240) -> str:
|
| 114 |
+
"""The command as logged: whole when short, else head and tail."""
|
| 115 |
+
cmd = (command or "").strip()
|
| 116 |
+
if len(cmd) <= limit:
|
| 117 |
+
return cmd
|
| 118 |
+
half = limit // 2
|
| 119 |
+
return cmd[:half] + " [...] " + cmd[-half:]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class TurnSource:
|
| 124 |
+
"""The operation stream of one trial, and its delivery bookkeeping."""
|
| 125 |
+
|
| 126 |
+
ops: list[Op]
|
| 127 |
+
logs_dir: Path | None = None
|
| 128 |
+
#: How the stream was verified: ``{"count", "sha256", "path", "removed"}``.
|
| 129 |
+
identity: dict[str, Any] = field(default_factory=dict)
|
| 130 |
+
|
| 131 |
+
n_delivered: int = 0
|
| 132 |
+
terminated_by: str | None = None
|
| 133 |
+
n_refusals: int = 0
|
| 134 |
+
n_explains: int = 0
|
| 135 |
+
log: list[Delivery] = field(default_factory=list)
|
| 136 |
+
|
| 137 |
+
# ---------------------------------------------------------------- building
|
| 138 |
+
@classmethod
|
| 139 |
+
def from_records(
|
| 140 |
+
cls,
|
| 141 |
+
records: list[Mapping[str, Any]],
|
| 142 |
+
*,
|
| 143 |
+
logs_dir: Path | str | None = None,
|
| 144 |
+
expect_count: int | str | None = None,
|
| 145 |
+
expect_sha256: str | None = None,
|
| 146 |
+
identity: dict[str, Any] | None = None,
|
| 147 |
+
) -> "TurnSource":
|
| 148 |
+
"""Build from parsed ``chunks.jsonl`` records, verifying count and sha."""
|
| 149 |
+
got_sha = canonical_sha256(records)
|
| 150 |
+
if expect_count is not None and str(expect_count).strip() != "":
|
| 151 |
+
if len(records) != int(str(expect_count).strip()):
|
| 152 |
+
raise StreamIdentityError(
|
| 153 |
+
f"stream op count mismatch: read {len(records)}, task expects "
|
| 154 |
+
f"{str(expect_count).strip()}"
|
| 155 |
+
)
|
| 156 |
+
if expect_sha256 and got_sha != str(expect_sha256).strip():
|
| 157 |
+
raise StreamIdentityError(
|
| 158 |
+
f"stream sha256 mismatch: read {got_sha[:16]}, task expects "
|
| 159 |
+
f"{str(expect_sha256).strip()[:16]}"
|
| 160 |
+
)
|
| 161 |
+
ops = [Op.from_dict(dict(r), fallback_index=i) for i, r in enumerate(records)]
|
| 162 |
+
ident = {"count": len(records), "sha256": got_sha,
|
| 163 |
+
"verified": bool(expect_count is not None or expect_sha256)}
|
| 164 |
+
ident.update(identity or {})
|
| 165 |
+
src = cls(ops=ops, logs_dir=Path(logs_dir) if logs_dir else None,
|
| 166 |
+
identity=ident)
|
| 167 |
+
src.write()
|
| 168 |
+
return src
|
| 169 |
+
|
| 170 |
+
@classmethod
|
| 171 |
+
def from_jsonl(cls, text: str, **kwargs: Any) -> "TurnSource":
|
| 172 |
+
return cls.from_records(_parse_records(text), **kwargs)
|
| 173 |
+
|
| 174 |
+
@classmethod
|
| 175 |
+
async def load(
|
| 176 |
+
cls,
|
| 177 |
+
environment: Any,
|
| 178 |
+
*,
|
| 179 |
+
logs_dir: Path | str | None = None,
|
| 180 |
+
path: str | None = None,
|
| 181 |
+
expect_count: int | str | None = None,
|
| 182 |
+
expect_sha256: str | None = None,
|
| 183 |
+
remove_after_load: bool = True,
|
| 184 |
+
require_identity: bool = True,
|
| 185 |
+
) -> "TurnSource":
|
| 186 |
+
"""Read the stream out of a running Harbor environment.
|
| 187 |
+
|
| 188 |
+
``path``, ``expect_count`` and ``expect_sha256`` default to the
|
| 189 |
+
``CONTEXTBENCH_STREAM_*`` values in the task's ``[environment.env]``, then
|
| 190 |
+
to the host process environment. Without a path, the stream is looked up
|
| 191 |
+
at ``<workdir>/stream/chunks.jsonl``. With ``require_identity`` (the
|
| 192 |
+
default) a task that records no count or sha is refused: an unverified
|
| 193 |
+
stream could be another task's.
|
| 194 |
+
"""
|
| 195 |
+
env_cfg = _task_env(environment)
|
| 196 |
+
|
| 197 |
+
def _setting(name: str, given: Any) -> Any:
|
| 198 |
+
if given is not None:
|
| 199 |
+
return given
|
| 200 |
+
return env_cfg.get(name) or os.environ.get(name)
|
| 201 |
+
|
| 202 |
+
expect_count = _setting(ENV_STREAM_COUNT, expect_count)
|
| 203 |
+
expect_sha256 = _setting(ENV_STREAM_SHA256, expect_sha256)
|
| 204 |
+
path = _setting(ENV_STREAM_PATH, path)
|
| 205 |
+
if require_identity and not (expect_count or expect_sha256):
|
| 206 |
+
raise StreamIdentityError(
|
| 207 |
+
f"the task records no {ENV_STREAM_COUNT} / {ENV_STREAM_SHA256}; "
|
| 208 |
+
"refusing to deliver an unverifiable stream (rebuild the task with "
|
| 209 |
+
"`contextbench package`)"
|
| 210 |
+
)
|
| 211 |
+
if not path:
|
| 212 |
+
workdir = getattr(getattr(environment, "task_env_config", None),
|
| 213 |
+
"workdir", None)
|
| 214 |
+
if not workdir:
|
| 215 |
+
res = await environment.exec("pwd", timeout_sec=30)
|
| 216 |
+
workdir = (getattr(res, "stdout", "") or "/").strip() or "/"
|
| 217 |
+
path = posixpath.join(workdir, STREAM_RELPATH)
|
| 218 |
+
|
| 219 |
+
# Read, parse and verify before removing anything. Under concurrent exec
|
| 220 |
+
# load the captured stdout can come back truncated; a verified retry
|
| 221 |
+
# recovers it, and the file is only deleted once a read has matched.
|
| 222 |
+
last_err: Exception | None = None
|
| 223 |
+
records: list[dict[str, Any]] = []
|
| 224 |
+
for attempt in range(READ_ATTEMPTS):
|
| 225 |
+
if attempt:
|
| 226 |
+
await asyncio.sleep(READ_BACKOFF_SEC * attempt)
|
| 227 |
+
res = await environment.exec(f"cat {shlex.quote(path)}", timeout_sec=120)
|
| 228 |
+
if getattr(res, "return_code", 1) != 0:
|
| 229 |
+
last_err = RuntimeError(
|
| 230 |
+
f"could not read the stream at {path} in the container: "
|
| 231 |
+
f"{(getattr(res, 'stderr', '') or getattr(res, 'stdout', ''))[:300]}"
|
| 232 |
+
)
|
| 233 |
+
continue
|
| 234 |
+
try:
|
| 235 |
+
records = _parse_records(getattr(res, "stdout", "") or "")
|
| 236 |
+
if not records:
|
| 237 |
+
raise RuntimeError(f"the stream at {path} is empty")
|
| 238 |
+
cls.from_records(records, expect_count=expect_count,
|
| 239 |
+
expect_sha256=expect_sha256)
|
| 240 |
+
except (json.JSONDecodeError, StreamIdentityError, RuntimeError) as err:
|
| 241 |
+
last_err = err
|
| 242 |
+
records = []
|
| 243 |
+
continue
|
| 244 |
+
break
|
| 245 |
+
if not records:
|
| 246 |
+
raise StreamIdentityError(
|
| 247 |
+
f"stream at {path} failed verification after {READ_ATTEMPTS} reads: "
|
| 248 |
+
f"{last_err}"
|
| 249 |
+
) from last_err
|
| 250 |
+
|
| 251 |
+
removed = False
|
| 252 |
+
if remove_after_load:
|
| 253 |
+
stream_dir = posixpath.dirname(path)
|
| 254 |
+
await environment.exec(f"rm -rf {shlex.quote(stream_dir)}", timeout_sec=60)
|
| 255 |
+
check = await environment.exec(
|
| 256 |
+
f"test -e {shlex.quote(path)}", timeout_sec=30
|
| 257 |
+
)
|
| 258 |
+
removed = getattr(check, "return_code", 0) != 0
|
| 259 |
+
if not removed:
|
| 260 |
+
raise RuntimeError(
|
| 261 |
+
f"could not remove {path} after loading it: the agent could read "
|
| 262 |
+
"ahead in the stream"
|
| 263 |
+
)
|
| 264 |
+
return cls.from_records(
|
| 265 |
+
records,
|
| 266 |
+
logs_dir=logs_dir,
|
| 267 |
+
expect_count=expect_count,
|
| 268 |
+
expect_sha256=expect_sha256,
|
| 269 |
+
identity={"path": path, "removed": removed},
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# -------------------------------------------------------------- properties
|
| 273 |
+
@property
|
| 274 |
+
def n_total(self) -> int:
|
| 275 |
+
return len(self.ops)
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def drained(self) -> bool:
|
| 279 |
+
"""True once every op has been delivered."""
|
| 280 |
+
return self.n_delivered >= self.n_total
|
| 281 |
+
|
| 282 |
+
@property
|
| 283 |
+
def done(self) -> bool:
|
| 284 |
+
"""True once the run has a terminal reason; the harness should stop."""
|
| 285 |
+
return self.terminated_by is not None
|
| 286 |
+
|
| 287 |
+
# ----------------------------------------------------------------- delivery
|
| 288 |
+
def _deliver(self, trigger: str, turn: int | None) -> str:
|
| 289 |
+
index = self.n_delivered
|
| 290 |
+
text = render_op(self.ops[index], remaining=self.n_total - (index + 1))
|
| 291 |
+
self.n_delivered += 1
|
| 292 |
+
self.log.append(Delivery("op", index, trigger, turn,
|
| 293 |
+
"start" if trigger == "<start>" else "ready"))
|
| 294 |
+
self.write()
|
| 295 |
+
return text
|
| 296 |
+
|
| 297 |
+
def first_turn(self, *, turn: int | None = None) -> str | None:
|
| 298 |
+
"""Op 0, delivered with the instruction. ``None`` for an empty stream."""
|
| 299 |
+
if self.n_delivered:
|
| 300 |
+
raise RuntimeError("first_turn() called after delivery started")
|
| 301 |
+
if not self.ops:
|
| 302 |
+
self.terminate("stream_exhausted")
|
| 303 |
+
return None
|
| 304 |
+
return self._deliver("<start>", turn)
|
| 305 |
+
|
| 306 |
+
def pending(
|
| 307 |
+
self, last_command: str | None, last_exit: int | None = 0, *,
|
| 308 |
+
turn: int | None = None,
|
| 309 |
+
) -> list[str]:
|
| 310 |
+
"""The user turns to append after the tool result of ``last_command``.
|
| 311 |
+
|
| 312 |
+
* standalone readiness, ops left: ``[next op]``;
|
| 313 |
+
* standalone readiness, stream drained: ``[]`` and ``terminated_by =
|
| 314 |
+
"stream_exhausted"`` (the harness must stop);
|
| 315 |
+
* standalone submit, ops left: ``[REFUSE_SUBMIT_TEXT]``;
|
| 316 |
+
* standalone submit, drained: ``[]`` and ``terminated_by = "submit"``;
|
| 317 |
+
* the marker mentioned but not standalone: ``[EXPLAIN_NON_STANDALONE_TEXT]``;
|
| 318 |
+
* anything else: ``[]``.
|
| 319 |
+
|
| 320 |
+
``last_exit`` is the command's exit code; ``None`` means the harness cannot
|
| 321 |
+
observe it (a terminal multiplexer), which is treated as success.
|
| 322 |
+
"""
|
| 323 |
+
if self.done:
|
| 324 |
+
return []
|
| 325 |
+
cmd = last_command or ""
|
| 326 |
+
code = 0 if last_exit is None else int(last_exit)
|
| 327 |
+
trigger = _excerpt(cmd)
|
| 328 |
+
if proto.is_ready_command(cmd, code):
|
| 329 |
+
if self.drained:
|
| 330 |
+
self.terminate("stream_exhausted")
|
| 331 |
+
return []
|
| 332 |
+
return [self._deliver(trigger, turn)]
|
| 333 |
+
if proto.is_submit_command(cmd, code):
|
| 334 |
+
return self.on_submit(trigger=trigger, turn=turn)
|
| 335 |
+
if proto.mentions_advance_marker(cmd):
|
| 336 |
+
self.n_explains += 1
|
| 337 |
+
self.log.append(Delivery("explain", None, trigger, turn, "mention"))
|
| 338 |
+
self.write()
|
| 339 |
+
return [proto.EXPLAIN_NON_STANDALONE_TEXT]
|
| 340 |
+
return []
|
| 341 |
+
|
| 342 |
+
def on_submit(self, *, trigger: str = "<submit>", turn: int | None = None) -> list[str]:
|
| 343 |
+
"""The agent asked to finish (by command or by the harness's own signal).
|
| 344 |
+
|
| 345 |
+
Before the stream is drained this is refused, and the refusal text is
|
| 346 |
+
returned for the harness to deliver; afterwards the run ends as ``submit``.
|
| 347 |
+
"""
|
| 348 |
+
if self.done:
|
| 349 |
+
return []
|
| 350 |
+
if not self.drained:
|
| 351 |
+
self.n_refusals += 1
|
| 352 |
+
self.log.append(Delivery("refuse_submit", None, _excerpt(trigger), turn,
|
| 353 |
+
"submit"))
|
| 354 |
+
self.write()
|
| 355 |
+
return [proto.REFUSE_SUBMIT_TEXT]
|
| 356 |
+
self.terminate("submit")
|
| 357 |
+
return []
|
| 358 |
+
|
| 359 |
+
def terminate(self, reason: str) -> None:
|
| 360 |
+
"""Record the terminal reason once; later calls do not overwrite it."""
|
| 361 |
+
if reason not in proto.TERMINATED_BY:
|
| 362 |
+
raise ValueError(f"unknown terminated_by {reason!r}")
|
| 363 |
+
if self.terminated_by is None:
|
| 364 |
+
self.terminated_by = reason
|
| 365 |
+
self.write()
|
| 366 |
+
|
| 367 |
+
# ------------------------------------------------------------------ record
|
| 368 |
+
def record(self) -> dict[str, Any]:
|
| 369 |
+
return {
|
| 370 |
+
"n_ops_delivered": self.n_delivered,
|
| 371 |
+
"n_ops_total": self.n_total,
|
| 372 |
+
"terminated_by": self.terminated_by,
|
| 373 |
+
"n_refusals": self.n_refusals,
|
| 374 |
+
"n_explains": self.n_explains,
|
| 375 |
+
"stream": self.identity,
|
| 376 |
+
"log": [d.to_dict() for d in self.log],
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
def write(self, logs_dir: Path | str | None = None) -> Path | None:
|
| 380 |
+
"""Write ``interactive_stream.json``. Best effort: never raises."""
|
| 381 |
+
target = Path(logs_dir) if logs_dir else self.logs_dir
|
| 382 |
+
if target is None:
|
| 383 |
+
return None
|
| 384 |
+
try:
|
| 385 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 386 |
+
out = target / STREAM_RECORD_NAME
|
| 387 |
+
out.write_text(json.dumps(self.record(), indent=2) + "\n", encoding="utf-8")
|
| 388 |
+
return out
|
| 389 |
+
except Exception:
|
| 390 |
+
return None
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _task_env(environment: Any) -> dict[str, str]:
|
| 394 |
+
cfg = getattr(environment, "task_env_config", None)
|
| 395 |
+
env = getattr(cfg, "env", None) or {}
|
| 396 |
+
try:
|
| 397 |
+
return {str(k): str(v) for k, v in dict(env).items()}
|
| 398 |
+
except Exception:
|
| 399 |
+
return {}
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/runner.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The pure-Python ContextBench runner.
|
| 2 |
+
|
| 3 |
+
The runner owns the turn protocol so an agent does not have to. It delivers one
|
| 4 |
+
operation per user turn, advances only on a standalone readiness marker, refuses an
|
| 5 |
+
early submit, enforces the budget wall on the agent's own reported context,
|
| 6 |
+
snapshots that context after every turn, and grades the run at the end.
|
| 7 |
+
|
| 8 |
+
The invariant the runner exists to hold: an operation enters the agent's context as
|
| 9 |
+
a user message appended by the runner, before the agent can act on it. The agent
|
| 10 |
+
controls only *when* the next operation arrives, never its content or its route
|
| 11 |
+
into the context.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Protocol, runtime_checkable
|
| 20 |
+
|
| 21 |
+
from . import stream as proto
|
| 22 |
+
from .graders import grade_run
|
| 23 |
+
from .stream import Op, render_op
|
| 24 |
+
from .tokens import count_tokens, record_snapshot
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"ContextAgent",
|
| 28 |
+
"Instance",
|
| 29 |
+
"DEFAULT_SYSTEM_PROMPT",
|
| 30 |
+
"load_instance",
|
| 31 |
+
"run",
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
DEFAULT_SYSTEM_PROMPT = (
|
| 35 |
+
"You are a careful assistant working through a long stream of operations that "
|
| 36 |
+
"does not fit in your context window. Handle each operation as it arrives, keep "
|
| 37 |
+
"in your context exactly what later operations will need, and let go of the "
|
| 38 |
+
"rest.\n\n" + proto.MARKER_PARAGRAPH_REPLY
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@runtime_checkable
|
| 43 |
+
class ContextAgent(Protocol):
|
| 44 |
+
"""What the runner needs from an agent.
|
| 45 |
+
|
| 46 |
+
``reset`` starts a fresh episode with the system prompt and the family
|
| 47 |
+
instruction. ``on_user_turn`` receives one user message -- an operation, or a
|
| 48 |
+
protocol message from the runner -- and returns the reply text. ``context``
|
| 49 |
+
returns the agent's current message list, which the runner snapshots and
|
| 50 |
+
measures against the budget: an agent that hides its context from the runner
|
| 51 |
+
cannot be graded on the paper metric.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def reset(self, system: str, instruction: str) -> None: ...
|
| 55 |
+
|
| 56 |
+
def on_user_turn(self, text: str) -> str: ...
|
| 57 |
+
|
| 58 |
+
def context(self) -> list[dict]: ...
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(frozen=True)
|
| 62 |
+
class Instance:
|
| 63 |
+
"""One generated instance on disk."""
|
| 64 |
+
|
| 65 |
+
path: Path
|
| 66 |
+
family: str
|
| 67 |
+
ops: list[Op]
|
| 68 |
+
gold: dict
|
| 69 |
+
meta: dict
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def n_ops(self) -> int:
|
| 73 |
+
return len(self.ops)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_instance(instance_dir: Path | str) -> Instance:
|
| 77 |
+
"""Read ``chunks.jsonl``, ``gold.json`` and ``meta.json`` from a directory."""
|
| 78 |
+
d = Path(instance_dir)
|
| 79 |
+
meta = json.loads((d / "meta.json").read_text(encoding="utf-8"))
|
| 80 |
+
gold = json.loads((d / "gold.json").read_text(encoding="utf-8"))
|
| 81 |
+
ops = proto.load_ops((d / "chunks.jsonl").read_text(encoding="utf-8").splitlines())
|
| 82 |
+
family = meta.get("task_family") or (gold.get("meta") or {}).get("task_family")
|
| 83 |
+
if not family:
|
| 84 |
+
raise ValueError(f"{d}: meta.json has no task_family")
|
| 85 |
+
return Instance(path=d, family=family, ops=ops, gold=gold, meta=meta)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def instruction_for(instance: Instance, *, delivery: str = "reply") -> str:
|
| 89 |
+
"""The instruction text for an instance's family."""
|
| 90 |
+
import importlib
|
| 91 |
+
|
| 92 |
+
module = importlib.import_module(
|
| 93 |
+
f"contextbench.tasks.{instance.family}.generate"
|
| 94 |
+
)
|
| 95 |
+
return module.instruction(instance.gold, delivery=delivery)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def run(
|
| 99 |
+
agent: ContextAgent,
|
| 100 |
+
instance_dir: Path | str,
|
| 101 |
+
*,
|
| 102 |
+
budget: int = 32768,
|
| 103 |
+
reserve: int = 2048,
|
| 104 |
+
out_dir: Path | str = "runs/latest",
|
| 105 |
+
max_turns: int | None = None,
|
| 106 |
+
system_prompt: str | None = None,
|
| 107 |
+
delivery: str = "reply",
|
| 108 |
+
) -> dict:
|
| 109 |
+
"""Run one instance end to end and return the result dict.
|
| 110 |
+
|
| 111 |
+
``budget`` and ``reserve`` set the wall: a turn whose snapshot exceeds
|
| 112 |
+
``budget - reserve`` tokens ends the run with ``terminated_by="budget_wall"``,
|
| 113 |
+
because a real serving stack would have refused the next request. ``max_turns``
|
| 114 |
+
is a safety stop, not part of the task: leave it unset for a full horizon.
|
| 115 |
+
|
| 116 |
+
Writes ``context_snapshots/turn-NNNN.json`` per turn, ``interactive_stream.json``
|
| 117 |
+
and ``result.json`` into ``out_dir``, and returns the same result dict.
|
| 118 |
+
"""
|
| 119 |
+
instance = load_instance(instance_dir)
|
| 120 |
+
out = Path(out_dir)
|
| 121 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 122 |
+
usable = budget - reserve
|
| 123 |
+
|
| 124 |
+
instruction = instruction_for(instance, delivery=delivery)
|
| 125 |
+
agent.reset(system_prompt or DEFAULT_SYSTEM_PROMPT, instruction)
|
| 126 |
+
|
| 127 |
+
total_ops = instance.n_ops
|
| 128 |
+
delivered = 0
|
| 129 |
+
step = 0
|
| 130 |
+
terminated_by: str | None = None
|
| 131 |
+
peak_tokens = 0
|
| 132 |
+
|
| 133 |
+
def _deliver_op(index: int) -> str:
|
| 134 |
+
return render_op(instance.ops[index], remaining=total_ops - (index + 1))
|
| 135 |
+
|
| 136 |
+
if total_ops == 0:
|
| 137 |
+
terminated_by = "stream_exhausted"
|
| 138 |
+
pending: str | None = None
|
| 139 |
+
else:
|
| 140 |
+
pending = _deliver_op(0)
|
| 141 |
+
delivered = 1
|
| 142 |
+
|
| 143 |
+
while pending is not None and terminated_by is None:
|
| 144 |
+
reply = agent.on_user_turn(pending) or ""
|
| 145 |
+
step += 1
|
| 146 |
+
|
| 147 |
+
messages = list(agent.context() or [])
|
| 148 |
+
tokens, _ = count_tokens(messages)
|
| 149 |
+
peak_tokens = max(peak_tokens, tokens)
|
| 150 |
+
record_snapshot(
|
| 151 |
+
out,
|
| 152 |
+
step,
|
| 153 |
+
messages,
|
| 154 |
+
{
|
| 155 |
+
"n_ops_delivered": delivered,
|
| 156 |
+
"n_ops_total": total_ops,
|
| 157 |
+
"budget": budget,
|
| 158 |
+
"reserve": reserve,
|
| 159 |
+
},
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if tokens > usable:
|
| 163 |
+
terminated_by = "budget_wall"
|
| 164 |
+
break
|
| 165 |
+
|
| 166 |
+
if proto.is_submit_line(reply) or proto.is_submit_command(reply):
|
| 167 |
+
if delivered < total_ops:
|
| 168 |
+
pending = proto.REFUSE_SUBMIT_TEXT
|
| 169 |
+
else:
|
| 170 |
+
terminated_by = "submit"
|
| 171 |
+
break
|
| 172 |
+
elif proto.is_ready_line(reply) or proto.is_ready_command(reply):
|
| 173 |
+
if delivered < total_ops:
|
| 174 |
+
pending = _deliver_op(delivered)
|
| 175 |
+
delivered += 1
|
| 176 |
+
else:
|
| 177 |
+
terminated_by = "stream_exhausted"
|
| 178 |
+
break
|
| 179 |
+
elif proto.mentions_advance_marker(reply):
|
| 180 |
+
pending = proto.EXPLAIN_NON_STANDALONE_TEXT
|
| 181 |
+
else:
|
| 182 |
+
pending = proto.NO_MARKER_TEXT
|
| 183 |
+
|
| 184 |
+
if max_turns is not None and step >= max_turns:
|
| 185 |
+
terminated_by = "max_steps"
|
| 186 |
+
break
|
| 187 |
+
|
| 188 |
+
if terminated_by is None:
|
| 189 |
+
terminated_by = "stream_exhausted"
|
| 190 |
+
|
| 191 |
+
stream_record = {
|
| 192 |
+
"n_ops_delivered": delivered,
|
| 193 |
+
"n_ops_total": total_ops,
|
| 194 |
+
"terminated_by": terminated_by,
|
| 195 |
+
}
|
| 196 |
+
(out / "interactive_stream.json").write_text(
|
| 197 |
+
json.dumps(stream_record, indent=2) + "\n", encoding="utf-8"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
rewards = grade_run(out, instance.gold)
|
| 201 |
+
result: dict[str, Any] = {
|
| 202 |
+
"task_family": instance.family,
|
| 203 |
+
"instance_dir": str(instance.path),
|
| 204 |
+
"out_dir": str(out),
|
| 205 |
+
"budget": budget,
|
| 206 |
+
"reserve": reserve,
|
| 207 |
+
"n_turns": step,
|
| 208 |
+
"peak_tokens": peak_tokens,
|
| 209 |
+
"reward": rewards.get("reward", 0.0),
|
| 210 |
+
"rewards": rewards,
|
| 211 |
+
**stream_record,
|
| 212 |
+
}
|
| 213 |
+
(out / "result.json").write_text(
|
| 214 |
+
json.dumps(result, indent=2, default=str) + "\n", encoding="utf-8"
|
| 215 |
+
)
|
| 216 |
+
return result
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/stream.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The ContextBench turn protocol: op rendering, readiness detection, refusals.
|
| 2 |
+
|
| 3 |
+
Pure Python. This module is the single definition of how an operation reaches the
|
| 4 |
+
agent and how the agent asks for the next one, so the Python runner and (phase 2)
|
| 5 |
+
the Harbor adapters cannot drift apart.
|
| 6 |
+
|
| 7 |
+
Readiness has two equivalent forms:
|
| 8 |
+
|
| 9 |
+
* ``READY_FOR_NEXT_OP`` as a **standalone line** of the reply -- for chat agents
|
| 10 |
+
driven by :mod:`contextbench.runner`, which have no shell;
|
| 11 |
+
* ``echo READY_FOR_NEXT_OP`` as a **standalone shell statement** -- for agents
|
| 12 |
+
with a bash tool, where the marker is a command the harness executes.
|
| 13 |
+
|
| 14 |
+
Both are deliberately strict about "standalone": the marker must not count when it
|
| 15 |
+
merely appears as an argument (``grep READY_FOR_NEXT_OP file``) or inside answer
|
| 16 |
+
data, because a spurious advance consumes an operation that is then lost forever.
|
| 17 |
+
A command that failed (non-zero exit) never advances either: the step did not
|
| 18 |
+
finish, so the op must not be handed over.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from typing import Iterable
|
| 26 |
+
|
| 27 |
+
__all__ = [
|
| 28 |
+
"ADVANCE_MARKER",
|
| 29 |
+
"SUBMIT_MARKER",
|
| 30 |
+
"TERMINATED_BY",
|
| 31 |
+
"Op",
|
| 32 |
+
"render_op",
|
| 33 |
+
"is_ready_line",
|
| 34 |
+
"is_ready_command",
|
| 35 |
+
"mentions_advance_marker",
|
| 36 |
+
"is_submit_line",
|
| 37 |
+
"is_submit_command",
|
| 38 |
+
"mentions_submit_marker",
|
| 39 |
+
"REFUSE_SUBMIT_TEXT",
|
| 40 |
+
"EXPLAIN_NON_STANDALONE_TEXT",
|
| 41 |
+
"NO_MARKER_TEXT",
|
| 42 |
+
"SUBMIT_PARAGRAPH",
|
| 43 |
+
"MARKER_PARAGRAPH",
|
| 44 |
+
"MARKER_PARAGRAPH_REPLY",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
ADVANCE_MARKER = "READY_FOR_NEXT_OP"
|
| 48 |
+
SUBMIT_MARKER = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
|
| 49 |
+
|
| 50 |
+
#: Every way a ContextBench run can end. ``timeout`` is produced by wall-clock
|
| 51 |
+
#: enforcement in the container runners; the pure-Python runner produces the
|
| 52 |
+
#: other four.
|
| 53 |
+
TERMINATED_BY = (
|
| 54 |
+
"submit",
|
| 55 |
+
"stream_exhausted",
|
| 56 |
+
"budget_wall",
|
| 57 |
+
"timeout",
|
| 58 |
+
"max_steps",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _standalone_line_re(marker: str) -> re.Pattern[str]:
|
| 63 |
+
"""The marker alone on a line, tolerating whitespace and code-fence quoting."""
|
| 64 |
+
return re.compile(
|
| 65 |
+
rf"^[ \t]*(?:`{{1,3}})?{re.escape(marker)}(?:`{{1,3}})?[ \t]*\.?[ \t]*$",
|
| 66 |
+
re.MULTILINE,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _standalone_command_re(marker: str) -> re.Pattern[str]:
|
| 71 |
+
"""``echo MARKER`` as a whole shell statement (quotes optional)."""
|
| 72 |
+
return re.compile(
|
| 73 |
+
rf"""^\s*(?:/bin/)?echo\s+(?:['"])?{re.escape(marker)}(?:['"])?\s*$"""
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_READY_LINE_RE = _standalone_line_re(ADVANCE_MARKER)
|
| 78 |
+
_READY_SEGMENT_RE = _standalone_command_re(ADVANCE_MARKER)
|
| 79 |
+
_SUBMIT_LINE_RE = _standalone_line_re(SUBMIT_MARKER)
|
| 80 |
+
_SUBMIT_SEGMENT_RE = _standalone_command_re(SUBMIT_MARKER)
|
| 81 |
+
|
| 82 |
+
#: Shell statement separators. A bundled command such as
|
| 83 |
+
#: ``printf '<<<ANSWER ...>>>'; echo READY_FOR_NEXT_OP`` advances, because its
|
| 84 |
+
#: last segment is a clean echo.
|
| 85 |
+
_SEPARATORS = re.compile(r";|\n|&&|\|\|")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_HEREDOC_OPEN = re.compile(r"<<(-?)\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\2")
|
| 89 |
+
_MULTILINE_QUOTED = re.compile(r"'[^']*\n[^']*'|\"(?:[^\"\\]|\\.)*\n(?:[^\"\\]|\\.)*\"")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _strip_heredoc_bodies(command: str) -> str:
|
| 93 |
+
"""Drop the body lines of every here-document; keep the line that opens it.
|
| 94 |
+
|
| 95 |
+
A here-document body is data fed to a program, not shell statements, so an
|
| 96 |
+
``echo READY_FOR_NEXT_OP`` line inside it never runs and must not count.
|
| 97 |
+
"""
|
| 98 |
+
lines = command.split("\n")
|
| 99 |
+
out: list[str] = []
|
| 100 |
+
i = 0
|
| 101 |
+
while i < len(lines):
|
| 102 |
+
line = lines[i]
|
| 103 |
+
out.append(line)
|
| 104 |
+
pending = _HEREDOC_OPEN.findall(line)
|
| 105 |
+
i += 1
|
| 106 |
+
for dash, _quote, word in pending:
|
| 107 |
+
while i < len(lines):
|
| 108 |
+
body_line = lines[i]
|
| 109 |
+
i += 1
|
| 110 |
+
if (body_line.lstrip("\t") if dash else body_line) == word:
|
| 111 |
+
break
|
| 112 |
+
return "\n".join(out)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _statements(command: str) -> list[str]:
|
| 116 |
+
"""Split a shell command into statements, ignoring here-document bodies and
|
| 117 |
+
quoted strings that span lines (both are data, not statements)."""
|
| 118 |
+
text = _strip_heredoc_bodies(command)
|
| 119 |
+
text = _MULTILINE_QUOTED.sub("''", text)
|
| 120 |
+
return _SEPARATORS.split(text)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass(frozen=True)
|
| 124 |
+
class Op:
|
| 125 |
+
"""One streamed operation, as it is stored in ``chunks.jsonl``."""
|
| 126 |
+
|
| 127 |
+
index: int
|
| 128 |
+
header: str
|
| 129 |
+
body: str
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def from_dict(cls, obj: dict, *, fallback_index: int = 0) -> "Op":
|
| 133 |
+
return cls(
|
| 134 |
+
index=int(obj.get("index", fallback_index)),
|
| 135 |
+
header=str(obj.get("header", "")),
|
| 136 |
+
body=str(obj.get("body", "")),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def render_op(op: Op, *, remaining: int) -> str:
|
| 141 |
+
"""The exact user-turn text for one operation.
|
| 142 |
+
|
| 143 |
+
``remaining`` is the number of operations that follow this one.
|
| 144 |
+
"""
|
| 145 |
+
return f"=== {op.header} ({remaining} op(s) remaining after this) ===\n{op.body}"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def load_ops(lines: Iterable[str]) -> list[Op]:
|
| 149 |
+
"""Parse ``chunks.jsonl`` lines into :class:`Op` objects."""
|
| 150 |
+
import json
|
| 151 |
+
|
| 152 |
+
ops: list[Op] = []
|
| 153 |
+
for line in lines:
|
| 154 |
+
if line.strip():
|
| 155 |
+
ops.append(Op.from_dict(json.loads(line), fallback_index=len(ops)))
|
| 156 |
+
return ops
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# --------------------------------------------------------------------- matching
|
| 160 |
+
def is_ready_line(reply: str) -> bool:
|
| 161 |
+
"""True when the reply carries the advance marker on a line of its own."""
|
| 162 |
+
return bool(reply) and bool(_READY_LINE_RE.search(reply))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def is_ready_command(command: str, exit_code: int = 0) -> bool:
|
| 166 |
+
"""True when ``command`` runs ``echo READY_FOR_NEXT_OP`` as a whole statement.
|
| 167 |
+
|
| 168 |
+
A failed command means the step did not finish, so it never advances.
|
| 169 |
+
"""
|
| 170 |
+
if not command or exit_code != 0:
|
| 171 |
+
return False
|
| 172 |
+
return any(_READY_SEGMENT_RE.match(seg) for seg in _statements(command))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def mentions_advance_marker(text: str) -> bool:
|
| 176 |
+
return bool(text) and ADVANCE_MARKER in text
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def is_submit_line(reply: str) -> bool:
|
| 180 |
+
return bool(reply) and bool(_SUBMIT_LINE_RE.search(reply))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def is_submit_command(command: str, exit_code: int = 0) -> bool:
|
| 184 |
+
if not command or exit_code != 0:
|
| 185 |
+
return False
|
| 186 |
+
return any(_SUBMIT_SEGMENT_RE.match(seg) for seg in _statements(command))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def mentions_submit_marker(text: str) -> bool:
|
| 190 |
+
return bool(text) and SUBMIT_MARKER in text
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ----------------------------------------------------------- texts sent back
|
| 194 |
+
#: Sent when the agent submits while operations are still undelivered.
|
| 195 |
+
REFUSE_SUBMIT_TEXT = (
|
| 196 |
+
"There is nothing to submit in this task and the run did NOT end. "
|
| 197 |
+
"Operations are still being delivered one at a time: run the "
|
| 198 |
+
f"standalone command `echo {ADVANCE_MARKER}` to receive the "
|
| 199 |
+
"next one, and keep doing that until you are told none remain."
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
#: Sent when the marker appeared but not as a standalone statement. Without this
|
| 203 |
+
#: the agent sees its command succeed, believes it advanced, and then stalls in
|
| 204 |
+
#: empty turns with no error signal anywhere.
|
| 205 |
+
EXPLAIN_NON_STANDALONE_TEXT = (
|
| 206 |
+
f"[{ADVANCE_MARKER} did NOT advance: it must be a STANDALONE "
|
| 207 |
+
f"command -- `echo {ADVANCE_MARKER}` on its own, or as the last "
|
| 208 |
+
f"statement after a `;`. It does not count when passed as an "
|
| 209 |
+
f"argument to printf/cat/grep. Your command ran normally; run the "
|
| 210 |
+
f"marker as its own statement to receive the next operation.]"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
#: Sent when a reply neither handled the op nor asked for the next one.
|
| 214 |
+
NO_MARKER_TEXT = (
|
| 215 |
+
f"[No {ADVANCE_MARKER} in your reply, so the stream did not advance. "
|
| 216 |
+
f"Finish the current operation, then put {ADVANCE_MARKER} on a line of "
|
| 217 |
+
f"its own to receive the next one.]"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
#: The two closing paragraphs a system prompt can carry. The submit contract is
|
| 221 |
+
#: wrong for a streamed task: an agent that submits before the stream is drained
|
| 222 |
+
#: loses every operation it has not seen.
|
| 223 |
+
SUBMIT_PARAGRAPH = (
|
| 224 |
+
"When you are finished, submit by running the standalone command\n"
|
| 225 |
+
f"`echo {SUBMIT_MARKER}` (with nothing else in that command).\n"
|
| 226 |
+
"After it runs you cannot continue."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
MARKER_PARAGRAPH = (
|
| 230 |
+
"This task is delivered to you one operation at a time. You do NOT submit and\n"
|
| 231 |
+
"you do NOT decide when it is over: after handling each operation, run the\n"
|
| 232 |
+
f"standalone command `echo {ADVANCE_MARKER}` (with nothing else in that\n"
|
| 233 |
+
"command) to receive the next one. Do this for EVERY operation, including the\n"
|
| 234 |
+
"one that says none remain -- that final marker is what ends the run, and the\n"
|
| 235 |
+
"harness stops you. Submitting early discards the work you just did."
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
MARKER_PARAGRAPH_REPLY = (
|
| 239 |
+
"This task is delivered to you one operation at a time. You do NOT decide when\n"
|
| 240 |
+
"it is over: after handling each operation, end your reply with\n"
|
| 241 |
+
f"{ADVANCE_MARKER} on a line of its own to receive the next one. Do this for\n"
|
| 242 |
+
"EVERY operation, including the one that says none remain. Submitting early\n"
|
| 243 |
+
"discards the work you just did."
|
| 244 |
+
)
|
harbor/kv-store-R1000-seed43/tests/_cb/contextbench/tokens.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token counting and per-turn context snapshots.
|
| 2 |
+
|
| 3 |
+
Every part of ContextBench that asks "how big is this context right now?" goes
|
| 4 |
+
through :func:`count_tokens`: exact ``o200k_base`` counts when ``tiktoken`` can be
|
| 5 |
+
imported, and a ``len // 3`` character estimate otherwise, so the package works
|
| 6 |
+
with no optional dependency and no network.
|
| 7 |
+
|
| 8 |
+
:func:`record_snapshot` persists the full retained context after each turn. The
|
| 9 |
+
snapshots are the paper metric's source of truth: an agent that offloads content
|
| 10 |
+
to disk and reads a value back only transiently still has that value captured in
|
| 11 |
+
the snapshot of the turn where it surfaced.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Iterator
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"SNAPSHOT_DIRNAME",
|
| 23 |
+
"count_text",
|
| 24 |
+
"count_tokens",
|
| 25 |
+
"get_encoder",
|
| 26 |
+
"iter_text",
|
| 27 |
+
"record_snapshot",
|
| 28 |
+
"snapshot_paths",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
SNAPSHOT_DIRNAME = "context_snapshots"
|
| 32 |
+
|
| 33 |
+
#: The character-per-token divisor used when tiktoken is unavailable.
|
| 34 |
+
FALLBACK_CHARS_PER_TOKEN = 3
|
| 35 |
+
|
| 36 |
+
_ENCODER: Any = None
|
| 37 |
+
_ENCODER_NAME: str | None = None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def get_encoder() -> Any:
|
| 41 |
+
"""A cached ``tiktoken`` encoder, or ``None`` when tiktoken is unavailable.
|
| 42 |
+
|
| 43 |
+
Defaults to ``o200k_base``; ``TIKTOKEN_ENCODING`` overrides it and
|
| 44 |
+
``cl100k_base`` is the second choice (its vocabulary may be cached when
|
| 45 |
+
``o200k_base`` is not).
|
| 46 |
+
"""
|
| 47 |
+
global _ENCODER, _ENCODER_NAME
|
| 48 |
+
if _ENCODER is not None or _ENCODER_NAME == "_failed":
|
| 49 |
+
return _ENCODER
|
| 50 |
+
try:
|
| 51 |
+
import tiktoken
|
| 52 |
+
except Exception:
|
| 53 |
+
_ENCODER_NAME = "_failed"
|
| 54 |
+
return None
|
| 55 |
+
for name in (os.environ.get("TIKTOKEN_ENCODING") or "o200k_base", "cl100k_base"):
|
| 56 |
+
try:
|
| 57 |
+
_ENCODER = tiktoken.get_encoding(name)
|
| 58 |
+
_ENCODER_NAME = name
|
| 59 |
+
return _ENCODER
|
| 60 |
+
except Exception:
|
| 61 |
+
continue # e.g. the vocabulary download is blocked offline
|
| 62 |
+
_ENCODER_NAME = "_failed"
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def encoder_name() -> str:
|
| 67 |
+
"""The method label that :func:`count_tokens` reports."""
|
| 68 |
+
get_encoder()
|
| 69 |
+
if _ENCODER_NAME in (None, "_failed"):
|
| 70 |
+
return f"approx_chars{FALLBACK_CHARS_PER_TOKEN}"
|
| 71 |
+
return f"tiktoken:{_ENCODER_NAME}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def iter_text(messages: list[Any] | None) -> Iterator[str]:
|
| 75 |
+
"""Yield every text piece of ``messages`` that reaches the model.
|
| 76 |
+
|
| 77 |
+
This includes ``tool_calls[*].function.arguments``, where a shell command
|
| 78 |
+
lives: a tool-heavy agent keeps most of its bytes there, so counting only
|
| 79 |
+
``content`` would undercount the real prompt by roughly a factor of two.
|
| 80 |
+
"""
|
| 81 |
+
for msg in messages or []:
|
| 82 |
+
content: Any
|
| 83 |
+
if isinstance(msg, dict):
|
| 84 |
+
reasoning = msg.get("reasoning_content")
|
| 85 |
+
if isinstance(reasoning, str):
|
| 86 |
+
yield reasoning
|
| 87 |
+
content = msg.get("content")
|
| 88 |
+
for call in msg.get("tool_calls") or []:
|
| 89 |
+
fn = call.get("function") if isinstance(call, dict) else None
|
| 90 |
+
if isinstance(fn, dict):
|
| 91 |
+
if fn.get("name"):
|
| 92 |
+
yield str(fn["name"])
|
| 93 |
+
if fn.get("arguments"):
|
| 94 |
+
yield str(fn["arguments"])
|
| 95 |
+
else:
|
| 96 |
+
content = msg
|
| 97 |
+
if isinstance(content, str):
|
| 98 |
+
yield content
|
| 99 |
+
elif isinstance(content, list):
|
| 100 |
+
for item in content:
|
| 101 |
+
if isinstance(item, dict):
|
| 102 |
+
yield str(item.get("text") or item.get("content") or "")
|
| 103 |
+
else:
|
| 104 |
+
yield str(item)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def count_text(text: str) -> int:
|
| 108 |
+
"""Token count of one string (exact with tiktoken, else ``len // 3``)."""
|
| 109 |
+
if not text:
|
| 110 |
+
return 0
|
| 111 |
+
enc = get_encoder()
|
| 112 |
+
if enc is None:
|
| 113 |
+
return max(1, len(text) // FALLBACK_CHARS_PER_TOKEN)
|
| 114 |
+
return len(enc.encode(text, disallowed_special=()))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def count_tokens(messages: list[Any] | None) -> tuple[int, str]:
|
| 118 |
+
"""Token count over a message list. Returns ``(tokens, method)``."""
|
| 119 |
+
total = sum(count_text(piece) for piece in iter_text(messages))
|
| 120 |
+
return total, encoder_name()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def snapshot_paths(logs_dir: Path | str) -> list[Path]:
|
| 124 |
+
"""Every ``context_snapshots/turn-*.json`` under ``logs_dir``, in turn order."""
|
| 125 |
+
import re
|
| 126 |
+
|
| 127 |
+
d = Path(logs_dir) / SNAPSHOT_DIRNAME
|
| 128 |
+
if not d.is_dir():
|
| 129 |
+
return []
|
| 130 |
+
|
| 131 |
+
def _turn(path: Path) -> int:
|
| 132 |
+
m = re.search(r"turn-(\d+)", path.name)
|
| 133 |
+
return int(m.group(1)) if m else -1
|
| 134 |
+
|
| 135 |
+
return sorted(d.glob("turn-*.json"), key=_turn)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def record_snapshot(
|
| 139 |
+
logs_dir: Path | str,
|
| 140 |
+
step: int,
|
| 141 |
+
messages: list[Any],
|
| 142 |
+
extra: dict[str, Any] | None = None,
|
| 143 |
+
) -> Path | None:
|
| 144 |
+
"""Persist one per-turn snapshot of the full retained context.
|
| 145 |
+
|
| 146 |
+
Writes ``<logs_dir>/context_snapshots/turn-NNNN.json`` holding ``step``,
|
| 147 |
+
``tokens``, ``token_method``, ``n_messages``, anything in ``extra``, and the
|
| 148 |
+
``messages`` themselves (last, so a human reading the file sees the
|
| 149 |
+
accounting first). Best effort: snapshotting is a logging side effect and
|
| 150 |
+
never raises into the run.
|
| 151 |
+
"""
|
| 152 |
+
try:
|
| 153 |
+
d = Path(logs_dir) / SNAPSHOT_DIRNAME
|
| 154 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 155 |
+
tokens, method = count_tokens(messages)
|
| 156 |
+
payload: dict[str, Any] = {
|
| 157 |
+
"step": step,
|
| 158 |
+
"tokens": tokens,
|
| 159 |
+
"token_method": method,
|
| 160 |
+
"n_messages": len(messages or []),
|
| 161 |
+
}
|
| 162 |
+
if extra:
|
| 163 |
+
payload.update(extra)
|
| 164 |
+
payload["messages"] = messages
|
| 165 |
+
out = d / f"turn-{step:04d}.json"
|
| 166 |
+
out.write_text(
|
| 167 |
+
json.dumps(payload, indent=2, default=str) + "\n", encoding="utf-8"
|
| 168 |
+
)
|
| 169 |
+
return out
|
| 170 |
+
except Exception:
|
| 171 |
+
return None
|
harbor/kv-store-R1000-seed43/tests/feasibility_receipt.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"verdict": "PASS",
|
| 3 |
+
"feasible": true,
|
| 4 |
+
"task_family": "kv_store",
|
| 5 |
+
"checks": {
|
| 6 |
+
"pressure": {
|
| 7 |
+
"pass": true,
|
| 8 |
+
"detail": "streamed 49717 / budget 32768 = P 1.52 (need > 1)"
|
| 9 |
+
},
|
| 10 |
+
"small_ops": {
|
| 11 |
+
"pass": true,
|
| 12 |
+
"detail": "max op 4909 tok (cap 5529 = usable 30720 / 5 x 0.9)"
|
| 13 |
+
},
|
| 14 |
+
"retained": {
|
| 15 |
+
"pass": true,
|
| 16 |
+
"detail": "retained 1688 tok [per-batch index 200 + answers 1488] (cap 13824 = usable / 2 x 0.9)"
|
| 17 |
+
},
|
| 18 |
+
"horizon": {
|
| 19 |
+
"pass": true,
|
| 20 |
+
"detail": "34 ops (need >= 4)"
|
| 21 |
+
}
|
| 22 |
+
},
|
| 23 |
+
"measured": {
|
| 24 |
+
"P": 1.517,
|
| 25 |
+
"streamed_tokens": 49717,
|
| 26 |
+
"max_op_tokens": 4909,
|
| 27 |
+
"retained_tokens": 1688,
|
| 28 |
+
"n_ops": 34
|
| 29 |
+
},
|
| 30 |
+
"budget": 32768,
|
| 31 |
+
"reserve": 2048,
|
| 32 |
+
"usable_tokens": 30720,
|
| 33 |
+
"cap_op_tokens": 5529,
|
| 34 |
+
"cap_retained_tokens": 13824,
|
| 35 |
+
"regime": "pressure",
|
| 36 |
+
"token_method": "tiktoken:o200k_base",
|
| 37 |
+
"validator_sha16": "ad7a9a4d10534c47"
|
| 38 |
+
}
|
harbor/kv-store-R1000-seed43/tests/gold.json
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"queries": [
|
| 3 |
+
{
|
| 4 |
+
"qid": 0,
|
| 5 |
+
"key": "K00101",
|
| 6 |
+
"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"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"qid": 1,
|
| 10 |
+
"key": "K00011",
|
| 11 |
+
"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"
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"qid": 2,
|
| 15 |
+
"key": "K00313",
|
| 16 |
+
"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"
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"qid": 3,
|
| 20 |
+
"key": "K00307",
|
| 21 |
+
"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"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"qid": 4,
|
| 25 |
+
"key": "K00769",
|
| 26 |
+
"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"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"qid": 5,
|
| 30 |
+
"key": "K00979",
|
| 31 |
+
"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"
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"qid": 6,
|
| 35 |
+
"key": "K00697",
|
| 36 |
+
"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"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"qid": 7,
|
| 40 |
+
"key": "K00485",
|
| 41 |
+
"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"
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"qid": 8,
|
| 45 |
+
"key": "K00974",
|
| 46 |
+
"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"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"qid": 9,
|
| 50 |
+
"key": "K00827",
|
| 51 |
+
"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"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"qid": 10,
|
| 55 |
+
"key": "K00203",
|
| 56 |
+
"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"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"qid": 11,
|
| 60 |
+
"key": "K00565",
|
| 61 |
+
"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"
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"qid": 12,
|
| 65 |
+
"key": "K00704",
|
| 66 |
+
"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"
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"qid": 13,
|
| 70 |
+
"key": "K00358",
|
| 71 |
+
"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"
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"qid": 14,
|
| 75 |
+
"key": "K00665",
|
| 76 |
+
"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"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"qid": 15,
|
| 80 |
+
"key": "K00586",
|
| 81 |
+
"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"
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"qid": 16,
|
| 85 |
+
"key": "K00867",
|
| 86 |
+
"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"
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"qid": 17,
|
| 90 |
+
"key": "K00879",
|
| 91 |
+
"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"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"qid": 18,
|
| 95 |
+
"key": "K00091",
|
| 96 |
+
"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"
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"qid": 19,
|
| 100 |
+
"key": "K00989",
|
| 101 |
+
"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"
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"qid": 20,
|
| 105 |
+
"key": "K00265",
|
| 106 |
+
"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"
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"qid": 21,
|
| 110 |
+
"key": "K00207",
|
| 111 |
+
"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"
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"qid": 22,
|
| 115 |
+
"key": "K00930",
|
| 116 |
+
"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"
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"qid": 23,
|
| 120 |
+
"key": "K00031",
|
| 121 |
+
"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"
|
| 122 |
+
}
|
| 123 |
+
],
|
| 124 |
+
"meta": {
|
| 125 |
+
"task_family": "kv_store",
|
| 126 |
+
"seed": 43,
|
| 127 |
+
"records": 1000,
|
| 128 |
+
"value_words": 24,
|
| 129 |
+
"records_per_chunk": 100,
|
| 130 |
+
"queries": 24,
|
| 131 |
+
"n_set": 1000,
|
| 132 |
+
"n_get": 24,
|
| 133 |
+
"n_batches": 10,
|
| 134 |
+
"n_actions": 34,
|
| 135 |
+
"approx_value_tokens": 48428,
|
| 136 |
+
"approx_per_value_tokens": 48
|
| 137 |
+
}
|
| 138 |
+
}
|
harbor/kv-store-R1000-seed43/tests/meta.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"task_family": "kv_store",
|
| 3 |
+
"seed": 43,
|
| 4 |
+
"records": 1000,
|
| 5 |
+
"value_words": 24,
|
| 6 |
+
"records_per_chunk": 100,
|
| 7 |
+
"queries": 24,
|
| 8 |
+
"n_set": 1000,
|
| 9 |
+
"n_get": 24,
|
| 10 |
+
"n_batches": 10,
|
| 11 |
+
"n_actions": 34,
|
| 12 |
+
"approx_value_tokens": 48428,
|
| 13 |
+
"approx_per_value_tokens": 48
|
| 14 |
+
}
|
harbor/kv-store-R1000-seed43/tests/test.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Grades the agent's own messages (context snapshots, else trajectory, else final
|
| 3 |
+
# report) with the ContextBench graders vendored next to this script. Runs after the
|
| 4 |
+
# agent has finished; writes /logs/verifier/reward.json.
|
| 5 |
+
set -u
|
| 6 |
+
PY=$(command -v python3 || command -v python) || {
|
| 7 |
+
echo "ContextBench grading needs python3 in the image; or verify on the host with" "contextbench.harbor.verifiers:ContextBenchVerifier" >&2
|
| 8 |
+
exit 2
|
| 9 |
+
}
|
| 10 |
+
PYTHONPATH=/tests/_cb "$PY" -m contextbench.harbor.reward --agent-dir /logs/agent --gold /tests/gold.json --out-dir /logs/verifier
|
harbor/kv-store-R1000-seed44/environment/stream/chunks.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|