RFC: Add streaming-stdio process API (`popen` / `Process`)
Goal
Add a popen()-style entry point on Sandbox that returns a live process handle exposing streaming stdin / stdout / stderr, so callers can drive bidirectional stdio protocols (MCP, LSP, REPLs, JSON-RPC over stdio) without losing the kernel-enforced jail.
Motivation
Today's Sandbox API is capture-mode only:
Sandbox.run(cmd)blocks and returns aResultwith bufferedstdout/stderr.Sandbox.spawn(cmd) + wait()exposes a live pid but no stream access; you still only get final buffered output.
That works for batch tools. It does not work for any subprocess whose protocol is request / response streamed over stdio while the process is alive. Concrete cases this blocks today:
- Running an untrusted MCP server inside a jail and connecting an MCP client to its stdio.
- Driving an LSP server in a jail.
- Hosting a REPL or interactive process whose output must be read as it arrives.
- Anything JSON-RPC over stdio.
The available workarounds are unattractive: either skip the Python API and shell out to sandlock run so a higher-level SDK can manage stdio, or build private stdio plumbing on top of the FFI. Neither composes well; both push complexity onto every caller.
Current state
Sandbox.run/spawn/wait(Python): capture-mode, seepython/src/sandlock/sandbox.py:463, 744, 757.sandlock_handle_*(FFI): no pipe-fd accessors;sandlock_handle_wait*always buffers stdout / stderr into the returned result.crates/sandlock-core/src/sandbox.rs: launch path always wires stdio for capture.
The Python Sandbox object also conflates two roles: it is a policy dataclass and a single-process controller (handle is stashed in _handle, so one Sandbox instance can only run one process at a time). That wart blocks straightforward "launch many processes from one policy" patterns.
Proposed API
Python
class Sandbox:
async def popen(
self,
cmd: Sequence[str],
*,
stdin: bool = True,
stdout: bool = True,
stderr: bool = True,
) -> "Process": ...
class Process:
pid: int
stdin: anyio.abc.ByteSendStream | None
stdout: anyio.abc.ByteReceiveStream | None
stderr: anyio.abc.ByteReceiveStream | None
async def wait(self) -> int: ... # exit code only
def terminate(self) -> None: ... # SIGTERM
def kill(self) -> None: ... # SIGKILL
async def __aenter__(self) -> "Process": ...
async def __aexit__(self, *exc) -> None: ...
Existing run, spawn, wait, cmd, fork are unchanged.
Rust core
pub enum StdioMode { Inherit, Piped, Null }
pub struct StdioConfig {
pub stdin: StdioMode,
pub stdout: StdioMode,
pub stderr: StdioMode,
}
impl Sandbox {
pub fn popen(&self, cmd: &[&str], io: StdioConfig)
-> Result<Child, SandlockError>;
}
pub struct Child { /* ... */ }
impl Child {
pub fn pid(&self) -> i32;
pub fn stdin(&mut self) -> Option<&mut ChildStdin>;
pub fn stdout(&mut self) -> Option<&mut ChildStdout>;
pub fn stderr(&mut self) -> Option<&mut ChildStderr>;
pub fn take_stdin(&mut self) -> Option<ChildStdin>;
pub fn take_stdout(&mut self) -> Option<ChildStdout>;
pub fn take_stderr(&mut self) -> Option<ChildStderr>;
pub fn wait(self) -> Result<ExitStatus, SandlockError>;
pub fn terminate(&self) -> Result<(), SandlockError>;
pub fn kill(&self) -> Result<(), SandlockError>;
}
Naming follows std::process::{Command, Child}. Existing Sandbox methods unchanged.
FFI
// Stdio modes
const int SANDLOCK_STDIO_INHERIT = 0;
const int SANDLOCK_STDIO_PIPED = 1;
const int SANDLOCK_STDIO_NULL = 2;
// Spawn with caller-managed stdio. *_out_fd receives the pipe fd when the
// matching mode is PIPED; otherwise -1. Caller owns and must close the fds.
sandlock_handle_t *sandlock_handle_popen(
SandboxBuilder *builder,
const char *const *argv, size_t argc,
int stdin_mode, int *stdin_out_fd,
int stdout_mode, int *stdout_out_fd,
int stderr_mode, int *stderr_out_fd
);
// Wait without buffering stdout / stderr (caller drained the pipes).
sandlock_result_t *sandlock_handle_wait_exit(
sandlock_handle_t *h, uint64_t timeout_ms);
// Signal the running process.
int sandlock_handle_terminate(sandlock_handle_t *h);
int sandlock_handle_kill(sandlock_handle_t *h);
Existing handle entry points (sandlock_handle_create*, sandlock_start, sandlock_handle_wait*, sandlock_handle_pid, sandlock_handle_free, port mappings, checkpoint) are unchanged.
Design rationale
Why a separate Process / Child type rather than putting streams on Sandbox:
Sandboxis a policy; a running process is an instance of that policy. Today's API stashes process state on the policy dataclass (_handle), which silently caps it at one process perSandbox. Splitting unblocks "launch many processes from one policy."- Streams only exist while a process is running. Putting them on
Sandboxwould either returnNonefor non-running instances or invent process state on the policy. Both are worse than a dedicated type. - The split is what
std::process,tokio::process, andanyio.open_processall converged on.subprocess.Popen(which conflates) is the cautionary tale.
popen() is async because streaming stdio is inherently async-shaped. Sync callers keep run() / spawn() / wait().
Example
async with await sandbox.popen(["server-bin", "--config", "x"]) as proc:
await proc.stdin.send(b'{"jsonrpc":"2.0","method":"...","id":1}\n')
chunk = await proc.stdout.receive(4096)
On context-manager exit: signal if still alive, wait, close pipes.
Implementation notes
- Rust core: extend the launch path with a stdio-mode variant that creates pipes (or inherits /
/dev/null) per stream and skips the existing capture reader threads. Reuse the seccomp / Landlock setup. - FFI: thread the three pipe fds out through the handle constructor.
sandlock_handle_wait_exitiswaitminus the buffered stdout / stderr fields. - Python: wrap the raw fds via anyio into
ByteReceiveStream/ByteSendStream. Context-manager lifecycle: kill on unclean exit, close fds, reap zombies. - anyio is already a transitive dependency via the
mcpextra. A sync-stream variant can be added later; do not dual-pave at first.
Open questions
popenvsopen_processfor the Python method name.popenreads as the right mental model; theProcessreturn type disambiguates fromsubprocess.Popen. Open toopen_processfor anyio symmetry.- Should
Process.wait()return an exit code, anExitStatus-like struct, or the existingResult? The existingResultincludes bufferedstdout/stderrwhich are meaningless in pipe mode. Lean: a slim type or bare exit code. - Does the legacy
Sandbox.spawn+waitkeep its current in-place shape, or migrate to also returnProcessand drop the stashed_handle? Pre-1.0 hard break is allowed; defer to a follow-up. - Behaviour if a
Processis dropped withoutwait(): kill-and-reap on drop, or leak-and-warn.std::process::Childleaks;tokio::process::Childcan kill if configured. Lean: kill on drop (safer default in a sandbox context).
Acceptance
Sandbox(net_allow=[]).popen(["cat"])round-trips a byte payload throughproc.stdin/proc.stdoutwhile the jail is enforced (verifiable by attempting a denied syscall inside the child).- Two processes can run concurrently from one
Sandboxinstance viapopen. - A subprocess killed via
proc.kill()returns a non-zero exit promptly; pipes close cleanly. - Dropping a
Processwithout callingwait()does not leak a child (verified bypgrep). - The
mcpPython SDK can drive a sandboxed MCP server end-to-end usingProcess.stdin/Process.stdoutasClientSessionstreams. - Rust integration test:
Sandbox::popen+Childround-trip undertokio.
Strong yes on the gap, and on the shape. The policy-vs-instance split — a separate Child / Process rather than streams hung off Sandbox — is the right call; subprocess.Popen's conflation is exactly the cautionary tale, and the cases genuinely blocked today (driving an MCP or LSP server over stdio while it's alive) can't be expressed in capture mode at all, not just awkwardly. A few notes from the current code, then an offer.
The launch path already has the seam
do_create(.., capture: bool) (sandbox.rs) branches on capture: the if capture arm sets up pipes that are drained internally into the buffered RunResult, and there are already inherit variants (create_interactive / spawn_interactive). So StdioMode::{Inherit, Piped, Null} isn't new machinery so much as generalizing a today-boolean (capture-vs-inherit, both streams together, no stdin pipe) into a per-stream enum. Piped is precisely "don't drain internally; hand the fd to the caller." That keeps Phase 1 small.
restore_interactive landed after the RFC was written
The checkpoint/restore merge (#105) added Sandbox::restore_interactive plus a ptrace seize/detach path and sandlock_handle_checkpoint on the FFI handle — there's now a second "live process" handle in the tree. Worth designing Child so it coexists with (or shares) that handle rather than becoming a third parallel notion. The RFC's "current state" predates this.
The conflation is still there
self._handle is stashed on the Sandbox dataclass (sandbox.py), so it's still one process per instance. Agree this is a real bug to fix rather than something popen should work around: returning a distinct Process is the natural place to stop parking process state on the policy. On open Q3, my lean is to fold the legacy spawn + wait into the same Process in the same pass (pre-1.0 break is cheap now, and leaving two process models around is what ages badly) — but a follow-up is fine if you'd rather land popen first.
Agree with your leans on the rest: popen over open_process; a slim exit type for wait() (the buffered stdout / stderr on today's Result are meaningless in pipe mode); kill-on-drop (the safe default in a jail).
Three things I'd raise:
- Signal the process group, not the pid. The child already does
setpgid(0, 0)at launch, and the existingSandbox::pause/resume/killsignal the whole group viakillpg.Child::kill/terminateshould do the same — a barekill(pid)leaks grandchildren if the child forks, and the acceptance test'spgrepcheck would pass forcatwhile quietly missing that. Note also the naming overlap:Sandbox::killalready exists as a group-SIGKILL, soChild::killneeds to be reconciled with it. take_*and&mutaccessors both — the dual surface invites use-after-take confusion (borrow a stream, take it, borrow again). Streaming callers move streams into read/write tasks, so I'd exposetake_*only and drop the borrowing accessors unless a concrete reader needs them.- Stdio permutations — 3×3 has nonsensical cells (inherit stdout + null stderr; piped stdin + inherit stdout). Worth documenting the sensible set or constraining the constructor, so the matrix doesn't become 27 supported combinations by accident.
One footgun for the docs: in Piped mode the caller now owns draining; a caller that stops reading stdout blocks the child at the first full-pipe write. Inherent to handing out the fd, but it moves from an internal capture detail to a user-visible contract, so it should be stated.
Offer
Happy to take Phase 1: Rust core Sandbox::popen() -> Child generalizing the capture seam into per-stream StdioMode, thin FFI threading the three pipe fds out, Python anyio wrapper with the context-manager kill-and-reap lifecycle. It follows std::process closely, so there's little to settle beyond Q3 (fold legacy spawn / wait now or later) and the signal-group / kill naming point. Say the word.
Yes please go for it, I appreciate your interest and help, @dzerik .