File size: 6,461 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
"""Verifier: run the submitted method on every sealed instance and score it with the core's metric.

For each sealed instance, in the order tests/sealed.json lists them, the method runs once through
runner.stage_and_run (the per-run budget, the solver account, a read-only copy of the inputs), then
the core's declared metric scores what it wrote. A method failure, a timeout, a non-zero metric exit
or an unreadable score gives the floor for that instance. The score is package_common.aggregate over
the instance scores, in the metric's own units and direction -- the plain mean unless AGGREGATE is
geometric, and the self-check calls the same function so a rehearsal cannot aggregate differently
(scope "instance") -- or the one score of a call over the whole side (scope "set"). A failed
build.sh scores the floor everywhere, and so does a grader failure. tests/reward_scale.py places
this score on the reward's [0, 1] scale.
"""

from __future__ import annotations

import json
import math
import os
import shutil
import sys
import tempfile
import time
import traceback
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import package_common as pc  # noqa: E402
import runner                # noqa: E402

SUBMISSION_DIR = Path(os.environ.get("SUBMISSION_DIR", "/app/methods/main"))
SEALED_DIR = HERE / "data"
ANSWERS_DIR = HERE / "data-answers"

# The sealed side's work list. It lives here, in the grader's image alone, and not in
# package_common.py, which the solver's image also holds: the ids disclose the sealed side's
# structure. It is read as data, never imported.
_SEALED = json.loads((HERE / "sealed.json").read_text())
SEALED_IDS = tuple(_SEALED["sealed_ids"])
SEALED_ANSWER_PATHS = _SEALED["answer_paths"]


def sealed_answers(iid: str) -> Path | None:
    """{answers} of one sealed instance -- pc.answers_for, against the grader's own table."""
    rel = SEALED_ANSWER_PATHS.get(iid)
    return None if rel is None else ANSWERS_DIR / rel
LOG_DIR = Path(os.environ.get("VERIFIER_LOG_DIR", "/logs/verifier"))
REWARD_FILES = ("reward.json", "reward.txt", "score_details.json")
HEAD_CHARS = 200                  # of the first output file, quoted when an instance scores the floor


def clear_rewards() -> None:
    for name in REWARD_FILES:
        try:
            os.unlink(LOG_DIR / name)
        except FileNotFoundError:
            pass


def write_safely(name: str, text: str) -> None:
    """Write one score file: remove whatever is at the path first, and never follow a link."""
    path = LOG_DIR / name
    try:
        os.unlink(path)
    except FileNotFoundError:
        pass
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
    with os.fdopen(fd, "w") as fh:
        fh.write(text)


def write_reward(value: float, details: dict) -> None:
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    if not math.isfinite(value):
        value = pc.FLOOR
    details["reward"] = value
    write_safely("score_details.json", json.dumps(details, indent=1) + "\n")
    write_safely("reward.txt", f"{value}\n")
    write_safely("reward.json", json.dumps({"reward": value}) + "\n")


def base_details() -> dict:
    return {"metric": "score", "direction": pc.DIRECTION, "floor": pc.FLOOR, "scope": pc.SCOPE,
            "per_run_budget_sec": pc.PER_RUN_BUDGET_SEC, "instances": [], "per_instance": []}


def head(texts: dict) -> str | None:
    text = texts.get(pc.OUTPUTS[0]) if pc.OUTPUTS else None
    return None if text is None else text[:HEAD_CHARS]


def grade() -> tuple[float, dict]:
    details = base_details()
    solver = runner.solver_ids()
    ok, note = runner.build_submission(SUBMISSION_DIR, solver)
    if not ok:
        details.update(status="build_failed", note=note, n_failed=len(SEALED_IDS))
        return pc.FLOOR, details

    set_root = Path(tempfile.mkdtemp(prefix="set_outputs_")) if pc.SCOPE == "set" else None
    scores, failed = [], 0
    try:
        for iid in SEALED_IDS:
            t0 = time.time()
            status, texts = runner.stage_and_run(SUBMISSION_DIR, SEALED_DIR / iid, pc.OUTPUTS,
                                                 pc.PER_RUN_BUDGET_SEC, solver)
            row = {"id": iid, "status": status, "run_sec": round(time.time() - t0, 3)}
            if pc.SCOPE == "set":
                pc.write_outputs(texts if status == "ok" else {}, set_root / iid)
                failed += status != "ok"
            elif status == "ok":
                m = pc.score_outputs(texts, SEALED_DIR / iid, sealed_answers(iid))
                row.update(score=m["score"], metric_exit=m["exit"], metric_sec=m["metric_sec"])
                if m["status"] != "ok":
                    row.update(status=m["status"], note=m["stdout"][-500:])
                scores.append(m["score"])
            else:
                row["score"] = pc.FLOOR
                scores.append(pc.FLOOR)
            if pc.SCOPE == "instance":
                failed += row["status"] != "ok"
                if row["score"] == pc.FLOOR:
                    row["output_head"] = head(texts)
            details["per_instance"].append(row)
            details["instances"].append(iid)

        if pc.SCOPE == "set":
            m = pc.metric_call(SEALED_DIR, ANSWERS_DIR if SEALED_ANSWER_PATHS else None, set_root)
            details.update(set_metric={k: m[k] for k in ("status", "exit", "metric_sec")},
                           status="ok", n_failed=failed)
            return m["score"], details
    finally:
        if set_root is not None:
            shutil.rmtree(set_root, ignore_errors=True)

    details.update(status="ok", n_failed=failed)
    return pc.aggregate(scores), details


def main() -> int:
    LOG_DIR.mkdir(parents=True, exist_ok=True)
    clear_rewards()                              # a leftover file must not survive as this score
    try:
        reward, details = grade()
    except Exception:                            # noqa: BLE001 - fail closed
        write_reward(pc.FLOOR, {**base_details(), "status": "grader_failed",
                                "error": traceback.format_exc()})
        traceback.print_exc()
        return 1
    write_reward(reward, details)
    print(f"score {reward:.6g} ({pc.DIRECTION} is better; status {details.get('status')}, "
          f"{len(details['instances'])} instances, {details.get('n_failed')} failed)")
    return 0


if __name__ == "__main__":
    sys.exit(main())