File size: 3,173 Bytes
0109502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
import subprocess
import sys
import tempfile
from dataclasses import dataclass

@dataclass
class ExecutionResult:
    attempted: bool
    passed: bool
    timed_out: bool
    returncode: int | None
    stdout: str
    stderr: str
    status: str
    isolation: str
    warning: str | None = None

def _linux_preexec(memory_limit_mb: int, cpu_seconds: int, process_limit: int):
    def apply_limits():
        import resource
        memory = memory_limit_mb * 1024 * 1024
        resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
        resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds))
        resource.setrlimit(resource.RLIMIT_NPROC, (process_limit, process_limit))
        resource.setrlimit(resource.RLIMIT_FSIZE, (16 * 1024 * 1024, 16 * 1024 * 1024))
        resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
    return apply_limits

def run_code(code: str, timeout_seconds: int = 3, memory_limit_mb: int = 1024,
             cpu_seconds: int = 2, process_limit: int = 512) -> ExecutionResult:
    """
    Development executor. On Linux it applies rlimits. On Windows, Python has no
    stdlib equivalent to setrlimit, so execution is explicitly marked limited.
    Production runs should use the Docker executor with network disabled.
    """
    with tempfile.TemporaryDirectory(prefix="py_lora_") as td:
        kwargs = {
            "cwd": td,
            "env": {
                **os.environ,
                "PYTHONIOENCODING": "utf-8",
                "PYTHONDONTWRITEBYTECODE": "1",
                "OPENBLAS_NUM_THREADS": "1",
                "OMP_NUM_THREADS": "1",
                "MKL_NUM_THREADS": "1",
            },
            "text": True,
            "capture_output": True,
            "timeout": timeout_seconds,
        }
        isolation = "windows_limited"
        warning = None
        if sys.platform.startswith("linux"):
            kwargs["preexec_fn"] = _linux_preexec(memory_limit_mb, cpu_seconds, process_limit)
            isolation = "linux_rlimit"
        elif os.name == "nt":
            warning = (
                "Windows local executor has timeout and temporary cwd only. "
                "Use Docker mode for production/untrusted code; Windows has no "
                "stdlib setrlimit equivalent."
            )
        else:
            warning = "No OS resource limits are available in this local executor."

        try:
            p = subprocess.run(
                [sys.executable, "-I", "-c", code],
                **kwargs,
            )
            status = "passed" if p.returncode == 0 else "failed"
            return ExecutionResult(
                True, p.returncode == 0, False, p.returncode,
                p.stdout[-4000:], p.stderr[-4000:], status, isolation, warning
            )
        except subprocess.TimeoutExpired as e:
            return ExecutionResult(
                True, False, True, None,
                (e.stdout or "")[-4000:] if isinstance(e.stdout, str) else "",
                (e.stderr or "")[-4000:] if isinstance(e.stderr, str) else "",
                "failed", isolation, warning
            )