File size: 4,743 Bytes
af5b4af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run one agent command in the episode workspace.

The command runs as nobody when the server is root, so it cannot read the
server code, the generators or the answers held in server memory. Output goes
to a root-owned file so a runaway writer cannot fill server memory, and every
nobody process is killed after each command so nothing lingers between steps
or into grading. Network is not blocked; the sandbox is the outer boundary.
"""

import os
import resource
import signal
import subprocess
import tempfile
import time

WALL_TIMEOUT_S = 20
CPU_SECONDS = 20
MEMORY_BYTES = 2 * 1024**3
FILE_BYTES = 20 * 1024**2
MAX_PROCESSES = 256
# A safety cap only. The operator's wrapper does not cut output; the arena's token budget
# ends an episode whose observation no longer fits, and that is the pressure to train under.
MAX_OUTPUT_CHARS = 60000
NOBODY = 65534

IS_ROOT = os.geteuid() == 0


def _limits() -> None:
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    resource.setrlimit(resource.RLIMIT_CPU, (CPU_SECONDS, CPU_SECONDS + 1))
    resource.setrlimit(resource.RLIMIT_AS, (MEMORY_BYTES, MEMORY_BYTES))
    resource.setrlimit(resource.RLIMIT_FSIZE, (FILE_BYTES, FILE_BYTES))
    resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256))
    if IS_ROOT:
        resource.setrlimit(resource.RLIMIT_NPROC, (MAX_PROCESSES, MAX_PROCESSES))
        os.setgroups([])
        os.setgid(NOBODY)
        os.setuid(NOBODY)


def kill_nobody() -> None:
    """SIGKILL every process owned by nobody (no-op unless root)."""
    if not IS_ROOT:
        return
    for _ in range(3):
        found = False
        for pid in os.listdir("/proc"):
            if not pid.isdigit():
                continue
            try:
                if os.stat(f"/proc/{pid}").st_uid == NOBODY:
                    os.kill(int(pid), signal.SIGKILL)
                    found = True
            except (FileNotFoundError, ProcessLookupError, PermissionError):
                pass
        if not found:
            return
        time.sleep(0.05)


def give_to_nobody(path: str) -> None:
    if not IS_ROOT:
        return
    for dirpath, dirnames, filenames in os.walk(path):
        os.chown(dirpath, NOBODY, NOBODY)
        for name in filenames:
            os.chown(os.path.join(dirpath, name), NOBODY, NOBODY)


def cut(text: str, limit: int = MAX_OUTPUT_CHARS) -> str:
    if len(text) <= limit:
        return text
    head = int(limit * 0.75)
    tail = limit - head
    return f"{text[:head]}\n...[{len(text) - limit} characters cut]...\n{text[-tail:]}"


def run(argv: list[str], cwd: str, stdin_text: str | None = None) -> tuple[int, str]:
    """Run argv as nobody in cwd. Returns (exit code, combined output, uncut)."""
    env = {
        "PATH": "/usr/local/bin:/usr/bin:/bin",
        "HOME": cwd,
        "LANG": "C.UTF-8",
        "TERM": "dumb",
        "PYTHONDONTWRITEBYTECODE": "1",
    }
    with tempfile.TemporaryFile() as sink:
        proc = subprocess.Popen(
            argv,
            cwd=cwd,
            env=env,
            stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,
            stdout=sink,
            stderr=subprocess.STDOUT,
            preexec_fn=_limits,
            start_new_session=True,
        )
        timed_out = False
        try:
            proc.communicate(
                input=stdin_text.encode() if stdin_text is not None else None,
                timeout=WALL_TIMEOUT_S,
            )
        except subprocess.TimeoutExpired:
            timed_out = True
        finally:
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
            proc.wait()
            kill_nobody()
        sink.seek(0)
        raw = sink.read(4 * 1024**2)
    text = raw.decode("utf-8", errors="replace")
    code = proc.returncode
    if timed_out:
        text += f"\n[stopped: {WALL_TIMEOUT_S} s time limit]"
        code = 124
    elif code == -signal.SIGXCPU:
        text += f"\n[stopped: {CPU_SECONDS} s CPU limit]"
    elif code == -signal.SIGXFSZ:
        text += "\n[stopped: file size limit (20 MB)]"
    return code, text


def run_command(cmd: str, cwd: str) -> tuple[int, str]:
    code, text = run(["/bin/bash", "-c", cmd], cwd)
    text = text.rstrip("\n")
    return code, cut(text) if text else ""


def write_file(path: str, content: str, cwd: str) -> tuple[int, str]:
    """Write content to path (relative to cwd unless absolute) as nobody, creating parents.
    Running as nobody is the path check: the server tree and system files are not writable."""
    script = 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"'
    return run(["/bin/sh", "-c", script, "sh", path], cwd, stdin_text=content)