File size: 3,706 Bytes
de0a028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Grade the answer file against tests/reference.json. Writes reward.txt (1/0), grade.json and a copy of the
answer (answer.txt) to VERIFIER_DIR. Any error -> reward 0. The sympy/mpmath wheels ship base64-encoded (plain git
text: the Hub stores binary files in LFS/Xet, which a plain `git checkout` without git-lfs cannot read)."""
import base64
import hashlib
import io
import json
import os
import stat
import sys
import tempfile
import zipfile

LIMIT = 10_000  # bytes
WHEELS = {"sympy-1.14.0-py3-none-any.whl": "e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", "mpmath-1.3.0-py3-none-any.whl": "a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c"}


def read_own(path):
    """Bytes of the regular file at exactly `path`: every folder on the way and the file are opened without
    following links (a FIFO cannot block it); one link only; at most LIMIT bytes."""
    parts = os.path.abspath(path).split("/")[1:]
    folder = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
    try:
        for part in parts[:-1]:
            inner = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=folder)
            os.close(folder)
            folder = inner
        fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder)
    finally:
        os.close(folder)
    with os.fdopen(fd, "rb") as stream:
        info = os.fstat(stream.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise ValueError("answer is not a regular file of its own")
        data = stream.read(LIMIT + 1)
    if len(data) > LIMIT:
        raise ValueError(f"answer file larger than {LIMIT} bytes")
    return data


def write_new(path, text):
    try:
        os.unlink(path)
    except FileNotFoundError:
        pass
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644)
    with os.fdopen(fd, "w") as stream:
        stream.write(text)


def load_grader(tests):
    lib = tempfile.mkdtemp(prefix="grader-lib-")
    for name, digest in WHEELS.items():
        blob = base64.b64decode(open(os.path.join(tests, name + ".b64"), "rb").read())
        if hashlib.sha256(blob).hexdigest() != digest:
            raise ValueError(f"wheel hash mismatch: {name}")
        with zipfile.ZipFile(io.BytesIO(blob)) as z:
            z.extractall(lib)
    sys.path[:0] = [lib, tests]
    import grader
    return grader


def main():
    tests, out = os.environ["TESTS_DIR"], os.environ["VERIFIER_DIR"]
    os.makedirs(out, exist_ok=True)
    write_new(os.path.join(out, "reward.txt"), "0")
    passed, why, submission = False, "grader error", ""
    try:
        try:
            submission = read_own(os.environ["ANSWER"]).decode("utf-8", "replace")
        except FileNotFoundError:
            submission, why = None, "no answer file"
        except (OSError, ValueError) as e:
            submission, why = None, f"answer file rejected: {e}"
        if submission is not None:
            write_new(os.path.join(out, "answer.txt"), submission)
            reference = json.loads(open(os.path.join(tests, "reference.json")).read())["answer"]
            grader = load_grader(tests)
            passed, why = grader.grade_safe(reference, submission, timeout=60) if submission.strip() else (False, "empty")
    except Exception as e:
        passed, why = False, f"grader error: {type(e).__name__}: {str(e)[:200]}"
    if passed:
        write_new(os.path.join(out, "reward.txt"), "1")
    write_new(os.path.join(out, "grade.json"), json.dumps({"passed": passed, "why": why, "submission": (submission or "")[:500]}))
    print("reward:", 1 if passed else 0, "|", why)


if __name__ == "__main__":
    main()