"""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 = 30.0 # seconds per method run METRIC_COMMAND = 'python3 metric/score.py --answers {answers} --output {output}' SCORE_FROM = 'stdout-first-line' SCOPE = 'instance' FLOOR = -1.0 DIRECTION = 'higher' AGGREGATE = 'mean' # mean or geometric GEOMETRIC_MIN = None # scores are clamped up to this before the geometric mean's log OUTPUTS = ('predictions.json',) # the files the method writes METRIC_TIMEOUT_SEC = 32.0 # seconds the metric may take per instance PRACTICE_ID = 'i61ebb6709feeb9c7' PRACTICE_IDS = ('i61ebb6709feeb9c7', 'idb7fa73eccb2106e', 'i56296f1bf549596e', 'i30bb1a11b82435fd', 'i0e1ad8c1aa832e03', 'i3abd7cec365edbcb', 'i4b3ff18aa4e0f81d', 'i58d37bf4633f9575', 'i8c2393a3d02d039e', 'i4b06d3d4919b2dee', 'i97e51dc901e85304', 'ibd6a4f35a77dce28', 'if03481e54a27d6f7', 'iabf61e8e35cbae63', 'i4f14173916845279', 'iee2dd95623ad3111', 'i38761948a43f13c1', 'i6f29d523eb1a9168', 'i366bae75dd495efc') # flat /app/data when there is one # {answers} of each instance, relative to its answers root; empty when the layout declares none ANSWER_PATHS = {'i61ebb6709feeb9c7': '.', 'idb7fa73eccb2106e': '.', 'i56296f1bf549596e': '.', 'i30bb1a11b82435fd': '.', 'i0e1ad8c1aa832e03': '.', 'i3abd7cec365edbcb': '.', 'i4b3ff18aa4e0f81d': '.', 'i58d37bf4633f9575': '.', 'i8c2393a3d02d039e': '.', 'i4b06d3d4919b2dee': '.', 'i97e51dc901e85304': '.', 'ibd6a4f35a77dce28': '.', 'if03481e54a27d6f7': '.', 'iabf61e8e35cbae63': '.', 'i4f14173916845279': '.', 'iee2dd95623ad3111': '.', 'i38761948a43f13c1': '.', 'i6f29d523eb1a9168': '.', 'i366bae75dd495efc': '.'} # ---- 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 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 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:": 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 metric_call(instance: Path, answers: Path | None, output: Path) -> 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". """ 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 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) 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_text(text, encoding="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