Skip to content

Commit 0d3717c

Browse files
authored
Merge pull request #7770 from songoow/codex/edgebench-best-only-result-token
fix(benchmark): authenticate best-only result fetches
2 parents 70f6431 + 983a206 commit 0d3717c

3 files changed

Lines changed: 120 additions & 2 deletions

File tree

‎benchmark/edgebench/feedback.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def _official_result(self, candidate):
199199
# Fetch only the sampler-admitted, selected native submission. Do not
200200
# read raw judge logs, verifier code or another run's result directory.
201201
response = self.session.get(f"{self.judge_url}/api/v1/result/{candidate['submission_id']}",
202-
timeout=(3, 5))
202+
params={"token": self.token}, timeout=(3, 5))
203203
response.raise_for_status()
204204
result = response.json()
205205
report = result.get("report")

‎benchmark/tests/test_edgebench_feedback.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ def test_silent_baseline_then_complete_official_improvement_and_source_identity(
123123
@pytest.mark.parametrize("fault", [None, "submission", "task", "score", "pass_rate", "invalid",
124124
"pending", "error", "epoch", "evaluator", "network"])
125125
def test_official_response_binding_failure_retries_without_advancing(publisher, monkeypatch, fault):
126+
publisher.bind({"SFORGE_TOKEN": "private-token"})
126127
baseline, candidate = row(1, 1, pass_rate=.5), row(2, 3, pass_rate=.75)
127128
archive(publisher, 2)
128129
expected = official_result(candidate)
@@ -164,8 +165,9 @@ def get(url, **kwargs):
164165
packet = json.loads(transport.files[str(FEEDBACK_FILE)])["latest"]
165166
assert packet["official_result"] == expected
166167
assert calls[-2][0].endswith("/api/v1/result/s2")
167-
assert "params" not in calls[-2][1] # No credentials go into the disclosed API body.
168+
assert calls[-2][1]["params"] == {"token": "private-token"}
168169
assert calls[-1][1]["params"] == {"admin_secret": "private-secret"}
170+
assert all(secret not in json.dumps(packet) for secret in ("private-token", "private-secret"))
169171
publisher.update(values, transport, None)
170172
assert publisher.notifications == 1
171173

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""Native HTTP authorization with synthetic completed grades and worker transport."""
2+
import json
3+
import logging
4+
from types import SimpleNamespace
5+
6+
import pytest
7+
8+
pytest.importorskip("sforge")
9+
from fastapi.testclient import TestClient
10+
from requests import Response
11+
from requests.exceptions import HTTPError
12+
from sforge.harness import judge_server
13+
from sforge.harness.config import SForgeConfig
14+
from sforge.harness.grading import EvalReport
15+
16+
from benchmark.edgebench.feedback import BestOnlyFeedback, FEEDBACK_FILE
17+
from benchmark.edgebench.online_judge import create_app
18+
from benchmark.tests.test_edgebench_feedback import Admissions, Transport, archive
19+
20+
21+
@pytest.mark.parametrize("registration,status", [("run", 200), ("other-run", 404), ("invalid", 401)])
22+
def test_native_result_authorization_controls_improvement_delivery(tmp_path, monkeypatch, registration, status):
23+
tasks = tmp_path / "tasks"
24+
tasks.mkdir()
25+
(tasks / "BENCHMARK.yaml").write_text("name: fixture\nbase_images: {python: {}}\n")
26+
(tasks / "fixture.json").write_text(json.dumps({
27+
"task_id": "fixture", "name": "Synthetic feedback", "base_image": "python",
28+
"platform": "linux/arm64", "cwd": "/tmp", "internet": False,
29+
"submit_paths": ["solver.py"], "submit_exclude": [],
30+
"work": {"image_tag": "fixture", "agent_query": "Synthetic fixture"},
31+
"judge": {"image_tag": "fixture", "eval_timeout": 15, "parser": "structured_json",
32+
"selection": "score_first", "score_direction": "maximize", "eval_cmd": "true"},
33+
}))
34+
# Preserve the native result/history owners and online registration routes;
35+
# no container, grading job or model is needed for the HTTP auth contract.
36+
monkeypatch.setattr(judge_server, "create_backend_from_config",
37+
lambda config: SimpleNamespace(backend_name="docker"))
38+
app = create_app(SForgeConfig(tasks_dir=tasks, log_dir=tmp_path / "judge"),
39+
slots=2, reservation={"slots": 2})
40+
with TestClient(app) as client:
41+
state = app.state.judge
42+
tokens = {}
43+
for run_id in ("run", "other-run"):
44+
response = client.post("/api/v1/register", json={
45+
"task_id": "fixture", "run_id": run_id, "max_agent_submissions": 0,
46+
"admin_secret": state.admin_secret,
47+
})
48+
assert response.status_code == 200
49+
tokens[run_id] = response.json()["token"]
50+
51+
reports = {}
52+
for n, score in enumerate((1., 3.), 1):
53+
round_id = state.consume_round(tokens["run"], "auto")[2]
54+
submission_id = f"s{n}"
55+
report = EvalReport(task_id="fixture", submission_id=submission_id,
56+
score=score, pass_rate=1., summary="Synthetic completed grade").to_dict()
57+
state._record_submission("run", submission_id, "fixture", round_id, report, None)
58+
state.submissions[submission_id] = {
59+
"run_id": "run", "task_id": "fixture", "round": round_id,
60+
"status": "completed", "report": report, "error": None,
61+
}
62+
reports[submission_id] = report
63+
before = state.resolve_token(tokens["run"])
64+
response = client.get("/api/v1/best-only/admission", params={"admin_secret": state.admin_secret})
65+
response.raise_for_status()
66+
sampler = Admissions()
67+
sampler.epoch, sampler.evaluators = response.json()["epoch"], response.json()["evaluators"]
68+
publisher = BestOnlyFeedback(trial=tmp_path, run_id="run", task_id="fixture", direction="maximize",
69+
judge_url="http://testserver", admin_secret=state.admin_secret,
70+
logger=logging.getLogger("fixture"), sampler=sampler)
71+
publisher.bind({"SFORGE_TOKEN": tokens.get(registration, "synthetic-invalid-registration")})
72+
73+
def native_get(url, *, params=None, timeout):
74+
# Adapt requests' timeout to the in-process client; route, query
75+
# parameters, auth enforcement and result serialization stay real.
76+
# Convert the TestClient response to the production requests contract;
77+
# Starlette may use httpx2 rather than httpx under the hood.
78+
native = client.get(url, params=params)
79+
response = Response()
80+
response.status_code = native.status_code
81+
response.url = str(native.url)
82+
response._content = native.content
83+
return response
84+
85+
monkeypatch.setattr(publisher.session, "get", native_get)
86+
transport = Transport()
87+
archive(publisher, 2)
88+
response = client.get("/api/v1/history", params={
89+
"token": tokens["run"], "admin_secret": state.admin_secret,
90+
})
91+
response.raise_for_status()
92+
values = response.json()
93+
try:
94+
if status != 200:
95+
with pytest.raises(HTTPError) as failure:
96+
publisher.update(values, transport, None)
97+
assert failure.value.response.status_code == status
98+
assert not transport.files
99+
assert publisher.score == 1. and publisher.notifications == 0
100+
assert not (publisher.directory / "delivered.jsonl").exists()
101+
else:
102+
publisher.update(values, transport, None)
103+
packet = json.loads(transport.files[str(FEEDBACK_FILE)])
104+
assert packet["latest"]["snapshot_id"] == "auto-2"
105+
assert packet["latest"]["official_result"]["report"] == reports["s2"]
106+
assert transport.files[packet["latest"]["source_archive"]] == b"agent source only"
107+
assert publisher.score == 3. and publisher.notifications == 1
108+
for secret in (*tokens.values(), state.admin_secret):
109+
assert secret not in json.dumps(packet)
110+
assert secret not in (publisher.directory / "delivered.jsonl").read_text()
111+
previous = dict(transport.files)
112+
publisher.update(values, transport, None)
113+
assert transport.files == previous and publisher.notifications == 1
114+
assert state.resolve_token(tokens["run"]) == before
115+
finally:
116+
publisher.close()

0 commit comments

Comments
 (0)