modelsaar 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modelsaar/__init__.py +13 -0
- modelsaar/adapters/__init__.py +27 -0
- modelsaar/adapters/base.py +274 -0
- modelsaar/adapters/ollama.py +317 -0
- modelsaar/adapters/openai_compat.py +296 -0
- modelsaar/catalogue/__init__.py +72 -0
- modelsaar/catalogue/starter.yaml +435 -0
- modelsaar/cli.py +880 -0
- modelsaar/clientconfig/__init__.py +364 -0
- modelsaar/config.py +631 -0
- modelsaar/doctor.py +233 -0
- modelsaar/evaluation/__init__.py +1 -0
- modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
- modelsaar/evaluation/harness.py +768 -0
- modelsaar/evaluation/judge.py +173 -0
- modelsaar/evaluation/sandbox.py +341 -0
- modelsaar/evaluation/scoring.py +233 -0
- modelsaar/learning.py +227 -0
- modelsaar/lifecycle.py +208 -0
- modelsaar/pipelines.py +439 -0
- modelsaar/probes.py +526 -0
- modelsaar/protocol/__init__.py +1 -0
- modelsaar/protocol/anthropic.py +401 -0
- modelsaar/protocol/decisions.py +229 -0
- modelsaar/protocol/openai.py +322 -0
- modelsaar/protocol/responses.py +560 -0
- modelsaar/protocol/sse.py +181 -0
- modelsaar/registry.py +229 -0
- modelsaar/responses_store.py +117 -0
- modelsaar/routing/__init__.py +1 -0
- modelsaar/routing/admission.py +359 -0
- modelsaar/routing/affinity.py +131 -0
- modelsaar/routing/cascade.py +53 -0
- modelsaar/routing/classifier.py +298 -0
- modelsaar/routing/decision.py +85 -0
- modelsaar/routing/eligibility.py +158 -0
- modelsaar/routing/requirements.py +290 -0
- modelsaar/routing/router.py +1026 -0
- modelsaar/routing/scoring.py +179 -0
- modelsaar/routing/tokens.py +114 -0
- modelsaar/runtime.py +82 -0
- modelsaar/security.py +63 -0
- modelsaar/server.py +1546 -0
- modelsaar/static/status.html +95 -0
- modelsaar/store.py +208 -0
- modelsaar/testing/__init__.py +1 -0
- modelsaar/testing/fakebackend.py +661 -0
- modelsaar-0.2.0.dist-info/METADATA +285 -0
- modelsaar-0.2.0.dist-info/RECORD +54 -0
- modelsaar-0.2.0.dist-info/WHEEL +5 -0
- modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
- modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
- modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
- modelsaar-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Optional LLM-judge pass — separate from the evaluation harness, never merged into its scores.
|
|
2
|
+
|
|
3
|
+
``modelsaar judge`` asks one local deployment (the *judge*) to grade other deployments' answers on tasks
|
|
4
|
+
the deterministic scorers cannot grade beyond "non-empty" (conversation, free-form writing), and reports:
|
|
5
|
+
|
|
6
|
+
* **identity** of the judge: deployment id, fingerprint, model, quantization, runtime and version, and the
|
|
7
|
+
rubric revision (``JUDGE_REVISION``);
|
|
8
|
+
* **bias disclosures**: whether the judge also graded its own answers (self-preference), plus the
|
|
9
|
+
standing caveats (verbosity/style preference, sensitivity to rubric wording, no access to ground truth);
|
|
10
|
+
* **cost**: judge calls, tokens and wall time — the judge is inference like any other;
|
|
11
|
+
* **the judge's own reliability on this task set**: its agreement with the deterministic scorers on tasks
|
|
12
|
+
that *do* have executable/exact scoring. Below ``MIN_AGREEMENT`` the report says the verdicts should
|
|
13
|
+
not be used.
|
|
14
|
+
|
|
15
|
+
The harness (`harness.py`, `scoring.py`) is not modified and its reports never contain judge verdicts.
|
|
16
|
+
The judge is addressed by its explicit deployment id, never through ``auto``; it sees the task prompt and
|
|
17
|
+
the candidate's answer, which stay on the hosts the operator already allowed for those deployments.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
from .harness import MAX_TOKENS, _request_body, _wilson, dataset_revision, load_tasks
|
|
31
|
+
from .scoring import SCORER_VERSION, score
|
|
32
|
+
|
|
33
|
+
JUDGE_REVISION = "2026.12.05-1"
|
|
34
|
+
MIN_AGREEMENT = 0.8
|
|
35
|
+
RUBRIC_TYPES = frozenset({"nonempty"}) # tasks whose deterministic scorer says nothing about quality
|
|
36
|
+
_VERDICT = re.compile(r"^\s*VERDICT:\s*(PASS|FAIL)\s*$", re.MULTILINE)
|
|
37
|
+
RUBRIC = (
|
|
38
|
+
"You are grading an answer. Read the task and the answer. The answer passes only if it does what the task "
|
|
39
|
+
"asks, is correct as far as the task allows checking, and is in the language the task calls for. "
|
|
40
|
+
"Do not reward length or style. Reply with exactly one line: VERDICT: PASS or VERDICT: FAIL"
|
|
41
|
+
)
|
|
42
|
+
BIAS_NOTES = [
|
|
43
|
+
"An LLM judge is not ground truth: it can prefer fluent, long or stylistically familiar answers.",
|
|
44
|
+
"A judge grading its own model family tends to favour it (self-preference); see judge_is_candidate.",
|
|
45
|
+
"Verdicts depend on the rubric wording (JUDGE_REVISION) and on the judge's own sampling settings.",
|
|
46
|
+
"The judge's agreement with deterministic scorers is measured on different tasks than the ones it grades alone.",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _task_text(task: dict[str, Any]) -> str:
|
|
51
|
+
out = []
|
|
52
|
+
for m in task["messages"]:
|
|
53
|
+
c = m.get("content")
|
|
54
|
+
if isinstance(c, list):
|
|
55
|
+
c = " ".join(p.get("text", "") for p in c if isinstance(p, dict) and p.get("type") == "text")
|
|
56
|
+
out.append(f"[{m['role']}] {c}")
|
|
57
|
+
return "\n".join(out)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def judge_body(judge: str, task: dict[str, Any], answer: str) -> dict[str, Any]:
|
|
61
|
+
prompt = f"{RUBRIC}\n\n### Task\n{_task_text(task)}\n\n### Answer\n{answer}\n\n### Your verdict"
|
|
62
|
+
return {"model": judge, "messages": [{"role": "user", "content": prompt}], "temperature": 0, "max_tokens": 1024}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_verdict(text: str) -> bool | None:
|
|
66
|
+
found = _VERDICT.findall(re.sub(r"<think>.*?</think>", "", text or "", flags=re.DOTALL))
|
|
67
|
+
return (found[0] == "PASS") if len(found) == 1 else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def run_judge(
|
|
71
|
+
gateway_url: str, api_key: str, admin_key: str, judge: str, candidates: list[str], tasks: list[dict[str, Any]],
|
|
72
|
+
simulated: bool = False, calibration_per_category: int = 2,
|
|
73
|
+
) -> dict[str, Any]: # fmt: skip
|
|
74
|
+
api = httpx.Client(base_url=gateway_url, headers={"Authorization": f"Bearer {api_key}"}, timeout=900)
|
|
75
|
+
admin = httpx.Client(base_url=gateway_url, headers={"Authorization": f"Bearer {admin_key}"}, timeout=30)
|
|
76
|
+
deps = {d["id"]: d for d in admin.get("/admin/status").json()["deployments"]}
|
|
77
|
+
for d in [judge, *candidates]:
|
|
78
|
+
if d not in deps or deps[d]["role"] != "generative":
|
|
79
|
+
raise SystemExit(f"{d!r} is not a generative deployment id of this gateway (aliases such as 'auto' are not accepted for a judge run)")
|
|
80
|
+
rubric = [t for t in tasks if t["expected"]["type"] in RUBRIC_TYPES and not t.get("tools")]
|
|
81
|
+
seen: dict[str, int] = {}
|
|
82
|
+
calib = []
|
|
83
|
+
for t in tasks:
|
|
84
|
+
if t["expected"]["type"] in RUBRIC_TYPES or t["expected"]["type"] in ("code_exec", "tool_call") or t.get("tools"):
|
|
85
|
+
continue # calibration needs text answers with exact/number/schema scoring
|
|
86
|
+
if seen.get(t["category"], 0) < calibration_per_category:
|
|
87
|
+
seen[t["category"]] = seen.get(t["category"], 0) + 1
|
|
88
|
+
calib.append(t)
|
|
89
|
+
cost = {"judge_calls": 0, "judge_prompt_tokens": 0, "judge_completion_tokens": 0, "judge_ms": 0.0, "candidate_calls": 0, "unparseable": 0}
|
|
90
|
+
records: list[dict[str, Any]] = []
|
|
91
|
+
|
|
92
|
+
def ask_judge(task: dict[str, Any], answer: str) -> bool | None:
|
|
93
|
+
t0 = time.monotonic()
|
|
94
|
+
r = api.post("/v1/chat/completions", json=judge_body(judge, task, answer))
|
|
95
|
+
cost["judge_calls"] += 1
|
|
96
|
+
cost["judge_ms"] += (time.monotonic() - t0) * 1000
|
|
97
|
+
if r.status_code != 200:
|
|
98
|
+
cost["unparseable"] += 1
|
|
99
|
+
return None
|
|
100
|
+
u = r.json().get("usage") or {}
|
|
101
|
+
cost["judge_prompt_tokens"] += int(u.get("prompt_tokens") or 0)
|
|
102
|
+
cost["judge_completion_tokens"] += int(u.get("completion_tokens") or 0)
|
|
103
|
+
v = parse_verdict(str(r.json()["choices"][0]["message"].get("content") or ""))
|
|
104
|
+
if v is None:
|
|
105
|
+
cost["unparseable"] += 1
|
|
106
|
+
return v
|
|
107
|
+
|
|
108
|
+
for cand in candidates:
|
|
109
|
+
for kind, subset in (("rubric", rubric), ("calibration", calib)):
|
|
110
|
+
for task in subset:
|
|
111
|
+
r = api.post("/v1/chat/completions", json=_request_body(task, cand, simulated))
|
|
112
|
+
cost["candidate_calls"] += 1
|
|
113
|
+
rec: dict[str, Any] = {"task": task["id"], "category": task["category"], "candidate": cand, "set": kind, "http": r.status_code}
|
|
114
|
+
if r.status_code == 200:
|
|
115
|
+
det, _ = score(task, r.json())
|
|
116
|
+
answer = str(r.json()["choices"][0]["message"].get("content") or "")
|
|
117
|
+
rec["deterministic"] = det
|
|
118
|
+
rec["judge"] = ask_judge(task, answer) if answer.strip() else False
|
|
119
|
+
records.append(rec)
|
|
120
|
+
|
|
121
|
+
def rate(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|
122
|
+
judged = [x for x in rows if x.get("judge") is not None]
|
|
123
|
+
k = sum(1 for x in judged if x["judge"])
|
|
124
|
+
lo, hi = _wilson(k, len(judged)) if judged else (0.0, 0.0)
|
|
125
|
+
return {"judged": len(judged), "passed": k, "pass_rate": round(k / len(judged), 3) if judged else None, "ci95": [round(lo, 3), round(hi, 3)]}
|
|
126
|
+
|
|
127
|
+
cal = [x for x in records if x["set"] == "calibration" and x.get("judge") is not None and x.get("deterministic") is not None]
|
|
128
|
+
agree = sum(1 for x in cal if x["judge"] == x["deterministic"])
|
|
129
|
+
agreement = round(agree / len(cal), 3) if cal else None
|
|
130
|
+
jd = deps[judge]
|
|
131
|
+
return {
|
|
132
|
+
"kind": "llm_judge_report",
|
|
133
|
+
"note": "Separate from `modelsaar eval`: judge verdicts are not task-success measurements and are never merged into evaluation reports or routing evidence.",
|
|
134
|
+
"judge": {
|
|
135
|
+
"deployment": judge, "fingerprint": jd.get("fingerprint"), "model": jd.get("model"), "quantization": jd.get("quantization"),
|
|
136
|
+
"runtime": (jd.get("fingerprint_inputs") or {}).get("runtime"), "identity": (jd.get("fingerprint_inputs") or {}).get("identity"),
|
|
137
|
+
"rubric_revision": JUDGE_REVISION, "rubric": RUBRIC,
|
|
138
|
+
"temperature": 0,
|
|
139
|
+
}, # fmt: skip
|
|
140
|
+
"conditions": {"simulated": simulated, "scorer_version": SCORER_VERSION, "candidate_max_tokens": MAX_TOKENS, "tasks_rubric": len(rubric), "tasks_calibration": len(calib), "created_at": time.time()},
|
|
141
|
+
"bias": {"judge_is_candidate": judge in candidates, "notes": BIAS_NOTES},
|
|
142
|
+
"cost": {**cost, "judge_ms": round(cost["judge_ms"])},
|
|
143
|
+
"judge_reliability": {
|
|
144
|
+
"agreement_with_deterministic_scorers": agreement, "calibration_pairs": len(cal), "min_agreement": MIN_AGREEMENT,
|
|
145
|
+
"usable": bool(cal) and agreement is not None and agreement >= MIN_AGREEMENT,
|
|
146
|
+
"reading": "usable only as a rough signal" if cal and agreement is not None and agreement >= MIN_AGREEMENT else "do not use these verdicts: the judge disagrees with exact scoring too often on this task set (or no calibration pairs exist)",
|
|
147
|
+
}, # fmt: skip
|
|
148
|
+
"candidates": {c: {"rubric_tasks": rate([x for x in records if x["candidate"] == c and x["set"] == "rubric"]), "self_judged": c == judge} for c in candidates},
|
|
149
|
+
"records": records,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def run_judge_cli(args) -> None: # type: ignore[no-untyped-def]
|
|
154
|
+
from ..config import default_config_path, load_config, read_keys
|
|
155
|
+
|
|
156
|
+
cfg = load_config(Path(args.config) if getattr(args, "config", None) else default_config_path())
|
|
157
|
+
tasks_path = Path(args.tasks) if args.tasks else None
|
|
158
|
+
tasks = load_tasks(tasks_path, args.limit)
|
|
159
|
+
rep = run_judge(
|
|
160
|
+
f"http://{cfg.server.host}:{cfg.server.port}", read_keys(cfg.resolve(cfg.server.api_keys_file))[0], read_keys(cfg.resolve(cfg.server.admin_key_file))[0],
|
|
161
|
+
args.judge, args.candidates, tasks,
|
|
162
|
+
) # fmt: skip
|
|
163
|
+
rep["conditions"].update(dataset_revision(tasks, tasks_path))
|
|
164
|
+
rel = rep["judge_reliability"]
|
|
165
|
+
print(f"judge {rep['judge']['deployment']} (rubric {JUDGE_REVISION}); self-judging: {rep['bias']['judge_is_candidate']}")
|
|
166
|
+
print(f"agreement with deterministic scorers: {rel['agreement_with_deterministic_scorers']} on {rel['calibration_pairs']} pairs -> {rel['reading']}")
|
|
167
|
+
for c, v in rep["candidates"].items():
|
|
168
|
+
r = v["rubric_tasks"]
|
|
169
|
+
print(f" {c:40s} judge pass {r['passed']}/{r['judged']} ci95={r['ci95']}{' (self-judged)' if v['self_judged'] else ''}")
|
|
170
|
+
print(f"cost: {rep['cost']}")
|
|
171
|
+
if args.out:
|
|
172
|
+
Path(args.out).write_text(json.dumps(rep, indent=2), encoding="utf-8")
|
|
173
|
+
print(f"report written to {args.out}")
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
"""Isolation backends for executing model-written code during evaluation.
|
|
2
|
+
|
|
3
|
+
The evaluator never runs generated code with ordinary host authority. Exactly one of these
|
|
4
|
+
backends is used, detected in this order:
|
|
5
|
+
|
|
6
|
+
1. ``bwrap`` (bubblewrap, Linux): new user/pid/net/ipc/uts namespaces; **only** the Python
|
|
7
|
+
runtime and the system library directories are bound read-only (input allowlist, see
|
|
8
|
+
``_bwrap_read_roots``), a private tmpfs ``/tmp``, the work directory bound at ``/tmp/work``.
|
|
9
|
+
The rest of the host filesystem does not exist inside the sandbox.
|
|
10
|
+
2. ``sandbox-exec`` (macOS): deny-by-default profile; reads allowed for the Python runtime, system
|
|
11
|
+
libraries/frameworks and the work directory; writes only under the work directory (and
|
|
12
|
+
``/dev``); no network. Host files outside those roots are not readable. **Alpha status:
|
|
13
|
+
unsupported pending verification** — the profile has not been executed on macOS, so the backend
|
|
14
|
+
is disabled unless ``MODELSAAR_MACOS_SANDBOX=verify`` is set (the owner's verification run);
|
|
15
|
+
without it ``code_exec`` tasks are skipped on macOS and the report says why.
|
|
16
|
+
3. Docker: ``--network none --read-only --tmpfs /tmp -m 512m --pids-limit 64`` with the
|
|
17
|
+
work directory mounted read-only at ``/work`` (image ``python:3.12-slim``); the container
|
|
18
|
+
sees no host path other than that directory.
|
|
19
|
+
|
|
20
|
+
In all cases: wall-clock timeout, CPU/address-space/file-size rlimits (host side for bwrap and
|
|
21
|
+
sandbox-exec, ``--ulimit``/``-m`` for Docker) and a hard cap on captured output. Completion is
|
|
22
|
+
evidenced by the trusted runner's nonce-keyed result record (``_program``), not by text the model
|
|
23
|
+
code prints. What the sandbox does NOT provide: protection against model code that targets the
|
|
24
|
+
evaluator process itself (same interpreter), or against resource use below the rlimits.
|
|
25
|
+
|
|
26
|
+
When no backend is available ``code_exec`` tasks are *skipped* (reported with their own
|
|
27
|
+
denominator); there is deliberately no unsandboxed fallback and no opt-in flag for one.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import functools
|
|
33
|
+
import json
|
|
34
|
+
import os
|
|
35
|
+
import secrets
|
|
36
|
+
import shutil
|
|
37
|
+
import subprocess
|
|
38
|
+
import sys
|
|
39
|
+
import tempfile
|
|
40
|
+
import uuid
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
SENTINEL = "__MODELSAAR_HARNESS_OK__" # former public completion marker; printing it proves nothing (see _program)
|
|
44
|
+
DOCKER_IMAGE = "python:3.12-slim"
|
|
45
|
+
BWRAP_WORK = "/tmp/work" # inside the sandbox; everything else is read-only or a private tmpfs
|
|
46
|
+
NO_BACKEND_REASON = "no isolation backend (install bubblewrap on Linux; macOS sandbox-exec; or Docker)"
|
|
47
|
+
MACOS_SANDBOX_ENV = "MODELSAAR_MACOS_SANDBOX" # "verify" enables the macOS backend (unsupported in the alpha otherwise)
|
|
48
|
+
|
|
49
|
+
MEMORY_BYTES = 512 * 1024 * 1024
|
|
50
|
+
OUTPUT_CAP_BYTES = 1024 * 1024 # kernel-enforced via RLIMIT_FSIZE on the capture files
|
|
51
|
+
STDOUT_KEEP = 64 * 1024 # bytes of stdout handed back to the scorer
|
|
52
|
+
STDERR_KEEP = 1000 # trailing characters of stderr handed back
|
|
53
|
+
PIDS_LIMIT = 64
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _probe(cmd: list[str], timeout: float = 10.0) -> tuple[bool, str]:
|
|
57
|
+
try:
|
|
58
|
+
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
59
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
60
|
+
return False, str(e)[:120]
|
|
61
|
+
if p.returncode != 0:
|
|
62
|
+
return False, (p.stderr or p.stdout).strip()[-120:]
|
|
63
|
+
return True, ""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@functools.lru_cache(maxsize=1)
|
|
67
|
+
def available() -> tuple[str | None, str]:
|
|
68
|
+
"""Return ``(backend_name, reason)``; ``backend_name`` is None when nothing usable exists.
|
|
69
|
+
|
|
70
|
+
The result is cached for the process (``available.cache_clear()`` resets it).
|
|
71
|
+
"""
|
|
72
|
+
notes: list[str] = []
|
|
73
|
+
if sys.platform.startswith("linux"):
|
|
74
|
+
bw = shutil.which("bwrap")
|
|
75
|
+
if bw:
|
|
76
|
+
true = shutil.which("true") or "/bin/true"
|
|
77
|
+
ok, why = _probe([bw, "--unshare-all", "--die-with-parent", "--ro-bind", "/usr", "/usr", "--ro-bind-try", "/lib", "/lib", "--ro-bind-try", "/lib64", "/lib64", "--ro-bind-try", "/bin", "/bin", "--tmpfs", "/tmp", "--", true])
|
|
78
|
+
if ok:
|
|
79
|
+
return "bwrap", f"bubblewrap at {bw}"
|
|
80
|
+
notes.append(f"bwrap present but unusable: {why}")
|
|
81
|
+
else:
|
|
82
|
+
notes.append("bwrap not installed")
|
|
83
|
+
if sys.platform == "darwin":
|
|
84
|
+
se = shutil.which("sandbox-exec")
|
|
85
|
+
if se and os.environ.get(MACOS_SANDBOX_ENV) == "verify":
|
|
86
|
+
return "sandbox-exec", f"macOS sandbox-exec at {se} ({MACOS_SANDBOX_ENV}=verify)"
|
|
87
|
+
if se:
|
|
88
|
+
# Alpha scope: the deny-by-default profile has not been executed on macOS yet, so the
|
|
89
|
+
# path is disabled and code_exec tasks are skipped there (reported as such). Setting
|
|
90
|
+
# MODELSAAR_MACOS_SANDBOX=verify enables it for the verification run only.
|
|
91
|
+
notes.append(f"macOS sandbox-exec is unsupported in this alpha pending verification (set {MACOS_SANDBOX_ENV}=verify to run the verification tests)")
|
|
92
|
+
else:
|
|
93
|
+
notes.append("sandbox-exec not found")
|
|
94
|
+
dk = shutil.which("docker")
|
|
95
|
+
if dk:
|
|
96
|
+
ok, why = _probe([dk, "info"], timeout=15.0)
|
|
97
|
+
if ok:
|
|
98
|
+
ok2, why2 = _probe([dk, "image", "inspect", DOCKER_IMAGE], timeout=15.0)
|
|
99
|
+
if ok2:
|
|
100
|
+
return "docker", f"docker at {dk} (image {DOCKER_IMAGE})"
|
|
101
|
+
notes.append(f"docker daemon reachable but image {DOCKER_IMAGE} is not pulled (run: docker pull {DOCKER_IMAGE})")
|
|
102
|
+
else:
|
|
103
|
+
notes.append(f"docker present but daemon not reachable: {why}")
|
|
104
|
+
else:
|
|
105
|
+
notes.append("docker not installed")
|
|
106
|
+
return None, NO_BACKEND_REASON + ("; " + "; ".join(notes) if notes else "")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _rlimits(timeout_s: float): # type: ignore[no-untyped-def]
|
|
110
|
+
"""preexec_fn applying host-side resource limits (inherited by the sandboxed process)."""
|
|
111
|
+
import resource
|
|
112
|
+
|
|
113
|
+
cpu = int(timeout_s) + 1
|
|
114
|
+
|
|
115
|
+
def _apply() -> None:
|
|
116
|
+
for res, val in (
|
|
117
|
+
(resource.RLIMIT_CPU, cpu),
|
|
118
|
+
(resource.RLIMIT_FSIZE, OUTPUT_CAP_BYTES),
|
|
119
|
+
(resource.RLIMIT_AS, MEMORY_BYTES),
|
|
120
|
+
(resource.RLIMIT_CORE, 0),
|
|
121
|
+
):
|
|
122
|
+
try:
|
|
123
|
+
resource.setrlimit(res, (val, val))
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
|
|
127
|
+
return _apply
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
RESULT_BEGIN = "__MODELSAAR_RESULT_BEGIN__"
|
|
131
|
+
RESULT_END = "__MODELSAAR_RESULT_END__"
|
|
132
|
+
|
|
133
|
+
_RUNNER = r'''
|
|
134
|
+
import io as __ms_io, json as __ms_json, sys as __ms_sys
|
|
135
|
+
# The nonce arrives on stdin from the evaluator and is never written to disk or the environment;
|
|
136
|
+
# stdin is closed before any model code runs.
|
|
137
|
+
try:
|
|
138
|
+
__ms_nonce = "" if (__ms_sys.stdin is None or __ms_sys.stdin.isatty()) else __ms_sys.stdin.readline().strip()
|
|
139
|
+
except Exception:
|
|
140
|
+
__ms_nonce = ""
|
|
141
|
+
try:
|
|
142
|
+
__ms_sys.stdin.close()
|
|
143
|
+
except Exception:
|
|
144
|
+
pass
|
|
145
|
+
__ms_real_stdout = __ms_sys.stdout
|
|
146
|
+
__ms_record = {"nonce": __ms_nonce, "model_ran": False, "harness_completed": False, "harness_stdout": "", "error": None}
|
|
147
|
+
__ms_model_out = __ms_io.StringIO()
|
|
148
|
+
__ms_sys.stdout = __ms_model_out # model-controlled output is captured, never counted as harness output
|
|
149
|
+
try:
|
|
150
|
+
exec(compile(__MS_MODEL_CODE__, "model.py", "exec"), globals())
|
|
151
|
+
__ms_record["model_ran"] = True
|
|
152
|
+
except BaseException as __ms_e: # noqa: BLE001 - the record must say why the harness never ran
|
|
153
|
+
__ms_record["error"] = "model code raised " + __ms_e.__class__.__name__ + ": " + str(__ms_e)[:200]
|
|
154
|
+
__ms_sys.stdout = __ms_real_stdout
|
|
155
|
+
__ms_record["model_stdout_chars"] = len(__ms_model_out.getvalue())
|
|
156
|
+
if __ms_record["model_ran"]:
|
|
157
|
+
__ms_harness_out = __ms_io.StringIO()
|
|
158
|
+
__ms_sys.stdout = __ms_harness_out
|
|
159
|
+
try:
|
|
160
|
+
exec(compile(__MS_HARNESS_CODE__, "harness.py", "exec"), globals())
|
|
161
|
+
__ms_record["harness_completed"] = True
|
|
162
|
+
except BaseException as __ms_e: # noqa: BLE001
|
|
163
|
+
__ms_record["error"] = "harness raised " + __ms_e.__class__.__name__ + ": " + str(__ms_e)[:200]
|
|
164
|
+
__ms_sys.stdout = __ms_real_stdout
|
|
165
|
+
__ms_record["harness_stdout"] = __ms_harness_out.getvalue()[:65536]
|
|
166
|
+
__ms_real_stdout.write("\n" + __MS_BEGIN__ + "\n" + __ms_json.dumps(__ms_record) + "\n" + __MS_END__ + "\n")
|
|
167
|
+
__ms_real_stdout.flush()
|
|
168
|
+
'''
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _program(code: str, harness: str) -> str:
|
|
172
|
+
"""The trusted runner: it reads a per-run nonce from stdin, executes the model code with its
|
|
173
|
+
stdout captured, then executes the task harness (trusted, task-authored) with *its* stdout
|
|
174
|
+
captured separately, and finally writes a result record framed by RESULT_BEGIN/RESULT_END and
|
|
175
|
+
keyed with the nonce. The scorer accepts a task only from that record: the harness's own output
|
|
176
|
+
(the externally checked behaviour) must match the expectation and ``harness_completed`` must be
|
|
177
|
+
true. Model code that prints the expected text or the public sentinel, exits early (``sys.exit``,
|
|
178
|
+
``os._exit``) or raises therefore never scores: there is no record, or the record says the
|
|
179
|
+
harness did not complete.
|
|
180
|
+
|
|
181
|
+
Limit (documented): everything runs in one interpreter, so model code that deliberately
|
|
182
|
+
inspects the runner's frames could recover the nonce; the protocol defeats marker echo and
|
|
183
|
+
early exit, not an adversary targeting the evaluator itself."""
|
|
184
|
+
return (
|
|
185
|
+
_RUNNER.replace("__MS_MODEL_CODE__", repr(code))
|
|
186
|
+
.replace("__MS_HARNESS_CODE__", repr(harness))
|
|
187
|
+
.replace("__MS_BEGIN__", repr(RESULT_BEGIN))
|
|
188
|
+
.replace("__MS_END__", repr(RESULT_END))
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def parse_result(stdout: str, nonce: str) -> dict | None:
|
|
193
|
+
"""Return the runner's result record when the framed record carries ``nonce``; else None."""
|
|
194
|
+
start = stdout.rfind(RESULT_BEGIN)
|
|
195
|
+
if start == -1:
|
|
196
|
+
return None
|
|
197
|
+
end = stdout.find(RESULT_END, start)
|
|
198
|
+
if end == -1:
|
|
199
|
+
return None
|
|
200
|
+
body = stdout[start + len(RESULT_BEGIN):end].strip()
|
|
201
|
+
try:
|
|
202
|
+
rec = json.loads(body)
|
|
203
|
+
except ValueError:
|
|
204
|
+
return None
|
|
205
|
+
if not isinstance(rec, dict) or rec.get("nonce") != nonce:
|
|
206
|
+
return None
|
|
207
|
+
return rec
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _runtime_read_roots() -> list[str]:
|
|
211
|
+
"""Paths the interpreter needs readable: the Python installation (prefix/base_prefix, the
|
|
212
|
+
executable's real location) and the system libraries. The user's files are not among them."""
|
|
213
|
+
roots = {os.path.realpath(sys.prefix), os.path.realpath(sys.base_prefix), os.path.realpath(sys.exec_prefix)}
|
|
214
|
+
exe = os.path.realpath(sys.executable)
|
|
215
|
+
roots.add(os.path.dirname(os.path.dirname(exe)))
|
|
216
|
+
return sorted(roots)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _macos_profile(workdir: str) -> str:
|
|
220
|
+
"""Deny by default. Allowed: process basics, reads of the Python runtime, system libraries and
|
|
221
|
+
frameworks, the work directory; writes only under the work directory and /dev; no network.
|
|
222
|
+
Host files outside those roots (the user's home, other projects) are not readable."""
|
|
223
|
+
reads = "".join(f' (subpath "{r}")\n' for r in _runtime_read_roots())
|
|
224
|
+
return (
|
|
225
|
+
"(version 1)\n"
|
|
226
|
+
"(deny default)\n"
|
|
227
|
+
"(allow process*)\n"
|
|
228
|
+
"(allow sysctl-read)\n"
|
|
229
|
+
"(allow mach-lookup)\n"
|
|
230
|
+
"(allow signal (target self))\n"
|
|
231
|
+
'(allow file-read* (literal "/") (literal "/dev/null") (literal "/dev/urandom") (literal "/dev/random") (literal "/dev/zero") (literal "/dev/tty"))\n'
|
|
232
|
+
'(allow file-read-metadata)\n'
|
|
233
|
+
'(allow file-read* (subpath "/usr/lib") (subpath "/usr/share") (subpath "/System") (subpath "/Library/Frameworks")\n'
|
|
234
|
+
' (subpath "/Library/Apple") (subpath "/opt/homebrew") (subpath "/usr/local") (subpath "/private/etc") (subpath "/etc")\n'
|
|
235
|
+
' (subpath "/private/var/db") (subpath "/var/db") (subpath "/Library/Preferences") (subpath "/private/var/select")\n'
|
|
236
|
+
' (subpath "/usr/bin") (subpath "/bin") (subpath "/usr/sbin") (subpath "/sbin"))\n'
|
|
237
|
+
f"(allow file-read* (subpath \"{workdir}\")\n{reads})\n"
|
|
238
|
+
f'(allow file-write* (subpath "{workdir}") (subpath "/dev"))\n'
|
|
239
|
+
"(allow file-ioctl (subpath \"/dev\"))\n"
|
|
240
|
+
"(deny network*)\n"
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _bwrap_read_roots() -> list[str]:
|
|
245
|
+
"""Directories bound read-only into the bubblewrap sandbox: shared libraries, the Python
|
|
246
|
+
installation (and the venv's base) and the directories ``sys.executable`` lives in."""
|
|
247
|
+
roots = {"/usr/lib", "/usr/lib64", "/lib", "/lib64", "/usr/local/lib", "/etc/ld.so.cache", "/etc/alternatives"}
|
|
248
|
+
roots |= set(_runtime_read_roots())
|
|
249
|
+
exe = os.path.realpath(sys.executable)
|
|
250
|
+
roots.add(os.path.dirname(exe))
|
|
251
|
+
return sorted(roots)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _command(backend: str, workdir: str, capdir: str, name: str, timeout_s: float) -> list[str]:
|
|
255
|
+
py = sys.executable
|
|
256
|
+
if backend == "bwrap":
|
|
257
|
+
# Input allowlist: only the Python runtime and the system library directories are bound
|
|
258
|
+
# (read-only). The rest of the host filesystem does not exist inside the sandbox.
|
|
259
|
+
# Order matters: the private /tmp first, then the read-only runtime roots (so a Python
|
|
260
|
+
# installation that itself lives under /tmp is still visible), then the work directory.
|
|
261
|
+
binds: list[str] = []
|
|
262
|
+
for r in _bwrap_read_roots():
|
|
263
|
+
binds += ["--ro-bind-try", r, r]
|
|
264
|
+
return [
|
|
265
|
+
"bwrap", "--unshare-all", "--die-with-parent",
|
|
266
|
+
"--tmpfs", "/tmp",
|
|
267
|
+
*binds,
|
|
268
|
+
"--bind", workdir, BWRAP_WORK,
|
|
269
|
+
"--chdir", BWRAP_WORK,
|
|
270
|
+
"--dev", "/dev", "--proc", "/proc",
|
|
271
|
+
"--new-session",
|
|
272
|
+
"--", py, "-I", "-B", f"{BWRAP_WORK}/prog.py",
|
|
273
|
+
]
|
|
274
|
+
if backend == "sandbox-exec":
|
|
275
|
+
prof = Path(capdir) / "profile.sb"
|
|
276
|
+
prof.write_text(_macos_profile(workdir), encoding="utf-8")
|
|
277
|
+
return ["sandbox-exec", "-f", str(prof), py, "-I", "-B", os.path.join(workdir, "prog.py")]
|
|
278
|
+
if backend == "docker":
|
|
279
|
+
return [
|
|
280
|
+
"docker", "run", "--rm", "-i", "--name", name,
|
|
281
|
+
"--network", "none", "--read-only", "--tmpfs", "/tmp",
|
|
282
|
+
"-m", "512m", "--pids-limit", str(PIDS_LIMIT),
|
|
283
|
+
"--ulimit", f"cpu={int(timeout_s) + 1}", "--ulimit", f"fsize={OUTPUT_CAP_BYTES}",
|
|
284
|
+
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
|
|
285
|
+
"-v", f"{workdir}:/work:ro", "-w", "/work",
|
|
286
|
+
"-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "HOME=/tmp", "-e", "TMPDIR=/tmp",
|
|
287
|
+
DOCKER_IMAGE, "python", "-I", "-B", "/work/prog.py",
|
|
288
|
+
]
|
|
289
|
+
raise ValueError(f"unknown sandbox backend {backend!r}")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def run(code: str, harness: str, timeout_s: float = 10.0) -> tuple[str, str, int, str]:
|
|
293
|
+
"""Execute ``code`` + ``harness`` in the detected sandbox.
|
|
294
|
+
|
|
295
|
+
Returns ``(stdout, stderr, returncode, backend)``; ``stdout`` carries the runner's framed result
|
|
296
|
+
record (see :func:`_program`), which the scorer extracts with :func:`parse_result` using the
|
|
297
|
+
nonce stored in ``run.last_nonce``. Raises ``RuntimeError`` when no backend is available
|
|
298
|
+
(callers must check :func:`available` and skip; there is no unsandboxed path).
|
|
299
|
+
``returncode`` is 124 on wall-clock timeout.
|
|
300
|
+
"""
|
|
301
|
+
backend, reason = available()
|
|
302
|
+
if backend is None:
|
|
303
|
+
raise RuntimeError(reason)
|
|
304
|
+
nonce = secrets.token_hex(16)
|
|
305
|
+
run.last_nonce = nonce # type: ignore[attr-defined]
|
|
306
|
+
with tempfile.TemporaryDirectory(prefix="modelsaar-eval-work-") as work, tempfile.TemporaryDirectory(prefix="modelsaar-eval-cap-") as cap:
|
|
307
|
+
workdir = os.path.realpath(work) # macOS: /var -> /private/var for the sandbox profile
|
|
308
|
+
Path(workdir, "prog.py").write_text(_program(code, harness), encoding="utf-8")
|
|
309
|
+
if backend == "docker":
|
|
310
|
+
os.chmod(workdir, 0o755)
|
|
311
|
+
os.chmod(os.path.join(workdir, "prog.py"), 0o644)
|
|
312
|
+
name = f"modelsaar-eval-{uuid.uuid4().hex[:12]}"
|
|
313
|
+
cmd = _command(backend, workdir, cap, name, timeout_s)
|
|
314
|
+
env = {
|
|
315
|
+
"PATH": os.environ.get("PATH", ""),
|
|
316
|
+
"PYTHONDONTWRITEBYTECODE": "1",
|
|
317
|
+
"PYTHONIOENCODING": "utf-8",
|
|
318
|
+
"HOME": BWRAP_WORK if backend == "bwrap" else workdir,
|
|
319
|
+
"TMPDIR": "/tmp" if backend == "bwrap" else workdir,
|
|
320
|
+
"LANG": "C.UTF-8",
|
|
321
|
+
}
|
|
322
|
+
if backend == "docker":
|
|
323
|
+
env = dict(os.environ) # the docker CLI needs its own context/config; isolation is the container's job
|
|
324
|
+
out_path, err_path = Path(cap, "stdout"), Path(cap, "stderr")
|
|
325
|
+
rc = 124
|
|
326
|
+
with open(out_path, "wb") as fo, open(err_path, "wb") as fe:
|
|
327
|
+
try:
|
|
328
|
+
p = subprocess.run(
|
|
329
|
+
cmd, input=(nonce + "\n").encode(), stdout=fo, stderr=fe, timeout=timeout_s, cwd=cap, env=env,
|
|
330
|
+
preexec_fn=_rlimits(timeout_s) if backend != "docker" and sys.platform != "win32" else None,
|
|
331
|
+
)
|
|
332
|
+
rc = p.returncode
|
|
333
|
+
except subprocess.TimeoutExpired:
|
|
334
|
+
if backend == "docker":
|
|
335
|
+
subprocess.run(["docker", "kill", name], capture_output=True, timeout=15)
|
|
336
|
+
rc = 124
|
|
337
|
+
stdout = out_path.read_bytes()[:STDOUT_KEEP].decode("utf-8", "replace")
|
|
338
|
+
stderr = err_path.read_bytes()[-4096:].decode("utf-8", "replace")[-STDERR_KEEP:]
|
|
339
|
+
if rc == 124:
|
|
340
|
+
stderr = (stderr + "\ntimeout").strip()
|
|
341
|
+
return stdout, stderr, rc, backend
|