grader: refuse links, hardlinks and non-regular answers (#120 review); check.py: cheat cases and Trials
Browse files- README.md +28 -13
- check.py +159 -54
- generate.py +49 -12
README.md
CHANGED
|
@@ -67,9 +67,13 @@ container holds another agent's number.
|
|
| 67 |
exactly `tests/expected.json`: a JSON array of the team's integers in ascending order, one per
|
| 68 |
agent. Anything else scores **0**: a missing or unreadable file, invalid JSON, `NaN`, a
|
| 69 |
non-array, strings, words, floats or booleans, a missing, extra or dropped duplicate number, and
|
| 70 |
-
a wrong order.
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
## Run it with Flock
|
| 75 |
|
|
@@ -90,25 +94,32 @@ uv run experiments/s3/metrics.py .flock/agg-p07-n04-<time>/
|
|
| 90 |
The checks that need no model, in one command (`uv` installs Harbor 0.25.0):
|
| 91 |
|
| 92 |
```sh
|
| 93 |
-
uv run check.py # the
|
| 94 |
-
uv run check.py --env docker # the
|
| 95 |
-
uv run check.py --env none # without the
|
| 96 |
```
|
| 97 |
|
| 98 |
1. **Generator:** `generate.py` reproduces `problems.json`, `tasks/` and `roles/` byte for byte;
|
| 99 |
another seed gives other problems; 32 problems of 16 integers in 1..99; the words read back
|
| 100 |
to their numbers; each task's team is its problem's first N numbers, and each role file holds
|
| 101 |
its own slot's number.
|
| 102 |
-
2. **Graders
|
| 103 |
-
|
| 104 |
-
team size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
3. **No-cheat, in the files:** a task folder holds only its five files, its instruction is the
|
| 106 |
same for every problem of its team size, the answer is only in `tests/` and `solution/`, and
|
| 107 |
the role files are outside `tasks/`.
|
| 108 |
-
4. **No-cheat, from inside
|
| 109 |
-
while "the agent works" and finds no `tests/` or `solution/` and no file
|
| 110 |
-
a role line or a hyphenated number word of the problem; then it writes
|
| 111 |
-
search finds it (a control), and the task's verifier scores it 1.
|
|
|
|
|
|
|
| 112 |
|
| 113 |
`--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads
|
| 114 |
`tests/` with the host's file owner, which a sandbox can't take when the host's uid is over
|
|
@@ -125,6 +136,10 @@ To check the grader alone with Harbor: `harbor run --path tasks/agg-p07-n04 --ag
|
|
| 125 |
`agents.role_files` gives the agent no number to share.
|
| 126 |
- **The grader can't see the board:** an agent could guess or copy a wrong number and still be
|
| 127 |
scored only on its file. The board export in the run directory shows what was said.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
- **One board per team.** The instruction has no run tag, so a reused board's earlier posts
|
| 129 |
would read as this team's: give each team a new board (Flock's local board is new each run;
|
| 130 |
delete a Space board after its run).
|
|
|
|
| 67 |
exactly `tests/expected.json`: a JSON array of the team's integers in ascending order, one per
|
| 68 |
agent. Anything else scores **0**: a missing or unreadable file, invalid JSON, `NaN`, a
|
| 69 |
non-array, strings, words, floats or booleans, a missing, extra or dropped duplicate number, and
|
| 70 |
+
a wrong order. The answer counts only as a regular file of its own at exactly
|
| 71 |
+
`/app/answer.json`: a symlink (e.g. to `/tests/expected.json`, which arrives only after the
|
| 72 |
+
agent is done), a link anywhere on the path (a symlinked `/app`), a hardlink, a directory or a
|
| 73 |
+
FIFO scores 0, and `expected.json` is read the same way. The grader follows no link an agent may
|
| 74 |
+
have left, writes 0 before it checks anything (a crash also scores 0), and keeps a copy of the
|
| 75 |
+
answer with the trial's results. Each agent is scored on its own answer; the team succeeds if
|
| 76 |
+
any agent scores 1.
|
| 77 |
|
| 78 |
## Run it with Flock
|
| 79 |
|
|
|
|
| 94 |
The checks that need no model, in one command (`uv` installs Harbor 0.25.0):
|
| 95 |
|
| 96 |
```sh
|
| 97 |
+
uv run check.py # the Trials on HF Sandboxes (HF_TOKEN, three cpu-basic sandboxes)
|
| 98 |
+
uv run check.py --env docker # the Trials in local docker
|
| 99 |
+
uv run check.py --env none # without the Trials
|
| 100 |
```
|
| 101 |
|
| 102 |
1. **Generator:** `generate.py` reproduces `problems.json`, `tasks/` and `roles/` byte for byte;
|
| 103 |
another seed gives other problems; 32 problems of 16 integers in 1..99; the words read back
|
| 104 |
to their numbers; each task's team is its problem's first N numbers, and each role file holds
|
| 105 |
its own slot's number.
|
| 106 |
+
2. **Graders**, run as Harbor runs them (`tests/` copied in after the agent is done, through
|
| 107 |
+
any link the agent left): on all 160 tasks the oracle scores 1, and wrong, partial, padded,
|
| 108 |
+
unsorted and duplicate-dropping answers score 0. On one task per team size, twelve kinds of
|
| 109 |
+
malformed answer score 0, and so do ten cheats: the answer as a symlink to the tests'
|
| 110 |
+
`expected.json` (dangling until the tests arrive; absolute or relative), a symlink or a
|
| 111 |
+
hardlink to a right answer elsewhere, a hardlink to `expected.json`, a symlinked `/app` (to a
|
| 112 |
+
right answer, or into the tests' folder), an `expected.json` planted as a link to the answer,
|
| 113 |
+
a directory and a FIFO (which must not hang the grader).
|
| 114 |
3. **No-cheat, in the files:** a task folder holds only its five files, its instruction is the
|
| 115 |
same for every problem of its team size, the answer is only in `tests/` and `solution/`, and
|
| 116 |
the role files are outside `tasks/`.
|
| 117 |
+
4. **No-cheat, from inside Trials** of `agg-p01-n16`, with probe agents (no model): one runs in
|
| 118 |
+
the container while "the agent works" and finds no `tests/` or `solution/` and no file
|
| 119 |
+
holding the answer, a role line or a hyphenated number word of the problem; then it writes
|
| 120 |
+
the answer, the same search finds it (a control), and the task's verifier scores it 1. Two
|
| 121 |
+
more leave `/app/answer.json` as a symlink to `/tests/expected.json`, and `/app` as a symlink
|
| 122 |
+
into a `/tests` they made: the verifier scores both 0.
|
| 123 |
|
| 124 |
`--env` takes a Harbor environment type or an import path. Harbor 0.25.0's `hf-sandbox` uploads
|
| 125 |
`tests/` with the host's file owner, which a sandbox can't take when the host's uid is over
|
|
|
|
| 136 |
`agents.role_files` gives the agent no number to share.
|
| 137 |
- **The grader can't see the board:** an agent could guess or copy a wrong number and still be
|
| 138 |
scored only on its file. The board export in the run directory shows what was said.
|
| 139 |
+
- **The verifier runs in the agent's container**, as in every Harbor task. The grader closes the
|
| 140 |
+
file-level holes above, but an agent that replaced the container's `python3` or `bash`, or
|
| 141 |
+
left a process running to rewrite the reward, could still forge one: check the run's board
|
| 142 |
+
export and the agents' transcripts when a result looks too good.
|
| 143 |
- **One board per team.** The instruction has no run tag, so a reused board's earlier posts
|
| 144 |
would read as this team's: give each team a new board (Flock's local board is new each run;
|
| 145 |
delete a Space board after its run).
|
check.py
CHANGED
|
@@ -4,26 +4,33 @@
|
|
| 4 |
# ///
|
| 5 |
"""s3-aggregation's checks that need no model (huggingface/flock#115, section 5):
|
| 6 |
|
| 7 |
-
uv run check.py # all of them; the
|
| 8 |
-
uv run check.py --env docker # the
|
| 9 |
-
uv run check.py --env none # skip the
|
| 10 |
|
| 11 |
1. Generator: generate.py reproduces problems.json, tasks/ and roles/ byte for byte from its
|
| 12 |
seed; another seed gives other problems; 32 problems of 16 integers in 1..99; the English
|
| 13 |
words read back to their numbers; each task's team is its problem's first N numbers, and each
|
| 14 |
role file holds its own slot's number.
|
| 15 |
-
2. Graders
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and
|
| 20 |
solution/; its instruction is the same for every problem of its team size; the answer is only
|
| 21 |
in tests/ and solution/; the role files live outside tasks/.
|
| 22 |
-
4. No-cheat, from inside
|
| 23 |
-
container while "the agent works" and finds no tests/ or solution/
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
`--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
|
| 28 |
uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
|
| 29 |
over 65535 (some clusters): use flock's `--env flock.harbor.envs:HFSandbox` there.
|
|
@@ -35,6 +42,7 @@ import base64
|
|
| 35 |
import json
|
| 36 |
import os
|
| 37 |
import shlex
|
|
|
|
| 38 |
import subprocess
|
| 39 |
import sys
|
| 40 |
import tempfile
|
|
@@ -108,15 +116,28 @@ def check_generator() -> None:
|
|
| 108 |
check({p.name for p in (HERE / "roles").iterdir()} == names, "roles/ has other folders")
|
| 109 |
|
| 110 |
|
| 111 |
-
def grade(task: Path, answer: bytes | None) -> int:
|
| 112 |
-
"""The task's
|
|
|
|
|
|
|
|
|
|
| 113 |
with tempfile.TemporaryDirectory() as d:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
return int((verifier / "reward.txt").read_text().strip())
|
| 121 |
|
| 122 |
|
|
@@ -152,17 +173,73 @@ def malformed(team: list[int]) -> dict[str, bytes | None]:
|
|
| 152 |
"invalid UTF-8": b"\xff" + dump}
|
| 153 |
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
def check_graders() -> dict[str, int]:
|
| 156 |
covered: dict[str, int] = {}
|
| 157 |
for task in sorted((HERE / "tasks").iterdir()):
|
| 158 |
team = json.loads((task / "tests" / "expected.json").read_text())
|
| 159 |
check(oracle(task) == 1, f"{task.name}: the oracle does not score 1")
|
| 160 |
-
cases = {k: json.dumps(v).encode() for k, v in wrong_answers(team).items()}
|
| 161 |
if task.name.startswith("agg-p01-"):
|
| 162 |
-
cases |= malformed(team)
|
| 163 |
-
|
|
|
|
| 164 |
covered[case] = covered.get(case, 0) + 1
|
| 165 |
-
check(grade(task, answer) == 0, f"{task.name}:
|
| 166 |
check(covered.get("duplicate-dropping", 0) > 0, "no task has a duplicate to drop")
|
| 167 |
return covered
|
| 168 |
|
|
@@ -200,30 +277,44 @@ search "${args[@]}" | sed 's/^/holds /'
|
|
| 200 |
mkdir -p /app && printf %s "$2" > /app/answer.json
|
| 201 |
search -e "$2" | sed 's/^/control /' # the same search finds the answer once it is written
|
| 202 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
|
| 205 |
try:
|
| 206 |
from harbor.agents.base import BaseAgent
|
| 207 |
|
| 208 |
class Probe(BaseAgent):
|
| 209 |
-
"""No model: looks around the container as an agent could while it
|
| 210 |
-
`probe.json` in its logs dir on the host, then the answer for the
|
|
|
|
| 211 |
|
| 212 |
-
def __init__(self, *args, secrets=(), answer="", task_instruction="",
|
|
|
|
| 213 |
super().__init__(*args, **kwargs)
|
| 214 |
-
self.
|
|
|
|
| 215 |
|
| 216 |
@staticmethod
|
| 217 |
def name() -> str:
|
| 218 |
return "s3-aggregation-probe"
|
| 219 |
|
| 220 |
def version(self) -> str:
|
| 221 |
-
return "
|
| 222 |
|
| 223 |
async def setup(self, environment) -> None:
|
| 224 |
pass
|
| 225 |
|
| 226 |
async def run(self, instruction, environment, context) -> None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
# the secrets travel base64-encoded: a copy of the command in the container would
|
| 228 |
# otherwise hold them
|
| 229 |
encoded = base64.b64encode("\n".join(self.secrets).encode()).decode()
|
|
@@ -243,7 +334,8 @@ except ImportError: # `--env none` needs no Harbor
|
|
| 243 |
Probe = None
|
| 244 |
|
| 245 |
|
| 246 |
-
async def
|
|
|
|
| 247 |
from harbor.models.trial.config import (
|
| 248 |
AgentConfig,
|
| 249 |
EnvironmentConfig,
|
|
@@ -252,45 +344,58 @@ async def check_trial(env: str, jobs: Path) -> dict:
|
|
| 252 |
)
|
| 253 |
from harbor.trial.trial import Trial
|
| 254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
task, roles = HERE / "tasks" / PROBE_TASK, HERE / "roles" / PROBE_TASK
|
| 256 |
answer = (task / "tests" / "expected.json").read_text().strip()
|
| 257 |
lines = [p.read_text().strip() for p in sorted(roles.glob("slot-*.md"))]
|
| 258 |
hyphenated = sorted({w for line in lines if "-" in (w := line.split(": ")[1])})
|
| 259 |
secrets = [answer, answer.replace(" ", ""), "Your private number:", *lines, *hyphenated]
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
agent=AgentConfig(import_path="__main__:Probe", kwargs={
|
| 268 |
-
"secrets": secrets, "answer": answer,
|
| 269 |
-
"task_instruction": (task / "instruction.md").read_text()}),
|
| 270 |
-
environment=environment)
|
| 271 |
-
trial = await Trial.create(config)
|
| 272 |
-
result = await trial.run()
|
| 273 |
-
probe_file = jobs / config.trial_name / "agent" / "probe.json"
|
| 274 |
-
probe = json.loads(probe_file.read_text()) if probe_file.is_file() else None
|
| 275 |
-
rewards = result.verifier_result.rewards if result.verifier_result else None
|
| 276 |
-
error = result.exception_info.exception_message if result.exception_info else None
|
| 277 |
-
check(probe is not None and probe["return_code"] == 0, f"Trial: the probe did not run ({error})")
|
| 278 |
if probe is not None:
|
| 279 |
check(not probe["visible"], f"Trial: visible while the agent works: {probe['visible']}")
|
| 280 |
check(not probe["holds"], f"Trial: files hold the team's numbers: {probe['holds']}")
|
| 281 |
check("/app/answer.json" in probe["control"],
|
| 282 |
f"Trial: the search did not find the written answer ({probe['control']})")
|
| 283 |
check(probe["instruction_is_the_task_text"], "Trial: the instruction is not the task's")
|
| 284 |
-
check(rewards == {"reward": 1.0},
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
|
| 288 |
def main() -> int:
|
| 289 |
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 290 |
parser.add_argument("--env", default="hf-sandbox",
|
| 291 |
-
help="Harbor environment type or import path for the
|
| 292 |
parser.add_argument("--jobs-dir", type=Path, default=None,
|
| 293 |
-
help="keep the
|
| 294 |
args = parser.parse_args()
|
| 295 |
check_generator()
|
| 296 |
print(f"1. generator: {len(failures)} failures")
|
|
@@ -305,8 +410,8 @@ def main() -> int:
|
|
| 305 |
with tempfile.TemporaryDirectory() as d:
|
| 306 |
jobs = args.jobs_dir or Path(d)
|
| 307 |
jobs.mkdir(parents=True, exist_ok=True)
|
| 308 |
-
report = asyncio.run(
|
| 309 |
-
print(f"4. no-cheat (
|
| 310 |
f"failures; {json.dumps(report)}")
|
| 311 |
for failure in failures:
|
| 312 |
print("FAIL:", failure)
|
|
|
|
| 4 |
# ///
|
| 5 |
"""s3-aggregation's checks that need no model (huggingface/flock#115, section 5):
|
| 6 |
|
| 7 |
+
uv run check.py # all of them; the Trials run on HF Sandboxes (HF_TOKEN)
|
| 8 |
+
uv run check.py --env docker # the Trials in local docker instead
|
| 9 |
+
uv run check.py --env none # skip the Trials
|
| 10 |
|
| 11 |
1. Generator: generate.py reproduces problems.json, tasks/ and roles/ byte for byte from its
|
| 12 |
seed; another seed gives other problems; 32 problems of 16 integers in 1..99; the English
|
| 13 |
words read back to their numbers; each task's team is its problem's first N numbers, and each
|
| 14 |
role file holds its own slot's number.
|
| 15 |
+
2. Graders, run as Harbor runs them (tests/ copied in after the agent is done): on every task,
|
| 16 |
+
the oracle (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or
|
| 17 |
+
duplicate-dropping answer scores 0. On one task per team size, malformed answers (missing,
|
| 18 |
+
empty, not JSON, NaN, an object, strings, words, floats, booleans, nested, a "####" prefix,
|
| 19 |
+
invalid UTF-8) and cheats score 0: the answer as a symlink to the tests' expected.json
|
| 20 |
+
(dangling until the tests arrive, absolute or relative), a symlink or a hardlink to a right
|
| 21 |
+
answer elsewhere, a hardlink to expected.json, a symlinked /app (to a right answer, or to the
|
| 22 |
+
tests' folder), an expected.json planted as a link to the answer before the tests arrive, a
|
| 23 |
+
directory and a FIFO (which must not hang the grader).
|
| 24 |
3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and
|
| 25 |
solution/; its instruction is the same for every problem of its team size; the answer is only
|
| 26 |
in tests/ and solution/; the role files live outside tasks/.
|
| 27 |
+
4. No-cheat, from inside Trials (`--env`), on `agg-p01-n16`, with probe agents (no model):
|
| 28 |
+
- one looks around the container while "the agent works" and finds no tests/ or solution/
|
| 29 |
+
and no file holding the answer, a role line or a hyphenated number word of the team (every
|
| 30 |
+
number of the problem); then it writes the answer, the same search finds it (a control),
|
| 31 |
+
and the task's own verifier scores it 1;
|
| 32 |
+
- one leaves /app/answer.json as a symlink to /tests/expected.json, another a symlinked /app
|
| 33 |
+
into a /tests it made: the verifier scores both 0.
|
| 34 |
`--env` takes a Harbor environment type or an import path. Harbor 0.25.0's hf-sandbox
|
| 35 |
uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is
|
| 36 |
over 65535 (some clusters): use flock's `--env flock.harbor.envs:HFSandbox` there.
|
|
|
|
| 42 |
import json
|
| 43 |
import os
|
| 44 |
import shlex
|
| 45 |
+
import shutil
|
| 46 |
import subprocess
|
| 47 |
import sys
|
| 48 |
import tempfile
|
|
|
|
| 116 |
check({p.name for p in (HERE / "roles").iterdir()} == names, "roles/ has other folders")
|
| 117 |
|
| 118 |
|
| 119 |
+
def grade(task: Path, answer: bytes | None = None, cheat=None) -> int:
|
| 120 |
+
"""The task's grader as Harbor runs it: `app/answer.json` stands for /app/answer.json and
|
| 121 |
+
`tests/` for /tests, whose files are copied in only after the agent is done, through any
|
| 122 |
+
link the agent left there (the worst case). `cheat(root)` lays out what an agent leaves
|
| 123 |
+
behind instead of `answer` (None: no file). Returns the reward."""
|
| 124 |
with tempfile.TemporaryDirectory() as d:
|
| 125 |
+
root = Path(d).resolve() # the grader takes paths without links
|
| 126 |
+
app, tests, verifier = root / "app", root / "tests", root / "verifier"
|
| 127 |
+
app.mkdir()
|
| 128 |
+
if cheat is not None:
|
| 129 |
+
cheat(root)
|
| 130 |
+
elif answer is not None:
|
| 131 |
+
(app / "answer.json").write_bytes(answer)
|
| 132 |
+
tests.mkdir(exist_ok=True)
|
| 133 |
+
for name in ("test.sh", "expected.json"):
|
| 134 |
+
shutil.copyfile(task / "tests" / name, tests / name)
|
| 135 |
+
try:
|
| 136 |
+
subprocess.run(["bash", str(tests / "test.sh")], capture_output=True, timeout=60,
|
| 137 |
+
env={**os.environ, "ANSWER": str(app / "answer.json"),
|
| 138 |
+
"VERIFIER_DIR": str(verifier)}, check=False)
|
| 139 |
+
except subprocess.TimeoutExpired:
|
| 140 |
+
return -1 # a grader that hangs is a failure too
|
| 141 |
return int((verifier / "reward.txt").read_text().strip())
|
| 142 |
|
| 143 |
|
|
|
|
| 173 |
"invalid UTF-8": b"\xff" + dump}
|
| 174 |
|
| 175 |
|
| 176 |
+
def cheats(task: Path) -> dict:
|
| 177 |
+
"""What an agent could leave behind to score without the answer, or with a right answer
|
| 178 |
+
that is not its own regular file: `cheat(root)` for grade()."""
|
| 179 |
+
right = (task / "tests" / "expected.json").read_bytes()
|
| 180 |
+
|
| 181 |
+
def link(target): # the answer as a symlink
|
| 182 |
+
return lambda root: (root / "app" / "answer.json").symlink_to(target(root))
|
| 183 |
+
|
| 184 |
+
def right_elsewhere(make):
|
| 185 |
+
def cheat(root):
|
| 186 |
+
(root / "elsewhere.json").write_bytes(right)
|
| 187 |
+
make(root / "elsewhere.json", root / "app" / "answer.json")
|
| 188 |
+
return cheat
|
| 189 |
+
|
| 190 |
+
def hardlink_expected(root): # as if the tests could be reached while the agent works
|
| 191 |
+
(root / "tests").mkdir()
|
| 192 |
+
shutil.copyfile(task / "tests" / "expected.json", root / "tests" / "expected.json")
|
| 193 |
+
os.link(root / "tests" / "expected.json", root / "app" / "answer.json")
|
| 194 |
+
|
| 195 |
+
def app_to(make_target):
|
| 196 |
+
def cheat(root):
|
| 197 |
+
(root / "app").rmdir()
|
| 198 |
+
(root / "app").symlink_to(make_target(root))
|
| 199 |
+
return cheat
|
| 200 |
+
|
| 201 |
+
def right_folder(root):
|
| 202 |
+
(root / "real").mkdir()
|
| 203 |
+
(root / "real" / "answer.json").write_bytes(right)
|
| 204 |
+
return root / "real"
|
| 205 |
+
|
| 206 |
+
def tests_folder(root):
|
| 207 |
+
(root / "tests").mkdir()
|
| 208 |
+
(root / "tests" / "answer.json").symlink_to("expected.json")
|
| 209 |
+
return root / "tests"
|
| 210 |
+
|
| 211 |
+
def planted_expected(root): # the upload writes the answer into it through the link
|
| 212 |
+
(root / "app" / "answer.json").write_bytes(b"[0]")
|
| 213 |
+
(root / "tests").mkdir()
|
| 214 |
+
(root / "tests" / "expected.json").symlink_to(root / "app" / "answer.json")
|
| 215 |
+
|
| 216 |
+
return {
|
| 217 |
+
"symlink to the tests' expected.json": link(lambda r: r / "tests" / "expected.json"),
|
| 218 |
+
"relative symlink to the tests' expected.json": link(
|
| 219 |
+
lambda r: Path("../tests/expected.json")),
|
| 220 |
+
"symlink to a right answer elsewhere": right_elsewhere(lambda s, d: d.symlink_to(s)),
|
| 221 |
+
"hardlink to a right answer elsewhere": right_elsewhere(os.link),
|
| 222 |
+
"hardlink to the tests' expected.json": hardlink_expected,
|
| 223 |
+
"symlinked /app with a right answer": app_to(right_folder),
|
| 224 |
+
"symlinked /app into the tests": app_to(tests_folder),
|
| 225 |
+
"expected.json planted as a link to the answer": planted_expected,
|
| 226 |
+
"a directory": lambda root: (root / "app" / "answer.json").mkdir(),
|
| 227 |
+
"a FIFO": lambda root: os.mkfifo(root / "app" / "answer.json"),
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
def check_graders() -> dict[str, int]:
|
| 232 |
covered: dict[str, int] = {}
|
| 233 |
for task in sorted((HERE / "tasks").iterdir()):
|
| 234 |
team = json.loads((task / "tests" / "expected.json").read_text())
|
| 235 |
check(oracle(task) == 1, f"{task.name}: the oracle does not score 1")
|
| 236 |
+
cases = {k: (json.dumps(v).encode(), None) for k, v in wrong_answers(team).items()}
|
| 237 |
if task.name.startswith("agg-p01-"):
|
| 238 |
+
cases |= {k: (v, None) for k, v in malformed(team).items()}
|
| 239 |
+
cases |= {k: (None, cheat) for k, cheat in cheats(task).items()}
|
| 240 |
+
for case, (answer, cheat) in cases.items():
|
| 241 |
covered[case] = covered.get(case, 0) + 1
|
| 242 |
+
check(grade(task, answer, cheat) == 0, f"{task.name}: {case} does not score 0")
|
| 243 |
check(covered.get("duplicate-dropping", 0) > 0, "no task has a duplicate to drop")
|
| 244 |
return covered
|
| 245 |
|
|
|
|
| 277 |
mkdir -p /app && printf %s "$2" > /app/answer.json
|
| 278 |
search -e "$2" | sed 's/^/control /' # the same search finds the answer once it is written
|
| 279 |
"""
|
| 280 |
+
# What a cheating agent leaves for the verifier, before the tests arrive
|
| 281 |
+
CHEATS = {
|
| 282 |
+
"symlink": "mkdir -p /app && ln -s /tests/expected.json /app/answer.json",
|
| 283 |
+
"symlinked-app": "mkdir -p /tests && ln -s expected.json /tests/answer.json"
|
| 284 |
+
" && rm -rf /app && ln -s /tests /app",
|
| 285 |
+
}
|
| 286 |
|
| 287 |
|
| 288 |
try:
|
| 289 |
from harbor.agents.base import BaseAgent
|
| 290 |
|
| 291 |
class Probe(BaseAgent):
|
| 292 |
+
"""No model. `mode` answer: looks around the container as an agent could while it
|
| 293 |
+
works, writes `probe.json` in its logs dir on the host, then the answer for the
|
| 294 |
+
verifier. Any other mode: leaves that cheat (CHEATS) instead."""
|
| 295 |
|
| 296 |
+
def __init__(self, *args, mode="answer", secrets=(), answer="", task_instruction="",
|
| 297 |
+
**kwargs):
|
| 298 |
super().__init__(*args, **kwargs)
|
| 299 |
+
self.mode, self.secrets, self.answer = mode, secrets, answer
|
| 300 |
+
self.task_instruction = task_instruction
|
| 301 |
|
| 302 |
@staticmethod
|
| 303 |
def name() -> str:
|
| 304 |
return "s3-aggregation-probe"
|
| 305 |
|
| 306 |
def version(self) -> str:
|
| 307 |
+
return "2"
|
| 308 |
|
| 309 |
async def setup(self, environment) -> None:
|
| 310 |
pass
|
| 311 |
|
| 312 |
async def run(self, instruction, environment, context) -> None:
|
| 313 |
+
if self.mode != "answer":
|
| 314 |
+
result = await environment.exec(CHEATS[self.mode], timeout_sec=60)
|
| 315 |
+
(self.logs_dir / "probe.json").write_text(json.dumps(
|
| 316 |
+
{"return_code": result.return_code, "cheat": CHEATS[self.mode]}))
|
| 317 |
+
return
|
| 318 |
# the secrets travel base64-encoded: a copy of the command in the container would
|
| 319 |
# otherwise hold them
|
| 320 |
encoded = base64.b64encode("\n".join(self.secrets).encode()).decode()
|
|
|
|
| 334 |
Probe = None
|
| 335 |
|
| 336 |
|
| 337 |
+
async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict) -> tuple[dict | None, dict]:
|
| 338 |
+
"""One Trial of PROBE_TASK with the probe in `mode`: (its probe.json, rewards and error)."""
|
| 339 |
from harbor.models.trial.config import (
|
| 340 |
AgentConfig,
|
| 341 |
EnvironmentConfig,
|
|
|
|
| 344 |
)
|
| 345 |
from harbor.trial.trial import Trial
|
| 346 |
|
| 347 |
+
sandbox = {"flavor": "cpu-basic", "job_timeout": 900}
|
| 348 |
+
environment = (EnvironmentConfig(import_path=env, kwargs=sandbox if "Sandbox" in env else {})
|
| 349 |
+
if ":" in env else
|
| 350 |
+
EnvironmentConfig(type=env, kwargs=sandbox if env == "hf-sandbox" else {}))
|
| 351 |
+
config = TrialConfig(
|
| 352 |
+
task=TaskConfig(path=HERE / "tasks" / PROBE_TASK), trial_name=f"probe-{mode}",
|
| 353 |
+
trials_dir=jobs, environment=environment,
|
| 354 |
+
agent=AgentConfig(import_path="__main__:Probe", kwargs={"mode": mode, **kwargs}))
|
| 355 |
+
result = await (await Trial.create(config)).run()
|
| 356 |
+
probe_file = jobs / config.trial_name / "agent" / "probe.json"
|
| 357 |
+
probe = json.loads(probe_file.read_text()) if probe_file.is_file() else None
|
| 358 |
+
return probe, {"rewards": result.verifier_result.rewards if result.verifier_result else None,
|
| 359 |
+
"error": result.exception_info.exception_message
|
| 360 |
+
if result.exception_info else None}
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
async def check_trials(env: str, jobs: Path) -> dict:
|
| 364 |
task, roles = HERE / "tasks" / PROBE_TASK, HERE / "roles" / PROBE_TASK
|
| 365 |
answer = (task / "tests" / "expected.json").read_text().strip()
|
| 366 |
lines = [p.read_text().strip() for p in sorted(roles.glob("slot-*.md"))]
|
| 367 |
hyphenated = sorted({w for line in lines if "-" in (w := line.split(": ")[1])})
|
| 368 |
secrets = [answer, answer.replace(" ", ""), "Your private number:", *lines, *hyphenated]
|
| 369 |
+
runs = await asyncio.gather(
|
| 370 |
+
run_trial(env, jobs, "answer", {"secrets": secrets, "answer": answer,
|
| 371 |
+
"task_instruction": (task / "instruction.md").read_text()}),
|
| 372 |
+
*(run_trial(env, jobs, mode, {}) for mode in CHEATS))
|
| 373 |
+
(probe, graded), *cheated = runs
|
| 374 |
+
check(probe is not None and probe["return_code"] == 0,
|
| 375 |
+
f"Trial: the probe did not run ({graded['error']})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
if probe is not None:
|
| 377 |
check(not probe["visible"], f"Trial: visible while the agent works: {probe['visible']}")
|
| 378 |
check(not probe["holds"], f"Trial: files hold the team's numbers: {probe['holds']}")
|
| 379 |
check("/app/answer.json" in probe["control"],
|
| 380 |
f"Trial: the search did not find the written answer ({probe['control']})")
|
| 381 |
check(probe["instruction_is_the_task_text"], "Trial: the instruction is not the task's")
|
| 382 |
+
check(graded["rewards"] == {"reward": 1.0},
|
| 383 |
+
f"Trial: the verifier gave the answer {graded['rewards']} ({graded['error']})")
|
| 384 |
+
report = {"answer": {"probe": probe, **graded, "searched_for": len(secrets)}}
|
| 385 |
+
for mode, (left, result) in zip(CHEATS, cheated, strict=True):
|
| 386 |
+
check(left is not None and left["return_code"] == 0, f"Trial: cheat {mode} not left")
|
| 387 |
+
check(result["rewards"] == {"reward": 0.0},
|
| 388 |
+
f"Trial: cheat {mode} gave {result['rewards']} ({result['error']})")
|
| 389 |
+
report[mode] = {"left": left, **result}
|
| 390 |
+
return report
|
| 391 |
|
| 392 |
|
| 393 |
def main() -> int:
|
| 394 |
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 395 |
parser.add_argument("--env", default="hf-sandbox",
|
| 396 |
+
help="Harbor environment type or import path for the Trials; none: skip")
|
| 397 |
parser.add_argument("--jobs-dir", type=Path, default=None,
|
| 398 |
+
help="keep the Trials' files here (default: a temporary directory)")
|
| 399 |
args = parser.parse_args()
|
| 400 |
check_generator()
|
| 401 |
print(f"1. generator: {len(failures)} failures")
|
|
|
|
| 410 |
with tempfile.TemporaryDirectory() as d:
|
| 411 |
jobs = args.jobs_dir or Path(d)
|
| 412 |
jobs.mkdir(parents=True, exist_ok=True)
|
| 413 |
+
report = asyncio.run(check_trials(args.env, jobs))
|
| 414 |
+
print(f"4. no-cheat (Trials on {args.env}, {PROBE_TASK}): {len(failures) - before} "
|
| 415 |
f"failures; {json.dumps(report)}")
|
| 416 |
for failure in failures:
|
| 417 |
print("FAIL:", failure)
|
generate.py
CHANGED
|
@@ -117,42 +117,79 @@ TEST_SH = r"""#!/bin/bash
|
|
| 117 |
# Reward 1 if /app/answer.json is exactly expected.json: a JSON array of the team's integers in
|
| 118 |
# ascending order, one per agent (equal numbers kept). Anything else scores 0: a missing or
|
| 119 |
# unreadable file, invalid UTF-8 or JSON, NaN or Infinity, a non-array, strings, floats or
|
| 120 |
-
# booleans, a missing, extra or dropped duplicate number, and a wrong order.
|
| 121 |
-
#
|
| 122 |
-
#
|
| 123 |
-
#
|
|
|
|
|
|
|
|
|
|
| 124 |
answer=${ANSWER:-/app/answer.json}
|
| 125 |
expected=${EXPECTED:-$(dirname "$0")/expected.json}
|
| 126 |
verifier=${VERIFIER_DIR:-/logs/verifier}
|
| 127 |
mkdir -p "$verifier"
|
|
|
|
| 128 |
echo 0 > "$verifier/reward.txt"
|
| 129 |
-
cp "$answer" "$verifier/answer.json" 2>/dev/null || true
|
| 130 |
ANSWER="$answer" EXPECTED="$expected" VERIFIER_DIR="$verifier" python3 - <<'PY' || true
|
| 131 |
import json
|
| 132 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
|
| 135 |
def reject_constant(name):
|
| 136 |
raise ValueError(f"{name} is not JSON")
|
| 137 |
|
| 138 |
|
| 139 |
-
def
|
| 140 |
-
|
| 141 |
-
return json.loads(stream.read().decode("utf-8"), parse_constant=reject_constant)
|
| 142 |
|
| 143 |
|
|
|
|
|
|
|
| 144 |
try:
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
valid = (
|
| 147 |
isinstance(answer, list)
|
| 148 |
and all(type(x) is int for x in answer) # not bool, float or str
|
| 149 |
and answer == expected
|
| 150 |
)
|
| 151 |
-
except Exception: # missing
|
| 152 |
valid = False
|
| 153 |
if valid:
|
| 154 |
-
|
| 155 |
-
stream.write("1")
|
| 156 |
print("reward:", 1 if valid else 0)
|
| 157 |
PY
|
| 158 |
"""
|
|
|
|
| 117 |
# Reward 1 if /app/answer.json is exactly expected.json: a JSON array of the team's integers in
|
| 118 |
# ascending order, one per agent (equal numbers kept). Anything else scores 0: a missing or
|
| 119 |
# unreadable file, invalid UTF-8 or JSON, NaN or Infinity, a non-array, strings, floats or
|
| 120 |
+
# booleans, a missing, extra or dropped duplicate number, and a wrong order.
|
| 121 |
+
# The answer counts only as a regular file of its own at exactly that path: a symlink (e.g. to
|
| 122 |
+
# /tests/expected.json, which arrives only now), a link anywhere on the path (a symlinked /app),
|
| 123 |
+
# a hardlink, a directory or a FIFO scores 0; expected.json is read the same way. Nothing here
|
| 124 |
+
# follows a link the agent may have left, and 0 is written before anything is checked, so a crash
|
| 125 |
+
# of the check also scores 0. A copy of the answer stays with the trial's results. ANSWER,
|
| 126 |
+
# EXPECTED and VERIFIER_DIR override the paths (no links in them), to test the grader locally.
|
| 127 |
answer=${ANSWER:-/app/answer.json}
|
| 128 |
expected=${EXPECTED:-$(dirname "$0")/expected.json}
|
| 129 |
verifier=${VERIFIER_DIR:-/logs/verifier}
|
| 130 |
mkdir -p "$verifier"
|
| 131 |
+
rm -f "$verifier/reward.txt" "$verifier/reward.json" "$verifier/answer.json"
|
| 132 |
echo 0 > "$verifier/reward.txt"
|
|
|
|
| 133 |
ANSWER="$answer" EXPECTED="$expected" VERIFIER_DIR="$verifier" python3 - <<'PY' || true
|
| 134 |
import json
|
| 135 |
import os
|
| 136 |
+
import stat
|
| 137 |
+
|
| 138 |
+
LIMIT = 1 << 20 # bytes
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def read_own(path):
|
| 142 |
+
# The bytes of the regular file at exactly `path`: every folder on the way is opened
|
| 143 |
+
# without following a link, and so is the file (a FIFO cannot block it); one link only.
|
| 144 |
+
parts = os.path.abspath(path).split("/")[1:]
|
| 145 |
+
folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
|
| 146 |
+
try:
|
| 147 |
+
for part in parts[:-1]:
|
| 148 |
+
inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)
|
| 149 |
+
os.close(folder)
|
| 150 |
+
folder = inner
|
| 151 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)
|
| 152 |
+
finally:
|
| 153 |
+
os.close(folder)
|
| 154 |
+
with os.fdopen(fd, "rb") as stream:
|
| 155 |
+
info = os.fstat(stream.fileno())
|
| 156 |
+
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
|
| 157 |
+
raise ValueError("not a regular file of its own")
|
| 158 |
+
data = stream.read(LIMIT + 1)
|
| 159 |
+
if len(data) > LIMIT:
|
| 160 |
+
raise ValueError("too large")
|
| 161 |
+
return data
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def write_new(path, text):
|
| 165 |
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644)
|
| 166 |
+
with os.fdopen(fd, "w") as stream:
|
| 167 |
+
stream.write(text)
|
| 168 |
|
| 169 |
|
| 170 |
def reject_constant(name):
|
| 171 |
raise ValueError(f"{name} is not JSON")
|
| 172 |
|
| 173 |
|
| 174 |
+
def parse(data):
|
| 175 |
+
return json.loads(data.decode("utf-8"), parse_constant=reject_constant)
|
|
|
|
| 176 |
|
| 177 |
|
| 178 |
+
verifier = os.environ["VERIFIER_DIR"]
|
| 179 |
+
valid = False
|
| 180 |
try:
|
| 181 |
+
data = read_own(os.environ["ANSWER"])
|
| 182 |
+
write_new(os.path.join(verifier, "answer.json"), data.decode("utf-8", "replace"))
|
| 183 |
+
answer, expected = parse(data), parse(read_own(os.environ["EXPECTED"]))
|
| 184 |
valid = (
|
| 185 |
isinstance(answer, list)
|
| 186 |
and all(type(x) is int for x in answer) # not bool, float or str
|
| 187 |
and answer == expected
|
| 188 |
)
|
| 189 |
+
except Exception: # missing, a link, not regular, invalid UTF-8 or JSON, NaN, RecursionError
|
| 190 |
valid = False
|
| 191 |
if valid:
|
| 192 |
+
write_new(os.path.join(verifier, "reward.txt"), "1")
|
|
|
|
| 193 |
print("reward:", 1 if valid else 0)
|
| 194 |
PY
|
| 195 |
"""
|