pi-office-math-bootstrap / scripts /pi_office_symbolic_sandbox.py
Jay Glidden
Upload folder using huggingface_hub
17cb132 verified
Raw History Blame Contribute Delete
10.2 kB
"""pi_office_symbolic_sandbox.py - Mode 3: secure symbolic execution.
The LLM generates a sympy script for novel math (roots, limits, integrals).
The sandbox executes it in an isolated subprocess and returns a
replayable execution receipt. The receipt certifies the EXECUTION (this
exact code produced this exact output), NOT that the answer is
mathematically proven - the code is the proof artifact.
Security model (best-effort isolation, documented):
- Static pre-gate: forbidden tokens are refused before execution.
- Subprocess: fresh interpreter, minimal env (no PATH/HOME/network vars),
empty temp cwd, stdin closed.
- Resource limits: CPU + memory via resource.setrlimit (POSIX), hard
timeout, stdout size cap.
- No network, no filesystem access to the workspace, no environment.
Residual risk: Python sandboxing is not absolute without containers; the
receipt binds query+code+stdout so any tampering is auditable.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import resource
import subprocess
import tempfile
import time
from pathlib import Path
SANDBOX_VERSION = "pi-office/symbolic-sandbox/1"
EXECUTION_TIMEOUT_SECONDS = 15
MAX_OUTPUT_CHARS = 20_000
MAX_CODE_CHARS = 8_000
# Static pre-gate: anything dangerous is refused outright.
_FORBIDDEN_PATTERNS = (
re.compile(r"\b(__import__|importlib|builtins|__builtins__|eval|exec|compile|globals|locals)\b"),
re.compile(r"\b(os|sys|subprocess|socket|pathlib|shutil|ctypes|multiprocessing|pty|signal)\b"),
re.compile(r"\b(open|file|read|write|unlink|remove|mkdir|chmod|system|popen|spawn)\b"),
re.compile(r"\b(getattr|setattr|delattr)\s*\("),
re.compile(r"\.__class__|\.__base__|\.__subclasses__|\.__mro__|\.__globals__|\.__code__"),
re.compile(r"__[a-z]+__"),
)
_ALLOWED_IMPORTS = ("sympy", "fractions", "math")
_IMPORT_RE = re.compile(r"^\s*import\s+(\S+)", re.M)
_FROM_IMPORT_RE = re.compile(r"^\s*from\s+(\S+)\s+import", re.M)
class SandboxRefusal(Exception):
"""The generated code was refused by the static gate."""
class SandboxError(Exception):
"""Execution failed (timeout, bad output, crash)."""
def _static_gate(code: str) -> None:
if len(code) > MAX_CODE_CHARS:
raise SandboxRefusal("code exceeds size limit")
# Comments are not executed -- strip them before the word-pattern scan so
# comments mentioning read/write/file/... cannot false-positive the gate.
scan = re.sub(r"#[^\n]*", "", code)
for pattern in _FORBIDDEN_PATTERNS:
if pattern.search(scan):
raise SandboxRefusal(f"forbidden construct: {pattern.pattern[:40]}")
for match in _IMPORT_RE.finditer(code):
module = match.group(1).split(".")[0]
if module not in _ALLOWED_IMPORTS:
raise SandboxRefusal(f"forbidden import: {module}")
for match in _FROM_IMPORT_RE.finditer(code):
module = match.group(1).split(".")[0]
if module not in _ALLOWED_IMPORTS:
raise SandboxRefusal(f"forbidden import: {module}")
def _worker_script(code: str) -> str:
"""Wrap the generated code with output framing inside the subprocess."""
import re as _re
# Import shim: the model commonly writes `from sympy import degrees, rad`
# but sympy does not export them - strip those names so they resolve
# from the worker's `from math import *`.
code = _re.sub(
r"from sympy import ([^\n]+)",
lambda m: "from sympy import "
+ ", ".join(
name.strip()
for name in m.group(1).split(",")
if name.strip() not in ("degrees", "rad")
),
code,
)
return (
"import json, resource, sys\n"
"import math as _math_mod\n"
"try:\n"
" resource.setrlimit(resource.RLIMIT_CPU, (15, 15))\n"
" resource.setrlimit(resource.RLIMIT_AS, (2 * 1024**3, 2 * 1024**3))\n"
"except Exception:\n"
" pass\n"
"import sympy as sp\n"
"from fractions import Fraction\n"
"from math import *\n"
"rad = radians # sympy codegen commonly uses rad() for degrees\n"
"sympy = sp # alias for bare `sympy.` attribute calls\n"
"from sympy import * # bare Eq/solve/symbols/pi/sqrt/... for generated code\n"
"def _V(_s):\n"
" try:\n"
" return sp.sympify(_s)\n"
" except Exception:\n"
" return _s\n"
"import io as _io\n"
"_captured = _io.StringIO()\n"
"_old_stdout = sys.stdout\n"
"sys.stdout = _captured\n"
"_output = {}\n"
"_print = print # shadow-proof: user code may rebind machinery\n"
"_json = json\n"
"_sys = sys\n"
"try:\n"
+ "\n".join(" " + line for line in code.splitlines())
+ "\n"
" _output['ok'] = True\n"
"except Exception as _e:\n"
" _output['ok'] = False\n"
" _output['error'] = str(_e)\n"
"try:\n"
" _candidates = {}\n"
" for _k, _v in list(globals().items()):\n"
" if (\n"
" not _k.startswith('_') and _k not in dir(_math_mod)\n"
" and _k not in ('json', 'sp', 'Fraction', 'resource')\n"
" and not isinstance(_v, sp.Symbol)\n"
" and not callable(_v)\n"
" ):\n"
" _candidates[_k] = _v\n"
" if 'result' in dir():\n"
" _output['result'] = result\n"
" _output['candidates'] = list(_candidates.values())\n"
" def _jsonsafe(o):\n"
" if isinstance(o, dict):\n"
" return {str(k): _jsonsafe(v) for k, v in o.items()}\n"
" if isinstance(o, (list, tuple, set)):\n"
" return [_jsonsafe(x) for x in o]\n"
" if o is None or isinstance(o, (str, int, float, bool)):\n"
" return o\n"
" return str(o)\n"
" _sys.stdout = _old_stdout\n"
" _output['captured_stdout'] = _captured.getvalue()[:200]\n"
" _print(_json.dumps(_jsonsafe(_output)))\n"
"except Exception as _we:\n"
" # worker machinery failed (shadowed print/json/sys, deep nesting,\n"
" # ...): emit a self-diagnosing JSON instead of dying silently\n"
" try:\n"
" _sys.stdout = _old_stdout\n"
" _output['ok'] = False\n"
" _output['worker_error'] = repr(_we)[:200]\n"
" _print(_json.dumps(_jsonsafe(_output)))\n"
" except Exception:\n"
" pass\n"
)
def execute_sympy(
code: str,
timeout: int = EXECUTION_TIMEOUT_SECONDS,
) -> dict[str, object]:
"""Static gate, then isolated subprocess execution. Returns the
execution record with the sandbox receipt payload."""
_static_gate(code)
script = _worker_script(code)
script_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
started = time.monotonic()
import sys
import site as _site
import sysconfig as _sysconfig
_lib_paths = [
_sysconfig.get_paths().get("purelib", ""),
_site.getusersitepackages(),
]
env = {
"PYTHONHASHSEED": "0",
"PYTHONIOENCODING": "utf-8",
"PYTHONDONTWRITEBYTECODE": "1",
"PYTHONPATH": os.pathsep.join(
path for path in _lib_paths if path and os.path.isdir(path)
),
}
with tempfile.TemporaryDirectory() as workdir:
try:
completed = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
text=True,
timeout=timeout,
env=env,
cwd=workdir,
stdin=subprocess.DEVNULL,
start_new_session=True,
)
except subprocess.TimeoutExpired:
raise SandboxError("execution timed out") from None
except OSError as error:
raise SandboxError(f"subprocess failed: {error}") from None
elapsed_ms = int((time.monotonic() - started) * 1000)
output = completed.stdout.strip()
if len(output) > MAX_OUTPUT_CHARS:
raise SandboxError("output exceeds size cap")
try:
parsed = json.loads(output)
except (json.JSONDecodeError, TypeError) as error:
stderr_tail = (completed.stderr or "").strip()[-400:]
raise SandboxError(
f"output is not JSON: {error}; stderr: {stderr_tail}"
) from error
if parsed.get("ok") is not True:
raise SandboxError(f"generated code failed: {parsed.get('error')}")
execution_hash = hashlib.sha256(
f"{script_hash}|{output}".encode("utf-8")
).hexdigest()
return {
"execution_mode": "symbolic_sandbox",
"sandbox_version": SANDBOX_VERSION,
"generated_code_sha256": script_hash,
"stdout": output,
"execution_hash": execution_hash,
"elapsed_ms": elapsed_ms,
}
def make_receipt(query: str, code: str, execution: dict[str, object]) -> dict[str, object]:
"""Bind query + code + stdout into the symbolic-execution receipt."""
query_hash = hashlib.sha256(query.encode("utf-8")).hexdigest()
receipt_hash = hashlib.sha256(
f"{query_hash}|{execution['execution_hash']}".encode("utf-8")
).hexdigest()
return {
"schema": "pi-office/symbolic-execution-receipt/1",
"protocol_version": "pi-office/verification-protocol/1",
"execution_mode": "symbolic_sandbox",
"sandbox_version": SANDBOX_VERSION,
"query_sha256": query_hash,
"generated_code_sha256": execution["generated_code_sha256"],
"stdout": execution["stdout"],
"execution_hash": execution["execution_hash"],
"receipt_sha256": receipt_hash,
"elapsed_ms": execution["elapsed_ms"],
"certification": (
"execution-certified: this exact generated code deterministically "
"produced this exact output in the sandbox; the code is the "
"replayable proof artifact. NOT a claim of mathematical proof."
),
}