File size: 7,443 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
"""The reward Harbor reads: grade.py grades the method exactly as built, and this places its score on [0, 1].

grade.py's score is the metric's own value, in its own units and direction (score_details.json "direction"),
aggregated over the sealed instances as the metric declares. Only that one aggregate is mapped, on a straight line
through the two anchors in reward_scale.json: the starter method's sealed score, which maps to 0, and the bound,
the score that maps to 1. Under the profile "log-linear" the line is drawn through the logarithms of the scores, so
equal ratios of a cost count equally. The result is clipped to [0, 1], so a failed build, a failed grader or a score
worse than the starter's gives 0.
score_details.json keeps the raw score ("raw_score"), the anchors ("reward_scale") and the unclipped value
("reward_unclipped").

A reward of 0 is on disk before any submitted code runs. A later reward replaces it only once all its files are
written, so a grader that stops, or a write that fails, leaves 0. A container that lacks the solver account, or whose
sealed files are not private to root, stops the grader before any reward is written, and the trial errors.
"""

from __future__ import annotations

import json
import math
import os
import signal
import stat
import sys
from pathlib import Path

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

SCALE = json.loads((HERE / "reward_scale.json").read_text())
LOG = SCALE.get("profile") == "log-linear"
SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)


def on_line(score: float) -> float:
    """The score as the line measures it: itself, or its natural logarithm on a log-linear scale."""
    return math.log(score) if LOG else score


def gain(score: float) -> float:
    """How far a score lies from the starter's, toward the improving side, in the units of the line."""
    if SCALE["direction"] == "lower":
        return on_line(SCALE["starter"]) - on_line(score)
    return on_line(score) - on_line(SCALE["starter"])


def check() -> None:
    """Refuse anchors that do not define the line: fail the trial loudly rather than report a wrong reward."""
    if SCALE.get("profile") not in ("linear", "log-linear"):
        raise ValueError(f"reward_scale.json: unknown profile {SCALE.get('profile')!r}")
    if SCALE.get("transform") != ("log" if LOG else None):
        raise ValueError(f"reward_scale.json: transform {SCALE.get('transform')!r} under profile {SCALE['profile']!r}")
    if SCALE.get("direction") not in ("lower", "higher") or SCALE["direction"] != grade.pc.DIRECTION:
        raise ValueError(f"reward_scale.json: direction {SCALE.get('direction')!r}, metric direction {grade.pc.DIRECTION!r}")
    if LOG and not (SCALE["starter"] > 0 and SCALE["bound"] > 0 and grade.pc.FLOOR > 0):
        raise ValueError("reward_scale.json: a log-linear scale needs a positive starter, bound and failure score")
    g = gain(SCALE["bound"])
    if not (math.isfinite(SCALE["starter"]) and math.isfinite(g) and g > 0):
        raise ValueError("reward_scale.json: the bound does not improve on the starter")
    if gain(grade.pc.FLOOR) > 0:
        raise ValueError("reward_scale.json: the failure score would earn a reward")


check()


def place(score: float) -> tuple[float, float]:
    """(reward in [0, 1], the unclipped value) for one raw score."""
    if not math.isfinite(score) or (LOG and score <= 0):
        return 0.0, float("nan")
    line = gain(score) / gain(SCALE["bound"])
    return min(1.0, max(0.0, line)), line


def refuse_broken_container() -> None:
    """A fault of the task itself, which no submission can cause: stop before any reward is written."""
    solver = grade.runner.solver_ids()
    if os.getuid() != 0 or solver is None or solver[0] == 0:
        raise SystemExit("the grader needs root and the unprivileged solver account")
    sealed = [HERE / "sealed.json", HERE / "reward_scale.json"]
    for top in (HERE / "data", HERE / "data-answers"):
        if top.exists():
            sealed += [top, *top.rglob("*")]
    for path in sealed:
        st = path.lstat()
        if st.st_uid != 0 or stat.S_IMODE(st.st_mode) & 0o077:
            raise SystemExit(f"{path.relative_to(HERE)} is not private to root")


def clear_reward_paths() -> None:
    """Remove whatever is at the reward paths. A directory is removed whole; a link is removed, never followed."""
    for name in grade.REWARD_FILES:
        path = grade.LOG_DIR / name
        if path.is_dir() and not path.is_symlink():
            shutil_rmtree(path)
        else:
            try:
                os.unlink(path)
            except FileNotFoundError:
                pass


def shutil_rmtree(path: Path) -> None:
    import shutil
    shutil.rmtree(path)


_write_raw = grade.write_reward
_staged: list = []
_delivered: dict = {}


def stage(name: str, text: str) -> None:
    """Write one score file beside its final name, never following a link."""
    part = grade.LOG_DIR / f".{name}.part"
    try:
        os.unlink(part)
    except FileNotFoundError:
        pass
    _staged.append((part, grade.LOG_DIR / name))
    fd = os.open(part, 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_files(value: float, details: dict) -> None:
    """All the score files or none: they are renamed over their final names only after every one is written."""
    try:
        _write_raw(value, details)
        for part, final in _staged:
            os.replace(part, final)
    finally:
        for part, _final in _staged:
            try:
                os.unlink(part)
            except FileNotFoundError:
                pass
        _staged.clear()


def clear_and_record_failure() -> None:
    """Runs before the first submitted code: from here on, whatever stops the grader leaves a reward of 0."""
    clear_reward_paths()
    write_files(0.0, {**grade.base_details(), "status": "not_finished", "raw_score": None, "reward_unclipped": None})


def write_reward(value: float, details: dict) -> None:
    reward, line = place(value)
    details["raw_score"] = value if math.isfinite(value) else None
    details["reward_scale"] = SCALE
    details["reward_unclipped"] = line if math.isfinite(line) else None
    write_files(reward, details)
    _delivered.update(reward=reward, raw=value)


grade.write_safely = stage
grade.clear_rewards = clear_and_record_failure
grade.write_reward = write_reward


class Interrupted(BaseException):
    """The grader was told to stop: it ends the method's processes and leaves the failure reward."""


def on_signal(signum, _frame) -> None:
    for s in SIGNALS:
        signal.signal(s, signal.SIG_IGN)
    solver = grade.runner.solver_ids()
    if solver is not None:
        grade.runner._reap_uid(solver[0])
    raise Interrupted(signum)


def main() -> int:
    refuse_broken_container()
    for s in SIGNALS:
        signal.signal(s, on_signal)
    try:
        rc = grade.main()
    except Interrupted as stop:
        write_reward(grade.pc.FLOOR, {**grade.base_details(), "status": "interrupted"})
        print(f"interrupted by signal {stop.args[0]}: reward 0")
        return 128 + int(stop.args[0])
    if _delivered:
        print(f"delivered reward {_delivered['reward']:.6g} (raw score {_delivered['raw']:.6g})")
    return rc


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