|
| 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