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

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

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/hicard-latent-encoder/task.toml +39 -25
  2. tasks/hicard-latent-encoder/tests/Dockerfile +2 -35
  3. tasks/hicard-latent-encoder/tests/finalize.py +59 -0
  4. tasks/hicard-latent-encoder/tests/test.sh +1 -18
  5. tasks/label-efficient-risk-estimator/environment/.dockerignore +1 -0
  6. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile +34 -0
  7. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/Dockerfile.are +52 -0
  8. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/drain.py +25 -0
  9. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/are/server.py +538 -0
  10. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/candidate_runner.py +142 -0
  11. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/compute_reward.py +20 -0
  12. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/grader_core.py +79 -0
  13. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/labels.npy +3 -0
  14. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/meta.json +1 -0
  15. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/surrogate_probs.npy +3 -0
  16. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/target_probs.npy +3 -0
  17. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/labels.npy +3 -0
  18. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/meta.json +1 -0
  19. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/surrogate_probs.npy +3 -0
  20. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/target_probs.npy +3 -0
  21. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/labels.npy +3 -0
  22. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/meta.json +1 -0
  23. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/surrogate_probs.npy +3 -0
  24. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/target_probs.npy +3 -0
  25. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/labels.npy +3 -0
  26. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/meta.json +1 -0
  27. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/surrogate_probs.npy +3 -0
  28. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/target_probs.npy +3 -0
  29. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/labels.npy +3 -0
  30. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/meta.json +1 -0
  31. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/surrogate_probs.npy +3 -0
  32. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/target_probs.npy +3 -0
  33. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/labels.npy +3 -0
  34. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/meta.json +1 -0
  35. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/surrogate_probs.npy +3 -0
  36. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/target_probs.npy +3 -0
  37. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/labels.npy +3 -0
  38. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/meta.json +1 -0
  39. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/surrogate_probs.npy +3 -0
  40. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/target_probs.npy +3 -0
  41. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/labels.npy +3 -0
  42. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/meta.json +1 -0
  43. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/surrogate_probs.npy +3 -0
  44. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/target_probs.npy +3 -0
  45. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/intermediate.sh +20 -0
  46. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements-verifier.txt +2 -0
  47. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/requirements.txt +2 -0
  48. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test.sh +20 -0
  49. tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test_state.py +319 -0
  50. tasks/label-efficient-risk-estimator/environment/docker-compose.yaml +76 -0
tasks/hicard-latent-encoder/task.toml CHANGED
@@ -1,57 +1,71 @@
1
  schema_version = "1.4"
2
- artifacts = [ "/app/output",]
 
 
3
 
4
  [task]
5
  name = "bespokelabs/hicard-latent-encoder"
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 = "Feature engineering"
15
- task_objective = [ "Implement", "Optimize",]
16
- artifact_type = [ "Single script or program",]
 
 
 
 
 
17
  expert_time_estimate_hours = 4.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 = 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/hicard-latent-encoder"
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 = "Feature engineering"
22
+ task_objective = [
23
+ "Implement",
24
+ "Optimize",
25
+ ]
26
+ artifact_type = [
27
+ "Single script or program",
28
+ ]
29
  expert_time_estimate_hours = 4.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/hicard-latent-encoder/tests/Dockerfile CHANGED
@@ -1,35 +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 mkdir -p /opt/harness \
27
- && cp /tests/candidate_runner.py /opt/harness/candidate_runner.py \
28
- && chown -R root:root /opt/harness /tests \
29
- && chmod 755 /opt/harness \
30
- && chmod 644 /opt/harness/candidate_runner.py \
31
- && chmod 700 /tests/hidden_data /tests/hidden_data/intermediate /tests/hidden_data/final \
32
- && chmod +x /tests/test.sh /tests/intermediate.sh \
33
- && find /tests /opt/harness -exec touch -d @1700000000 {} +
34
-
35
- WORKDIR /tests
 
1
+ FROM python:3.12-slim
2
+ COPY . /tests/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tasks/hicard-latent-encoder/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/hicard-latent-encoder/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
- trap 'if [ ! -s /logs/verifier/reward.txt ]; then echo 0 > /logs/verifier/reward.txt; fi' EXIT TERM INT
10
-
11
- chmod -R go-rwx /tests
12
-
13
- export GRADER_SPLIT=final
14
-
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/label-efficient-risk-estimator/environment/.dockerignore ADDED
@@ -0,0 +1 @@
 
 
1
+ are-grader-ctx
tasks/label-efficient-risk-estimator/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/output /logs/verifier /grade_run
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/label-efficient-risk-estimator/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/output /logs/verifier /grade_run
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/label-efficient-risk-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/label-efficient-risk-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/label-efficient-risk-estimator/environment/are-grader-ctx/candidate_runner.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import signal
4
+ import socket
5
+ import struct
6
+ import sys
7
+ import time
8
+ import types
9
+
10
+ import numpy as np
11
+
12
+ _HDR = struct.Struct("<c")
13
+ _I32 = struct.Struct("<i")
14
+ _F64 = struct.Struct("<d")
15
+
16
+
17
+ def _sendall(sock, data):
18
+ sock.sendall(data)
19
+
20
+
21
+ def _recv_exact(sock, n):
22
+ buf = b""
23
+ while len(buf) < n:
24
+ chunk = sock.recv(n - len(buf))
25
+ if not chunk:
26
+ raise ConnectionError("scorer closed the label channel")
27
+ buf += chunk
28
+ return buf
29
+
30
+
31
+ def _request_label(sock, index):
32
+ _sendall(sock, _HDR.pack(b"L") + _I32.pack(int(index)))
33
+ return _I32.unpack(_recv_exact(sock, 4))[0]
34
+
35
+
36
+ def _run_one_seed(sock, code, module_path, submission_dir, pool, budget, seed):
37
+ """Executed in the grandchild only. Never returns."""
38
+ try:
39
+ os.setpgid(0, 0)
40
+ except OSError:
41
+ pass
42
+ try:
43
+ sys.path.insert(0, submission_dir)
44
+ mod = types.ModuleType("candidate_estimator")
45
+ mod.__file__ = module_path
46
+ exec(code, mod.__dict__)
47
+ Estimator = mod.Estimator
48
+ rng = np.random.default_rng([pool["_cseed"], seed])
49
+ est = Estimator(pool["_view"], budget, rng)
50
+ n_pool = pool["_view"]["n_pool"]
51
+ for _ in range(budget):
52
+ idx = est.next_index()
53
+ idx = int(idx)
54
+ if not (0 <= idx < n_pool):
55
+ raise ValueError(f"next_index returned {idx}, outside [0, {n_pool})")
56
+ label = _request_label(sock, idx)
57
+ if label < 0:
58
+ raise RuntimeError("label budget exhausted")
59
+ est.observe(idx, label)
60
+ value = float(est.estimate())
61
+ if not np.isfinite(value):
62
+ raise ValueError(f"estimate() returned {value}")
63
+ _sendall(sock, _HDR.pack(b"R") + _I32.pack(seed) + _F64.pack(value))
64
+ _recv_exact(sock, 1)
65
+ os._exit(0)
66
+ except BaseException:
67
+ try:
68
+ sys.stderr.write(f"[seed {seed}] candidate failed\n")
69
+ except Exception:
70
+ pass
71
+ os._exit(3)
72
+
73
+
74
+ def main():
75
+ ap = argparse.ArgumentParser()
76
+ ap.add_argument("--pool", required=True)
77
+ ap.add_argument("--submission-dir", required=True)
78
+ ap.add_argument("--entry", required=True)
79
+ ap.add_argument("--budget", type=int, required=True)
80
+ ap.add_argument("--seeds", type=int, required=True)
81
+ ap.add_argument("--seed-start", type=int, default=0)
82
+ ap.add_argument("--cell-seed", type=int, required=True)
83
+ ap.add_argument("--per-seed-timeout", type=float, required=True)
84
+ ap.add_argument("--sock-fd", type=int, required=True)
85
+ args = ap.parse_args()
86
+
87
+ sock = socket.socket(fileno=args.sock_fd)
88
+
89
+ with open(args.entry, "rb") as fh:
90
+ src = fh.read()
91
+ code = compile(src, args.entry, "exec")
92
+
93
+ npz = np.load(args.pool)
94
+ target_probs = np.ascontiguousarray(npz["target_probs"], dtype=np.float64)
95
+ surrogate_probs = np.ascontiguousarray(npz["surrogate_probs"], dtype=np.float64)
96
+ n_pool, n_classes = target_probs.shape
97
+
98
+ for seed in range(args.seed_start, args.seed_start + args.seeds):
99
+ _sendall(sock, _HDR.pack(b"S") + _I32.pack(seed))
100
+ if _recv_exact(sock, 1) != b"\x01":
101
+ sys.stderr.write("scorer refused the seed handshake\n")
102
+ return 1
103
+ perm = np.random.default_rng([args.cell_seed, seed, 0x5EED]).permutation(n_pool)
104
+ view = {
105
+ "target_probs": np.ascontiguousarray(target_probs[perm]),
106
+ "surrogate_probs": np.ascontiguousarray(surrogate_probs[perm]),
107
+ "n_classes": int(n_classes),
108
+ "n_pool": int(n_pool),
109
+ }
110
+ pool = {"_view": view, "_cseed": args.cell_seed}
111
+ pid = os.fork()
112
+ if pid == 0:
113
+ _run_one_seed(sock, code, args.entry, args.submission_dir, pool,
114
+ args.budget, seed)
115
+ deadline = time.monotonic() + args.per_seed_timeout
116
+ status = None
117
+ while True:
118
+ done, status = os.waitpid(pid, os.WNOHANG)
119
+ if done:
120
+ break
121
+ if time.monotonic() > deadline:
122
+ for sig in (signal.SIGKILL,):
123
+ try:
124
+ os.killpg(pid, sig)
125
+ except OSError:
126
+ try:
127
+ os.kill(pid, sig)
128
+ except OSError:
129
+ pass
130
+ os.waitpid(pid, 0)
131
+ status = -1
132
+ break
133
+ time.sleep(0.0005)
134
+ if status != 0:
135
+ _sendall(sock, _HDR.pack(b"F") + _I32.pack(seed))
136
+ _recv_exact(sock, 1)
137
+ _sendall(sock, _HDR.pack(b"Q") + _I32.pack(0))
138
+ return 0
139
+
140
+
141
+ if __name__ == "__main__":
142
+ sys.exit(main())
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/compute_reward.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ from pathlib import Path
4
+
5
+ REWARD_PATH = Path("/logs/verifier/reward.txt")
6
+
7
+ try:
8
+ REWARD_PATH.parent.mkdir(parents=True, exist_ok=True)
9
+ payload = json.loads(Path("/logs/verifier/metric.json").read_text())
10
+ if not payload.get("valid", False):
11
+ raise ValueError(f"invalid submission: {payload.get('reason')}")
12
+ value = float(payload["reward"])
13
+ if not math.isfinite(value):
14
+ raise ValueError("non-finite reward")
15
+ reward = f"{min(1.0, max(0.0, value)):.12g}"
16
+ REWARD_PATH.write_text(reward + "\n")
17
+ print(f"reward={reward}")
18
+ except Exception as exc:
19
+ REWARD_PATH.write_text("0\n")
20
+ print(f"reward=0 (fallback: {exc})")
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/grader_core.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import math
3
+
4
+ import numpy as np
5
+
6
+ BUDGETS = (50, 100, 200, 400)
7
+ N_SEEDS = 4000
8
+ PER_SEED_TIMEOUT_S = 5.0
9
+ PER_CELL_TIMEOUT_S = 900.0
10
+ SE_CAP = 100.0
11
+ RATIO_CAP = 1.0e4
12
+
13
+ M0 = 1.0
14
+ BASELINE_SCORE = 0.68
15
+ HIGHER_IS_BETTER = False
16
+
17
+ _SALT = "2508-09093/label-efficient-risk-estimator/v1"
18
+
19
+
20
+ def cell_seed(instance_id: str, budget: int) -> int:
21
+ """Deterministic per-cell seed. Identical on both sides of the socket."""
22
+ h = hashlib.sha256(f"{_SALT}|{instance_id}|{budget}".encode()).digest()
23
+ return int.from_bytes(h[:8], "big")
24
+
25
+
26
+ def seed_permutation(cseed: int, seed: int, n_pool: int) -> np.ndarray:
27
+ """Row order the candidate sees for this (cell, seed). Defeats any {row -> label} cache."""
28
+ return np.random.default_rng([cseed, seed, 0x5EED]).permutation(n_pool)
29
+
30
+
31
+ def exact_risk(target_probs: np.ndarray, labels: np.ndarray) -> float:
32
+ """R = (1/N) sum_i -log target_probs[i, y_i] over the WHOLE pool."""
33
+ p = target_probs[np.arange(labels.shape[0]), labels]
34
+ return float(np.mean(-np.log(np.clip(p, 1e-300, None))))
35
+
36
+
37
+ def reference_squared_errors(target_probs, labels, budget, cseed, seeds):
38
+ """Uniform-random acquisition + plain sample mean, on the same seeds and the same
39
+ permuted view the candidate is given. This is the metric's denominator."""
40
+ n_pool = labels.shape[0]
41
+ risk = exact_risk(target_probs, labels)
42
+ nll = -np.log(np.clip(target_probs[np.arange(n_pool), labels], 1e-300, None))
43
+ out = np.empty(len(seeds), dtype=np.float64)
44
+ for k, s in enumerate(seeds):
45
+ perm = seed_permutation(cseed, s, n_pool)
46
+ nll_perm = nll[perm]
47
+ rng = np.random.default_rng([cseed, s])
48
+ idx = rng.choice(n_pool, size=budget, replace=False)
49
+ out[k] = (float(np.mean(nll_perm[idx])) - risk) ** 2
50
+ return out
51
+
52
+
53
+ def cell_ratio(agent_se: np.ndarray, ref_se: np.ndarray) -> float:
54
+ """median-over-seeds squared error of the candidate, divided by the reference's."""
55
+ num = float(np.median(agent_se))
56
+ den = float(np.median(ref_se))
57
+ if not math.isfinite(den) or den <= 0.0:
58
+ den = 1e-12
59
+ return float(min(RATIO_CAP, num / den))
60
+
61
+
62
+ def aggregate(cell_ratios) -> float:
63
+ """The graded metric: the median of the per-cell ratios."""
64
+ vals = np.asarray(list(cell_ratios), dtype=np.float64)
65
+ if vals.size == 0 or not np.all(np.isfinite(vals)):
66
+ return float(RATIO_CAP)
67
+ return float(np.median(vals))
68
+
69
+
70
+ def graded_reward(metric: float, valid: bool) -> float:
71
+ """rational_squash on two task-derived anchors. Clamped again in compute_reward.py."""
72
+ if not valid or metric is None or not math.isfinite(metric):
73
+ return 0.0
74
+ sigma = 1.0 if HIGHER_IS_BETTER else -1.0
75
+ x = sigma * (metric - M0)
76
+ x_ref = sigma * (BASELINE_SCORE - M0)
77
+ assert x_ref > 0, "malformed task: the anchor does not beat the trivial baseline"
78
+ u = max(0.0, x) / x_ref
79
+ return u / (1.0 + u)
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a8dff3df8f6fe7a9e7ff5ed5edb178a2b98ec1f126a5e8917b611ed281e8a8a
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool01", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ae14107d3dbcec2ed1b2f953dffb0d865ee719797e690a97fff5cac5948f9d7
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool01/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0420c93f9d48642ab0d63708c1ec50be496c832757735d4894bd9d617d51bac0
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc6cabb575d3c13c53555ce23580a7b761ab0c86011249ef6f9a11df9e20df1b
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool02", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a649eb72f08691a25e469f81971a99b75e5ad778ec183c5daec53d4e7d66421a
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool02/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:044c8ff01b0a345c21dcf267104a55659c059165d3aba899bc2757589a482643
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acb1e8f224bed55336d0a2b34fb52dbf358fee6756cb8da1c433338b47e52cc7
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool04", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:793c086283dafeabc146cf930f6d9ebcf81f87bc61dff174c0be7a544ea82015
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool04/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9f11869708df4edc13bd2cdaf01f556317d6552e835ee7fcffb27dddc440e65
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a8dff3df8f6fe7a9e7ff5ed5edb178a2b98ec1f126a5e8917b611ed281e8a8a
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool07", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ae14107d3dbcec2ed1b2f953dffb0d865ee719797e690a97fff5cac5948f9d7
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/final/pool07/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d821ed4c955b7e246292f3d6f22f9657f12c3c4b4fe3bb81e9c57c10d56e6740
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool00", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool00/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fb01211123bf70da5cf0b5109e51643c38e7f7b34de104178a61c94e3ef3579
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19110f7553e90eab5a2aff29615133dca46655ccb270a67e0a8e6a0d56ee7f9b
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool03", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88f687bdcaf414d53554563a8b084f696a00ecfb6f047aab86631c760ace8d39
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool03/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00002ad5d2699c949ae50b950559145c79dd92db9025b1c0b2ee27ae8de53b7e
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool05", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool05/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f90902a1c70205718cb080ae1fe17c44426a71ce6d751e09b52e795e229f546b
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/labels.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:179ab42ad9ed2a7fcb4f0cdafb076bcfc35ce161a8687715c753770448744700
3
+ size 16128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/meta.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"pool_id": "pool06", "n_pool": 2000, "n_classes": 2}
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/surrogate_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:994d602d6b276632b059555ac14fc91bb549225b8c91e85fd2d7b78e96eb2d56
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/hidden_data/intermediate/pool06/target_probs.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:89f71218e7112cf1949f2777fa0a6f8686cf48347ac7f9ac374011a65cd2c291
3
+ size 32128
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/intermediate.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT
11
+
12
+ chmod -R go-rwx /tests
13
+
14
+ cd /tests
15
+ export GRADE_SPLIT=intermediate
16
+ /usr/local/bin/python3 -m pytest \
17
+ --ctrf /logs/verifier/ctrf.json /tests/test_state.py -rA
18
+ /usr/local/bin/python3 /tests/compute_reward.py
19
+
20
+ exit 0
tasks/label-efficient-risk-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/label-efficient-risk-estimator/environment/are-grader-ctx/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ numpy==2.3.2
2
+ scipy==1.16.1
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 '[ -s /logs/verifier/reward.txt ] || printf "0\n" > /logs/verifier/reward.txt' EXIT
11
+
12
+ chmod -R go-rwx /tests
13
+
14
+ cd /tests
15
+ export GRADE_SPLIT=final
16
+ /usr/local/bin/python3 -m pytest --ctrf /logs/verifier/ctrf.json \
17
+ /tests/test_state.py -rA
18
+ /usr/local/bin/python3 /tests/compute_reward.py
19
+
20
+ exit 0
tasks/label-efficient-risk-estimator/environment/are-grader-ctx/test_state.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import socket
5
+ import struct
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from concurrent.futures import ProcessPoolExecutor
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ import grader_core as GC
17
+
18
+ PY = "/usr/local/bin/python3"
19
+ TESTS_DIR = Path(__file__).resolve().parent
20
+ RUNNER_SRC = TESTS_DIR / "candidate_runner.py"
21
+ DELIVERABLE_DIR = Path("/app/output")
22
+ ENTRY_NAME = "estimator.py"
23
+ STAGE = Path("/grade_run")
24
+ LOGS = Path("/logs/verifier")
25
+ AGENT_UID, AGENT_GID = 1001, 1001
26
+ MAX_SUBMISSION_BYTES = 256 * 1024 * 1024
27
+ MAX_SUBMISSION_FILES = 2000
28
+
29
+ _HDR = struct.Struct("<c")
30
+ _I32 = struct.Struct("<i")
31
+ _F64 = struct.Struct("<d")
32
+
33
+
34
+ def harvest_submission():
35
+ """Copy /app/output into a root-owned staging tree, refusing every link.
36
+
37
+ Every submitted path is treated as hostile: symlinks and hard links are rejected
38
+ before anything is copied (checked at every depth), and the copy itself never
39
+ follows a link. A privileged copy that dereferenced a submitted symlink would
40
+ materialise sealed verifier files into the tree the score is computed from.
41
+ """
42
+ dest = STAGE / "submission"
43
+ if dest.exists():
44
+ shutil.rmtree(dest)
45
+ if DELIVERABLE_DIR.is_symlink():
46
+ return None, f"{DELIVERABLE_DIR} is a symlink"
47
+ if not DELIVERABLE_DIR.is_dir():
48
+ return None, f"no deliverable directory at {DELIVERABLE_DIR}"
49
+ total, count = 0, 0
50
+ for root, dirs, files in os.walk(DELIVERABLE_DIR, followlinks=False):
51
+ for name in list(dirs) + list(files):
52
+ p = Path(root) / name
53
+ st = p.lstat()
54
+ if p.is_symlink():
55
+ return None, f"symlink in the deliverable tree: {p}"
56
+ if p.is_file() and st.st_nlink > 1:
57
+ return None, f"hard link in the deliverable tree: {p}"
58
+ if p.is_file():
59
+ total += st.st_size
60
+ count += 1
61
+ elif not p.is_dir():
62
+ return None, f"not a regular file or directory: {p}"
63
+ if count == 0:
64
+ return None, "the deliverable directory is empty"
65
+ if total > MAX_SUBMISSION_BYTES or count > MAX_SUBMISSION_FILES:
66
+ return None, f"deliverable too large: {count} files, {total} bytes"
67
+ shutil.copytree(DELIVERABLE_DIR, dest, symlinks=True)
68
+ for root, dirs, files in os.walk(dest):
69
+ os.chmod(root, 0o755)
70
+ for name in files:
71
+ os.chmod(Path(root) / name, 0o644)
72
+ entry = dest / ENTRY_NAME
73
+ if entry.is_symlink() or not entry.is_file() or entry.stat().st_size == 0:
74
+ return None, f"missing or empty entry point {DELIVERABLE_DIR / ENTRY_NAME}"
75
+ return dest, None
76
+
77
+
78
+ def seal_filesystem():
79
+ """Leave uid 1001 no writable directory, so no candidate state can survive a seed."""
80
+ for path in ("/tmp", "/var/tmp", "/dev/shm", "/home/agent", "/app", "/app/output"):
81
+ try:
82
+ os.chown(path, 0, 0)
83
+ os.chmod(path, 0o755)
84
+ except OSError:
85
+ pass
86
+
87
+
88
+ def _launch_runner(cell_dir, submission_dir, budget, cseed, n_seeds, seed0, child_fd):
89
+ argv = [PY, "-I", str(cell_dir / "candidate_runner.py"),
90
+ "--pool", str(cell_dir / "pool.npz"),
91
+ "--submission-dir", str(submission_dir),
92
+ "--entry", str(Path(submission_dir) / ENTRY_NAME),
93
+ "--budget", str(budget), "--seeds", str(n_seeds),
94
+ "--seed-start", str(seed0),
95
+ "--cell-seed", str(cseed),
96
+ "--per-seed-timeout", str(GC.PER_SEED_TIMEOUT_S),
97
+ "--sock-fd", str(child_fd)]
98
+ env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "HOME": "/home/agent",
99
+ "TMPDIR": "/nonexistent", "PYTHONDONTWRITEBYTECODE": "1",
100
+ "PYTHONSAFEPATH": "1", "PYTHONHASHSEED": "0", "OMP_NUM_THREADS": "1",
101
+ "MKL_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1",
102
+ "NUMEXPR_NUM_THREADS": "1", "LC_ALL": "C"}
103
+ err = subprocess.DEVNULL
104
+ if os.environ.get("GRADE_DEBUG"):
105
+ err = open(Path(cell_dir) / "candidate_stderr.log", "wb")
106
+ prefix = []
107
+ for cand, args in (("/usr/sbin/runuser", ["-u", "agent", "--"]),
108
+ ("/usr/bin/setpriv", [f"--reuid={AGENT_UID}",
109
+ f"--regid={AGENT_GID}", "--clear-groups", "--"])):
110
+ if os.path.exists(cand):
111
+ prefix = [cand] + args
112
+ break
113
+ kwargs = {}
114
+ if not prefix:
115
+ kwargs = {"user": AGENT_UID, "group": AGENT_GID, "extra_groups": []}
116
+ return subprocess.Popen(prefix + argv, env=env, start_new_session=True,
117
+ pass_fds=(child_fd,), stdout=subprocess.DEVNULL,
118
+ stderr=err, cwd=str(cell_dir), **kwargs)
119
+
120
+
121
+ def _serve(sock, labels, budget, cseed, seeds, deadline):
122
+ """Label oracle. Enforces the budget and the one-shot, in-order seed protocol."""
123
+ n_pool = labels.shape[0]
124
+ estimates, used, answered, perm = {}, 0, True, None
125
+ expected = list(seeds)
126
+ pos, current = 0, None
127
+ violation = None
128
+ try:
129
+ while True:
130
+ remaining = deadline - time.monotonic()
131
+ if remaining <= 0:
132
+ violation = "cell wall-clock budget exhausted"
133
+ break
134
+ sock.settimeout(remaining)
135
+ head = sock.recv(1)
136
+ if not head:
137
+ break
138
+ if head == b"S":
139
+ s = _I32.unpack(_recv_exact(sock, 4))[0]
140
+ if pos >= len(expected) or s != expected[pos]:
141
+ violation = f"out-of-order seed handshake: {s} after {current}"
142
+ break
143
+ current, used, answered = s, 0, False
144
+ pos += 1
145
+ perm = GC.seed_permutation(cseed, s, n_pool)
146
+ sock.sendall(b"\x01")
147
+ elif head == b"L":
148
+ j = _I32.unpack(_recv_exact(sock, 4))[0]
149
+ if answered or used >= budget or not (0 <= j < n_pool):
150
+ sock.sendall(_I32.pack(-1))
151
+ else:
152
+ used += 1
153
+ sock.sendall(_I32.pack(int(labels[perm[j]])))
154
+ elif head == b"R":
155
+ s = _I32.unpack(_recv_exact(sock, 4))[0]
156
+ v = _F64.unpack(_recv_exact(sock, 8))[0]
157
+ if s != current or answered:
158
+ violation = f"duplicate or stray result for seed {s}"
159
+ sock.sendall(b"\x01")
160
+ break
161
+ estimates[s], answered = v, True
162
+ sock.sendall(b"\x01")
163
+ elif head == b"F":
164
+ _recv_exact(sock, 4)
165
+ answered = True
166
+ sock.sendall(b"\x01")
167
+ elif head == b"Q":
168
+ _recv_exact(sock, 4)
169
+ break
170
+ else:
171
+ violation = f"unknown opcode {head!r}"
172
+ break
173
+ except (socket.timeout, ConnectionError, OSError, struct.error) as exc:
174
+ if violation is None and len(estimates) < len(expected):
175
+ violation = f"label channel ended early ({type(exc).__name__})"
176
+ return estimates, violation
177
+
178
+
179
+ def _recv_exact(sock, n):
180
+ buf = b""
181
+ while len(buf) < n:
182
+ chunk = sock.recv(n - len(buf))
183
+ if not chunk:
184
+ raise ConnectionError("candidate closed the label channel")
185
+ buf += chunk
186
+ return buf
187
+
188
+
189
+ def grade_cell(job):
190
+ """Runs in a root worker process. Returns the cell's ratio and diagnostics.
191
+
192
+ Any failure inside this worker is reported as a worst-case cell rather than being
193
+ allowed to abort the grade, so the reward path always reaches compute_reward.py.
194
+ """
195
+ try:
196
+ return _grade_cell(job)
197
+ except Exception as exc:
198
+ return {"instance": job[1], "budget": job[2], "risk": None,
199
+ "ratio": GC.RATIO_CAP, "n_ok": 0, "n_seeds": job[4],
200
+ "violation": f"scorer error: {type(exc).__name__}: {exc}"}
201
+
202
+
203
+ def _grade_cell(job):
204
+ inst_dir, instance_id, budget, submission_dir, n_seeds, seed0 = job
205
+ inst_dir = Path(inst_dir)
206
+ target = np.load(inst_dir / "target_probs.npy").astype(np.float64)
207
+ surrogate = np.load(inst_dir / "surrogate_probs.npy").astype(np.float64)
208
+ labels = np.load(inst_dir / "labels.npy").astype(np.int64)
209
+ cseed = GC.cell_seed(instance_id, budget)
210
+ risk = GC.exact_risk(target, labels)
211
+ seeds = list(range(seed0, seed0 + n_seeds))
212
+ ref_se = GC.reference_squared_errors(target, labels, budget, cseed, seeds)
213
+
214
+ cell_dir = Path(tempfile.mkdtemp(prefix=f"cell_{instance_id}_{budget}_", dir=str(STAGE)))
215
+ os.chmod(cell_dir, 0o755)
216
+ np.savez(cell_dir / "pool.npz", target_probs=target, surrogate_probs=surrogate)
217
+ shutil.copy2(RUNNER_SRC, cell_dir / "candidate_runner.py")
218
+ os.chmod(cell_dir / "pool.npz", 0o644)
219
+ os.chmod(cell_dir / "candidate_runner.py", 0o644)
220
+
221
+ parent_sock, child_sock = socket.socketpair()
222
+ proc = None
223
+ try:
224
+ proc = _launch_runner(cell_dir, submission_dir, budget, cseed, n_seeds, seed0,
225
+ child_sock.fileno())
226
+ child_sock.close()
227
+ estimates, violation = _serve(parent_sock, labels, budget, cseed, seeds,
228
+ time.monotonic() + GC.PER_CELL_TIMEOUT_S)
229
+ finally:
230
+ if os.environ.get("GRADE_DEBUG"):
231
+ try:
232
+ tail = (cell_dir / "candidate_stderr.log").read_bytes()[-4000:]
233
+ if tail:
234
+ print(f"[stderr {instance_id} M={budget}]\n{tail.decode(errors='replace')}")
235
+ except OSError:
236
+ pass
237
+ try:
238
+ parent_sock.close()
239
+ except OSError:
240
+ pass
241
+ if proc is not None:
242
+ try:
243
+ os.killpg(os.getpgid(proc.pid), 9)
244
+ except OSError:
245
+ pass
246
+ try:
247
+ proc.wait(timeout=30)
248
+ except Exception:
249
+ pass
250
+ shutil.rmtree(cell_dir, ignore_errors=True)
251
+
252
+ agent_se = np.full(n_seeds, GC.SE_CAP, dtype=np.float64)
253
+ if violation is None:
254
+ for s, v in estimates.items():
255
+ k = s - seed0
256
+ if 0 <= k < n_seeds and np.isfinite(v):
257
+ agent_se[k] = min(GC.SE_CAP, (float(v) - risk) ** 2)
258
+ n_ok = int(np.sum(agent_se < GC.SE_CAP))
259
+ return {"instance": instance_id, "budget": budget, "risk": risk,
260
+ "ratio": GC.cell_ratio(agent_se, ref_se), "n_ok": n_ok,
261
+ "n_seeds": n_seeds, "violation": violation}
262
+
263
+
264
+ def _write_metric(payload):
265
+ LOGS.mkdir(parents=True, exist_ok=True)
266
+ (LOGS / "metric.json").write_text(json.dumps(payload, indent=2, sort_keys=True))
267
+
268
+
269
+ def test_reward():
270
+ """Execute the candidate estimator over every sealed cell and write metric.json.
271
+
272
+ WHAT: drives the candidate's /app/output/estimator.py through the full adaptive
273
+ acquisition protocol on the sealed pools, computes the median relative
274
+ risk-estimation error against the verifier's own uniform-random reference, and maps
275
+ it to the graded reward.
276
+ WHY: the reward has to come from EXECUTING candidate code on inputs that were never
277
+ in the agent image, never from reading a file the candidate wrote.
278
+ """
279
+ split = os.environ.get("GRADE_SPLIT", "final")
280
+ hidden = TESTS_DIR / "hidden_data" / split
281
+ n_seeds = int(os.environ.get("GRADE_SEEDS", GC.N_SEEDS))
282
+ seed0 = int(os.environ.get("GRADE_SEED_OFFSET", 0))
283
+ STAGE.mkdir(parents=True, exist_ok=True)
284
+ os.chmod(STAGE, 0o755)
285
+
286
+ submission_dir, reason = harvest_submission()
287
+ if submission_dir is None:
288
+ _write_metric({"valid": False, "reason": reason, "reward": 0.0,
289
+ "metric": None, "split": split})
290
+ print(f"INVALID SUBMISSION: {reason}")
291
+ assert False, reason
292
+
293
+ seal_filesystem()
294
+ instances = sorted(p for p in hidden.iterdir() if p.is_dir())
295
+ assert instances, f"no sealed instances under {hidden}"
296
+ jobs = [(str(p), p.name, b, str(submission_dir), n_seeds, seed0)
297
+ for p in instances for b in GC.BUDGETS]
298
+
299
+ workers = min(8, len(jobs))
300
+ with ProcessPoolExecutor(max_workers=workers) as pool:
301
+ cells = list(pool.map(grade_cell, jobs))
302
+
303
+ metric = GC.aggregate(c["ratio"] for c in cells)
304
+ reward = GC.graded_reward(metric, valid=True)
305
+ _write_metric({"valid": True, "split": split, "metric": metric, "reward": reward,
306
+ "n_seeds": n_seeds, "seed_offset": seed0,
307
+ "cells": cells})
308
+ if split != "intermediate":
309
+ for c in sorted(cells, key=lambda c: (c["instance"], c["budget"])):
310
+ print(f" {c['instance']:>16s} M={c['budget']:>3d} "
311
+ f"relative_error={c['ratio']:.4f} seeds_ok={c['n_ok']}/{c['n_seeds']}"
312
+ + (f" [{c['violation']}]" if c["violation"] else ""))
313
+ print(f"median relative risk-estimation error = {metric:.4f} "
314
+ f"over {len(cells)} cells")
315
+ assert np.isfinite(metric)
316
+
317
+
318
+ if __name__ == "__main__":
319
+ test_reward()
tasks/label-efficient-risk-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: "2700"
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: "2700"
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