File size: 13,588 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
"""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.
Scope "set" also scores each instance alone with the same metric, onto its row: a diagnostic
that the score never reads (score_details.json says so in per_instance_scores).
"""

from __future__ import annotations

import functools
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
    if text is None:
        return None
    return text[:HEAD_CHARS].decode("utf-8", "replace") if isinstance(text, bytes) else text[:HEAD_CHARS]


DIAGNOSTIC = ("diagnostic: each instance scored alone with the same metric; the reward is the one "
              "call over the whole side (set_metric)")


def score_alone(rows: list, set_root: Path) -> None:
    """Scope "set": each row's score is the metric over that instance alone, a diagnostic.

    The call is laid out as the call over the whole side is, holding only this instance's `<id>/`:
    copies of its inputs, its answers and its output. A failed run's row takes the floor, and so
    does a call that fails, with the metric's status. Nothing here can change the reward: the
    reward is written before this runs, and an error leaves the row at the floor.
    """
    for row in rows:
        iid = row["id"]
        if row["status"] != "ok":
            row["score"] = pc.FLOOR
            continue
        one = None
        try:
            one = Path(tempfile.mkdtemp(prefix="one_instance_"))
            shutil.copytree(SEALED_DIR / iid, one / "instance" / iid, symlinks=True)
            answers = one / "answers" if SEALED_ANSWER_PATHS else None
            if answers is not None:
                answers.mkdir()
                if (ANSWERS_DIR / iid).is_dir():
                    shutil.copytree(ANSWERS_DIR / iid, answers / iid, symlinks=True)
            shutil.copytree(set_root / iid, one / "output" / iid)
            m = pc.metric_call(one / "instance", answers, one / "output")
            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:])
        except Exception as e:                   # noqa: BLE001 - a diagnostic never costs the reward
            row.update(score=pc.FLOOR, status="metric_failed", note=f"not scored alone: {e}"[:500])
        finally:
            if one is not None:
                shutil.rmtree(one, ignore_errors=True)


CAPS_FILE = HERE / "caps.json"


def sealed_caps() -> dict:
    """{sealed id: seconds}, each at most the per-run budget; {} when the package has no caps.json.

    The file sits beside sealed.json and, like it, is root's alone: a cap is computed from its
    instance, so the list belongs to the sealed side. A malformed file raises, and grading fails
    closed (main) rather than give an instance more time than the round did."""
    if not CAPS_FILE.is_file():
        return {}
    caps = json.loads(CAPS_FILE.read_text())
    if not isinstance(caps, dict):
        raise ValueError(f"caps.json holds a {type(caps).__name__}, not {{id: seconds}}")
    out = {}
    for iid, sec in caps.items():
        if isinstance(sec, bool) or not isinstance(sec, (int, float)) or not math.isfinite(sec) or sec <= 0:
            raise ValueError(f"caps.json gives {iid!r} {sec!r}, not a positive number of seconds")
        out[str(iid)] = min(float(sec), float(pc.PER_RUN_BUDGET_SEC))
    return out


def capped(run_one, caps: dict):
    """runner.stage_and_run (run_one), passing each sealed instance its own cap in place of the
    per-run budget: caps.get(iid, budget), the instance known by its directory under data/. grade()
    binds it for this process before its loop, so the loop itself stays the one every package runs
    (and C2 still reads the budget that loop passes)."""
    by_dir = {str(SEALED_DIR / iid): sec for iid, sec in caps.items()}

    def run(submission_dir, data_dir, outputs, budget_sec, *rest):
        return run_one(submission_dir, data_dir, outputs, by_dir.get(str(data_dir), budget_sec), *rest)
    return run


def in_waves(run_one, cpus: list, timing: dict):
    """Single-core timing: runner.stage_and_run (run_one) for the loop in grade(). Its first call makes the
    method directory read-only and runs every sealed instance, len(cpus) at once, instance i on cpus[i %
    len(cpus)], wave after wave (runner.run_wave); each call then hands back its own instance's run, and
    that run's run.sh seconds as runner.LAST_RUN_SEC. So the loop scores the runs one by one, in id order,
    as it scores runs made one at a time.

    Returns (that function, the list grade() appends its rows to): a row appended there takes its own run's
    wall seconds, CPU seconds and CPU from the record, since the loop's clock timed only the hand-back.
    `timing` (score_details' own) records whether this process kept the out-of-memory killer off itself."""
    record, k = {}, len(cpus)

    def run(submission_dir, data_dir, outputs, budget_sec, *rest):
        if not record:
            runner.read_only_method(Path(submission_dir))
            uid = rest[0][0] if rest and rest[0] is not None else None
            timing["oom_protected"] = runner.protect_self()     # where the container permits it
            try:
                for start in range(0, len(SEALED_IDS), k):
                    wave = SEALED_IDS[start:start + k]
                    calls = [functools.partial(run_one, submission_dir, SEALED_DIR / iid, outputs, budget_sec,
                                               *rest) for iid in wave]
                    for iid, rec in zip(wave, runner.run_wave(calls, cpus[:len(wave)], uid)):
                        record[str(SEALED_DIR / iid)] = rec
            finally:
                runner.protect_self(False)
        rec = record[str(data_dir)]
        runner.LAST_RUN_SEC = rec["last_run_sec"]
        return rec["status"], rec.pop("texts")

    class Rows(list):
        def append(self, row):
            rec = record.get(str(SEALED_DIR / row["id"]), {})
            row.update({key: rec[key] for key in ("run_sec", "cpu_sec", "cpu") if key in rec})
            super().append(row)
    return run, Rows()


def grade() -> tuple[float, dict]:
    details = base_details()
    caps = sealed_caps()
    if caps:
        runner.stage_and_run = capped(runner.stage_and_run, caps)
    if getattr(pc, "TIMING", "lane") == "single-core":       # fails closed without one core per run
        cpus = runner.core_cpus(int(pc.GRADING_CORES))
        details["timing"] = {"mode": "single-core", "cpus": cpus}
        runner.stage_and_run, details["per_instance"] = in_waves(runner.stage_and_run, cpus, details["timing"])
    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, heads = [], 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)}
            row["solver_sec"] = getattr(runner, "LAST_RUN_SEC", None)   # run.sh alone: what {elapsed} reads
            if pc.SCOPE == "set":
                pc.write_outputs(texts if status == "ok" else {}, set_root / iid)
                failed += status != "ok"
                heads[iid] = head(texts)
            elif status == "ok":
                pc.ELAPSED = row["solver_sec"]
                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,
                               timeout=pc.whole_side_timeout(len(SEALED_IDS)))
            details.update(set_metric={k: m[k] for k in ("status", "exit", "metric_sec")},
                           status="ok", n_failed=failed)
            if m["score"] == pc.FLOOR:             # quoted as the instance scope quotes a floored instance
                for row in details["per_instance"]:
                    row["output_head"] = heads.get(row["id"])
            write_reward(m["score"], dict(details))     # the reward first: the diagnostic cannot cost it
            score_alone(details["per_instance"], set_root)
            details["per_instance_scores"] = DIAGNOSTIC
            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())