File size: 9,051 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
"""Values the grader and the self-check share, and the one function that calls the core's metric.

Nothing about the sealed instances is in this file: their ids and answer paths are in
`tests/sealed.json`, which only the grader's image holds.
"""

from __future__ import annotations

import json
import math
import os
import shlex
import shutil
import subprocess
import tempfile
import time
from pathlib import Path

# ---- the task's constants ----
PER_RUN_BUDGET_SEC = 2.0          # seconds per method run
METRIC_COMMAND = 'python3 metric/metric.py --data {instance} --output {output}'
SCORE_FROM = 'stdout-first-line'
SCOPE = 'instance'
FLOOR = 0.0
DIRECTION = 'higher'
AGGREGATE = 'mean'        # mean or geometric
GEOMETRIC_MIN = None  # scores are clamped up to this before the geometric mean's log
OUTPUTS = ('submission.txt',)              # the files the method writes
METRIC_TIMEOUT_SEC = 30.0       # seconds the metric may take per instance
PRACTICE_ID = 'v0000'
PRACTICE_IDS = ('v0000', 'v0001', 'v0002', 'v0003', 'v0004', 'v0005', 'v0006', 'v0007', 'v0008', 'v0009')     # flat /app/data when there is one
# {answers} of each instance, relative to its answers root; empty when the layout declares none
ANSWER_PATHS = {}

# ---- end of the task's constants ----


def practice_dirs() -> list[tuple[str, Path, Path | None]]:
    """(id, inputs, answers root) for every practice instance, in the order of PRACTICE_IDS.

    One practice instance sits flat under /app/data; several sit in a subdirectory each, named by
    the instance id."""
    root, answers = Path("/app/data"), Path("/app/data-answers")
    ids = globals().get("PRACTICE_IDS") or (PRACTICE_ID,)
    if len(ids) == 1:
        return [(ids[0], root, answers if answers.exists() else None)]
    return [(i, root / i, (answers / i) if (answers / i).exists() else None) for i in ids]


CORE = Path(os.environ.get("CORE_DIR", "/app/core"))
# Where the metric's programs are found. Root starts the metric after the method has run, and the method can
# write to none of these directories.
METRIC_PATH = '/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin'
STDOUT_KEPT = 2000                     # characters of the metric's stdout kept in the record
# The run time a metric that reads {elapsed} is given (a round scored by its time): the caller sets it from runner.LAST_RUN_SEC right before it scores that run's output,
# and metric_call uses it once and clears it, so a call without it fails closed instead of reading
# another instance's time.
ELAPSED: float | None = None


def aggregate(scores: list[float]) -> float:
    """The aggregate score, from the per-instance scores. The grader and the self-check share this, so
    a rehearsal aggregates exactly as grading does. AGGREGATE says which of the two below applies.

    `mean` is the plain arithmetic mean, in the metric's own units, and is the default.

    `geometric` is the **geometric mean**, `exp(mean(log(s)))`, in the metric's own units -- NOT the
    mean of the logs, which is its logarithm and lives on a different scale. On a cost metric it
    measures each instance's **relative** improvement, so an instance whose absolute cost is orders
    of magnitude larger than its neighbours' does not dominate the aggregate. Each score is first
    clamped up to GEOMETRIC_MIN, which keeps the log finite for a score of 0 or below."""
    if not scores:
        raise ValueError("no per-instance scores to aggregate")
    if globals().get("AGGREGATE", "mean") != "geometric":
        return sum(scores) / len(scores)
    lo = GEOMETRIC_MIN
    return math.exp(sum(math.log(max(s, lo)) for s in scores) / len(scores))


def answers_for(root: Path, iid: str) -> Path | None:
    """{answers} for one instance: its answers under `root`, or None if the layout declares none."""
    rel = ANSWER_PATHS.get(iid)
    return None if rel is None else Path(root) / rel


def _fill(token: str, values: dict) -> str:
    for key, value in values.items():
        token = token.replace("{" + key + "}", str(value))
    return token


def _read_score(stdout: str) -> float | None:
    """The score as SCORE_FROM says -- the first stdout line, or <key> of the last JSON-object line;
    None if it cannot be read."""
    lines = stdout.splitlines()
    try:
        if SCORE_FROM == "stdout-first-line":
            value = float(lines[0].strip())
        else:                                    # "stdout-json:<key>": the last line that is a JSON object
            key = SCORE_FROM.split(":", 1)[1]
            value = None
            for line in reversed(lines):
                try:
                    obj = json.loads(line)
                except ValueError:
                    continue
                if isinstance(obj, dict):
                    value = float(obj[key])
                    break
    except (IndexError, KeyError, TypeError, ValueError):
        return None
    if value is None or not math.isfinite(value):
        return None
    return value


def whole_side_timeout(n: int) -> float:
    """What one call over a whole side of n instances may spend (scope "set"): n calls' worth."""
    return max(1, n) * METRIC_TIMEOUT_SEC


def metric_call(instance: Path, answers: Path | None, output: Path, timeout: float | None = None) -> dict:
    """Run the core's declared metric command once and read its score.

    The placeholders are filled with the given paths and a fresh {scratch}; the command runs in
    CORE with CORE_DIR set, under METRIC_TIMEOUT_SEC. Any failure gives the floor:
    status "metric_failed" (non-zero exit), "metric_timeout" or "unreadable_score".
    A call over a whole side passes `timeout`, whole_side_timeout of its size, instead.
    A command that reads {elapsed} is given ELAPSED, the run's measured seconds, and fails closed
    ("metric_failed") when the caller set none.
    """
    global ELAPSED
    elapsed, ELAPSED = ELAPSED, None
    if "{elapsed}" in METRIC_COMMAND and elapsed is None:
        return {"score": FLOOR, "status": "metric_failed", "exit": None, "metric_sec": 0.0,
                "stdout": "the metric reads {elapsed}, and this call was given no measured run time"}
    program = shutil.which(shlex.split(METRIC_COMMAND)[0], path=METRIC_PATH)
    if program is None:
        return {"score": FLOOR, "status": "metric_failed", "exit": None, "metric_sec": 0.0,
                "stdout": "the metric's program is not on METRIC_PATH"}
    scratch = Path(tempfile.mkdtemp(prefix="metric_scratch_"))
    values = {"instance": instance, "output": output, "scratch": scratch}
    if elapsed is not None:
        values["elapsed"] = f"{elapsed:.3f}"
    if answers is not None:
        values["answers"] = answers
    argv = [program] + [_fill(t, values) for t in shlex.split(METRIC_COMMAND)[1:]]
    env = dict(os.environ, PATH=METRIC_PATH, CORE_DIR=str(CORE), PYTHONDONTWRITEBYTECODE="1")
    t0 = time.time()
    try:
        p = subprocess.run(argv, cwd=str(CORE), env=env, capture_output=True, text=True,
                           errors="replace", timeout=METRIC_TIMEOUT_SEC if timeout is None else timeout)
    except subprocess.TimeoutExpired:
        return {"score": FLOOR, "status": "metric_timeout", "exit": None, "stdout": "",
                "metric_sec": round(time.time() - t0, 3)}
    finally:
        shutil.rmtree(scratch, ignore_errors=True)
    rec = {"exit": p.returncode, "stdout": p.stdout[:STDOUT_KEPT],
           "metric_sec": round(time.time() - t0, 3)}
    if p.returncode != 0:
        return {"score": FLOOR, "status": "metric_failed", **rec}
    score = _read_score(p.stdout)
    if score is None:
        return {"score": FLOOR, "status": "unreadable_score", **rec}
    return {"score": score, "status": "ok", **rec}


def write_outputs(texts: dict, out: Path) -> None:
    """The declared output files, as read by runner._read_output, into a fresh directory.

    The metric runs as root, so it never reads the method's own work directory: a leftover link
    there could lead it to another file. Only regular files the runner already read are
    written, and a file the method did not write stays absent.
    """
    out.mkdir(mode=0o700, parents=True, exist_ok=False)
    for name in OUTPUTS:
        text = texts.get(name)
        if text is not None:
            path = out / name
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(text if isinstance(text, bytes) else text.encode("utf-8"))


def score_outputs(texts: dict, instance: Path, answers: Path | None) -> dict:
    """Score one instance's outputs with the metric; the record metric_call returns."""
    root = Path(tempfile.mkdtemp(prefix="metric_out_"))
    try:
        write_outputs(texts, root / "output")
        return metric_call(instance, answers, root / "output")
    finally:
        shutil.rmtree(root, ignore_errors=True)


def better(a: float, b: float) -> bool:
    """True when score a is better than score b in the core's direction."""
    return a > b if DIRECTION == "higher" else a < b