AniBespoke commited on
Commit
2cfd41b
·
verified ·
1 Parent(s): 44e2ee9

AutoResearchExam v1.1: run on Harbor main with any agent harness (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/shortest-valid-ci-l2-ece/environment/docker-compose.yaml +76 -0
  2. tasks/shortest-valid-ci-l2-ece/task.toml +39 -25
  3. tasks/shortest-valid-ci-l2-ece/tests/Dockerfile +2 -41
  4. tasks/shortest-valid-ci-l2-ece/tests/finalize.py +59 -0
  5. tasks/shortest-valid-ci-l2-ece/tests/test.sh +1 -17
  6. tasks/sketched-newton-cov-estimator/environment/.dockerignore +1 -0
  7. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile +31 -0
  8. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile.are +49 -0
  9. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/drain.py +25 -0
  10. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/server.py +538 -0
  11. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/compute_reward.py +19 -0
  12. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/grader_core.py +268 -0
  13. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/harness/runner.py +116 -0
  14. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_0.json +31 -0
  15. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_1.json +31 -0
  16. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_2.json +31 -0
  17. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_3.json +31 -0
  18. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_0.json +31 -0
  19. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_1.json +31 -0
  20. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_2.json +31 -0
  21. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_3.json +31 -0
  22. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/intermediate.sh +19 -0
  23. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/oracle.py +38 -0
  24. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements-verifier.txt +2 -0
  25. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements.txt +2 -0
  26. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/run_one.py +35 -0
  27. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test.sh +19 -0
  28. tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test_state.py +39 -0
  29. tasks/sketched-newton-cov-estimator/environment/docker-compose.yaml +76 -0
  30. tasks/sketched-newton-cov-estimator/task.toml +39 -25
  31. tasks/sketched-newton-cov-estimator/tests/Dockerfile +2 -31
  32. tasks/sketched-newton-cov-estimator/tests/finalize.py +59 -0
  33. tasks/sketched-newton-cov-estimator/tests/test.sh +1 -18
  34. tasks/sopcc-online-chance-constrained-policy/environment/.dockerignore +1 -0
  35. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile +34 -0
  36. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile.are +52 -0
  37. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/drain.py +25 -0
  38. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/server.py +538 -0
  39. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/compute_reward.py +18 -0
  40. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/grader_core.py +46 -0
  41. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/final/panel.npz +3 -0
  42. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/intermediate/panel.npz +3 -0
  43. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/intermediate.sh +29 -0
  44. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/policy_worker.py +132 -0
  45. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements-verifier.txt +2 -0
  46. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements.txt +5 -0
  47. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/runner.py +517 -0
  48. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/sopcc.py +212 -0
  49. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test.sh +30 -0
  50. tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test_state.py +229 -0
tasks/shortest-valid-ci-l2-ece/environment/docker-compose.yaml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network).
2
+ services:
3
+ main:
4
+ depends_on:
5
+ grader:
6
+ condition: service_healthy
7
+ volumes:
8
+ - are-deliverable-0:/app/output
9
+
10
+ grader:
11
+ build:
12
+ context: ./are-grader-ctx
13
+ dockerfile: Dockerfile.are
14
+ args:
15
+ ARE_ROLE: val
16
+ platform: linux/amd64
17
+ environment:
18
+ ARE_ROLE: val
19
+ ARE_PORT: "8000"
20
+ ARE_BUDGET_SEC: "86400"
21
+ ARE_ARTIFACT_PATHS: "/app/output"
22
+ ARE_AGENT_UID: "1001"
23
+ ARE_GRADE_TIMEOUT_SEC: "1800"
24
+ volumes:
25
+ - are-deliverable-0:/run/are-deliverable/app/output
26
+ - are-secret:/run/are-secret
27
+ expose:
28
+ - "8000"
29
+ cap_add: [SYS_ADMIN]
30
+ networks: [default, are-private]
31
+ cpus: 8
32
+ mem_limit: 14336m
33
+ depends_on:
34
+ test-grader:
35
+ condition: service_healthy
36
+ healthcheck:
37
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"]
38
+ interval: 2s
39
+ timeout: 5s
40
+ retries: 60
41
+ start_period: 5s
42
+
43
+ test-grader:
44
+ build:
45
+ context: ./are-grader-ctx
46
+ dockerfile: Dockerfile.are
47
+ args:
48
+ ARE_ROLE: test
49
+ platform: linux/amd64
50
+ environment:
51
+ ARE_ROLE: test
52
+ ARE_PORT: "8001"
53
+ ARE_ARTIFACT_PATHS: "/app/output"
54
+ ARE_GRADE_TIMEOUT_SEC: "1800"
55
+ expose:
56
+ - "8001"
57
+ volumes:
58
+ - are-secret:/run/are-secret
59
+ cap_add: [SYS_ADMIN]
60
+ networks: [are-private]
61
+ cpus: 8
62
+ mem_limit: 14336m
63
+ healthcheck:
64
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"]
65
+ interval: 2s
66
+ timeout: 5s
67
+ retries: 60
68
+ start_period: 5s
69
+
70
+ volumes:
71
+ are-deliverable-0: {}
72
+ are-secret: {}
73
+
74
+ networks:
75
+ are-private:
76
+ internal: true
tasks/shortest-valid-ci-l2-ece/task.toml CHANGED
@@ -1,56 +1,70 @@
1
  schema_version = "1.4"
2
- artifacts = [ "/app/output",]
 
 
3
 
4
  [task]
5
  name = "bespokelabs/shortest-valid-ci-l2-ece"
6
- version = "1.0.0"
7
  description = ""
8
- keywords = [ "autoresearch", "machine-learning", "benchmark",]
9
- [[task.authors]]
10
- name = "Bespoke Labs"
 
 
 
 
 
11
 
12
  [metadata]
13
  category = "Machine Learning and AI"
14
  subcategory = "Model evaluation and benchmarking"
15
- task_objective = [ "Implement", "Optimize",]
16
- artifact_type = [ "Single script or program",]
 
 
 
 
 
17
  expert_time_estimate_hours = 6.0
 
 
18
 
19
  [verifier]
20
- timeout_sec = 1800.0
21
  environment_mode = "separate"
22
- collect = []
23
 
24
- [verifier.env]
 
 
 
25
 
26
  [verifier.environment]
27
  network_mode = "no-network"
28
- build_timeout_sec = 3600.0
29
- os = "linux"
30
- cpus = 8
31
- memory_mb = 14336
32
- storage_mb = 153600
33
  gpus = 0
34
- mcp_servers = []
35
-
36
- [verifier.environment.env]
37
 
38
  [agent]
39
  network_mode = "allowlist"
40
- allowed_hosts = [ "api.openai.com", "api.anthropic.com",]
41
- timeout_sec = 21600.0
 
 
 
 
42
 
43
  [environment]
44
- network_mode = "allowlist"
45
- allowed_hosts = [ "api.openai.com", "api.anthropic.com",]
46
  build_timeout_sec = 3600.0
47
  os = "linux"
48
  cpus = 8
49
  memory_mb = 14336
50
  storage_mb = 153600
51
  gpus = 0
52
- mcp_servers = []
 
 
53
 
54
  [environment.env]
55
-
56
- [solution.env]
 
1
  schema_version = "1.4"
2
+ artifacts = [
3
+ { source = "/var/lib/are", service = "grader" },
4
+ ]
5
 
6
  [task]
7
  name = "bespokelabs/shortest-valid-ci-l2-ece"
8
+ version = "1.1.0"
9
  description = ""
10
+ keywords = [
11
+ "autoresearch",
12
+ "machine-learning",
13
+ "benchmark",
14
+ ]
15
+ authors = [
16
+ { name = "Bespoke Labs" },
17
+ ]
18
 
19
  [metadata]
20
  category = "Machine Learning and AI"
21
  subcategory = "Model evaluation and benchmarking"
22
+ task_objective = [
23
+ "Implement",
24
+ "Optimize",
25
+ ]
26
+ artifact_type = [
27
+ "Single script or program",
28
+ ]
29
  expert_time_estimate_hours = 6.0
30
+ are_version = "1.1"
31
+ budget_seconds = 86400
32
 
33
  [verifier]
34
+ timeout_sec = 600.0
35
  environment_mode = "separate"
 
36
 
37
+ [[verifier.collect]]
38
+ service = "grader"
39
+ command = "/opt/are/venv/bin/python /opt/are/drain.py"
40
+ timeout_sec = 3600.0
41
 
42
  [verifier.environment]
43
  network_mode = "no-network"
44
+ build_timeout_sec = 600.0
45
+ cpus = 1
46
+ memory_mb = 1024
 
 
47
  gpus = 0
 
 
 
48
 
49
  [agent]
50
  network_mode = "allowlist"
51
+ allowed_hosts = [
52
+ "api.openai.com",
53
+ "api.anthropic.com",
54
+ "grader",
55
+ ]
56
+ timeout_sec = 86400.0
57
 
58
  [environment]
59
+ network_mode = "public"
 
60
  build_timeout_sec = 3600.0
61
  os = "linux"
62
  cpus = 8
63
  memory_mb = 14336
64
  storage_mb = 153600
65
  gpus = 0
66
+ mcp_servers = [
67
+ { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" },
68
+ ]
69
 
70
  [environment.env]
 
 
tasks/shortest-valid-ci-l2-ece/tests/Dockerfile CHANGED
@@ -1,41 +1,2 @@
1
- FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
-
3
- ENTRYPOINT []
4
- ENV PYTHONPATH=
5
- ENV PYTHONSAFEPATH=1
6
- ENV DEBIAN_FRONTEND=noninteractive \
7
- PYTHONHASHSEED=0 \
8
- PIP_NO_CACHE_DIR=1 \
9
- PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
- OMP_NUM_THREADS=1 \
11
- MKL_NUM_THREADS=1 \
12
- OPENBLAS_NUM_THREADS=1 \
13
- NUMEXPR_NUM_THREADS=1
14
-
15
- RUN useradd --create-home --uid 1001 agent
16
-
17
- COPY ./requirements.txt /tmp/requirements.txt
18
- COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
19
- RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
20
- -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
21
- && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
22
-
23
- RUN mkdir -p /app/output /logs/verifier /opt/candrun
24
-
25
- COPY . /tests
26
-
27
- RUN cp /tests/run_call.py /opt/candrun/run_call.py \
28
- && chown root:root /opt/candrun /opt/candrun/run_call.py \
29
- && chmod 755 /opt/candrun \
30
- && chmod 444 /opt/candrun/run_call.py \
31
- && chown -R root:root /tests /home/agent \
32
- && chmod 755 /home/agent \
33
- && chmod 755 /tmp /var/tmp \
34
- && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
35
- && chmod +x /tests/test.sh /tests/intermediate.sh \
36
- && find /tests -exec touch -d @1700000000 {} +
37
-
38
- WORKDIR /tests
39
-
40
- ENV HF_HUB_OFFLINE=1
41
- ENV TRANSFORMERS_OFFLINE=1
 
1
+ FROM python:3.12-slim
2
+ COPY . /tests/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tasks/shortest-valid-ci-l2-ece/tests/finalize.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final verifier: score the run from the grader ledger.
2
+
3
+ reward hidden test score of the submission with the best validation score
4
+ (ties go to the earlier submission); 0 if nothing was submitted.
5
+ auarc area under the curve of that same quantity over the wall-clock budget,
6
+ using the time each validation score became available, divided by the
7
+ budget. 0 before the first graded submission.
8
+ """
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ STATE = Path("/var/lib/are")
14
+ OUT = Path("/logs/verifier")
15
+ OUT.mkdir(parents=True, exist_ok=True)
16
+
17
+ meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {}
18
+ budget = float(meta.get("budget_seconds") or 1.0)
19
+
20
+ subs: dict[int, dict] = {}
21
+ ledger = STATE / "ledger.jsonl"
22
+ for line in (ledger.read_text().splitlines() if ledger.exists() else []):
23
+ ev = json.loads(line)
24
+ s = subs.setdefault(ev["id"], {"id": ev["id"]})
25
+ if ev["event"] == "submitted":
26
+ s["submitted_t"] = ev["t"]
27
+ elif ev["event"] == "val":
28
+ s["val"] = ev["score"]
29
+ s["val_t"] = ev["t"]
30
+ elif ev["event"] == "test":
31
+ s["test"] = ev["score"]
32
+
33
+ graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"])
34
+
35
+ # Step function of the hidden score of the best-validation pick over time.
36
+ auc, best, last_t, cur = 0.0, None, 0.0, 0.0
37
+ timeline = []
38
+ for s in graded:
39
+ t = min(s["val_t"], budget)
40
+ auc += cur * (t - last_t)
41
+ last_t = t
42
+ if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]):
43
+ best = s
44
+ cur = float(best.get("test") or 0.0)
45
+ timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"),
46
+ "pick": best["id"]})
47
+ auc += cur * (budget - last_t) if last_t < budget else 0.0
48
+
49
+ reward = {
50
+ "reward": float(best.get("test") or 0.0) if best else 0.0,
51
+ "auarc": auc / budget,
52
+ "best_val": float(best["val"]) if best else 0.0,
53
+ "n_submissions": float(len(subs)),
54
+ "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())),
55
+ }
56
+ (OUT / "reward.json").write_text(json.dumps(reward))
57
+ (OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"],
58
+ "submissions": timeline}, indent=1))
59
+ print(json.dumps(reward, indent=1))
tasks/shortest-valid-ci-l2-ece/tests/test.sh CHANGED
@@ -1,18 +1,2 @@
1
  #!/bin/bash
2
- set -u
3
-
4
- mkdir -p /logs/verifier
5
- chown root:root /logs/verifier 2>/dev/null || true
6
- chmod 755 /logs/verifier 2>/dev/null || true
7
- rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
8
-
9
- trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo "0" > /logs/verifier/reward.txt; fi' EXIT
10
-
11
- chmod -R go-rwx /tests
12
-
13
- export GRADE_SPLIT=final
14
- cd /tests
15
- /usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
16
- /usr/local/bin/python3 /tests/compute_reward.py
17
-
18
- exit 0
 
1
  #!/bin/bash
2
+ python3 /tests/finalize.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tasks/sketched-newton-cov-estimator/environment/.dockerignore ADDED
@@ -0,0 +1 @@
 
 
1
+ are-grader-ctx
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
+
3
+ ENTRYPOINT []
4
+ ENV PYTHONPATH=
5
+ ENV PYTHONSAFEPATH=1
6
+ ENV DEBIAN_FRONTEND=noninteractive \
7
+ PYTHONHASHSEED=0 \
8
+ PIP_NO_CACHE_DIR=1 \
9
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
+ OMP_NUM_THREADS=1 \
11
+ OPENBLAS_NUM_THREADS=1 \
12
+ MKL_NUM_THREADS=1
13
+
14
+ RUN useradd --create-home --uid 1001 agent
15
+
16
+ COPY ./requirements.txt /tmp/requirements.txt
17
+ COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
18
+ RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
19
+ -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
20
+ && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
21
+
22
+ RUN mkdir -p /app/output /logs/verifier
23
+
24
+ COPY . /tests
25
+
26
+ RUN chown -R root:root /tests \
27
+ && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
28
+ && chmod +x /tests/test.sh /tests/intermediate.sh \
29
+ && find /tests -exec touch -d @1700000000 {} +
30
+
31
+ WORKDIR /tests
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/Dockerfile.are ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
+
3
+ ENTRYPOINT []
4
+ ENV PYTHONPATH=
5
+ ENV PYTHONSAFEPATH=1
6
+ ENV DEBIAN_FRONTEND=noninteractive \
7
+ PYTHONHASHSEED=0 \
8
+ PIP_NO_CACHE_DIR=1 \
9
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
+ OMP_NUM_THREADS=1 \
11
+ OPENBLAS_NUM_THREADS=1 \
12
+ MKL_NUM_THREADS=1
13
+
14
+ RUN useradd --create-home --uid 1001 agent
15
+
16
+ COPY ./requirements.txt /tmp/requirements.txt
17
+ COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
18
+ RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
19
+ -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
20
+ && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
21
+
22
+ RUN mkdir -p /app/output /logs/verifier
23
+
24
+ COPY . /tests
25
+
26
+ RUN chown -R root:root /tests \
27
+ && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
28
+ && chmod +x /tests/test.sh /tests/intermediate.sh \
29
+ && find /tests -exec touch -d @1700000000 {} +
30
+
31
+ WORKDIR /tests
32
+
33
+
34
+ # ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ----
35
+ ARG ARE_ROLE
36
+ # python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack
37
+ # ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip.
38
+ RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \
39
+ && if "$PY" -m venv /opt/are/venv; then \
40
+ /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \
41
+ else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \
42
+ && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi
43
+ COPY are/ /opt/are/
44
+ # The val grader, whose output reaches the agent, never holds the private grader or its
45
+ # data. The test grader keeps everything; nothing from it reaches the agent.
46
+ RUN rm -rf /tests/are /tests/Dockerfile.are \
47
+ && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi
48
+ ENV ARE_ROLE=$ARE_ROLE
49
+ CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"]
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/drain.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier collect hook, run after the agent stops.
2
+
3
+ Grades the final workspace as one last submission (unless it equals the last one),
4
+ then waits until every submission has both grades recorded.
5
+ """
6
+
7
+ import json
8
+ import time
9
+ import urllib.request
10
+ from pathlib import Path
11
+
12
+ TOKEN = Path("/run/are-secret/token").read_text().strip()
13
+ H = {"x-are-token": TOKEN}
14
+
15
+ req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H)
16
+ with urllib.request.urlopen(req, timeout=120) as resp:
17
+ print("final:", json.loads(resp.read()), flush=True)
18
+
19
+ while True:
20
+ with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp:
21
+ state = json.loads(resp.read())
22
+ print(state, flush=True)
23
+ if state["val_pending"] == 0 and state["test_pending"] == 0:
24
+ break
25
+ time.sleep(5)
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/are/server.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ARE 1.1 grader sidecar.
2
+
3
+ One image, two roles:
4
+
5
+ - ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a
6
+ REST fallback. On submit it snapshots the shared deliverable volume, grades the
7
+ snapshot with the task's public grader (intermediate.sh), and returns only that
8
+ score. Every snapshot is also sent to the test grader; the hidden score goes to a
9
+ root-only ledger and never back to the agent.
10
+ - ARE_ROLE=test ("test-grader" service). On a private network that only the val
11
+ grader can reach. Grades snapshots with the task's private grader (test.sh).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import gzip
18
+ import hashlib
19
+ import io
20
+ import secrets
21
+ import json
22
+ import os
23
+ import queue
24
+ import shutil
25
+ import subprocess
26
+ import tarfile
27
+ import threading
28
+ import time
29
+ import urllib.request
30
+ from pathlib import Path
31
+
32
+ from fastmcp import FastMCP
33
+ from starlette.requests import Request
34
+ from starlette.responses import JSONResponse, Response
35
+
36
+ ROLE = os.environ.get("ARE_ROLE", "val")
37
+ PORT = int(os.environ.get("ARE_PORT", "8000"))
38
+ STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are"))
39
+ ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p]
40
+ # The shared deliverable volume. Its parent is root-only, so submitted code (which every
41
+ # task grader runs as the unprivileged agent user) cannot reach it to write back to the agent.
42
+ SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable"))
43
+ AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001"))
44
+ BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400"))
45
+ GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800"))
46
+ TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001")
47
+ FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192"))
48
+ SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh"
49
+ # Shared only by the two graders (a volume the agent's container never mounts). The test
50
+ # grader writes a fresh token at startup; every internal request must carry it, so the
51
+ # agent cannot reach the test grader or the internal endpoints even on a shared network.
52
+ TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token"))
53
+ TOKEN = ""
54
+
55
+
56
+ def _authorized(request: Request) -> bool:
57
+ """Internal endpoints need the graders' token; an unset token never matches."""
58
+ return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN)
59
+
60
+
61
+ def _net_isolation_available() -> bool:
62
+ try:
63
+ return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0
64
+ except Exception:
65
+ return False
66
+
67
+
68
+ NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace
69
+
70
+ T0 = time.time()
71
+ _lock = threading.Lock()
72
+
73
+
74
+ def _elapsed() -> float:
75
+ return round(time.time() - T0, 1)
76
+
77
+
78
+ def _ledger(event: dict) -> None:
79
+ event = {"t": _elapsed(), "wall": time.time(), **event}
80
+ for attempt in range(3):
81
+ try:
82
+ with _lock, open(STATE / "ledger.jsonl", "a") as fh:
83
+ fh.write(json.dumps(event) + "\n")
84
+ return
85
+ except OSError:
86
+ if attempt == 2:
87
+ raise
88
+ time.sleep(1)
89
+
90
+
91
+ def _kill_grading_processes(proc: subprocess.Popen) -> None:
92
+ """Kill everything a timed-out grade started, including processes that left its group."""
93
+ try:
94
+ os.killpg(proc.pid, 9)
95
+ except ProcessLookupError:
96
+ pass
97
+ _kill_other_processes()
98
+
99
+
100
+ def _kill_other_processes() -> None:
101
+ """Kill every process run by the agent user. Every task grader runs submitted code as
102
+ that user, so this stops all graded code (detached or not) and nothing else: the grader
103
+ server, the task's own grader and Harbor's hooks run as root."""
104
+ for entry in Path("/proc").iterdir():
105
+ if not entry.name.isdigit():
106
+ continue
107
+ try:
108
+ if entry.stat().st_uid == AGENT_UID:
109
+ os.kill(int(entry.name), 9)
110
+ except (ProcessLookupError, PermissionError, FileNotFoundError):
111
+ pass
112
+
113
+
114
+ # Places the agent user (who runs submitted code inside every task grader) can write.
115
+ _BASELINE: set[str] = set() # every path that existed when the grader started (its image)
116
+
117
+
118
+ def _walk_one_fs(base: Path):
119
+ """Every path under base on base's own filesystem (skips /proc, /sys and other mounts)."""
120
+ dev = base.stat().st_dev
121
+ for root, dirs, files in os.walk(base):
122
+ dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev]
123
+ for name in dirs + files:
124
+ yield Path(root) / name
125
+
126
+
127
+ def _all_paths() -> set[str]:
128
+ out = set()
129
+ for base in (Path("/"), Path("/dev/shm")):
130
+ if base.is_dir():
131
+ out.update(str(q) for q in _walk_one_fs(base))
132
+ return out
133
+
134
+
135
+ def _protected(path: str) -> bool:
136
+ keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)]
137
+ return any(path == k or path.startswith(k + "/") for k in keep)
138
+
139
+
140
+ def _fresh_state() -> None:
141
+ """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier
142
+ container did. The grader container lives for the whole run, so before each grade
143
+ stop anything an earlier grade left running and delete every file it created,
144
+ whoever wrote it. The deliverable volume and the token are separate mounts and are
145
+ never walked; the grader's own state is kept."""
146
+ _kill_other_processes()
147
+ # System V shared memory, semaphores and queues outlive processes; this server uses none.
148
+ subprocess.run(["ipcrm", "--all"], capture_output=True)
149
+ for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True):
150
+ if _protected(path):
151
+ continue
152
+ try:
153
+ q = Path(path)
154
+ if q.is_dir() and not q.is_symlink():
155
+ shutil.rmtree(q, ignore_errors=True)
156
+ else:
157
+ q.unlink()
158
+ except OSError:
159
+ pass
160
+
161
+
162
+ def grade_snapshot(tar_bytes: bytes, tag: str) -> dict:
163
+ """Extract a snapshot over the artifact paths and run this role's grader script."""
164
+ _fresh_state()
165
+ for path in ARTIFACT_PATHS:
166
+ p = Path(path)
167
+ if p.exists():
168
+ shutil.rmtree(p)
169
+ p.mkdir(parents=True)
170
+ with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf:
171
+ tf.extractall("/", filter="tar")
172
+ logs = Path("/logs/verifier")
173
+ if logs.exists():
174
+ shutil.rmtree(logs)
175
+ logs.mkdir(parents=True)
176
+ started = time.time()
177
+ # Submitted code runs with no network, as in ARE 1.0's verifier.
178
+ cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT]
179
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
180
+ cwd="/tests", start_new_session=True)
181
+ try:
182
+ out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC)
183
+ error = None
184
+ except subprocess.TimeoutExpired:
185
+ _kill_grading_processes(proc)
186
+ out, err = proc.communicate()
187
+ error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s"
188
+ output = (out or "") + (err or "")
189
+ # Nothing a grade started may keep running after it, not even detached processes.
190
+ _kill_other_processes()
191
+ score = 0.0
192
+ reward_file = logs / "reward.txt"
193
+ if reward_file.exists():
194
+ try:
195
+ score = float(reward_file.read_text().strip() or 0)
196
+ except ValueError:
197
+ error = error or "unparseable reward"
198
+ metric = None
199
+ if (logs / "metric.json").exists():
200
+ try:
201
+ metric = json.loads((logs / "metric.json").read_text())
202
+ except ValueError:
203
+ pass
204
+ (STATE / "logs").mkdir(exist_ok=True)
205
+ (STATE / "logs" / f"{tag}.log").write_text(output)
206
+ return {
207
+ "score": score,
208
+ "metric": metric,
209
+ "error": error,
210
+ "net_isolated": NET_ISOLATED,
211
+ "seconds": round(time.time() - started, 1),
212
+ # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr).
213
+ "output_tail": (out or "")[-FEEDBACK_TAIL:],
214
+ }
215
+
216
+
217
+ mcp = FastMCP("are")
218
+
219
+
220
+ # ---------------------------------------------------------------- test role
221
+
222
+
223
+ _grade_lock = threading.Lock()
224
+
225
+
226
+ def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict:
227
+ # A request that timed out on the caller's side may still be grading; the next one
228
+ # waits for it rather than sharing /app/output and /logs/verifier with it.
229
+ with _grade_lock:
230
+ return grade_snapshot(tar_bytes, tag)
231
+
232
+
233
+ if ROLE == "test":
234
+
235
+ @mcp.custom_route("/grade", methods=["POST"])
236
+ async def http_grade(request: Request) -> Response:
237
+ if not _authorized(request):
238
+ return JSONResponse({"error": "forbidden"}, status_code=403)
239
+ tag = request.query_params.get("tag", "x")
240
+ body = await request.body()
241
+ result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test")
242
+ return JSONResponse(result)
243
+
244
+
245
+ # ----------------------------------------------------------------- val role
246
+
247
+
248
+ class Board:
249
+ """Submissions and their grading state. Hidden scores are never stored here."""
250
+
251
+ def __init__(self) -> None:
252
+ self.subs: dict[int, dict] = {}
253
+ self.val_q: queue.Queue[int] = queue.Queue()
254
+ self.next_id = 1
255
+ self.test_pending = 0
256
+ self.last_digest: str | None = None
257
+
258
+ def public(self, sid: int) -> dict:
259
+ s = self.subs[sid]
260
+ out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")}
261
+ if s["status"] == "graded":
262
+ v = s["val"]
263
+ out.update(
264
+ validation_score=v["score"],
265
+ error=v["error"],
266
+ grading_seconds=v["seconds"],
267
+ grader_output_tail=v["output_tail"],
268
+ )
269
+ return out
270
+
271
+ def best(self) -> dict | None:
272
+ graded = [s for s in self.subs.values() if s["status"] == "graded"]
273
+ if not graded:
274
+ return None
275
+ b = max(graded, key=lambda s: (s["val"]["score"], -s["id"]))
276
+ return {"id": b["id"], "validation_score": b["val"]["score"]}
277
+
278
+
279
+ board = Board()
280
+
281
+
282
+ def snapshot() -> bytes:
283
+ """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0)."""
284
+ raw = io.BytesIO()
285
+ with tarfile.open(fileobj=raw, mode="w") as tf:
286
+ for path in ARTIFACT_PATHS:
287
+ src = SUBMISSION_ROOT / path.lstrip("/")
288
+ tf.add(str(src), arcname=path.lstrip("/"))
289
+ out = io.BytesIO()
290
+ with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz:
291
+ gz.write(raw.getvalue())
292
+ return out.getvalue()
293
+
294
+
295
+ def do_submit(note: str, final: bool = False) -> dict:
296
+ with _lock:
297
+ pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"]
298
+ if pending and not final:
299
+ return {
300
+ "error": f"Submission {pending[0]} is still being graded. One submission is "
301
+ f"graded at a time: check result({pending[0]}) and submit again "
302
+ "once it has its score.",
303
+ "pending_id": pending[0],
304
+ }
305
+ sid = board.next_id
306
+ board.next_id += 1
307
+ board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(),
308
+ "status": "queued"}
309
+ try:
310
+ data = snapshot()
311
+ digest = hashlib.sha256(data).hexdigest()
312
+ (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data)
313
+ _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data),
314
+ "sha256": digest, "final": final})
315
+ except Exception as exc:
316
+ with _lock:
317
+ board.subs.pop(sid, None) # release the slot; the id is not reused
318
+ return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. "
319
+ "Make sure nothing is writing to it, then submit again."}
320
+ board.last_digest = digest
321
+ with _lock:
322
+ board.test_pending += 1
323
+ board.val_q.put(sid)
324
+ return {"id": sid, "status": "queued",
325
+ "hint": "Grading has started. Check result(id) for the validation score."}
326
+
327
+
328
+ def final_submit() -> dict:
329
+ """After the agent stops: grade the final workspace unless it was already submitted."""
330
+ try:
331
+ data = snapshot()
332
+ except Exception as exc:
333
+ return {"error": f"final snapshot failed: {exc}"}
334
+ if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest:
335
+ return {"skipped": "final workspace equals the last submission"}
336
+ return do_submit("final workspace (automatic)", final=True)
337
+
338
+
339
+ def grade_worker() -> None:
340
+ """Grade each submission on val, then on test, one submission at a time.
341
+
342
+ The val score is published as soon as it is ready. The next submission's val grade
343
+ waits until this test grade is done, so the two graders never run at the same time.
344
+ """
345
+ while True:
346
+ sid = board.val_q.get()
347
+ board.subs[sid]["status"] = "grading"
348
+ data = b""
349
+ try:
350
+ data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes()
351
+ res = grade_snapshot(data, f"{sid:04d}-val")
352
+ except Exception as exc:
353
+ res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}",
354
+ "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""}
355
+ board.subs[sid]["val"] = res
356
+ board.subs[sid]["status"] = "graded"
357
+ try:
358
+ _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}})
359
+ except OSError as exc: # keep grading later submissions
360
+ print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True)
361
+ test_grade(sid, data)
362
+
363
+
364
+ def test_grade(sid: int, data: bytes) -> None:
365
+ try:
366
+ _test_grade(sid, data)
367
+ finally:
368
+ with _lock:
369
+ board.test_pending -= 1
370
+
371
+
372
+ def _test_grade(sid: int, data: bytes) -> None:
373
+ """Send one snapshot to the test grader. A failed request is retried (the same snapshot
374
+ is graded again, so a retry can only recover the honest score); a request that ran
375
+ past its timeout is not, since the grade itself already took the full time."""
376
+ started = time.time()
377
+ for attempt in range(3):
378
+ try:
379
+ req = urllib.request.Request(
380
+ f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST",
381
+ headers={"x-are-token": TOKEN},
382
+ )
383
+ with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp:
384
+ res = json.loads(resp.read())
385
+ break
386
+ except Exception as exc: # recorded, never shown to the agent
387
+ res = {"score": None, "metric": None, "error": f"test grader: {exc}",
388
+ "seconds": round(time.time() - started, 1)}
389
+ if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError):
390
+ break
391
+ time.sleep(5)
392
+ try:
393
+ _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}})
394
+ except OSError as exc: # keep grading later submissions
395
+ print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True)
396
+
397
+
398
+ def with_time(out: dict) -> dict:
399
+ """Wall-clock accounting on every reply, as the v1 harness gave each phase."""
400
+ out["total_budget_seconds"] = BUDGET_SEC
401
+ out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1)
402
+ return out
403
+
404
+
405
+ def status_dict() -> dict:
406
+ return {
407
+ "submissions": len(board.subs),
408
+ "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()),
409
+ "best": board.best(),
410
+ }
411
+
412
+
413
+ def current_result(sid: int) -> dict:
414
+ return board.public(sid)
415
+
416
+
417
+ if ROLE == "val":
418
+
419
+ @mcp.tool
420
+ async def submit(note: str = "") -> dict:
421
+ """Submit the current deliverable for grading.
422
+
423
+ Snapshots the deliverable directory right now (later edits do not affect this
424
+ submission) and starts grading it on the public validation split. Returns at
425
+ once with a submission id. One submission is graded at a time: check `result`
426
+ and submit again once the previous submission has its score. `note` is a short
427
+ description of what changed.
428
+ """
429
+ return with_time(await asyncio.to_thread(do_submit, note))
430
+
431
+ @mcp.tool
432
+ async def result(id: int) -> dict:
433
+ """The current state of a submission: queued, grading, or graded with its
434
+ validation score and grader output. Returns immediately."""
435
+ if id not in board.subs:
436
+ return {"error": f"unknown submission id {id}"}
437
+ return with_time(current_result(id))
438
+
439
+ @mcp.tool
440
+ async def status() -> dict:
441
+ """Submission count, whether one is being graded, the best validation score,
442
+ and the time budget and time remaining."""
443
+ return with_time(status_dict())
444
+
445
+ @mcp.custom_route("/submit", methods=["POST"])
446
+ async def http_submit(request: Request) -> Response:
447
+ note = request.query_params.get("note", "")
448
+ return JSONResponse(with_time(await asyncio.to_thread(do_submit, note)))
449
+
450
+ @mcp.custom_route("/result/{sid}", methods=["GET"])
451
+ async def http_result(request: Request) -> Response:
452
+ sid = int(request.path_params["sid"])
453
+ if sid not in board.subs:
454
+ return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404)
455
+ return JSONResponse(with_time(current_result(sid)))
456
+
457
+ @mcp.custom_route("/status", methods=["GET"])
458
+ async def http_status(request: Request) -> Response:
459
+ return JSONResponse(with_time(status_dict()))
460
+
461
+ @mcp.custom_route("/final", methods=["POST"])
462
+ async def http_final(request: Request) -> Response:
463
+ if not _authorized(request):
464
+ return JSONResponse({"error": "forbidden"}, status_code=403)
465
+ # Collect hook, after the agent has stopped.
466
+ return JSONResponse(await asyncio.to_thread(final_submit))
467
+
468
+ @mcp.custom_route("/drain", methods=["GET"])
469
+ async def http_drain(request: Request) -> Response:
470
+ if not _authorized(request):
471
+ return JSONResponse({"error": "forbidden"}, status_code=403)
472
+ # Used by the verifier collect hook after the agent has stopped.
473
+ pending = sum(s["status"] != "graded" for s in board.subs.values())
474
+ return JSONResponse({"val_pending": pending, "test_pending": board.test_pending})
475
+
476
+
477
+ def _gpus() -> list[str]:
478
+ try:
479
+ out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20)
480
+ return [l for l in out.stdout.splitlines() if l.strip()]
481
+ except Exception:
482
+ return []
483
+
484
+
485
+ @mcp.custom_route("/health", methods=["GET"])
486
+ async def health(request: Request) -> Response:
487
+ return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)})
488
+
489
+
490
+ def _setup_token() -> None:
491
+ global TOKEN
492
+ if ROLE == "test":
493
+ TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
494
+ os.chmod(TOKEN_FILE.parent, 0o700)
495
+ TOKEN = secrets.token_hex(32)
496
+ TOKEN_FILE.write_text(TOKEN)
497
+ os.chmod(TOKEN_FILE, 0o600)
498
+ else:
499
+ for _ in range(300): # the test grader is healthy before this one starts
500
+ if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip():
501
+ break
502
+ time.sleep(1)
503
+ TOKEN = TOKEN_FILE.read_text().strip()
504
+ if not TOKEN:
505
+ raise SystemExit("ARE: empty internal token; refusing to start")
506
+
507
+
508
+ def main() -> None:
509
+ global NET_ISOLATED
510
+ NET_ISOLATED = _net_isolation_available()
511
+ if not NET_ISOLATED:
512
+ # Graded code must never have a network path (for example back through /submit).
513
+ raise SystemExit("ARE grader: cannot run grades without network access "
514
+ "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start")
515
+ STATE.mkdir(parents=True, exist_ok=True)
516
+ _BASELINE.update(_all_paths())
517
+ _setup_token()
518
+ STATE.mkdir(parents=True, exist_ok=True)
519
+ os.chmod(STATE, 0o700)
520
+ (STATE / "snapshots").mkdir(exist_ok=True)
521
+ if ROLE == "val":
522
+ # The deliverable volume starts empty and root-owned; hand it to the agent user.
523
+ SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True)
524
+ os.chmod(SUBMISSION_ROOT, 0o700)
525
+ for path in ARTIFACT_PATHS:
526
+ src = SUBMISSION_ROOT / path.lstrip("/")
527
+ src.mkdir(parents=True, exist_ok=True)
528
+ os.chown(src, AGENT_UID, AGENT_UID)
529
+ (STATE / "meta.json").write_text(json.dumps(
530
+ {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS}
531
+ ))
532
+ threading.Thread(target=grade_worker, daemon=True).start()
533
+ mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False,
534
+ uvicorn_config={"timeout_keep_alive": 86400})
535
+
536
+
537
+ if __name__ == "__main__":
538
+ main()
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/compute_reward.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ from pathlib import Path
4
+
5
+ REWARD_PATH = Path("/logs/verifier/reward.txt")
6
+ METRIC_PATH = Path("/logs/verifier/metric.json")
7
+
8
+ try:
9
+ REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
10
+ value = float(json.loads(METRIC_PATH.read_text())["reward"])
11
+ if not math.isfinite(value):
12
+ raise ValueError("non-finite reward")
13
+ reward = f"{min(1.0, max(0.0, value)):.12g}"
14
+ REWARD_PATH.write_text(reward + "\n")
15
+ print(f"reward={reward}")
16
+ except Exception as exc:
17
+ REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
18
+ REWARD_PATH.write_text("0\n")
19
+ print(f"reward=0 (fallback: {exc})")
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/grader_core.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import os
4
+ import shutil
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ import oracle
17
+
18
+ TESTS_DIR = Path(__file__).resolve().parent
19
+
20
+ ENTRY_POINT = "estimator.py"
21
+ REPLICATIONS = int(os.environ.get("GRADER_REPLICATIONS", "20"))
22
+ REPLICATION_TIMEOUT_S = 90.0
23
+ TRIVIAL_ERROR = 1.0
24
+ RUN_AS_UID = int(os.environ.get("GRADER_RUN_AS_UID", "1001"))
25
+ WORKERS = int(os.environ.get("GRADER_WORKERS", "8"))
26
+ GLOBAL_DEADLINE_S = float(os.environ.get("GRADER_DEADLINE_S", "1200"))
27
+
28
+ M0 = 1.0
29
+ BASELINE_SCORE = 0.013
30
+
31
+
32
+ def reward_from_metric(metric):
33
+ """log-ratio squash: 0 at the trivial baseline, 0.5 at the reference, -> 1, no cutoff."""
34
+ if metric is None:
35
+ return 0.0
36
+ m = float(metric)
37
+ if not math.isfinite(m) or m < 0.0:
38
+ return 0.0
39
+ if m == 0.0:
40
+ return 1.0
41
+ u = math.log(M0 / m) / math.log(M0 / BASELINE_SCORE)
42
+ if u <= 0.0:
43
+ return 0.0
44
+ return u / (1.0 + u)
45
+
46
+
47
+ def load_instances(split_dir):
48
+ paths = sorted(Path(split_dir).glob("inst_*.json"))
49
+ if not paths:
50
+ raise RuntimeError(f"no instances under {split_dir}")
51
+ return [json.loads(p.read_text()) for p in paths]
52
+
53
+
54
+ def instance_covariance(inst):
55
+ d = int(inst["d"])
56
+ Sigma = np.full((d, d), float(inst["equi_r"]))
57
+ np.fill_diagonal(Sigma, 1.0)
58
+ return Sigma
59
+
60
+
61
+ def true_functional(inst):
62
+ """w' Xi* w for one instance, from the closed form. Never leaves this process."""
63
+ d = int(inst["d"])
64
+ Xi = oracle.xi_star(instance_covariance(inst), float(inst["sigma"]) ** 2, int(inst["tau"]))
65
+ w = np.full(d, 1.0 / d)
66
+ return float(w @ Xi @ w)
67
+
68
+
69
+ def draw_samples(inst, seed):
70
+ """The realized samples of one replication. The only thing the child is given."""
71
+ d, T = int(inst["d"]), int(inst["T"])
72
+ L = np.linalg.cholesky(instance_covariance(inst))
73
+ rng = np.random.default_rng(seed)
74
+ A = rng.standard_normal((T, d)) @ L.T
75
+ b = A @ np.asarray(inst["x_star"], dtype=np.float64) + rng.standard_normal(T) * float(inst["sigma"])
76
+ return A, b
77
+
78
+
79
+ def _launch(workdir, timeout_s):
80
+ """Run the deliverable in its own session as an unprivileged uid, hard-killed on time.
81
+
82
+ Output goes to a file rather than a pipe, so an agent that prints without bound cannot
83
+ grow the trusted process's memory; only the last 2 kB is ever read back.
84
+ """
85
+ py = sys.executable
86
+ script = str(workdir / "run_one.py")
87
+ argv = [py, script, "--workdir", str(workdir)]
88
+ kwargs = dict(cwd=str(workdir / "out"), start_new_session=True,
89
+ user=RUN_AS_UID, group=RUN_AS_UID, env={
90
+ "PATH": "/usr/local/bin:/usr/bin:/bin",
91
+ "HOME": str(workdir / "out"), "TMPDIR": str(workdir / "out"),
92
+ "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1",
93
+ "MKL_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1",
94
+ "PYTHONHASHSEED": "0", "PYTHONDONTWRITEBYTECODE": "1"})
95
+
96
+ log = workdir / "child.log"
97
+ with open(log, "wb") as fh:
98
+ proc = subprocess.Popen(argv, stdout=fh, stderr=subprocess.STDOUT, **kwargs)
99
+ try:
100
+ proc.communicate(timeout=timeout_s)
101
+ rc = proc.returncode
102
+ except subprocess.TimeoutExpired:
103
+ try:
104
+ os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
105
+ except Exception:
106
+ proc.kill()
107
+ proc.communicate()
108
+ rc = "timeout"
109
+ tail = ""
110
+ try:
111
+ with open(log, "rb") as fh:
112
+ fh.seek(max(0, log.stat().st_size - 2000))
113
+ tail = fh.read().decode("utf-8", "replace")
114
+ except Exception:
115
+ pass
116
+ return rc, tail
117
+
118
+
119
+ def run_replication(inst, rep, solution_dir, workroot, timeout_s):
120
+ """Prepare a scratch dir, run one replication, return the raw functional or a failure."""
121
+ out = {"instance": inst["name"], "rep": rep, "status": "error", "v_hat": None, "detail": ""}
122
+ if timeout_s <= 1.0:
123
+ out["status"] = "deadline"
124
+ return out
125
+ work = Path(tempfile.mkdtemp(dir=workroot, prefix=f"{inst['name']}_r{rep}_"))
126
+ try:
127
+ shutil.copy2(TESTS_DIR / "run_one.py", work / "run_one.py")
128
+ shutil.copytree(TESTS_DIR / "harness", work / "harness")
129
+ shutil.copytree(solution_dir, work / "solution", symlinks=True)
130
+ seed = int(inst["seed_base"]) + 2 * rep
131
+ A, b = draw_samples(inst, seed)
132
+ np.save(work / "samples_a.npy", A, allow_pickle=False)
133
+ np.save(work / "samples_b.npy", b, allow_pickle=False)
134
+ (work / "job.json").write_text(json.dumps(
135
+ {"d": int(inst["d"]), "T": int(inst["T"]), "tau": int(inst["tau"]),
136
+ "alg_seed": seed + 1}))
137
+ del A, b
138
+ for p in [work] + list(work.rglob("*")):
139
+ os.chmod(p, 0o755 if p.is_dir() else 0o644)
140
+ (work / "out").mkdir()
141
+ os.chown(work / "out", RUN_AS_UID, RUN_AS_UID)
142
+ os.chmod(work / "out", 0o700)
143
+
144
+ rc, err = _launch(work, timeout_s)
145
+ if rc == "timeout":
146
+ out["status"] = "timeout"
147
+ out["detail"] = f"exceeded {timeout_s:.0f}s"
148
+ return out
149
+ if rc != 0:
150
+ out["status"] = "crashed"
151
+ out["detail"] = err.strip()[-600:]
152
+ return out
153
+
154
+ res = work / "out" / "result.npy"
155
+ if not res.exists():
156
+ out["status"] = "no_output"
157
+ return out
158
+ try:
159
+ M = np.load(res, allow_pickle=False)
160
+ except Exception as exc:
161
+ out["status"] = "unparseable"
162
+ out["detail"] = str(exc)[:200]
163
+ return out
164
+ d = int(inst["d"])
165
+ if M.shape != (d, d) or M.dtype != np.float64:
166
+ out["status"] = "bad_shape"
167
+ out["detail"] = f"got shape {M.shape} dtype {M.dtype}"
168
+ return out
169
+ if not np.all(np.isfinite(M)):
170
+ out["status"] = "non_finite"
171
+ return out
172
+ w = np.full(d, 1.0 / d)
173
+ out["v_hat"] = float(w @ M @ w)
174
+ out["status"] = "ok"
175
+ return out
176
+ except Exception as exc:
177
+ out["status"] = "infra_error"
178
+ out["detail"] = f"{type(exc).__name__}: {exc}"[:300]
179
+ return out
180
+ finally:
181
+ shutil.rmtree(work, ignore_errors=True)
182
+
183
+
184
+ def grade(split_dir, deliverable_dir, workroot=None, replications=REPLICATIONS):
185
+ t0 = time.time()
186
+ instances = load_instances(split_dir)
187
+ truth = {i["name"]: true_functional(i) for i in instances}
188
+
189
+ entry = Path(deliverable_dir) / ENTRY_POINT
190
+ have_entry = entry.is_file() and entry.stat().st_size > 0
191
+ results = []
192
+
193
+ if have_entry:
194
+ workroot = workroot or tempfile.mkdtemp(prefix="grade_")
195
+ os.chmod(workroot, 0o711)
196
+ staged = Path(workroot) / "solution"
197
+ shutil.rmtree(staged, ignore_errors=True)
198
+ src = Path(deliverable_dir)
199
+ for p in [src] + list(src.rglob("*")):
200
+ if p.is_symlink():
201
+ raise RuntimeError(f"symlink in deliverable is not allowed: {p}")
202
+ shutil.copytree(deliverable_dir, staged, symlinks=True)
203
+ for p in [staged] + list(staged.rglob("*")):
204
+ os.chmod(p, 0o755 if p.is_dir() else 0o644)
205
+
206
+ jobs = [(i, r) for i in instances for r in range(replications)]
207
+
208
+ def work(job):
209
+ inst, rep = job
210
+ left = GLOBAL_DEADLINE_S - (time.time() - t0)
211
+ return run_replication(inst, rep, staged, workroot,
212
+ min(REPLICATION_TIMEOUT_S, left))
213
+
214
+ with ThreadPoolExecutor(max_workers=WORKERS) as pool:
215
+ results = list(pool.map(work, jobs))
216
+ else:
217
+ for inst in instances:
218
+ for rep in range(replications):
219
+ results.append({"instance": inst["name"], "rep": rep,
220
+ "status": "missing_entry_point", "v_hat": None, "detail": ""})
221
+
222
+ per_instance = {}
223
+ for inst in instances:
224
+ name = inst["name"]
225
+ rows = [r for r in results if r["instance"] == name]
226
+ bad = [r for r in rows if r["status"] != "ok"]
227
+ if bad or len(rows) != replications:
228
+ per_instance[name] = {"error": TRIVIAL_ERROR, "failed": len(bad) + replications - len(rows)}
229
+ continue
230
+ v = truth[name]
231
+ rel = np.array([r["v_hat"] for r in rows], dtype=np.float64) / v - 1.0
232
+ sd = float(rel.std(ddof=1)) if len(rel) > 1 else float("nan")
233
+ per_instance[name] = {"error": float(abs(rel.mean())), "failed": 0,
234
+ "signed_mean": float(rel.mean()),
235
+ "sd_per_replication": sd,
236
+ "mc_error": sd / math.sqrt(len(rel))}
237
+
238
+ metric = float(np.mean([per_instance[i["name"]]["error"] for i in instances]))
239
+ n_failed = sum(1 for r in results if r["status"] != "ok")
240
+ statuses = {}
241
+ for r in results:
242
+ statuses[r["status"]] = statuses.get(r["status"], 0) + 1
243
+ first_detail = next((r["detail"] for r in results if r["status"] != "ok" and r["detail"]), "")
244
+
245
+ return {
246
+ "metric": metric,
247
+ "reward": reward_from_metric(metric),
248
+ "replications_per_instance": replications,
249
+ "replications_failed": n_failed,
250
+ "replication_status_counts": statuses,
251
+ "first_failure_detail": first_detail,
252
+ "per_instance": per_instance,
253
+ "wall_clock_s": round(time.time() - t0, 1),
254
+ }
255
+
256
+
257
+ def summary_lines(report):
258
+ """The only thing printed to stdout. Aggregates only -- no per-instance detail."""
259
+ return [
260
+ f"replications per instance : {report['replications_per_instance']}",
261
+ f"replications failed : {report['replications_failed']}"
262
+ + (f" {report['replication_status_counts']}" if report["replications_failed"] else ""),
263
+ f"first failure : {report['first_failure_detail'][:600]}"
264
+ if report["first_failure_detail"] else "first failure : -",
265
+ f"metric (lower is better) : {report['metric']:.6f}",
266
+ f"reward : {report['reward']:.6f}",
267
+ f"grading wall clock (s) : {report['wall_clock_s']}",
268
+ ]
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/harness/runner.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import solve_triangular
3
+
4
+ _BLOCK = 8192
5
+
6
+
7
+ def make_config(d, T, tau, w=None):
8
+ """The `config` dict handed to `estimate`. Contains no instance secrets."""
9
+ if w is None:
10
+ w = np.full(d, 1.0 / d)
11
+ return {
12
+ "d": int(d),
13
+ "T": int(T),
14
+ "tau": int(tau),
15
+ "q": 1,
16
+ "sketch": "kaczmarz",
17
+ "beta": 0.505,
18
+ "c_beta": 1.0,
19
+ "loss": "squared_error_linear_regression",
20
+ "x0": np.zeros(d),
21
+ "B0": np.eye(d),
22
+ "w": np.asarray(w, dtype=np.float64),
23
+ }
24
+
25
+
26
+ def draw_samples(instance, seed):
27
+ """Draw the T samples of one replication from an instance's parameters.
28
+
29
+ `instance` needs the keys d, T, sigma, x_star and either Sigma_a or (equi_r).
30
+ Returns (A, b) with A of shape (T, d) and b of shape (T,).
31
+ """
32
+ d, T = int(instance["d"]), int(instance["T"])
33
+ Sigma_a = instance_covariance(instance)
34
+ L = np.linalg.cholesky(Sigma_a)
35
+ rng = np.random.default_rng(seed)
36
+ A = rng.standard_normal((T, d)) @ L.T
37
+ eps = rng.standard_normal(T) * float(instance["sigma"])
38
+ b = A @ np.asarray(instance["x_star"], dtype=np.float64) + eps
39
+ return A, b
40
+
41
+
42
+ def instance_covariance(instance):
43
+ """Equi-correlation design: [Sigma_a]_ii = 1, [Sigma_a]_ij = r for i != j."""
44
+ d = int(instance["d"])
45
+ r = float(instance["equi_r"])
46
+ Sigma = np.full((d, d), r)
47
+ np.fill_diagonal(Sigma, 1.0)
48
+ return Sigma
49
+
50
+
51
+ def stream_from_samples(A, b, config, alg_seed):
52
+ """Yield one record per iteration. `A` is (T, d), `b` is (T,).
53
+
54
+ Each record is a fresh dict holding read-only arrays. The runner never writes into an
55
+ array it has already yielded, so a record stays valid for as long as you keep it.
56
+ t int, the iteration index
57
+ x (d,) x_{t+1}, the iterate AFTER this step's update
58
+ alpha float the realized stepsize alpha_t
59
+ g (d,) the stochastic gradient at x_t
60
+ H (d, d) the sample Hessian at x_t
61
+ B (d, d) the Hessian average B_t used by this step's inner solve
62
+ sketch_idx (tau,) the Kaczmarz indices used by this step's inner solve
63
+ """
64
+ d = int(config["d"])
65
+ T = int(config["T"])
66
+ tau = int(config["tau"])
67
+ beta = float(config["beta"])
68
+ c_beta = float(config["c_beta"])
69
+
70
+ x = np.array(config["x0"], dtype=np.float64)
71
+ B = np.array(config["B0"], dtype=np.float64)
72
+ rng = np.random.default_rng(alg_seed)
73
+
74
+ idx_block = None
75
+ u_block = None
76
+ for t in range(T):
77
+ k = t % _BLOCK
78
+ if k == 0:
79
+ n = min(_BLOCK, T - t)
80
+ idx_block = rng.integers(0, d, size=(n, tau))
81
+ u_block = rng.random(n)
82
+
83
+ a = A[t]
84
+ g = a * (a @ x - b[t])
85
+
86
+ idx = idx_block[k]
87
+ sel = B[:, idx]
88
+ nrm = np.sqrt(np.einsum("ij,ij->j", sel, sel))
89
+ F = sel / nrm
90
+ dx = F @ solve_triangular(np.tril(F.T @ F), -g[idx] / nrm, lower=True,
91
+ unit_diagonal=True, check_finite=False, overwrite_b=True)
92
+
93
+ beta_t = c_beta / (t + 1.0) ** beta
94
+ alpha = beta_t + u_block[k] * beta_t * beta_t
95
+ x = x + alpha * dx
96
+
97
+ H = np.outer(a, a)
98
+ for arr in (x, g, H, B, idx):
99
+ arr.flags.writeable = False
100
+ yield {
101
+ "t": t,
102
+ "x": x,
103
+ "alpha": float(alpha),
104
+ "g": g,
105
+ "H": H,
106
+ "B": B,
107
+ "sketch_idx": idx,
108
+ }
109
+
110
+ B = ((t + 1.0) * B + H) / (t + 2.0)
111
+
112
+
113
+ def make_stream(instance, config, sample_seed, alg_seed):
114
+ """Convenience wrapper: draw an instance's samples, then stream one replication."""
115
+ A, b = draw_samples(instance, sample_seed)
116
+ return stream_from_samples(A, b, config, alg_seed)
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_0.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealF0",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 20,
6
+ "equi_r": 0.132076,
7
+ "sigma": 1.035163,
8
+ "x_star": [
9
+ -0.019722108888,
10
+ -0.043768990181,
11
+ -0.016978953849,
12
+ -0.041987901786,
13
+ -0.027223042407,
14
+ 0.006300373844,
15
+ 0.013943979186,
16
+ -0.019059026608,
17
+ 0.008421650997,
18
+ -0.079513148397,
19
+ -0.071653297202,
20
+ 0.053201419509,
21
+ -0.060378806686,
22
+ -0.085022153445,
23
+ -0.005837723371,
24
+ 0.101380431414,
25
+ 0.047635755492,
26
+ 7.7076412e-05,
27
+ -0.07658615567,
28
+ 0.025033501465
29
+ ],
30
+ "seed_base": 841200185
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_1.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealF1",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 40,
6
+ "equi_r": 0.222325,
7
+ "sigma": 0.805114,
8
+ "x_star": [
9
+ -0.082932808961,
10
+ 0.038545870624,
11
+ 0.004312618402,
12
+ -0.055654625394,
13
+ 0.020893374205,
14
+ -0.124393736972,
15
+ 0.057071827706,
16
+ 0.043785304794,
17
+ -0.042946668716,
18
+ 0.019317748747,
19
+ 0.002910150262,
20
+ -0.037568440259,
21
+ -0.055793184577,
22
+ 0.056245388685,
23
+ -0.031427430157,
24
+ 0.008295253253,
25
+ 0.053125175571,
26
+ -0.040845921657,
27
+ -0.040308878577,
28
+ -0.018703000051
29
+ ],
30
+ "seed_base": 939721810
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_2.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealF2",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 10,
6
+ "equi_r": 0.151511,
7
+ "sigma": 0.874065,
8
+ "x_star": [
9
+ 0.095956898049,
10
+ -0.004996400008,
11
+ 0.006311228453,
12
+ 0.011112538622,
13
+ -0.009496748634,
14
+ -0.015015359292,
15
+ -0.005287695998,
16
+ 0.048944383801,
17
+ -0.062397368507,
18
+ 0.00238404898,
19
+ -0.100809118235,
20
+ 0.028671325467,
21
+ -0.068214488049,
22
+ -0.023500778765,
23
+ 0.056537806242,
24
+ -0.033217168108,
25
+ -0.030644999212,
26
+ 0.011702616777,
27
+ -0.048161361361,
28
+ -0.100400192593
29
+ ],
30
+ "seed_base": 755664261
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/final/inst_3.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealF3",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 20,
6
+ "equi_r": 0.271258,
7
+ "sigma": 1.751414,
8
+ "x_star": [
9
+ 0.024972636039,
10
+ 0.03533280065,
11
+ 0.093659428727,
12
+ -0.041126527796,
13
+ -0.024346355273,
14
+ -0.083137388327,
15
+ -0.037750722609,
16
+ 0.066469180419,
17
+ -0.003471314605,
18
+ 0.091974410156,
19
+ -0.010119253259,
20
+ -0.010260004657,
21
+ -0.053269325588,
22
+ 0.047791864094,
23
+ 0.04810807302,
24
+ -0.004704687523,
25
+ 0.003928567812,
26
+ 0.006460957598,
27
+ 0.03196080178,
28
+ -0.084265993839
29
+ ],
30
+ "seed_base": 996720305
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_0.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealI0",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 10,
6
+ "equi_r": 0.242438,
7
+ "sigma": 1.987579,
8
+ "x_star": [
9
+ 0.035973464612,
10
+ 0.027253032917,
11
+ -0.031596861933,
12
+ -0.018343116487,
13
+ -0.020911424013,
14
+ -0.1491477536,
15
+ 0.013498660293,
16
+ 0.006200096616,
17
+ -0.015070425319,
18
+ 0.022844567177,
19
+ -0.077994643809,
20
+ -0.003851103026,
21
+ -0.032669570035,
22
+ 0.041203220648,
23
+ -0.007091550034,
24
+ 0.00811292529,
25
+ 0.065859152925,
26
+ 0.046109225502,
27
+ -0.04484870205,
28
+ -0.07431256495
29
+ ],
30
+ "seed_base": 801608310
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_1.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealI1",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 40,
6
+ "equi_r": 0.112021,
7
+ "sigma": 1.160481,
8
+ "x_star": [
9
+ -0.03426103133,
10
+ 0.01757527391,
11
+ -0.114675095472,
12
+ -0.03974628369,
13
+ -0.057236905083,
14
+ 0.005505864975,
15
+ 0.044311780829,
16
+ -0.017366965234,
17
+ -0.040559344461,
18
+ -0.045404460944,
19
+ -0.002066011218,
20
+ -0.071839758821,
21
+ -0.05194956085,
22
+ -0.05814472584,
23
+ -0.021194042223,
24
+ -0.029639640005,
25
+ -0.038732120007,
26
+ 0.098609447255,
27
+ 0.026606893038,
28
+ -0.00214245734
29
+ ],
30
+ "seed_base": 942125480
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_2.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealI2",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 20,
6
+ "equi_r": 0.150641,
7
+ "sigma": 1.9847,
8
+ "x_star": [
9
+ 0.061912698266,
10
+ -0.011329243664,
11
+ 0.001349428686,
12
+ -0.033716256102,
13
+ -0.066686683827,
14
+ -0.040736213303,
15
+ 0.055910365725,
16
+ -0.023177050316,
17
+ 0.037218968578,
18
+ -0.038877559169,
19
+ 0.071259066126,
20
+ 0.022718553147,
21
+ 0.075966470665,
22
+ -0.009292402812,
23
+ -0.116543497448,
24
+ 0.017304237725,
25
+ -0.038278283045,
26
+ -0.044425847335,
27
+ -0.057455316556,
28
+ 0.012664324105
29
+ ],
30
+ "seed_base": 462111903
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/hidden_data/intermediate/inst_3.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "sealI3",
3
+ "d": 20,
4
+ "T": 300000,
5
+ "tau": 40,
6
+ "equi_r": 0.265884,
7
+ "sigma": 0.501666,
8
+ "x_star": [
9
+ -0.00495812216,
10
+ 0.057794303105,
11
+ -0.132022500532,
12
+ 5.8374263e-05,
13
+ 0.011778313649,
14
+ -0.067304320932,
15
+ 0.053298500444,
16
+ -0.00069184491,
17
+ 0.031638710103,
18
+ -0.067837987423,
19
+ -0.002114095999,
20
+ -0.05050766958,
21
+ 0.040031360963,
22
+ -0.028814842159,
23
+ 0.037268534752,
24
+ -0.018590979209,
25
+ 0.016295358434,
26
+ -0.07212676206,
27
+ 0.008673464269,
28
+ -0.061859333449
29
+ ],
30
+ "seed_base": 385455181
31
+ }
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/intermediate.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+
4
+ mkdir -p /logs/verifier
5
+ chown root:root /logs/verifier 2>/dev/null || true
6
+ chmod 755 /logs/verifier 2>/dev/null || true
7
+ rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
8
+
9
+ printf '0\n' > /logs/verifier/reward.txt
10
+ trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi' EXIT
11
+
12
+ chmod -R go-rwx /tests
13
+
14
+ export GRADE_SPLIT=intermediate
15
+ cd /tests
16
+ /usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
17
+ /usr/local/bin/python3 /tests/compute_reward.py
18
+
19
+ exit 0
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/oracle.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def _projectors(B):
5
+ """P[i] = b_i b_i^T / ||b_i||^2 for every column b_i of B."""
6
+ nrm2 = np.einsum("ij,ij->j", B, B)
7
+ return np.einsum("ik,jk->kij", B, B) / nrm2[:, None, None]
8
+
9
+
10
+ def xi_star(Sigma_a, sigma2, tau):
11
+ """The limiting covariance of the last iterate, exactly."""
12
+ Sigma_a = np.asarray(Sigma_a, dtype=np.float64)
13
+ d = Sigma_a.shape[0]
14
+ Omega = float(sigma2) * np.linalg.inv(Sigma_a)
15
+
16
+ Q = np.eye(d)[None, :, :] - _projectors(Sigma_a)
17
+ C = np.linalg.matrix_power(Q.mean(axis=0), int(tau))
18
+
19
+ A = Omega.copy()
20
+ for _ in range(int(tau)):
21
+ A = np.einsum("kij,jl,kml->im", Q, A, Q) / d
22
+
23
+ RHS = Omega - C @ Omega - Omega @ C + A
24
+ RHS = 0.5 * (RHS + RHS.T)
25
+
26
+ M = np.eye(d) - C
27
+ M = 0.5 * (M + M.T)
28
+ s, U = np.linalg.eigh(M)
29
+ if s.min() <= 1e-12:
30
+ raise ValueError("I - C* is singular; Xi* does not exist for this instance")
31
+ Theta = 1.0 / (s[:, None] + s[None, :])
32
+ Xi = U @ (Theta * (U.T @ RHS @ U)) @ U.T
33
+ return 0.5 * (Xi + Xi.T)
34
+
35
+
36
+ def sandwich(Sigma_a, sigma2):
37
+ """Omega*/2, the exact-solver (tau -> infinity) limit. Used only by build-time checks."""
38
+ return 0.5 * float(sigma2) * np.linalg.inv(np.asarray(Sigma_a, dtype=np.float64))
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements-verifier.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pytest==8.3.5
2
+ pytest-json-ctrf==0.3.5
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ numpy==2.5.2
2
+ scipy==1.18.0
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/run_one.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+
9
+ def main():
10
+ ap = argparse.ArgumentParser()
11
+ ap.add_argument("--workdir", required=True)
12
+ args = ap.parse_args()
13
+ work = Path(args.workdir)
14
+
15
+ sys.path.insert(0, str(work / "harness"))
16
+ import runner
17
+
18
+ spec = json.loads((work / "job.json").read_text())
19
+ config = runner.make_config(spec["d"], spec["T"], spec["tau"])
20
+
21
+ A = np.load(work / "samples_a.npy", mmap_mode="r", allow_pickle=False)
22
+ b = np.load(work / "samples_b.npy", mmap_mode="r", allow_pickle=False)
23
+ stream = runner.stream_from_samples(A, b, config, spec["alg_seed"])
24
+
25
+ sys.path.insert(0, str(work / "solution"))
26
+ import estimator
27
+
28
+ out = estimator.estimate(stream, config)
29
+ out = np.asarray(out, dtype=np.float64)
30
+ np.save(work / "out" / "result.npy", out, allow_pickle=False)
31
+ return 0
32
+
33
+
34
+ if __name__ == "__main__":
35
+ sys.exit(main())
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+
4
+ mkdir -p /logs/verifier
5
+ chown root:root /logs/verifier 2>/dev/null || true
6
+ chmod 755 /logs/verifier 2>/dev/null || true
7
+ rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
8
+
9
+ printf '0\n' > /logs/verifier/reward.txt
10
+ trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi' EXIT
11
+
12
+ chmod -R go-rwx /tests
13
+
14
+ export GRADE_SPLIT=final
15
+ cd /tests
16
+ /usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
17
+ /usr/local/bin/python3 /tests/compute_reward.py
18
+
19
+ exit 0
tasks/sketched-newton-cov-estimator/environment/are-grader-ctx/test_state.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
7
+ import grader_core
8
+
9
+ DELIVERABLE = Path(os.environ.get("GRADER_DELIVERABLE", "/app/output"))
10
+ SPLIT = os.environ.get("GRADE_SPLIT", "final")
11
+ SPLIT_DIR = Path(os.environ.get(
12
+ "GRADER_SPLIT_DIR", str(Path(__file__).resolve().parent / "hidden_data" / SPLIT)))
13
+ METRIC_PATH = Path(os.environ.get("GRADER_METRIC_PATH", "/logs/verifier/metric.json"))
14
+
15
+
16
+ def test_limiting_covariance_estimator():
17
+ """Run the submitted estimator over every sealed instance and score its variance error.
18
+
19
+ The agent's code runs only in per-replication subprocesses launched by grader_core, as a
20
+ non-root uid, with no access to the instance parameters or to the true covariance. This
21
+ process recomputes the metric from verifier-owned ground truth; nothing the submission
22
+ reports about itself is read.
23
+ """
24
+ report = {"metric": None, "reward": 0.0, "split": SPLIT}
25
+ try:
26
+ report = grader_core.grade(str(SPLIT_DIR), str(DELIVERABLE))
27
+ report["split"] = SPLIT
28
+ except Exception as exc:
29
+ report["error"] = f"{type(exc).__name__}: {exc}"
30
+ finally:
31
+ METRIC_PATH.parent.mkdir(parents=True, exist_ok=True)
32
+ METRIC_PATH.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n")
33
+
34
+ print("")
35
+ for line in grader_core.summary_lines(report) if "error" not in report else \
36
+ [f"grading failed: {report['error']}", "metric (lower is better) : n/a",
37
+ "reward : 0.000000"]:
38
+ print(line)
39
+ assert "error" not in report, report.get("error")
tasks/sketched-newton-cov-estimator/environment/docker-compose.yaml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ARE 1.1: grading lives in sidecars. Harbor configures `main` (build, limits, network).
2
+ services:
3
+ main:
4
+ depends_on:
5
+ grader:
6
+ condition: service_healthy
7
+ volumes:
8
+ - are-deliverable-0:/app/output
9
+
10
+ grader:
11
+ build:
12
+ context: ./are-grader-ctx
13
+ dockerfile: Dockerfile.are
14
+ args:
15
+ ARE_ROLE: val
16
+ platform: linux/amd64
17
+ environment:
18
+ ARE_ROLE: val
19
+ ARE_PORT: "8000"
20
+ ARE_BUDGET_SEC: "86400"
21
+ ARE_ARTIFACT_PATHS: "/app/output"
22
+ ARE_AGENT_UID: "1001"
23
+ ARE_GRADE_TIMEOUT_SEC: "1500"
24
+ volumes:
25
+ - are-deliverable-0:/run/are-deliverable/app/output
26
+ - are-secret:/run/are-secret
27
+ expose:
28
+ - "8000"
29
+ cap_add: [SYS_ADMIN]
30
+ networks: [default, are-private]
31
+ cpus: 8
32
+ mem_limit: 14336m
33
+ depends_on:
34
+ test-grader:
35
+ condition: service_healthy
36
+ healthcheck:
37
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"]
38
+ interval: 2s
39
+ timeout: 5s
40
+ retries: 60
41
+ start_period: 5s
42
+
43
+ test-grader:
44
+ build:
45
+ context: ./are-grader-ctx
46
+ dockerfile: Dockerfile.are
47
+ args:
48
+ ARE_ROLE: test
49
+ platform: linux/amd64
50
+ environment:
51
+ ARE_ROLE: test
52
+ ARE_PORT: "8001"
53
+ ARE_ARTIFACT_PATHS: "/app/output"
54
+ ARE_GRADE_TIMEOUT_SEC: "1500"
55
+ expose:
56
+ - "8001"
57
+ volumes:
58
+ - are-secret:/run/are-secret
59
+ cap_add: [SYS_ADMIN]
60
+ networks: [are-private]
61
+ cpus: 8
62
+ mem_limit: 14336m
63
+ healthcheck:
64
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=2)"]
65
+ interval: 2s
66
+ timeout: 5s
67
+ retries: 60
68
+ start_period: 5s
69
+
70
+ volumes:
71
+ are-deliverable-0: {}
72
+ are-secret: {}
73
+
74
+ networks:
75
+ are-private:
76
+ internal: true
tasks/sketched-newton-cov-estimator/task.toml CHANGED
@@ -1,57 +1,71 @@
1
  schema_version = "1.4"
2
- artifacts = [ "/app/output",]
 
 
3
 
4
  [task]
5
  name = "bespokelabs/sketched-newton-cov-estimator"
6
- version = "1.0.0"
7
  description = ""
8
- keywords = [ "autoresearch", "machine-learning", "benchmark",]
9
- [[task.authors]]
10
- name = "Bespoke Labs"
 
 
 
 
 
11
 
12
  [metadata]
13
  category = "Model Training and ML Infrastructure"
14
  subcategory = "Evaluation infrastructure"
15
- task_objective = [ "Implement", "Optimize",]
16
- artifact_type = [ "Single script or program",]
 
 
 
 
 
17
  expert_time_estimate_hours = 6.0
 
 
18
 
19
  [verifier]
20
- timeout_sec = 1500.0
21
  environment_mode = "separate"
22
- collect = []
23
 
24
- [verifier.env]
 
 
 
25
 
26
  [verifier.environment]
27
  network_mode = "no-network"
28
- build_timeout_sec = 3600.0
29
- os = "linux"
30
- cpus = 8
31
- memory_mb = 14336
32
- storage_mb = 153600
33
  gpus = 0
34
- mcp_servers = []
35
-
36
- [verifier.environment.env]
37
 
38
  [agent]
39
  network_mode = "allowlist"
40
- allowed_hosts = [ "api.openai.com", "api.anthropic.com",]
41
- timeout_sec = 14400.0
 
 
 
 
42
  user = "agent"
43
 
44
  [environment]
45
- network_mode = "allowlist"
46
- allowed_hosts = [ "api.openai.com", "api.anthropic.com",]
47
  build_timeout_sec = 3600.0
48
  os = "linux"
49
  cpus = 8
50
  memory_mb = 14336
51
  storage_mb = 153600
52
  gpus = 0
53
- mcp_servers = []
 
 
54
 
55
  [environment.env]
56
-
57
- [solution.env]
 
1
  schema_version = "1.4"
2
+ artifacts = [
3
+ { source = "/var/lib/are", service = "grader" },
4
+ ]
5
 
6
  [task]
7
  name = "bespokelabs/sketched-newton-cov-estimator"
8
+ version = "1.1.0"
9
  description = ""
10
+ keywords = [
11
+ "autoresearch",
12
+ "machine-learning",
13
+ "benchmark",
14
+ ]
15
+ authors = [
16
+ { name = "Bespoke Labs" },
17
+ ]
18
 
19
  [metadata]
20
  category = "Model Training and ML Infrastructure"
21
  subcategory = "Evaluation infrastructure"
22
+ task_objective = [
23
+ "Implement",
24
+ "Optimize",
25
+ ]
26
+ artifact_type = [
27
+ "Single script or program",
28
+ ]
29
  expert_time_estimate_hours = 6.0
30
+ are_version = "1.1"
31
+ budget_seconds = 86400
32
 
33
  [verifier]
34
+ timeout_sec = 600.0
35
  environment_mode = "separate"
 
36
 
37
+ [[verifier.collect]]
38
+ service = "grader"
39
+ command = "/opt/are/venv/bin/python /opt/are/drain.py"
40
+ timeout_sec = 3600.0
41
 
42
  [verifier.environment]
43
  network_mode = "no-network"
44
+ build_timeout_sec = 600.0
45
+ cpus = 1
46
+ memory_mb = 1024
 
 
47
  gpus = 0
 
 
 
48
 
49
  [agent]
50
  network_mode = "allowlist"
51
+ allowed_hosts = [
52
+ "api.openai.com",
53
+ "api.anthropic.com",
54
+ "grader",
55
+ ]
56
+ timeout_sec = 86400.0
57
  user = "agent"
58
 
59
  [environment]
60
+ network_mode = "public"
 
61
  build_timeout_sec = 3600.0
62
  os = "linux"
63
  cpus = 8
64
  memory_mb = 14336
65
  storage_mb = 153600
66
  gpus = 0
67
+ mcp_servers = [
68
+ { name = "are", transport = "streamable-http", url = "http://grader:8000/mcp" },
69
+ ]
70
 
71
  [environment.env]
 
 
tasks/sketched-newton-cov-estimator/tests/Dockerfile CHANGED
@@ -1,31 +1,2 @@
1
- FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
-
3
- ENTRYPOINT []
4
- ENV PYTHONPATH=
5
- ENV PYTHONSAFEPATH=1
6
- ENV DEBIAN_FRONTEND=noninteractive \
7
- PYTHONHASHSEED=0 \
8
- PIP_NO_CACHE_DIR=1 \
9
- PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
- OMP_NUM_THREADS=1 \
11
- OPENBLAS_NUM_THREADS=1 \
12
- MKL_NUM_THREADS=1
13
-
14
- RUN useradd --create-home --uid 1001 agent
15
-
16
- COPY ./requirements.txt /tmp/requirements.txt
17
- COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
18
- RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
19
- -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
20
- && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
21
-
22
- RUN mkdir -p /app/output /logs/verifier
23
-
24
- COPY . /tests
25
-
26
- RUN chown -R root:root /tests \
27
- && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
28
- && chmod +x /tests/test.sh /tests/intermediate.sh \
29
- && find /tests -exec touch -d @1700000000 {} +
30
-
31
- WORKDIR /tests
 
1
+ FROM python:3.12-slim
2
+ COPY . /tests/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tasks/sketched-newton-cov-estimator/tests/finalize.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final verifier: score the run from the grader ledger.
2
+
3
+ reward hidden test score of the submission with the best validation score
4
+ (ties go to the earlier submission); 0 if nothing was submitted.
5
+ auarc area under the curve of that same quantity over the wall-clock budget,
6
+ using the time each validation score became available, divided by the
7
+ budget. 0 before the first graded submission.
8
+ """
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ STATE = Path("/var/lib/are")
14
+ OUT = Path("/logs/verifier")
15
+ OUT.mkdir(parents=True, exist_ok=True)
16
+
17
+ meta = json.loads((STATE / "meta.json").read_text()) if (STATE / "meta.json").exists() else {}
18
+ budget = float(meta.get("budget_seconds") or 1.0)
19
+
20
+ subs: dict[int, dict] = {}
21
+ ledger = STATE / "ledger.jsonl"
22
+ for line in (ledger.read_text().splitlines() if ledger.exists() else []):
23
+ ev = json.loads(line)
24
+ s = subs.setdefault(ev["id"], {"id": ev["id"]})
25
+ if ev["event"] == "submitted":
26
+ s["submitted_t"] = ev["t"]
27
+ elif ev["event"] == "val":
28
+ s["val"] = ev["score"]
29
+ s["val_t"] = ev["t"]
30
+ elif ev["event"] == "test":
31
+ s["test"] = ev["score"]
32
+
33
+ graded = sorted((s for s in subs.values() if "val" in s), key=lambda s: s["val_t"])
34
+
35
+ # Step function of the hidden score of the best-validation pick over time.
36
+ auc, best, last_t, cur = 0.0, None, 0.0, 0.0
37
+ timeline = []
38
+ for s in graded:
39
+ t = min(s["val_t"], budget)
40
+ auc += cur * (t - last_t)
41
+ last_t = t
42
+ if best is None or s["val"] > best["val"] or (s["val"] == best["val"] and s["id"] < best["id"]):
43
+ best = s
44
+ cur = float(best.get("test") or 0.0)
45
+ timeline.append({"t": s["val_t"], "id": s["id"], "val": s["val"], "test": s.get("test"),
46
+ "pick": best["id"]})
47
+ auc += cur * (budget - last_t) if last_t < budget else 0.0
48
+
49
+ reward = {
50
+ "reward": float(best.get("test") or 0.0) if best else 0.0,
51
+ "auarc": auc / budget,
52
+ "best_val": float(best["val"]) if best else 0.0,
53
+ "n_submissions": float(len(subs)),
54
+ "n_test_graded": float(sum(s.get("test") is not None for s in subs.values())),
55
+ }
56
+ (OUT / "reward.json").write_text(json.dumps(reward))
57
+ (OUT / "timeline.json").write_text(json.dumps({"budget": budget, "selected": best and best["id"],
58
+ "submissions": timeline}, indent=1))
59
+ print(json.dumps(reward, indent=1))
tasks/sketched-newton-cov-estimator/tests/test.sh CHANGED
@@ -1,19 +1,2 @@
1
  #!/bin/bash
2
- set -u
3
-
4
- mkdir -p /logs/verifier
5
- chown root:root /logs/verifier 2>/dev/null || true
6
- chmod 755 /logs/verifier 2>/dev/null || true
7
- rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
8
-
9
- printf '0\n' > /logs/verifier/reward.txt
10
- trap 'if [ ! -s /logs/verifier/reward.txt ]; then printf "0\n" > /logs/verifier/reward.txt; fi' EXIT
11
-
12
- chmod -R go-rwx /tests
13
-
14
- export GRADE_SPLIT=final
15
- cd /tests
16
- /usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
17
- /usr/local/bin/python3 /tests/compute_reward.py
18
-
19
- exit 0
 
1
  #!/bin/bash
2
+ python3 /tests/finalize.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tasks/sopcc-online-chance-constrained-policy/environment/.dockerignore ADDED
@@ -0,0 +1 @@
 
 
1
+ are-grader-ctx
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
+
3
+ ENTRYPOINT []
4
+ ENV PYTHONPATH=
5
+ ENV PYTHONSAFEPATH=1
6
+ ENV DEBIAN_FRONTEND=noninteractive \
7
+ PYTHONHASHSEED=0 \
8
+ PIP_NO_CACHE_DIR=1 \
9
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
+ OMP_NUM_THREADS=1 \
11
+ MKL_NUM_THREADS=1 \
12
+ OPENBLAS_NUM_THREADS=1
13
+
14
+ RUN useradd --create-home --uid 1001 agent
15
+
16
+ COPY ./requirements.txt /tmp/requirements.txt
17
+ COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
18
+ RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
19
+ -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
20
+ && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
21
+
22
+ RUN mkdir -p /app/solution /logs/verifier
23
+
24
+ COPY . /tests
25
+
26
+ RUN chown -R root:root /tests \
27
+ && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
28
+ && chmod +x /tests/test.sh /tests/intermediate.sh \
29
+ && find /tests -exec touch -d @1700000000 {} +
30
+
31
+ WORKDIR /tests
32
+
33
+ ENV HF_HUB_OFFLINE=1
34
+ ENV TRANSFORMERS_OFFLINE=1
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/Dockerfile.are ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM --platform=linux/amd64 public.ecr.aws/docker/library/python:3.13-slim-bookworm@sha256:01f42367a0a94ad4bc17111776fd66e3500c1d87c15bbd6055b7371d39c124fb
2
+
3
+ ENTRYPOINT []
4
+ ENV PYTHONPATH=
5
+ ENV PYTHONSAFEPATH=1
6
+ ENV DEBIAN_FRONTEND=noninteractive \
7
+ PYTHONHASHSEED=0 \
8
+ PIP_NO_CACHE_DIR=1 \
9
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
10
+ OMP_NUM_THREADS=1 \
11
+ MKL_NUM_THREADS=1 \
12
+ OPENBLAS_NUM_THREADS=1
13
+
14
+ RUN useradd --create-home --uid 1001 agent
15
+
16
+ COPY ./requirements.txt /tmp/requirements.txt
17
+ COPY ./requirements-verifier.txt /tmp/requirements-verifier.txt
18
+ RUN /usr/local/bin/python3 -m pip install --no-cache-dir \
19
+ -r /tmp/requirements.txt -r /tmp/requirements-verifier.txt \
20
+ && rm /tmp/requirements.txt /tmp/requirements-verifier.txt
21
+
22
+ RUN mkdir -p /app/solution /logs/verifier
23
+
24
+ COPY . /tests
25
+
26
+ RUN chown -R root:root /tests \
27
+ && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
28
+ && chmod +x /tests/test.sh /tests/intermediate.sh \
29
+ && find /tests -exec touch -d @1700000000 {} +
30
+
31
+ WORKDIR /tests
32
+
33
+ ENV HF_HUB_OFFLINE=1
34
+ ENV TRANSFORMERS_OFFLINE=1
35
+
36
+
37
+ # ---- ARE 1.1 grader layer (appended to the task's own verifier Dockerfile) ----
38
+ ARG ARE_ROLE
39
+ # python.org images ship /usr/local/bin/python3; distro-python bases (kaggle GPU) lack
40
+ # ensurepip, so fall back to a pip-less venv filled by the base interpreter's pip.
41
+ RUN PY=$(command -v /usr/local/bin/python3 || command -v python3) \
42
+ && if "$PY" -m venv /opt/are/venv; then \
43
+ /opt/are/venv/bin/pip install --no-cache-dir "fastmcp==2.14.7"; \
44
+ else rm -rf /opt/are/venv && "$PY" -m venv --without-pip /opt/are/venv \
45
+ && "$PY" -m pip --python /opt/are/venv/bin/python install --no-cache-dir "fastmcp==2.14.7"; fi
46
+ COPY are/ /opt/are/
47
+ # The val grader, whose output reaches the agent, never holds the private grader or its
48
+ # data. The test grader keeps everything; nothing from it reaches the agent.
49
+ RUN rm -rf /tests/are /tests/Dockerfile.are \
50
+ && if [ "$ARE_ROLE" = "val" ]; then rm -rf /tests/test.sh /tests/hidden_data/final; fi
51
+ ENV ARE_ROLE=$ARE_ROLE
52
+ CMD ["/opt/are/venv/bin/python", "/opt/are/server.py"]
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/drain.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verifier collect hook, run after the agent stops.
2
+
3
+ Grades the final workspace as one last submission (unless it equals the last one),
4
+ then waits until every submission has both grades recorded.
5
+ """
6
+
7
+ import json
8
+ import time
9
+ import urllib.request
10
+ from pathlib import Path
11
+
12
+ TOKEN = Path("/run/are-secret/token").read_text().strip()
13
+ H = {"x-are-token": TOKEN}
14
+
15
+ req = urllib.request.Request("http://localhost:8000/final", method="POST", headers=H)
16
+ with urllib.request.urlopen(req, timeout=120) as resp:
17
+ print("final:", json.loads(resp.read()), flush=True)
18
+
19
+ while True:
20
+ with urllib.request.urlopen(urllib.request.Request("http://localhost:8000/drain", headers=H), timeout=30) as resp:
21
+ state = json.loads(resp.read())
22
+ print(state, flush=True)
23
+ if state["val_pending"] == 0 and state["test_pending"] == 0:
24
+ break
25
+ time.sleep(5)
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/are/server.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ARE 1.1 grader sidecar.
2
+
3
+ One image, two roles:
4
+
5
+ - ARE_ROLE=val ("grader" service). Reachable from the agent. Serves MCP tools and a
6
+ REST fallback. On submit it snapshots the shared deliverable volume, grades the
7
+ snapshot with the task's public grader (intermediate.sh), and returns only that
8
+ score. Every snapshot is also sent to the test grader; the hidden score goes to a
9
+ root-only ledger and never back to the agent.
10
+ - ARE_ROLE=test ("test-grader" service). On a private network that only the val
11
+ grader can reach. Grades snapshots with the task's private grader (test.sh).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import gzip
18
+ import hashlib
19
+ import io
20
+ import secrets
21
+ import json
22
+ import os
23
+ import queue
24
+ import shutil
25
+ import subprocess
26
+ import tarfile
27
+ import threading
28
+ import time
29
+ import urllib.request
30
+ from pathlib import Path
31
+
32
+ from fastmcp import FastMCP
33
+ from starlette.requests import Request
34
+ from starlette.responses import JSONResponse, Response
35
+
36
+ ROLE = os.environ.get("ARE_ROLE", "val")
37
+ PORT = int(os.environ.get("ARE_PORT", "8000"))
38
+ STATE = Path(os.environ.get("ARE_STATE_DIR", "/var/lib/are"))
39
+ ARTIFACT_PATHS = [p for p in os.environ.get("ARE_ARTIFACT_PATHS", "/app/output").split(":") if p]
40
+ # The shared deliverable volume. Its parent is root-only, so submitted code (which every
41
+ # task grader runs as the unprivileged agent user) cannot reach it to write back to the agent.
42
+ SUBMISSION_ROOT = Path(os.environ.get("ARE_SUBMISSION_ROOT", "/run/are-deliverable"))
43
+ AGENT_UID = int(os.environ.get("ARE_AGENT_UID", "1001"))
44
+ BUDGET_SEC = float(os.environ.get("ARE_BUDGET_SEC", "14400"))
45
+ GRADE_TIMEOUT_SEC = float(os.environ.get("ARE_GRADE_TIMEOUT_SEC", "1800"))
46
+ TEST_GRADER_URL = os.environ.get("ARE_TEST_GRADER_URL", "http://test-grader:8001")
47
+ FEEDBACK_TAIL = int(os.environ.get("ARE_FEEDBACK_TAIL_CHARS", "8192"))
48
+ SCRIPT = "/tests/intermediate.sh" if ROLE == "val" else "/tests/test.sh"
49
+ # Shared only by the two graders (a volume the agent's container never mounts). The test
50
+ # grader writes a fresh token at startup; every internal request must carry it, so the
51
+ # agent cannot reach the test grader or the internal endpoints even on a shared network.
52
+ TOKEN_FILE = Path(os.environ.get("ARE_TOKEN_FILE", "/run/are-secret/token"))
53
+ TOKEN = ""
54
+
55
+
56
+ def _authorized(request: Request) -> bool:
57
+ """Internal endpoints need the graders' token; an unset token never matches."""
58
+ return bool(TOKEN) and secrets.compare_digest(request.headers.get("x-are-token", ""), TOKEN)
59
+
60
+
61
+ def _net_isolation_available() -> bool:
62
+ try:
63
+ return subprocess.run(["unshare", "-n", "true"], capture_output=True, timeout=10).returncode == 0
64
+ except Exception:
65
+ return False
66
+
67
+
68
+ NET_ISOLATED = False # set at startup: grader scripts run in an empty network namespace
69
+
70
+ T0 = time.time()
71
+ _lock = threading.Lock()
72
+
73
+
74
+ def _elapsed() -> float:
75
+ return round(time.time() - T0, 1)
76
+
77
+
78
+ def _ledger(event: dict) -> None:
79
+ event = {"t": _elapsed(), "wall": time.time(), **event}
80
+ for attempt in range(3):
81
+ try:
82
+ with _lock, open(STATE / "ledger.jsonl", "a") as fh:
83
+ fh.write(json.dumps(event) + "\n")
84
+ return
85
+ except OSError:
86
+ if attempt == 2:
87
+ raise
88
+ time.sleep(1)
89
+
90
+
91
+ def _kill_grading_processes(proc: subprocess.Popen) -> None:
92
+ """Kill everything a timed-out grade started, including processes that left its group."""
93
+ try:
94
+ os.killpg(proc.pid, 9)
95
+ except ProcessLookupError:
96
+ pass
97
+ _kill_other_processes()
98
+
99
+
100
+ def _kill_other_processes() -> None:
101
+ """Kill every process run by the agent user. Every task grader runs submitted code as
102
+ that user, so this stops all graded code (detached or not) and nothing else: the grader
103
+ server, the task's own grader and Harbor's hooks run as root."""
104
+ for entry in Path("/proc").iterdir():
105
+ if not entry.name.isdigit():
106
+ continue
107
+ try:
108
+ if entry.stat().st_uid == AGENT_UID:
109
+ os.kill(int(entry.name), 9)
110
+ except (ProcessLookupError, PermissionError, FileNotFoundError):
111
+ pass
112
+
113
+
114
+ # Places the agent user (who runs submitted code inside every task grader) can write.
115
+ _BASELINE: set[str] = set() # every path that existed when the grader started (its image)
116
+
117
+
118
+ def _walk_one_fs(base: Path):
119
+ """Every path under base on base's own filesystem (skips /proc, /sys and other mounts)."""
120
+ dev = base.stat().st_dev
121
+ for root, dirs, files in os.walk(base):
122
+ dirs[:] = [d for d in dirs if os.lstat(os.path.join(root, d)).st_dev == dev]
123
+ for name in dirs + files:
124
+ yield Path(root) / name
125
+
126
+
127
+ def _all_paths() -> set[str]:
128
+ out = set()
129
+ for base in (Path("/"), Path("/dev/shm")):
130
+ if base.is_dir():
131
+ out.update(str(q) for q in _walk_one_fs(base))
132
+ return out
133
+
134
+
135
+ def _protected(path: str) -> bool:
136
+ keep = [str(STATE), "/opt/are", str(TOKEN_FILE.parent)]
137
+ return any(path == k or path.startswith(k + "/") for k in keep)
138
+
139
+
140
+ def _fresh_state() -> None:
141
+ """Start every grade from the grader image's own files, as ARE 1.0's fresh verifier
142
+ container did. The grader container lives for the whole run, so before each grade
143
+ stop anything an earlier grade left running and delete every file it created,
144
+ whoever wrote it. The deliverable volume and the token are separate mounts and are
145
+ never walked; the grader's own state is kept."""
146
+ _kill_other_processes()
147
+ # System V shared memory, semaphores and queues outlive processes; this server uses none.
148
+ subprocess.run(["ipcrm", "--all"], capture_output=True)
149
+ for path in sorted(_all_paths() - _BASELINE, key=lambda q: q.count("/"), reverse=True):
150
+ if _protected(path):
151
+ continue
152
+ try:
153
+ q = Path(path)
154
+ if q.is_dir() and not q.is_symlink():
155
+ shutil.rmtree(q, ignore_errors=True)
156
+ else:
157
+ q.unlink()
158
+ except OSError:
159
+ pass
160
+
161
+
162
+ def grade_snapshot(tar_bytes: bytes, tag: str) -> dict:
163
+ """Extract a snapshot over the artifact paths and run this role's grader script."""
164
+ _fresh_state()
165
+ for path in ARTIFACT_PATHS:
166
+ p = Path(path)
167
+ if p.exists():
168
+ shutil.rmtree(p)
169
+ p.mkdir(parents=True)
170
+ with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf:
171
+ tf.extractall("/", filter="tar")
172
+ logs = Path("/logs/verifier")
173
+ if logs.exists():
174
+ shutil.rmtree(logs)
175
+ logs.mkdir(parents=True)
176
+ started = time.time()
177
+ # Submitted code runs with no network, as in ARE 1.0's verifier.
178
+ cmd = (["unshare", "-n"] if NET_ISOLATED else []) + ["bash", SCRIPT]
179
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
180
+ cwd="/tests", start_new_session=True)
181
+ try:
182
+ out, err = proc.communicate(timeout=GRADE_TIMEOUT_SEC)
183
+ error = None
184
+ except subprocess.TimeoutExpired:
185
+ _kill_grading_processes(proc)
186
+ out, err = proc.communicate()
187
+ error = f"grader timed out after {GRADE_TIMEOUT_SEC:.0f}s"
188
+ output = (out or "") + (err or "")
189
+ # Nothing a grade started may keep running after it, not even detached processes.
190
+ _kill_other_processes()
191
+ score = 0.0
192
+ reward_file = logs / "reward.txt"
193
+ if reward_file.exists():
194
+ try:
195
+ score = float(reward_file.read_text().strip() or 0)
196
+ except ValueError:
197
+ error = error or "unparseable reward"
198
+ metric = None
199
+ if (logs / "metric.json").exists():
200
+ try:
201
+ metric = json.loads((logs / "metric.json").read_text())
202
+ except ValueError:
203
+ pass
204
+ (STATE / "logs").mkdir(exist_ok=True)
205
+ (STATE / "logs" / f"{tag}.log").write_text(output)
206
+ return {
207
+ "score": score,
208
+ "metric": metric,
209
+ "error": error,
210
+ "net_isolated": NET_ISOLATED,
211
+ "seconds": round(time.time() - started, 1),
212
+ # What the agent sees, as in ARE 1.0: the grader's stdout tail (not stderr).
213
+ "output_tail": (out or "")[-FEEDBACK_TAIL:],
214
+ }
215
+
216
+
217
+ mcp = FastMCP("are")
218
+
219
+
220
+ # ---------------------------------------------------------------- test role
221
+
222
+
223
+ _grade_lock = threading.Lock()
224
+
225
+
226
+ def _grade_one_at_a_time(tar_bytes: bytes, tag: str) -> dict:
227
+ # A request that timed out on the caller's side may still be grading; the next one
228
+ # waits for it rather than sharing /app/output and /logs/verifier with it.
229
+ with _grade_lock:
230
+ return grade_snapshot(tar_bytes, tag)
231
+
232
+
233
+ if ROLE == "test":
234
+
235
+ @mcp.custom_route("/grade", methods=["POST"])
236
+ async def http_grade(request: Request) -> Response:
237
+ if not _authorized(request):
238
+ return JSONResponse({"error": "forbidden"}, status_code=403)
239
+ tag = request.query_params.get("tag", "x")
240
+ body = await request.body()
241
+ result = await asyncio.to_thread(_grade_one_at_a_time, body, f"{tag}-test")
242
+ return JSONResponse(result)
243
+
244
+
245
+ # ----------------------------------------------------------------- val role
246
+
247
+
248
+ class Board:
249
+ """Submissions and their grading state. Hidden scores are never stored here."""
250
+
251
+ def __init__(self) -> None:
252
+ self.subs: dict[int, dict] = {}
253
+ self.val_q: queue.Queue[int] = queue.Queue()
254
+ self.next_id = 1
255
+ self.test_pending = 0
256
+ self.last_digest: str | None = None
257
+
258
+ def public(self, sid: int) -> dict:
259
+ s = self.subs[sid]
260
+ out = {k: s[k] for k in ("id", "note", "submitted_at_s", "status")}
261
+ if s["status"] == "graded":
262
+ v = s["val"]
263
+ out.update(
264
+ validation_score=v["score"],
265
+ error=v["error"],
266
+ grading_seconds=v["seconds"],
267
+ grader_output_tail=v["output_tail"],
268
+ )
269
+ return out
270
+
271
+ def best(self) -> dict | None:
272
+ graded = [s for s in self.subs.values() if s["status"] == "graded"]
273
+ if not graded:
274
+ return None
275
+ b = max(graded, key=lambda s: (s["val"]["score"], -s["id"]))
276
+ return {"id": b["id"], "validation_score": b["val"]["score"]}
277
+
278
+
279
+ board = Board()
280
+
281
+
282
+ def snapshot() -> bytes:
283
+ """Deterministic tar.gz of the deliverable: same content, same bytes (gzip mtime 0)."""
284
+ raw = io.BytesIO()
285
+ with tarfile.open(fileobj=raw, mode="w") as tf:
286
+ for path in ARTIFACT_PATHS:
287
+ src = SUBMISSION_ROOT / path.lstrip("/")
288
+ tf.add(str(src), arcname=path.lstrip("/"))
289
+ out = io.BytesIO()
290
+ with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz:
291
+ gz.write(raw.getvalue())
292
+ return out.getvalue()
293
+
294
+
295
+ def do_submit(note: str, final: bool = False) -> dict:
296
+ with _lock:
297
+ pending = [s["id"] for s in board.subs.values() if s["status"] != "graded"]
298
+ if pending and not final:
299
+ return {
300
+ "error": f"Submission {pending[0]} is still being graded. One submission is "
301
+ f"graded at a time: check result({pending[0]}) and submit again "
302
+ "once it has its score.",
303
+ "pending_id": pending[0],
304
+ }
305
+ sid = board.next_id
306
+ board.next_id += 1
307
+ board.subs[sid] = {"id": sid, "note": note[:500], "submitted_at_s": _elapsed(),
308
+ "status": "queued"}
309
+ try:
310
+ data = snapshot()
311
+ digest = hashlib.sha256(data).hexdigest()
312
+ (STATE / "snapshots" / f"{sid:04d}.tar.gz").write_bytes(data)
313
+ _ledger({"event": "submitted", "id": sid, "note": note[:500], "bytes": len(data),
314
+ "sha256": digest, "final": final})
315
+ except Exception as exc:
316
+ with _lock:
317
+ board.subs.pop(sid, None) # release the slot; the id is not reused
318
+ return {"error": f"Could not snapshot the deliverable ({exc}). Nothing was submitted. "
319
+ "Make sure nothing is writing to it, then submit again."}
320
+ board.last_digest = digest
321
+ with _lock:
322
+ board.test_pending += 1
323
+ board.val_q.put(sid)
324
+ return {"id": sid, "status": "queued",
325
+ "hint": "Grading has started. Check result(id) for the validation score."}
326
+
327
+
328
+ def final_submit() -> dict:
329
+ """After the agent stops: grade the final workspace unless it was already submitted."""
330
+ try:
331
+ data = snapshot()
332
+ except Exception as exc:
333
+ return {"error": f"final snapshot failed: {exc}"}
334
+ if board.subs and hashlib.sha256(data).hexdigest() == board.last_digest:
335
+ return {"skipped": "final workspace equals the last submission"}
336
+ return do_submit("final workspace (automatic)", final=True)
337
+
338
+
339
+ def grade_worker() -> None:
340
+ """Grade each submission on val, then on test, one submission at a time.
341
+
342
+ The val score is published as soon as it is ready. The next submission's val grade
343
+ waits until this test grade is done, so the two graders never run at the same time.
344
+ """
345
+ while True:
346
+ sid = board.val_q.get()
347
+ board.subs[sid]["status"] = "grading"
348
+ data = b""
349
+ try:
350
+ data = (STATE / "snapshots" / f"{sid:04d}.tar.gz").read_bytes()
351
+ res = grade_snapshot(data, f"{sid:04d}-val")
352
+ except Exception as exc:
353
+ res = {"score": 0.0, "metric": None, "error": f"grader failed: {exc}",
354
+ "net_isolated": NET_ISOLATED, "seconds": 0.0, "output_tail": ""}
355
+ board.subs[sid]["val"] = res
356
+ board.subs[sid]["status"] = "graded"
357
+ try:
358
+ _ledger({"event": "val", "id": sid, **{k: res[k] for k in ("score", "metric", "error", "seconds", "net_isolated")}})
359
+ except OSError as exc: # keep grading later submissions
360
+ print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True)
361
+ test_grade(sid, data)
362
+
363
+
364
+ def test_grade(sid: int, data: bytes) -> None:
365
+ try:
366
+ _test_grade(sid, data)
367
+ finally:
368
+ with _lock:
369
+ board.test_pending -= 1
370
+
371
+
372
+ def _test_grade(sid: int, data: bytes) -> None:
373
+ """Send one snapshot to the test grader. A failed request is retried (the same snapshot
374
+ is graded again, so a retry can only recover the honest score); a request that ran
375
+ past its timeout is not, since the grade itself already took the full time."""
376
+ started = time.time()
377
+ for attempt in range(3):
378
+ try:
379
+ req = urllib.request.Request(
380
+ f"{TEST_GRADER_URL}/grade?tag={sid:04d}", data=data, method="POST",
381
+ headers={"x-are-token": TOKEN},
382
+ )
383
+ with urllib.request.urlopen(req, timeout=2 * GRADE_TIMEOUT_SEC + 300) as resp:
384
+ res = json.loads(resp.read())
385
+ break
386
+ except Exception as exc: # recorded, never shown to the agent
387
+ res = {"score": None, "metric": None, "error": f"test grader: {exc}",
388
+ "seconds": round(time.time() - started, 1)}
389
+ if attempt == 2 or isinstance(exc, TimeoutError) or isinstance(getattr(exc, "reason", None), TimeoutError):
390
+ break
391
+ time.sleep(5)
392
+ try:
393
+ _ledger({"event": "test", "id": sid, **{k: res.get(k) for k in ("score", "metric", "error", "seconds", "net_isolated")}})
394
+ except OSError as exc: # keep grading later submissions
395
+ print(f"ARE grader: ledger write failed for {sid}: {exc}", flush=True)
396
+
397
+
398
+ def with_time(out: dict) -> dict:
399
+ """Wall-clock accounting on every reply, as the v1 harness gave each phase."""
400
+ out["total_budget_seconds"] = BUDGET_SEC
401
+ out["time_remaining_seconds"] = round(max(0.0, BUDGET_SEC - _elapsed()), 1)
402
+ return out
403
+
404
+
405
+ def status_dict() -> dict:
406
+ return {
407
+ "submissions": len(board.subs),
408
+ "queued_or_grading": sum(s["status"] != "graded" for s in board.subs.values()),
409
+ "best": board.best(),
410
+ }
411
+
412
+
413
+ def current_result(sid: int) -> dict:
414
+ return board.public(sid)
415
+
416
+
417
+ if ROLE == "val":
418
+
419
+ @mcp.tool
420
+ async def submit(note: str = "") -> dict:
421
+ """Submit the current deliverable for grading.
422
+
423
+ Snapshots the deliverable directory right now (later edits do not affect this
424
+ submission) and starts grading it on the public validation split. Returns at
425
+ once with a submission id. One submission is graded at a time: check `result`
426
+ and submit again once the previous submission has its score. `note` is a short
427
+ description of what changed.
428
+ """
429
+ return with_time(await asyncio.to_thread(do_submit, note))
430
+
431
+ @mcp.tool
432
+ async def result(id: int) -> dict:
433
+ """The current state of a submission: queued, grading, or graded with its
434
+ validation score and grader output. Returns immediately."""
435
+ if id not in board.subs:
436
+ return {"error": f"unknown submission id {id}"}
437
+ return with_time(current_result(id))
438
+
439
+ @mcp.tool
440
+ async def status() -> dict:
441
+ """Submission count, whether one is being graded, the best validation score,
442
+ and the time budget and time remaining."""
443
+ return with_time(status_dict())
444
+
445
+ @mcp.custom_route("/submit", methods=["POST"])
446
+ async def http_submit(request: Request) -> Response:
447
+ note = request.query_params.get("note", "")
448
+ return JSONResponse(with_time(await asyncio.to_thread(do_submit, note)))
449
+
450
+ @mcp.custom_route("/result/{sid}", methods=["GET"])
451
+ async def http_result(request: Request) -> Response:
452
+ sid = int(request.path_params["sid"])
453
+ if sid not in board.subs:
454
+ return JSONResponse({"error": f"unknown submission id {sid}"}, status_code=404)
455
+ return JSONResponse(with_time(current_result(sid)))
456
+
457
+ @mcp.custom_route("/status", methods=["GET"])
458
+ async def http_status(request: Request) -> Response:
459
+ return JSONResponse(with_time(status_dict()))
460
+
461
+ @mcp.custom_route("/final", methods=["POST"])
462
+ async def http_final(request: Request) -> Response:
463
+ if not _authorized(request):
464
+ return JSONResponse({"error": "forbidden"}, status_code=403)
465
+ # Collect hook, after the agent has stopped.
466
+ return JSONResponse(await asyncio.to_thread(final_submit))
467
+
468
+ @mcp.custom_route("/drain", methods=["GET"])
469
+ async def http_drain(request: Request) -> Response:
470
+ if not _authorized(request):
471
+ return JSONResponse({"error": "forbidden"}, status_code=403)
472
+ # Used by the verifier collect hook after the agent has stopped.
473
+ pending = sum(s["status"] != "graded" for s in board.subs.values())
474
+ return JSONResponse({"val_pending": pending, "test_pending": board.test_pending})
475
+
476
+
477
+ def _gpus() -> list[str]:
478
+ try:
479
+ out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20)
480
+ return [l for l in out.stdout.splitlines() if l.strip()]
481
+ except Exception:
482
+ return []
483
+
484
+
485
+ @mcp.custom_route("/health", methods=["GET"])
486
+ async def health(request: Request) -> Response:
487
+ return JSONResponse({"ok": True, "role": ROLE, "gpus": await asyncio.to_thread(_gpus)})
488
+
489
+
490
+ def _setup_token() -> None:
491
+ global TOKEN
492
+ if ROLE == "test":
493
+ TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
494
+ os.chmod(TOKEN_FILE.parent, 0o700)
495
+ TOKEN = secrets.token_hex(32)
496
+ TOKEN_FILE.write_text(TOKEN)
497
+ os.chmod(TOKEN_FILE, 0o600)
498
+ else:
499
+ for _ in range(300): # the test grader is healthy before this one starts
500
+ if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip():
501
+ break
502
+ time.sleep(1)
503
+ TOKEN = TOKEN_FILE.read_text().strip()
504
+ if not TOKEN:
505
+ raise SystemExit("ARE: empty internal token; refusing to start")
506
+
507
+
508
+ def main() -> None:
509
+ global NET_ISOLATED
510
+ NET_ISOLATED = _net_isolation_available()
511
+ if not NET_ISOLATED:
512
+ # Graded code must never have a network path (for example back through /submit).
513
+ raise SystemExit("ARE grader: cannot run grades without network access "
514
+ "(needs `unshare -n`, i.e. CAP_SYS_ADMIN); refusing to start")
515
+ STATE.mkdir(parents=True, exist_ok=True)
516
+ _BASELINE.update(_all_paths())
517
+ _setup_token()
518
+ STATE.mkdir(parents=True, exist_ok=True)
519
+ os.chmod(STATE, 0o700)
520
+ (STATE / "snapshots").mkdir(exist_ok=True)
521
+ if ROLE == "val":
522
+ # The deliverable volume starts empty and root-owned; hand it to the agent user.
523
+ SUBMISSION_ROOT.mkdir(parents=True, exist_ok=True)
524
+ os.chmod(SUBMISSION_ROOT, 0o700)
525
+ for path in ARTIFACT_PATHS:
526
+ src = SUBMISSION_ROOT / path.lstrip("/")
527
+ src.mkdir(parents=True, exist_ok=True)
528
+ os.chown(src, AGENT_UID, AGENT_UID)
529
+ (STATE / "meta.json").write_text(json.dumps(
530
+ {"t0_wall": T0, "budget_seconds": BUDGET_SEC, "artifact_paths": ARTIFACT_PATHS}
531
+ ))
532
+ threading.Thread(target=grade_worker, daemon=True).start()
533
+ mcp.run(transport="http", host="0.0.0.0", port=PORT, show_banner=False,
534
+ uvicorn_config={"timeout_keep_alive": 86400})
535
+
536
+
537
+ if __name__ == "__main__":
538
+ main()
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/compute_reward.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ from pathlib import Path
4
+
5
+ REWARD_PATH = Path("/logs/verifier/reward.txt")
6
+
7
+ try:
8
+ value = float(json.loads(Path("/logs/verifier/metric.json").read_text())["reward"])
9
+ if not math.isfinite(value):
10
+ raise ValueError("non-finite reward")
11
+ reward = f"{min(1.0, max(0.0, value)):.12g}"
12
+ REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
13
+ REWARD_PATH.write_text(reward + "\n")
14
+ print(f"reward={reward}")
15
+ except Exception as exc:
16
+ REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
17
+ REWARD_PATH.write_text("0\n")
18
+ print(f"reward=0 (fallback: {exc})")
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/grader_core.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
9
+
10
+ import sopcc
11
+
12
+ HIDDEN = Path(__file__).resolve().parent / "hidden_data"
13
+ SPLITS = ("final", "intermediate")
14
+
15
+ ANCHORS = {
16
+
17
+ "final": (4.212162974044415, 5.403678393388951),
18
+ "intermediate": (4.90108511497506, 5.935456731233547),
19
+ }
20
+
21
+
22
+ def load_panel(split: str):
23
+ """The sealed panel for `split`: instances plus their pre-drawn cost noise."""
24
+ if split not in SPLITS:
25
+ raise ValueError(f"unknown split {split!r}")
26
+ with np.load(HIDDEN / split / "panel.npz") as data:
27
+ coords, rewards, noise, draw = (data["coords"], data["rewards"],
28
+ data["noise"], data["draw"])
29
+ return [
30
+ {"draw": int(draw[i]), "index": i,
31
+ "instance": sopcc.instance_from_arrays(coords[i], rewards[i]),
32
+ "noise": noise[i]}
33
+ for i in range(coords.shape[0])
34
+ ]
35
+
36
+
37
+ def graded_reward(metric: float, split: str) -> float:
38
+ """Map the raw metric to a reward in [0, 1): 0 at m0, 0.5 at m_ref, no cutoff above."""
39
+ m0, m_ref = ANCHORS[split]
40
+ x_ref = m_ref - m0
41
+ if not x_ref > 0:
42
+ raise AssertionError("malformed task: the reference does not beat the trivial baseline")
43
+ if not np.isfinite(metric):
44
+ return 0.0
45
+ u = max(0.0, float(metric) - m0) / x_ref
46
+ return u / (1.0 + u)
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/final/panel.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b034f0a99b9a9f72228a791c6216acbf68dc22dc33fc3f6d4ededd34f0330a7f
3
+ size 605757
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/hidden_data/intermediate/panel.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c457412f004826b4404e915b5b81e17400cef99f395d5bb76241ea770f2aaeb4
3
+ size 605708
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/intermediate.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+
4
+ set -u
5
+
6
+
7
+
8
+ reward_floor() {
9
+ if [ ! -s /logs/verifier/reward.txt ]; then
10
+ mkdir -p /logs/verifier
11
+ printf '0\n' > /logs/verifier/reward.txt
12
+ fi
13
+ }
14
+ trap reward_floor EXIT
15
+
16
+ mkdir -p /logs/verifier
17
+ chown root:root /logs/verifier 2>/dev/null || true
18
+ chmod 755 /logs/verifier 2>/dev/null || true
19
+ rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
20
+
21
+ chmod -R go-rwx /tests
22
+
23
+ cd /tests
24
+ export GRADE_SPLIT=intermediate
25
+ /usr/local/bin/python3 -m pytest \
26
+ --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
27
+ /usr/local/bin/python3 /tests/compute_reward.py
28
+
29
+ exit 0
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/policy_worker.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ import json
5
+ import os
6
+ import resource
7
+ import sys
8
+ import traceback
9
+
10
+
11
+ def _fail(reply, stage, exc):
12
+ reply({"ok": False, "stage": stage, "error": f"{type(exc).__name__}: {exc}",
13
+ "traceback": traceback.format_exc(limit=6)[-1200:]})
14
+
15
+
16
+ def _apply_limits(limits: dict) -> None:
17
+ """Cap this process before any candidate code is imported.
18
+
19
+ Set here rather than by the caller so there is no window between exec and the cap, and
20
+ the hard limit is set too: candidate code can lower these but never raise them.
21
+ """
22
+ cpu = int(limits["cpu_seconds"])
23
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu + 1, cpu + 3))
24
+ for name, key in (("RLIMIT_AS", "address_space_bytes"),
25
+ ("RLIMIT_FSIZE", "file_size_bytes"),
26
+ ("RLIMIT_NOFILE", "open_files")):
27
+ value = int(limits[key])
28
+ soft, hard = resource.getrlimit(getattr(resource, name))
29
+ if hard != resource.RLIM_INFINITY:
30
+ value = min(value, hard)
31
+ resource.setrlimit(getattr(resource, name), (value, value))
32
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
33
+
34
+
35
+ def main() -> int:
36
+ solution_dir = os.path.abspath(sys.argv[1])
37
+ entry = os.path.join(solution_dir, "policy.py")
38
+ _apply_limits(json.loads(sys.argv[2]))
39
+
40
+ reply_fd = os.dup(1)
41
+ os.dup2(2, 1)
42
+ sys.stdout = sys.stderr
43
+ channel = os.fdopen(reply_fd, "w", buffering=1)
44
+
45
+ def reply(obj):
46
+ channel.write(json.dumps(obj) + "\n")
47
+ channel.flush()
48
+
49
+ import numpy as np
50
+ try:
51
+ import torch
52
+ torch.set_num_threads(1)
53
+ except ImportError:
54
+ pass
55
+
56
+ policy = None
57
+ for raw in sys.stdin:
58
+ raw = raw.strip()
59
+ if not raw:
60
+ continue
61
+ msg = json.loads(raw)
62
+ cmd = msg.get("cmd")
63
+
64
+ if cmd == "init":
65
+ if not os.path.isfile(entry):
66
+ reply({"ok": False, "stage": "import", "error": f"no entry point at {entry}"})
67
+ return 0
68
+ try:
69
+ if solution_dir not in sys.path:
70
+ sys.path.insert(0, solution_dir)
71
+ spec = importlib.util.spec_from_file_location("candidate_policy", entry)
72
+ module = importlib.util.module_from_spec(spec)
73
+ sys.modules["candidate_policy"] = module
74
+ spec.loader.exec_module(module)
75
+ policy_cls = getattr(module, "Policy")
76
+ except Exception as exc:
77
+ _fail(reply, "import", exc)
78
+ return 0
79
+ try:
80
+ policy = policy_cls(int(msg["seed"]))
81
+ except Exception as exc:
82
+ _fail(reply, "construct", exc)
83
+ return 0
84
+ try:
85
+ instance = {
86
+ "coords": np.asarray(msg["instance"]["coords"], dtype=np.float64),
87
+ "rewards": np.asarray(msg["instance"]["rewards"], dtype=np.float64),
88
+ "dist": np.asarray(msg["instance"]["dist"], dtype=np.float64),
89
+ "start": int(msg["instance"]["start"]),
90
+ "goal": int(msg["instance"]["goal"]),
91
+ "budget": float(msg["instance"]["budget"]),
92
+ "p_fail": float(msg["instance"]["p_fail"]),
93
+ "cost_model": str(msg["instance"]["cost_model"]),
94
+ }
95
+ policy.prepare(instance)
96
+ except Exception as exc:
97
+ _fail(reply, "prepare", exc)
98
+ return 0
99
+ reply({"ok": True})
100
+
101
+ elif cmd == "act":
102
+ obs = msg["obs"]
103
+ obs = {
104
+ "current": int(obs["current"]),
105
+ "visited": np.asarray(obs["visited"], dtype=bool),
106
+ "remaining_budget": float(obs["remaining_budget"]),
107
+ "collected_reward": float(obs["collected_reward"]),
108
+ "step": int(obs["step"]),
109
+ }
110
+ try:
111
+ action = policy.act(obs)
112
+ except Exception as exc:
113
+ reply({"ok": False, "stage": "act",
114
+ "error": f"{type(exc).__name__}: {exc}"})
115
+ continue
116
+ if isinstance(action, bool) or not isinstance(action, (int, np.integer)):
117
+ reply({"ok": True, "action": None,
118
+ "kind": type(action).__name__})
119
+ else:
120
+ reply({"ok": True, "action": int(action)})
121
+
122
+ elif cmd == "bye":
123
+ return 0
124
+
125
+ else:
126
+ reply({"ok": False, "stage": "protocol", "error": f"unknown command {cmd!r}"})
127
+ return 0
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ sys.exit(main())
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements-verifier.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ pytest==8.3.5
2
+ pytest-json-ctrf==0.3.5
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ --index-url https://download.pytorch.org/whl/cpu
2
+ --extra-index-url https://pypi.org/simple
3
+ numpy==2.5.2
4
+ scipy==1.18.0
5
+ torch==2.13.0+cpu
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/runner.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ctypes
4
+ import json
5
+ import os
6
+ import resource
7
+ import select
8
+ import shutil
9
+ import signal
10
+ import stat
11
+ import sys
12
+ import tempfile
13
+ import threading
14
+ import time
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from dataclasses import dataclass, field
17
+
18
+ import numpy as np
19
+
20
+
21
+
22
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
+
24
+ import sopcc
25
+
26
+ CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
27
+ CPU_POLL_INTERVAL = 2.0
28
+ PR_SET_CHILD_SUBREAPER = 36
29
+
30
+ _LOCK = threading.Lock()
31
+ _WORKERS: set[int] = set()
32
+ _ESCAPED_CPU = 0.0
33
+
34
+
35
+ @dataclass
36
+ class Sandbox:
37
+ """Resource and privilege policy applied to every candidate process."""
38
+
39
+ cpu_seconds: float = 75.0
40
+ timeout: float = 150.0
41
+ address_space_bytes: int = 6 * 1024 ** 3
42
+ file_size_bytes: int = 64 * 1024 ** 2
43
+ open_files: int = 256
44
+ run_as_uid: int | None = None
45
+ run_as_gid: int | None = None
46
+ new_session: bool = True
47
+ env: dict = field(default_factory=dict)
48
+
49
+
50
+ class WorkerGone(Exception):
51
+ """The candidate process died, hung, or stopped speaking the protocol."""
52
+
53
+
54
+ class _LineChannel:
55
+ """Deadline-bounded line reads straight off a pipe fd."""
56
+
57
+ def __init__(self, fd: int):
58
+ self.fd = fd
59
+ self.buf = b""
60
+
61
+ def readline(self, deadline: float) -> bytes:
62
+ while b"\n" not in self.buf:
63
+ left = deadline - time.monotonic()
64
+ if left <= 0:
65
+ raise WorkerGone("wall-clock budget exhausted")
66
+ ready, _, _ = select.select([self.fd], [], [], min(left, 0.5))
67
+ if not ready:
68
+ continue
69
+ chunk = os.read(self.fd, 1 << 16)
70
+ if not chunk:
71
+ raise WorkerGone("candidate process closed the channel")
72
+ self.buf += chunk
73
+ line, _, self.buf = self.buf.partition(b"\n")
74
+ return line
75
+
76
+
77
+ def _write_line(fd: int, payload: bytes, deadline: float) -> None:
78
+ view = memoryview(payload + b"\n")
79
+ while view:
80
+ left = deadline - time.monotonic()
81
+ if left <= 0:
82
+ raise WorkerGone("wall-clock budget exhausted")
83
+ _, ready, _ = select.select([], [fd], [], min(left, 0.5))
84
+ if not ready:
85
+ continue
86
+ try:
87
+ written = os.write(fd, view)
88
+ except (BrokenPipeError, OSError) as exc:
89
+ raise WorkerGone(f"candidate process is not reading: {exc}") from exc
90
+ view = view[written:]
91
+
92
+
93
+ def _become_subreaper() -> None:
94
+ """Adopt orphaned descendants of every candidate instead of leaving them to init.
95
+
96
+ A candidate that forks and lets the parent exit would otherwise hand the orphan to pid 1,
97
+ outside any tree walked below. With this set, such an orphan is re-parented to this process,
98
+ where `_tree` recognises it (a child of ours that is not a worker we started) and it is
99
+ charged, killed and reaped along with the candidate's own tree.
100
+ """
101
+ try:
102
+ ctypes.CDLL(None, use_errno=True).prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0)
103
+ except (OSError, AttributeError):
104
+ pass
105
+
106
+
107
+ def _scan() -> dict[int, tuple[int, float]]:
108
+ """pid -> (ppid, CPU seconds) for every live process.
109
+
110
+ The CPU figure is utime + stime + cutime + cstime: the process's own threads plus every
111
+ child it has already reaped, so a helper that burns CPU and exits between two scans is
112
+ still charged to whoever reaped it.
113
+ """
114
+ procs: dict[int, tuple[int, float]] = {}
115
+ try:
116
+ names = os.listdir("/proc")
117
+ except OSError:
118
+ return procs
119
+ for name in names:
120
+ if not name.isdigit():
121
+ continue
122
+ try:
123
+ with open(f"/proc/{name}/stat", "rb") as fh:
124
+ raw = fh.read()
125
+ except OSError:
126
+ continue
127
+ cut = raw.rfind(b")")
128
+ if cut < 0:
129
+ continue
130
+ fields = raw[cut + 2:].split()
131
+ if len(fields) < 15:
132
+ continue
133
+ try:
134
+ procs[int(name)] = (int(fields[1]),
135
+ sum(int(f) for f in fields[11:15]) / CLOCK_TICKS)
136
+ except ValueError:
137
+ continue
138
+ return procs
139
+
140
+
141
+ def _tree(procs: dict[int, tuple[int, float]], root: int) -> tuple[set[int], set[int]]:
142
+ """(`root` plus its live descendants, adopted orphans plus theirs), both by parent pid.
143
+
144
+ Parentage is what setsid(2) cannot change, which is why the session id is not used. An
145
+ adopted orphan (a child of this process that is not a worker it started) cannot be
146
+ attributed to one instance, so it is charged to every instance: the candidate is the same
147
+ code in each of them. Call with `_LOCK` held.
148
+ """
149
+ children: dict[int, list[int]] = {}
150
+ for pid, (ppid, _) in procs.items():
151
+ children.setdefault(ppid, []).append(pid)
152
+
153
+ def walk(roots) -> set[int]:
154
+ members: set[int] = set()
155
+ stack = list(roots)
156
+ while stack:
157
+ pid = stack.pop()
158
+ if pid in members:
159
+ continue
160
+ members.add(pid)
161
+ stack.extend(children.get(pid, []))
162
+ return members
163
+
164
+ own = walk([root])
165
+ orphans = walk(pid for pid in children.get(os.getpid(), []) if pid not in _WORKERS) - own
166
+ return own, orphans
167
+
168
+
169
+ def _charge(procs: dict[int, tuple[int, float]], own: set[int], orphans: set[int]) -> float:
170
+ return sum(procs[pid][1] for pid in own | orphans if pid in procs) + _ESCAPED_CPU
171
+
172
+
173
+ def _tree_cpu(root: int) -> float:
174
+ """CPU seconds the instance rooted at `root` is charged for right now."""
175
+ with _LOCK:
176
+ procs = _scan()
177
+ return _charge(procs, *_tree(procs, root))
178
+
179
+
180
+ def _end_instance(proc) -> float:
181
+ """Kill the instance's tree, reap what this process adopted, and return the final charge."""
182
+ global _ESCAPED_CPU
183
+ with _LOCK:
184
+ procs = _scan()
185
+ own, orphans = _tree(procs, proc.pid)
186
+ charge = _charge(procs, own, orphans)
187
+ try:
188
+ os.killpg(proc.pid, signal.SIGKILL)
189
+ except (ProcessLookupError, PermissionError, OSError):
190
+ pass
191
+ for _ in range(2):
192
+ for pid in set().union(*_tree(_scan(), proc.pid)):
193
+ try:
194
+ os.kill(pid, signal.SIGKILL)
195
+ except (ProcessLookupError, PermissionError, OSError):
196
+ pass
197
+ try:
198
+ proc.stdin.close()
199
+ proc.stdout.close()
200
+ except OSError:
201
+ pass
202
+ try:
203
+ proc.wait(timeout=10)
204
+ except Exception:
205
+ pass
206
+ _WORKERS.discard(proc.pid)
207
+
208
+
209
+
210
+ deadline = time.monotonic() + 5.0
211
+ while True:
212
+ pending = 0
213
+ for pid, (ppid, cpu) in _scan().items():
214
+ if ppid != os.getpid() or pid in _WORKERS:
215
+ continue
216
+ try:
217
+ reaped, _ = os.waitpid(pid, os.WNOHANG)
218
+ except ChildProcessError:
219
+ continue
220
+ if not reaped:
221
+ pending += 1
222
+ elif pid not in own:
223
+ _ESCAPED_CPU += cpu
224
+ if not pending or time.monotonic() >= deadline:
225
+ break
226
+ time.sleep(0.05)
227
+ return charge
228
+
229
+
230
+ def validate_solution_dir(path: str, max_bytes: int) -> tuple[bool, str, int]:
231
+ """Reject a deliverable tree that is missing, oversized, or contains links.
232
+
233
+ A symlink or a hard link inside a tree the harness copies is an attempt to make a
234
+ privileged copy materialise a file from somewhere else, so it is refused outright
235
+ rather than followed.
236
+ """
237
+ if not os.path.isdir(path):
238
+ return False, f"no deliverable directory at {path}", 0
239
+ if os.path.islink(path):
240
+ return False, "deliverable directory is a symlink", 0
241
+ total = 0
242
+ for root, dirs, files in os.walk(path, followlinks=False):
243
+ for name in dirs + files:
244
+ full = os.path.join(root, name)
245
+ info = os.lstat(full)
246
+ if stat.S_ISLNK(info.st_mode):
247
+ return False, f"symlink in deliverable: {os.path.relpath(full, path)}", total
248
+ if stat.S_ISREG(info.st_mode):
249
+ if info.st_nlink > 1:
250
+ return False, f"hard link in deliverable: {os.path.relpath(full, path)}", total
251
+ total += info.st_size
252
+ elif not stat.S_ISDIR(info.st_mode):
253
+ return False, f"non-regular file in deliverable: {os.path.relpath(full, path)}", total
254
+ if total > max_bytes:
255
+ return False, f"deliverable exceeds {max_bytes} bytes", total
256
+ if not os.path.isfile(os.path.join(path, "policy.py")):
257
+ return False, f"no entry point at {os.path.join(path, 'policy.py')}", total
258
+ return True, "ok", total
259
+
260
+
261
+ def stage_candidate(src: str, dst: str, own_uid: int | None = None) -> str:
262
+ """Copy a validated deliverable to a location the candidate cannot rewrite mid-grade.
263
+
264
+ `src` is treated as hostile and must already have passed `validate_solution_dir`; the
265
+ copy keeps symlinks as symlinks rather than following them. The caller is responsible
266
+ for `dst`'s parent being traversable by the uid the candidate runs as.
267
+ """
268
+ if os.path.exists(dst):
269
+ shutil.rmtree(dst)
270
+ shutil.copytree(src, dst, symlinks=True)
271
+ for root, dirs, files in os.walk(dst):
272
+ for name in dirs:
273
+ os.chmod(os.path.join(root, name), 0o755)
274
+ for name in files:
275
+ os.chmod(os.path.join(root, name), 0o644)
276
+ os.chmod(dst, 0o755)
277
+ if own_uid is not None:
278
+ for root, dirs, files in os.walk(dst):
279
+ for name in dirs + files:
280
+ os.chown(os.path.join(root, name), own_uid, own_uid)
281
+ os.chown(dst, own_uid, own_uid)
282
+ return dst
283
+
284
+
285
+ def _instance_payload(instance: dict) -> dict:
286
+ return {
287
+ "coords": instance["coords"].tolist(),
288
+ "rewards": instance["rewards"].tolist(),
289
+ "dist": instance["dist"].tolist(),
290
+ "start": int(instance["start"]),
291
+ "goal": int(instance["goal"]),
292
+ "budget": float(instance["budget"]),
293
+ "p_fail": float(instance["p_fail"]),
294
+ "cost_model": str(instance["cost_model"]),
295
+ }
296
+
297
+
298
+ def run_instance(
299
+ sandbox: Sandbox,
300
+ candidate_dir: str,
301
+ worker_path: str,
302
+ python_exe: str,
303
+ instance: dict,
304
+ noise: np.ndarray,
305
+ seed: int,
306
+ episodes: int = sopcc.EPISODES_PER_INSTANCE,
307
+ ) -> dict:
308
+ """Grade one instance: `episodes` episodes of one candidate process."""
309
+ import subprocess
310
+
311
+ limits = {
312
+ "cpu_seconds": float(sandbox.cpu_seconds),
313
+ "address_space_bytes": int(sandbox.address_space_bytes),
314
+ "file_size_bytes": int(sandbox.file_size_bytes),
315
+ "open_files": int(sandbox.open_files),
316
+ }
317
+ cmd = [python_exe, "-I", "-B", worker_path, candidate_dir, json.dumps(limits)]
318
+ privilege = {}
319
+ if sandbox.run_as_uid is not None:
320
+ privilege = {"user": int(sandbox.run_as_uid),
321
+ "group": int(sandbox.run_as_gid if sandbox.run_as_gid is not None
322
+ else sandbox.run_as_uid),
323
+ "extra_groups": []}
324
+
325
+
326
+
327
+ scratch = tempfile.mkdtemp(prefix="sopcc-run-")
328
+ if sandbox.run_as_uid is not None:
329
+ os.chown(scratch, int(sandbox.run_as_uid),
330
+ int(sandbox.run_as_gid if sandbox.run_as_gid is not None
331
+ else sandbox.run_as_uid))
332
+ os.chmod(scratch, 0o700)
333
+ env = {
334
+ "PATH": "/usr/local/bin:/usr/local/sbin:/usr/bin:/bin",
335
+ "HOME": scratch,
336
+ "TMPDIR": scratch,
337
+ "PYTHONHASHSEED": "0",
338
+ "PYTHONDONTWRITEBYTECODE": "1",
339
+ "OMP_NUM_THREADS": "1",
340
+ "MKL_NUM_THREADS": "1",
341
+ "OPENBLAS_NUM_THREADS": "1",
342
+ "NUMEXPR_NUM_THREADS": "1",
343
+ }
344
+ env.update(sandbox.env)
345
+
346
+ errlog = open(os.path.join(scratch, "stderr.log"), "w+b")
347
+ deadline = time.monotonic() + float(sandbox.timeout)
348
+ report = {
349
+ "seed": int(seed),
350
+ "episodes": [],
351
+ "cpu_seconds": 0.0,
352
+ "wall_seconds": 0.0,
353
+ "abort": None,
354
+ "stderr_tail": "",
355
+ }
356
+ started = time.monotonic()
357
+ proc = None
358
+ _become_subreaper()
359
+ try:
360
+ with _LOCK:
361
+ proc = subprocess.Popen(
362
+ cmd,
363
+ stdin=subprocess.PIPE,
364
+ stdout=subprocess.PIPE,
365
+ stderr=errlog,
366
+ cwd="/",
367
+ env=env,
368
+ close_fds=True,
369
+ start_new_session=bool(sandbox.new_session),
370
+ **privilege,
371
+ )
372
+ _WORKERS.add(proc.pid)
373
+ try:
374
+ resource.prlimit(proc.pid, resource.RLIMIT_CPU,
375
+ (int(sandbox.cpu_seconds) + 1, int(sandbox.cpu_seconds) + 3))
376
+ except (PermissionError, ProcessLookupError, OSError):
377
+ pass
378
+ reader = _LineChannel(proc.stdout.fileno())
379
+ writer = proc.stdin.fileno()
380
+
381
+ next_poll = [time.monotonic()]
382
+
383
+ def _exchange(payload: dict) -> dict:
384
+ _write_line(writer, json.dumps(payload).encode(), deadline)
385
+ now = time.monotonic()
386
+ if now >= next_poll[0]:
387
+ next_poll[0] = now + CPU_POLL_INTERVAL
388
+ cpu = _tree_cpu(proc.pid)
389
+ report["cpu_seconds"] = max(report["cpu_seconds"], cpu)
390
+ if cpu > sandbox.cpu_seconds:
391
+ raise WorkerGone(f"cpu budget exhausted ({cpu:.1f}s)")
392
+ line = reader.readline(deadline)
393
+ try:
394
+ return json.loads(line)
395
+ except (ValueError, UnicodeDecodeError) as exc:
396
+ raise WorkerGone(f"unparseable reply: {exc}") from exc
397
+
398
+ ack = _exchange({"cmd": "init", "seed": int(seed),
399
+ "instance": _instance_payload(instance)})
400
+ if not ack.get("ok"):
401
+ report["abort"] = f"{ack.get('stage', 'init')}: {ack.get('error', 'refused')}"
402
+ raise WorkerGone(report["abort"])
403
+
404
+ for episode in range(int(episodes)):
405
+ def choose(obs):
406
+ message = {
407
+ "cmd": "act",
408
+ "obs": {
409
+ "current": int(obs["current"]),
410
+ "visited": [bool(v) for v in obs["visited"]],
411
+ "remaining_budget": float(obs["remaining_budget"]),
412
+ "collected_reward": float(obs["collected_reward"]),
413
+ "step": int(obs["step"]),
414
+ },
415
+ }
416
+ answer = _exchange(message)
417
+ if not answer.get("ok"):
418
+ raise sopcc.InvalidAction(
419
+ f"policy raised {answer.get('error', 'an exception')}")
420
+ action = answer.get("action")
421
+ if action is None:
422
+ raise sopcc.InvalidAction(
423
+ f"action is {answer.get('kind', 'None')}, not an int")
424
+ return int(action)
425
+
426
+ outcome = sopcc.run_episode(instance, noise[episode], choose)
427
+ report["episodes"].append(outcome)
428
+ except WorkerGone as exc:
429
+ report["abort"] = report["abort"] or str(exc)
430
+ except Exception as exc:
431
+ report["abort"] = f"{type(exc).__name__}: {exc}"
432
+ finally:
433
+ if proc is not None:
434
+ report["cpu_seconds"] = max(report["cpu_seconds"], _end_instance(proc))
435
+ report["wall_seconds"] = time.monotonic() - started
436
+ try:
437
+ errlog.seek(0)
438
+ report["stderr_tail"] = errlog.read(4096).decode("utf-8", "replace")
439
+ except OSError:
440
+ pass
441
+ errlog.close()
442
+ shutil.rmtree(scratch, ignore_errors=True)
443
+
444
+ while len(report["episodes"]) < int(episodes):
445
+ report["episodes"].append(
446
+ {"delivered": 0.0, "failed": True,
447
+ "reason": f"aborted: {report['abort'] or 'unknown'}", "visits": 0,
448
+ "traversals": 0})
449
+ return report
450
+
451
+
452
+ def grade_panel(
453
+ panel,
454
+ sandbox: Sandbox,
455
+ candidate_dir: str,
456
+ worker_path: str,
457
+ python_exe: str | None = None,
458
+ workers: int = 8,
459
+ seed_base: int = 1000,
460
+ episodes: int = sopcc.EPISODES_PER_INSTANCE,
461
+ retry_budget: int = 4,
462
+ ) -> dict:
463
+ """Grade a whole panel, at most `workers` instances at a time, and aggregate the metric."""
464
+ python_exe = python_exe or sys.executable
465
+ reports: list[dict | None] = [None] * len(panel)
466
+ with ThreadPoolExecutor(max_workers=max(1, min(workers, len(panel)))) as pool:
467
+ futures = {
468
+ pool.submit(
469
+ run_instance, sandbox, candidate_dir, worker_path, python_exe,
470
+ panel[i]["instance"], panel[i]["noise"], seed_base + i, episodes,
471
+ ): i
472
+ for i in range(len(panel))
473
+ }
474
+ for future, i in futures.items():
475
+ reports[i] = future.result()
476
+
477
+
478
+
479
+
480
+ retries = []
481
+ for i, report in enumerate(reports):
482
+ if retry_budget <= 0:
483
+ break
484
+ abort = report["abort"] or ""
485
+ infra = ("closed the channel" in abort) or ("is not reading" in abort)
486
+ if not infra or report["wall_seconds"] > 0.25 * sandbox.timeout:
487
+ continue
488
+ retry_budget -= 1
489
+ retries.append({"instance": i, "first_abort": abort})
490
+ reports[i] = run_instance(
491
+ sandbox, candidate_dir, worker_path, python_exe,
492
+ panel[i]["instance"], panel[i]["noise"], seed_base + i, episodes)
493
+
494
+ delivered, failed, draws = [], [], []
495
+ for i, report in enumerate(reports):
496
+ for outcome in report["episodes"]:
497
+ delivered.append(outcome["delivered"])
498
+ failed.append(outcome["failed"])
499
+ draws.append(panel[i].get("draw", 0))
500
+ summary = sopcc.panel_metric(delivered, failed)
501
+ delivered_arr = np.asarray(delivered, dtype=np.float64)
502
+ failed_arr = np.asarray(failed, dtype=bool)
503
+ draw_arr = np.asarray(draws, dtype=np.int64)
504
+ per_draw = {}
505
+ for draw in sorted(set(draws)):
506
+ mask = draw_arr == draw
507
+ per_draw[int(draw)] = sopcc.panel_metric(delivered_arr[mask], failed_arr[mask])
508
+ summary["per_draw"] = per_draw
509
+ summary["draw_metric_mean"] = float(
510
+ np.mean([per_draw[d]["metric"] for d in sorted(per_draw)])) if per_draw else 0.0
511
+ summary["instances"] = len(panel)
512
+ summary["retried_instances"] = retries
513
+ summary["aborted_instances"] = sum(1 for r in reports if r["abort"])
514
+ summary["max_cpu_seconds"] = max((r["cpu_seconds"] for r in reports), default=0.0)
515
+ summary["max_wall_seconds"] = max((r["wall_seconds"] for r in reports), default=0.0)
516
+ summary["reports"] = reports
517
+ return summary
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/sopcc.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+
6
+ N_VERTICES = 40
7
+ START = 0
8
+ GOAL = 1
9
+ BUDGET = 2.0
10
+ P_FAIL = 0.1
11
+ COST_MODEL = "exponential_mean_equals_euclidean"
12
+
13
+
14
+ EPISODES_PER_INSTANCE = 32
15
+ MAX_TRAVERSALS = 48
16
+
17
+
18
+ FAILURE_ALLOWANCE = 0.10
19
+ PENALTY_SLOPE = 10.0
20
+
21
+
22
+ DEV_ENTROPY = 20240917
23
+ DEV_DRAWS = 4
24
+ DEV_INSTANCES_PER_DRAW = 50
25
+
26
+
27
+ def instance_seed(entropy: int, index: int) -> np.random.SeedSequence:
28
+ """Seed sequence for instance `index` of the family rooted at `entropy`."""
29
+ return np.random.SeedSequence(entropy=int(entropy), spawn_key=(int(index), 0))
30
+
31
+
32
+ def noise_seed(entropy: int, index: int, variant: int = 0) -> np.random.SeedSequence:
33
+ """Seed sequence for the pre-drawn cost noise of instance `index`.
34
+
35
+ `variant` draws an independent noise realisation for the same instance, which is how the
36
+ build measures the metric's own sampling noise.
37
+ """
38
+ key = (int(index), 1) if int(variant) == 0 else (int(index), 1, int(variant))
39
+ return np.random.SeedSequence(entropy=int(entropy), spawn_key=key)
40
+
41
+
42
+ def euclidean_matrix(coords: np.ndarray) -> np.ndarray:
43
+ diff = coords[:, None, :] - coords[None, :, :]
44
+ dist = np.sqrt((diff * diff).sum(axis=-1))
45
+ np.fill_diagonal(dist, 0.0)
46
+ return dist
47
+
48
+
49
+ def make_instance(seed_sequence: np.random.SeedSequence) -> dict:
50
+ """One SOPCC instance: complete graph, U[0,1]^2 coordinates, U[0,1] vertex rewards.
51
+
52
+ The start and goal vertex rewards are forced to 0.0, so no reward is collected for
53
+ free by starting or finishing.
54
+ """
55
+ rng = np.random.Generator(np.random.PCG64(seed_sequence))
56
+ coords = rng.random((N_VERTICES, 2))
57
+ rewards = rng.random(N_VERTICES)
58
+ rewards[START] = 0.0
59
+ rewards[GOAL] = 0.0
60
+ return instance_from_arrays(coords, rewards)
61
+
62
+
63
+ def instance_from_arrays(coords: np.ndarray, rewards: np.ndarray) -> dict:
64
+ coords = np.ascontiguousarray(coords, dtype=np.float64)
65
+ rewards = np.ascontiguousarray(rewards, dtype=np.float64)
66
+ return {
67
+ "coords": coords,
68
+ "rewards": rewards,
69
+ "dist": euclidean_matrix(coords),
70
+ "start": START,
71
+ "goal": GOAL,
72
+ "budget": BUDGET,
73
+ "p_fail": P_FAIL,
74
+ "cost_model": COST_MODEL,
75
+ }
76
+
77
+
78
+ def make_noise(
79
+ seed_sequence: np.random.SeedSequence,
80
+ episodes: int = EPISODES_PER_INSTANCE,
81
+ traversals: int = MAX_TRAVERSALS,
82
+ ) -> np.ndarray:
83
+ """Pre-drawn unit-Exponential cost multipliers, one row of `traversals` per episode.
84
+
85
+ The realised cost of the k-th traversal of an episode is `dist[u, v] * noise[k]`, so
86
+ every traversal costs an Exponential variate with mean equal to the Euclidean edge
87
+ length, and two submissions see the identical random stream.
88
+ """
89
+ rng = np.random.Generator(np.random.PCG64(seed_sequence))
90
+ return rng.exponential(1.0, size=(int(episodes), int(traversals)))
91
+
92
+
93
+ def make_dev_panel(draws: int = DEV_DRAWS, instances_per_draw: int = DEV_INSTANCES_PER_DRAW):
94
+ """The public dev panel: `draws` independent draws of `instances_per_draw` instances."""
95
+ panel = []
96
+ for draw in range(int(draws)):
97
+ for k in range(int(instances_per_draw)):
98
+ index = draw * int(instances_per_draw) + k
99
+ panel.append(
100
+ {
101
+ "draw": draw,
102
+ "index": index,
103
+ "instance": make_instance(instance_seed(DEV_ENTROPY, index)),
104
+ "noise": make_noise(noise_seed(DEV_ENTROPY, index)),
105
+ }
106
+ )
107
+ return panel
108
+
109
+
110
+ class InvalidAction(Exception):
111
+ """The policy returned something that is not a legal next vertex."""
112
+
113
+
114
+ def check_action(action, current: int, visited: np.ndarray) -> int:
115
+ """Validate one action, returning it as an int or raising InvalidAction."""
116
+ if isinstance(action, bool) or not isinstance(action, (int, np.integer)):
117
+ raise InvalidAction(f"action is {type(action).__name__}, not an int")
118
+ a = int(action)
119
+ if not 0 <= a < N_VERTICES:
120
+ raise InvalidAction(f"action {a} out of range")
121
+ if a == current:
122
+ raise InvalidAction("action is the current vertex")
123
+ if a != GOAL and visited[a]:
124
+ raise InvalidAction(f"action {a} is an already visited vertex")
125
+ return a
126
+
127
+
128
+ def run_episode(instance: dict, noise_row: np.ndarray, choose) -> dict:
129
+ """Drive one episode. `choose(obs)` returns the next vertex, or raises.
130
+
131
+ Returns a dict with `delivered` (0.0 unless the goal was reached inside budget),
132
+ `failed`, `reason`, `visits` (count of distinct non-start vertices collected) and
133
+ `traversals`.
134
+ """
135
+ dist = instance["dist"]
136
+ rewards = instance["rewards"]
137
+ visited = np.zeros(N_VERTICES, dtype=bool)
138
+ visited[START] = True
139
+ current = START
140
+ remaining = float(instance["budget"])
141
+ collected = 0.0
142
+ step = 0
143
+
144
+ while True:
145
+ if step >= MAX_TRAVERSALS:
146
+ return _failed("traversal_cap", collected, step)
147
+ obs = {
148
+ "current": int(current),
149
+ "visited": visited.copy(),
150
+ "remaining_budget": float(remaining),
151
+ "collected_reward": float(collected),
152
+ "step": int(step),
153
+ }
154
+ try:
155
+ action = check_action(choose(obs), current, visited)
156
+ except InvalidAction as exc:
157
+ return _failed(f"invalid_action: {exc}", collected, step)
158
+ cost = float(dist[current, action]) * float(noise_row[step])
159
+ remaining -= cost
160
+ step += 1
161
+ if remaining < 0.0:
162
+ return _failed("budget_exhausted", collected, step)
163
+ if action == GOAL:
164
+ return {
165
+ "delivered": float(collected),
166
+ "failed": False,
167
+ "reason": "goal",
168
+ "visits": int(visited.sum()) - 1,
169
+ "traversals": step,
170
+ "remaining_budget": float(remaining),
171
+ }
172
+ visited[action] = True
173
+ collected += float(rewards[action])
174
+ current = action
175
+
176
+
177
+ def _failed(reason: str, collected: float, step: int) -> dict:
178
+ return {
179
+ "delivered": 0.0,
180
+ "failed": True,
181
+ "reason": reason,
182
+ "visits": 0,
183
+ "traversals": int(step),
184
+ "collected_when_failed": float(collected),
185
+ }
186
+
187
+
188
+ def penalty(failure_rate: float) -> float:
189
+ """1.0 while the failure rate respects the allowance, ramping linearly to 0.0."""
190
+ f = float(failure_rate)
191
+ if f <= FAILURE_ALLOWANCE:
192
+ return 1.0
193
+ return max(0.0, 1.0 - PENALTY_SLOPE * (f - FAILURE_ALLOWANCE))
194
+
195
+
196
+ def panel_metric(delivered, failed) -> dict:
197
+ """Penalised mean delivered reward over a panel of episodes."""
198
+ delivered = np.asarray(delivered, dtype=np.float64)
199
+ failed = np.asarray(failed, dtype=bool)
200
+ if delivered.size == 0:
201
+ return {"metric": 0.0, "R": 0.0, "F": 1.0, "penalty": 0.0, "episodes": 0}
202
+ R = float(delivered.mean())
203
+ F = float(failed.mean())
204
+ p = penalty(F)
205
+ return {
206
+ "metric": R * p,
207
+ "R": R,
208
+ "F": F,
209
+ "penalty": p,
210
+ "episodes": int(delivered.size),
211
+ "delivered_std": float(delivered.std(ddof=1)) if delivered.size > 1 else 0.0,
212
+ }
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+
4
+
5
+ set -u
6
+
7
+
8
+
9
+ reward_floor() {
10
+ if [ ! -s /logs/verifier/reward.txt ]; then
11
+ mkdir -p /logs/verifier
12
+ printf '0\n' > /logs/verifier/reward.txt
13
+ fi
14
+ }
15
+ trap reward_floor EXIT
16
+
17
+ mkdir -p /logs/verifier
18
+ chown root:root /logs/verifier 2>/dev/null || true
19
+ chmod 755 /logs/verifier 2>/dev/null || true
20
+ rm -f /logs/verifier/reward.txt /logs/verifier/ctrf.json /logs/verifier/metric.json
21
+
22
+ chmod -R go-rwx /tests
23
+
24
+ cd /tests
25
+ export GRADE_SPLIT=final
26
+ /usr/local/bin/python3 -m pytest \
27
+ --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
28
+ /usr/local/bin/python3 /tests/compute_reward.py
29
+
30
+ exit 0
tasks/sopcc-online-chance-constrained-policy/environment/are-grader-ctx/test_state.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import json
5
+ import os
6
+ import shutil
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+
14
+ import grader_core
15
+ import runner
16
+ import sopcc
17
+
18
+ TESTS = Path(__file__).resolve().parent
19
+ DELIVERABLE = Path("/app/solution")
20
+ STAGING = Path("/tmp/sopcc-candidate")
21
+ LOGS = Path("/logs/verifier")
22
+
23
+
24
+ MAX_DELIVERABLE_BYTES = 50 * 1024 * 1024
25
+ CPU_SECONDS_PER_INSTANCE = 75.0
26
+ WALL_SECONDS_PER_INSTANCE = 150.0
27
+ ADDRESS_SPACE_BYTES = 6 * 1024 ** 3
28
+ FILE_SIZE_BYTES = 64 * 1024 ** 2
29
+ OPEN_FILES = 256
30
+ AGENT_UID = 1001
31
+ AGENT_GID = 1001
32
+ WORKERS = 8
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+ SANDBOX = runner.Sandbox(
42
+ cpu_seconds=CPU_SECONDS_PER_INSTANCE,
43
+ timeout=WALL_SECONDS_PER_INSTANCE,
44
+ address_space_bytes=ADDRESS_SPACE_BYTES,
45
+ file_size_bytes=FILE_SIZE_BYTES,
46
+ open_files=OPEN_FILES,
47
+ run_as_uid=AGENT_UID,
48
+ run_as_gid=AGENT_GID,
49
+ new_session=True,
50
+ )
51
+
52
+
53
+ def _write_metric(payload: dict) -> None:
54
+ LOGS.mkdir(parents=True, exist_ok=True)
55
+ (LOGS / "metric.json").write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
56
+
57
+
58
+ def _redacted(split: str) -> bool:
59
+ """The intermediate grader's stdout goes back to the agent, so it stays aggregate-only."""
60
+ return split != "final"
61
+
62
+
63
+ @pytest.fixture(scope="session")
64
+ def graded() -> dict:
65
+ """Grade the sealed panel exactly once, and write the metric file."""
66
+ split = os.environ.get("GRADE_SPLIT", "final")
67
+ payload = {
68
+ "split": split,
69
+ "metric": 0.0,
70
+ "reward": 0.0,
71
+ "R": 0.0,
72
+ "F": 1.0,
73
+ "penalty": 0.0,
74
+ "valid": False,
75
+ "reason": "grading did not complete",
76
+ }
77
+ _write_metric(payload)
78
+
79
+ if split not in grader_core.SPLITS:
80
+ payload["reason"] = f"unknown split {split!r}"
81
+ _write_metric(payload)
82
+ return payload
83
+
84
+ ok, reason, size = runner.validate_solution_dir(str(DELIVERABLE), MAX_DELIVERABLE_BYTES)
85
+ payload["deliverable_bytes"] = size
86
+ if not ok:
87
+ payload["reason"] = f"deliverable rejected: {reason}"
88
+ _write_metric(payload)
89
+ return payload
90
+
91
+ panel = grader_core.load_panel(split)
92
+ STAGING.parent.mkdir(parents=True, exist_ok=True)
93
+ if STAGING.exists():
94
+ shutil.rmtree(STAGING)
95
+ STAGING.mkdir()
96
+ STAGING.chmod(0o755)
97
+ candidate = runner.stage_candidate(str(DELIVERABLE), str(STAGING / "solution"))
98
+
99
+
100
+
101
+
102
+ worker = STAGING / "policy_worker.py"
103
+ shutil.copyfile(TESTS / "policy_worker.py", worker)
104
+ os.chown(worker, 0, 0)
105
+ worker.chmod(0o644)
106
+
107
+ summary = runner.grade_panel(
108
+ panel, SANDBOX, candidate,
109
+ worker_path=str(worker),
110
+ python_exe=sys.executable,
111
+ workers=WORKERS,
112
+ episodes=sopcc.EPISODES_PER_INSTANCE,
113
+ )
114
+ reasons = collections.Counter()
115
+ aborts = []
116
+ for i, report in enumerate(summary["reports"]):
117
+ for outcome in report["episodes"]:
118
+ if outcome["failed"]:
119
+ reasons[outcome["reason"].split(":")[0]] += 1
120
+ if report["abort"]:
121
+ aborts.append({
122
+ "instance": i,
123
+ "abort": report["abort"],
124
+ "cpu_seconds": report["cpu_seconds"],
125
+ "wall_seconds": report["wall_seconds"],
126
+
127
+
128
+ "unexplained": (("closed the channel" in report["abort"]
129
+ or "is not reading" in report["abort"])
130
+ and report["wall_seconds"] < 0.25 * WALL_SECONDS_PER_INSTANCE
131
+ and report["cpu_seconds"] < 0.5 * CPU_SECONDS_PER_INSTANCE),
132
+ })
133
+
134
+ payload.update({
135
+ "metric": summary["metric"],
136
+ "reward": grader_core.graded_reward(summary["metric"], split),
137
+ "R": summary["R"],
138
+ "F": summary["F"],
139
+ "penalty": summary["penalty"],
140
+ "episodes": summary["episodes"],
141
+ "instances": summary["instances"],
142
+ "per_draw_metric": {str(d): summary["per_draw"][d]["metric"]
143
+ for d in sorted(summary["per_draw"])},
144
+ "per_draw_F": {str(d): summary["per_draw"][d]["F"]
145
+ for d in sorted(summary["per_draw"])},
146
+ "delivered_std": summary["delivered_std"],
147
+ "failure_reasons": dict(reasons),
148
+ "aborted_instances": summary["aborted_instances"],
149
+ "aborts": aborts,
150
+ "unexplained_aborts": sum(1 for a in aborts if a["unexplained"]),
151
+ "retried_instances": summary["retried_instances"],
152
+ "max_cpu_seconds": summary["max_cpu_seconds"],
153
+ "max_wall_seconds": summary["max_wall_seconds"],
154
+ "valid": True,
155
+ "reason": "ok",
156
+ })
157
+ _write_metric(payload)
158
+
159
+ if _redacted(split):
160
+ print(f"episodes: {payload['episodes']} over {payload['instances']} instances")
161
+ print(f"failure rate F: {payload['F']:.4f} penalty factor: {payload['penalty']:.4f}")
162
+ print("failure rate per draw: " + ", ".join(
163
+ f"{d}={v:.4f}" for d, v in payload["per_draw_F"].items()))
164
+ print("failure reasons: " + (", ".join(
165
+ f"{k}={v}" for k, v in sorted(reasons.items())) or "none"))
166
+ print(f"largest per-instance cpu {payload['max_cpu_seconds']:.1f}s of "
167
+ f"{CPU_SECONDS_PER_INSTANCE:.0f}s, wall {payload['max_wall_seconds']:.1f}s of "
168
+ f"{WALL_SECONDS_PER_INSTANCE:.0f}s")
169
+ print(f"instances that ended early: {payload['aborted_instances']}"
170
+ + (" (" + "; ".join(a["abort"][:80] for a in aborts[:3]) + ")" if aborts else ""))
171
+ else:
172
+ print(json.dumps({k: v for k, v in payload.items() if k != "failure_reasons"},
173
+ indent=2, sort_keys=True))
174
+ print("failure reasons: " + json.dumps(dict(reasons), sort_keys=True))
175
+ return payload
176
+
177
+
178
+ def test_deliverable_runs(graded):
179
+ """The submitted policy must exist, import, and answer decisions at all.
180
+
181
+ WHY: everything else is meaningless if the deliverable never ran. A missing, oversized,
182
+ link-bearing or unimportable deliverable is scored 0 rather than skipped.
183
+ """
184
+ assert graded["valid"], graded["reason"]
185
+ assert graded["episodes"] == graded["instances"] * sopcc.EPISODES_PER_INSTANCE
186
+
187
+
188
+ def test_metric_is_well_formed(graded):
189
+ """The metric and its parts must be finite and inside their definitions.
190
+
191
+ WHY: the reward is a function of these numbers, so a NaN or an out-of-range failure rate
192
+ has to fail loudly here instead of propagating into reward.txt.
193
+ """
194
+ assert 0.0 <= graded["F"] <= 1.0
195
+ assert 0.0 <= graded["penalty"] <= 1.0
196
+ assert graded["R"] >= 0.0
197
+ assert graded["metric"] == pytest.approx(graded["R"] * graded["penalty"], abs=1e-9)
198
+ assert 0.0 <= graded["reward"] < 1.0
199
+
200
+
201
+ def test_reward_follows_the_metric(graded):
202
+ """The reward written for this run must be exactly the map applied to the measured metric.
203
+
204
+ WHY: the reward is the only number that leaves the verifier, and it is computed once in the
205
+ fixture. This re-derives it from the metric through the same map, so a mis-keyed split or a
206
+ hand-edited payload cannot slip a different number into reward.txt. It also pins the floor:
207
+ a metric at or below the trivial anchor is worth exactly 0.
208
+ """
209
+ split = graded["split"]
210
+ assert graded["reward"] == pytest.approx(
211
+ grader_core.graded_reward(graded["metric"], split), abs=1e-12)
212
+ m0, m_ref = grader_core.ANCHORS[split]
213
+ assert m_ref > m0
214
+ assert grader_core.graded_reward(m0, split) == 0.0
215
+ assert grader_core.graded_reward(m0 - 1.0, split) == 0.0
216
+ assert grader_core.graded_reward(m_ref, split) == pytest.approx(0.5, abs=1e-12)
217
+
218
+
219
+ def test_no_infrastructure_failure(graded):
220
+ """No instance may end early for a reason that is not the policy's own doing.
221
+
222
+ WHY: an instance whose child process vanished contributes 32 failures and drags the metric
223
+ down. Retries absorb a transient death; anything still unexplained afterwards is surfaced
224
+ here, on a channel the candidate cannot reach or trigger, instead of being folded silently
225
+ into a low score. A policy that crashes or blows its own budget is NOT unexplained.
226
+ """
227
+ assert graded.get("unexplained_aborts", 0) == 0, (
228
+ f"{graded.get('unexplained_aborts')} instances died without spending their own "
229
+ f"budget: {[a for a in graded.get('aborts', []) if a['unexplained']][:3]}")