Repository Public
1# V8 — every process that runs strategy code is confined by the OS23Before v8 an approved `strategy.py` (possibly written by the AI research agent) ran in a child process with a minimal4environment and a timeout, and nothing else: the laboratory's purity guard is a Python-level lint, not a boundary.5Since v8 **one module starts every laboratory process** — `services/api/src/agents/lab.ts` (`labExec`) — and every such6process is one Python interpreter inside a deny-default `sandbox-exec` profile (`labSandboxProfile` in7`packages/core/src/research-sandbox.ts`). Nothing in signing, limits, policy, mandates or order decisions changed.89| Entry point | Code | Data in | Out |10|---|---|---|---|11| spot signal | `agents/live.ts` `runSignal` | stdin (JSON) | stdout (JSON) |12| perp signal | `agents/perp-signal.ts` `runPerpSignal` | stdin | stdout |13| describe (listing, registration) | `agents/strategies.ts` `describe`, `perp-strategies.ts` `describePerp` | — | stdout |14| spot backtest | `agents/strategies.ts` `backtest` | **files exported by the API** (`exportCandles`) | report file in the scratch directory |15| perp backtest | `agents/perp-strategies.ts` `perpBacktest` | bundle file prepared by the API (unchanged) | report file |16| research evaluation | `research/lab.ts` `labRun` → `labExec` | the job's frozen data set (files) | report files |1718## The profile1920- **Network: none.** No rule at all — no loopback port, no Unix socket, no DNS, no listening.21- **Process: no `process-fork`.** `fork()`, `posix_spawn()` and `subprocess` fail with `EPERM`; `process-exec` is allowed22 for the interpreter only. So no helper program (`curl`, `sh`, `ps`) can be started and **nothing can outlive a call**:23 the `setsid` escape described in `docs/v7/RESEARCH-RUNTIME.md` needs a fork first and does not exist here. (SBPL has no24 rule for `setsid` itself and none for "fork after setsid"; denying fork is what works. The research *job* profile — a25 coding agent that needs a shell — still allows fork: its residual is unchanged and still documented there.)26- **Other processes are invisible**: `(deny process-info*)` + `(allow process-info* (target self))`, and27 `(deny sysctl-read (sysctl-name-prefix "kern.proc"))`. See "Finding" below.28- **Files, read-only:** `research/src`, `research/schema`, `research/.venv`, the interpreter's install prefix, **the one29 strategy directory of the call**, the caller's data. System: `/usr/lib`, `/System/Library`, the dyld cache, the timezone30 database. Measured on macOS 27 arm64 with the uv-managed CPython 3.12 and the full numerical stack: the interpreter31 runs with *none* of the system paths (everything comes from the dyld shared cache); they are kept as dyld's fallback.32 Not readable: the application checkout beyond those `research/` paths, the home directory, `~/.ssh`, `~/.config`,33 `~/.pm2`, `/usr/bin`, `/etc`, Homebrew (added only when the interpreter itself is a Homebrew build), `/tmp` at large,34 other strategies.35- **Files, read-write:** one scratch directory, fresh per call and removed afterwards (owned by the caller when it needs36 the report). `HOME` and `TMPDIR` point to it.37- **Environment:** built from nothing (`PATH`, `HOME`, `TMPDIR`, `PYTHONPATH`, `PYTHONDONTWRITEBYTECODE`,38 `JOBLIB_MULTIPROCESSING=0`, `MPLCONFIGDIR`, `LANG`, `UV_OFFLINE`). No secret, **no database URL**.39- **Interpreter:** `research/.venv/bin/python -P -s -B -m …` directly. `uv run` is not used any more: under a read-only40 tree it wants its cache and configuration under the home directory; the direct call needs neither.4142## The spot backtest no longer opens the database4344`spq.backtest` used to receive `DATABASE_URL` (`RESEARCH_DATABASE_URL` when set) and read the `candles` table itself.45Now the API exports the same rows to `<scratch>/data/<source>/<SYMBOL>_<interval>.csv` and passes `--data-dir`/`--source`.46`RESEARCH_DATABASE_URL`, when set, is still where the API reads them from (a read-only session). The laboratory code is unchanged:47pandas 3.1.1 parses decimal text to the exact float64 (200 000 random values written in shortest round-trip form, 048mismatches; `float_precision="round_trip"` is deprecated there as redundant), i.e. the values of the `double precision` column. The cross-run trial ledger (`research/results/ledger.jsonl`) is written by the API only: the process works on a49copy, the lines it appended are merged, a rewritten history is not.5051Proof of identical results: `services/api/test/lab-identity.test.ts` (database path vs file path, every report field but52the timestamp, and the ledger) and, on real data (`spw_v5_market`, ETH/LINK/AAVE, 17 509 hourly bars, 2026-11-11):53`ma_trend/2`, `ts_momentum/2`, `vol_target_trend/2` — three reports of ~160 kB each, byte-identical apart from54`generated_at`.5556## Limits of one call5758| Limit | How | Measured |59|---|---|---|60| wall clock | timer in the API → `SIGKILL` of the process group (signals 60 s, backtests 20–30 min) | killed at the timeout, process gone |61| CPU seconds | `ulimit -t` set by a `/bin/sh` wrapper **outside** the sandbox, inherited across `exec` (4 × the wall clock, min 60 s) | `ulimit -t 2` kills a busy Python loop with `SIGXCPU` after 2.0 s, also with BLAS threads (CPU time is summed over threads) |62| file size | `ulimit -f` (2 GiB per file) | a 4 MiB write under a 1 MiB limit stops at 1 MiB (`EFBIG`) |63| address space / data / RSS | **not available**: `ulimit -v`, `-d`, `-m` answer `Invalid argument` on macOS 27 arm64, and a Python process allocated 4 GiB under each | — |64| resident memory | a watchdog in the API reads the child's RSS every second (`ps -o rss=`) and kills above the ceiling (signals 2 GiB, others 4 GiB; `SPW_LAB_SIGNAL_MAX_RSS_MB`, `SPW_LAB_MAX_RSS_MB`) | a strategy allocating 32 MiB blocks is killed above a 400 MiB ceiling within seconds. It is a poll, not a quota: a fast allocator can overshoot for up to one second |65| output | signals: killed beyond 100 kB of stdout; others truncated at 2 MB | — |6667Latency of one signal call (`ma_trend/3`, 1 000 bars × 2 symbols, 7 runs): sandboxed median **210 ms** (205–215);68the pre-v8 `uv run` median 199 ms (198–211). About +10 ms, 0.006 % of a one-hour bar. The self-test costs ~40 ms every69ten minutes.7071## Fail closed7273`labExec` refuses to run anything (`LabUnavailable`) when `sandbox-exec` does not exist, the interpreter is missing, or the74profile does not confine. "Does not confine" is decided by a **self-test**: a tiny interpreter run under the real profile75must be refused the home directory, a socket, a fork and a write outside; it runs at first use, every ten minutes, and76again after any sandbox error. Consequences: a signal call throws → the engine holds (`research_log` "Order not placed");77describe answers `bad_strategy`; a backtest ends with a note; a research evaluation is refused.7879- Health: `GET /api/v1/monitor/health` → `lab: { mode: 'sandbox-exec' | 'off' | 'unavailable', ok, reason, checkedAt,80 lastFailure, calls, refused }` (Monitor screen), and the start-up line of the API.81- Alerts: `system.lab_sandbox_unavailable` (critical, once per episode), `system.lab_sandbox_back` (info),82 `system.lab_sandbox_off` (critical, once per day while set).83- **Escape hatch, development only:** `SPW_LAB_SANDBOX=off` (default: on). Same interpreter, environment and limits, no84 OS confinement; logged at first use, reported as `mode: 'off'`, alerted daily. Never set it on a machine holding funds.85 The older `SPW_RESEARCH_SANDBOX` is gone (it silently ran the evaluation unconfined when the sandbox was missing).8687## Finding fixed on the way: a sandboxed job could read other processes' environment8889The V7 profile had a blanket `(allow sysctl-read)`. `sysctl kern.procargs2.<pid>` returns the arguments **and the90environment** of any process of the same user — from inside the research job's sandbox that is the runner's environment91(the model API key, the runner secret) and, on the API node during an evaluation, the API's (`DATABASE_URL`, the signer92secret). Verified: with the V7 profile a sandboxed Python read a canary from another process's environment; `(deny93default)` also did not stop `proc_pidpath` / `proc_listallpids` of other processes. `ps -E` itself was already refused.94Both profiles now carry the two deny rules above (`services/research-runner/test/sandbox.test.ts` "v8: the environment of95a process outside the sandbox…").9697## Tests9899```bash100npx vitest run services/api/test/lab-sandbox.test.ts # hostile strategy through the 5 entry points, limits, fail closed101npx vitest run services/api/test/lab-identity.test.ts # 18 spot + 7 perp library strategies byte-identical; backtest ≡; latency102npx vitest run services/research-runner/test/sandbox.test.ts103```104The hostile strategy (`services/api/test/lab-hostile.ts`) runs in a laboratory copy whose lint is **disabled**, and reaches105files, sockets, fork and `sysctl` through `posix`, `_socket` and `ctypes` — entry points the runtime guard does not patch.10628 attempts at import and again inside `target_weights`, three positive controls through the same primitives; the same107strategy run once unconfined against local stand-ins leaks 14 of them, which shows the probes detect a leak.108109## Not closed110111- Memory is polled, not capped by the kernel. Existence of a path can still be inferred (`ENOENT` vs `EPERM`), and the112 names in `/` are listable.113- A strategy can still burn CPU up to the timeout and return garbage weights: the engine's and the signer's limits are114 what bound the consequences, as before.115- `sandbox-exec` is deprecated by Apple; on another platform nothing runs unless the development switch is set.116- The research **job** (the coding agent with a shell) keeps `process-fork`; its `setsid` residual is unchanged.117