Skip to main content

pysandbox

CI CodeQL PyPI License Python Release

An asynchronous Wasmtime-backed Python sandbox with two-way RPC.

Installation

Install a prebuilt wheel from PyPI:

pip install pysandbox-wasi

For source builds, including builds that reuse the platform-independent component-runtime artifact, see Building.

Demo

python -m pysandbox.demo

One-Shot Execution

import asyncio

from pysandbox import PythonRuntime, RpcContext, RuntimeLimits


async def main() -> None:
  runtime = PythonRuntime()

  @runtime.rpc.expose
  def add(context: RpcContext, /, a: int, b: int) -> int:
    return a + b

  try:
    result = await runtime.execute(
      'print("2 + 5 =", await add(2, 5), flush=True)',
      limits=RuntimeLimits(timeout=30),
    )
    print(result.output.text, end="")
  finally:
    await runtime.close()


asyncio.run(main())

Exposed host handlers may be synchronous or asynchronous. Guest proxies are asynchronous, so guest code calls them with await. Each handler receives an RpcContext containing the worker and request IDs as its positional-only first argument. Pass rpc_methods={"method"} to execute() or run() to restrict which exposed methods that guest may call. Methods that are valid Python identifiers receive convenience proxy functions in the guest namespace. Non-identifier names are deliberately hidden from that namespace and must be invoked explicitly with await call("method/name", ...).

Persistent Workers

run() starts a persistent guest and returns immediately:

worker = runtime.run(
  """
value = 40

def increment(amount):
    global value
    value += amount
    return value
"""
)

print(await worker.call(("increment",), None, 2))
await worker.close()

The worker preserves its Python globals between calls. worker.task resolves when the guest exits, and worker.result.output exposes output collected so far. Calls made after the worker stops, or still pending when it closes, raise WorkerStoppedError. Worker calls are dispatched concurrently by default. Pass spin_concurrent=False to process them sequentially:

worker = runtime.run(program, spin_concurrent=False)

Both execute() and run() accept spin. It defaults to False for one-shot execution and True for persistent workers.

The positional options slot controls the call without reserving guest keyword arguments:

from pysandbox import AddFuel, WorkerCallOptions

options = WorkerCallOptions(
  fuel=AddFuel(500_000, cap=2_000_000),
  timeout=10,
)
print(await worker.call(("increment",), options, 2))

WorkerCallOptions.timeout limits how long the caller waits. It does not cancel the guest operation, which may continue executing and producing side effects.

call_function() executes an asynchronous function body against the worker's persistent globals. Values are passed as explicit keyword-only arguments, and the positional fuel slot accepts SetFuel, AddFuel, or None:

result = await worker.call_function(
  """
await asyncio.sleep(1)
return add(add(a, b), add(c, d))
""",
  AddFuel(500_000, cap=2_000_000),
  a=1,
  b=2,
  c=3,
  d=4,
)

Limits

Limits belong to an execution:

limits = RuntimeLimits(
  max_memory_bytes=128 * 1024 * 1024,
  max_output_bytes=256 * 1024,
  max_guest_rpc_bytes=10 * 1024 * 1024,
  fuel=2**64 - 1,
  timeout=30,
)

Persistent workers can update limits while running:

await worker.set_fuel(1_000_000)
await worker.add_fuel(500_000, cap=2_000_000)
await worker.set_limits(max_output_bytes=512 * 1024, timeout=60)

CPU Sharing

Active workers share the sandbox subprocess's measured CPU capacity. Configure the process-wide sampler when creating the runtime:

from pysandbox import CpuShareConfig, PythonRuntime

runtime = PythonRuntime(
  cpu_share=CpuShareConfig(
    enabled=True,
    limit_percent=100.0,
    sample_interval=0.1,
    activity_timeout=0.3,
  ),
)

Each execution has an integer weight, defaulting to one:

worker = runtime.run(program, limits=RuntimeLimits(cpu_share_weight=2))
await worker.set_limits(cpu_share_weight=4)

limit_percent=100 caps the whole sandbox subprocess at approximately one logical core; 200 permits two. Use None for weighted fairness without a total CPU ceiling.

Weights are progressive rather than reserved. A worker consumes its first weight unit before spilling into its second, so unused units remain available to other active workers. CPU sharing is disabled by default. Fuel limits and epoch interruption remain active when it is disabled.

Output

stdout and stderr are retained as interlaced output events:

print(result.output.stdout)
print(result.output.stderr)
print(result.output.text)

result.output is a live, read-only sequence. Existing references observe new worker output as it arrives; slicing it produces a detached Output snapshot.

formatted_text() can mark transitions between streams:

print(
  result.output.formatted_text(stderr=(b"\x1b[31m", b"\x1b[0m")),
  end="",
)

SystemExit and os._exit() produce TerminationReason.EXITED; their status is available as result.exit_code. The componentized Python runtime preserves 0 but normalizes every nonzero exit status to 1 through WASI Preview 3's success/failure exit operation. Other uncaught BaseException subclasses are reported as guest errors with a guest traceback.

Virtual Filesystem

/python is the packaged, immutable Python runtime. Other guest paths can be served by a host VFS:

from pysandbox import (
  PythonRuntime,
  VfsDirectoryEntry,
  VfsMetadata,
  VirtualFileSystem,
)


class Vfs(VirtualFileSystem):
  async def stat(self, path: str) -> VfsMetadata: ...

  async def read(self, path: str) -> bytes: ...

  async def list(self, path: str) -> list[VfsDirectoryEntry]: ...

  async def write(
    self,
    path: str,
    data: bytes,
    offset: int | None,
  ) -> None: ...


runtime = PythonRuntime(vfs=Vfs(), cache_vfs=True)

VirtualFileSystem requires stat, read, and list. Writable filesystems may implement write, delete, mkdir, append, truncate, and rename. Unsupported optional operations raise NotImplementedError. Native fallbacks provide append from an offset write, truncate from a complete read and rewrite, and non-atomic file rename from read, write, and delete. Directory rename requires an explicit implementation.

VfsMetadata and VfsDirectoryEntry expose independent read and write permissions. The guest receives normal filesystem errors for denied, unsupported, missing, conflicting, and non-empty-directory operations.

Handlers may be synchronous or asynchronous. With caching enabled, results are shared across workers until the host calls await runtime.invalidate_vfs(path). Passing no path clears the whole cache. Successful responses are cached by default. Set cache_vfs_negative=True to also cache non-I/O errors such as missing paths; overload, transport, and malformed-response errors are never cached. Successful mutations invalidate the affected cached paths. Directory invalidation removes its cached subtree; directory rename moves an already-cached subtree without scanning every cached path.

worker_queue_capacity bounds pending executions and user-level calls for each worker. When either queue is full, new work fails immediately without blocking traffic for other workers:

runtime = PythonRuntime(worker_queue_capacity=256)

host_dispatch_concurrency limits the combined number of guest RPC and VFS callbacks actively dispatched into the host Python application:

runtime = PythonRuntime(host_dispatch_concurrency=64)

host_dispatch_queue_capacity separately bounds pending host operations. When that queue is full, guest RPC and VFS operations receive an immediate overload error while connection routing remains responsive.

guest_dispatch_request_concurrency and guest_dispatch_request_queue_capacity apply the same controls independently to each worker. RPC and VFS requests share the worker's limits, preventing one guest from consuming the sandbox-wide host dispatch budget. Configure them on the execution's RuntimeLimits.

Wasmtime compilation is cached by default in the platform cache directory. Disable it or select an explicit directory with compilation_cache:

from pathlib import Path

runtime = PythonRuntime(compilation_cache=False)
runtime = PythonRuntime(compilation_cache=Path("custom-cache"))

True uses platformdirs.user_cache_path("pysandbox") / "wasmtime".

Packages

Resolve pure-Python wheels into immutable, reusable package layers, then attach the resulting environment to an execution:

from pysandbox import Package

environment = await runtime.packages.resolve(
  Package("requests==2.32.5", build=False),
  cache="by_version",
)
result = await runtime.execute(
  "import requests; print(requests.__version__)",
  packages=environment,
)

Dependencies are included by default. Set include_dependencies=False to resolve only the requested distribution. build=False rejects source distributions; enabling builds runs their build backend on the trusted host. Only compatible pure-Python wheels are accepted. source may point to a wheel, source archive, or source directory.

Package resolution and extraction can be bounded independently for the direct package and its dependencies:

package = Package(
  "example==1.0",
  build=False,
  max_size=10 * 1024 * 1024,
  max_files=1_000,
  max_dependencies=100,
  max_dependency_size=10 * 1024 * 1024,
  max_dependency_files=1_000,
)

All five limits default to None. They bound downloads and extracted wheel or source contents. An enabled source build is trusted host code and its build process is not sandboxed by these limits.

runtime.packages.cache exposes add(), resolve(), remove(), and packages(). The default uses the platform cache directory returned by platformdirs.user_cache_path("pysandbox"). Pass package_cache=PackageCache(path) to PythonRuntime to choose another location. cache="never" creates temporary layers owned by the returned environment; call environment.close() when it is no longer in use.

Internals

A PyO3 extension supervises a shared Rust sandbox subprocess without blocking the application's asyncio loop. The subprocess shares its Wasmtime engine and compiled component while giving every worker an isolated Store, component instance, CPython state, memory, capabilities, limits, and output stream.

See DOCS.md for the complete architecture and CONTRIBUTING.md for development, testing, and build instructions.

Metadata

Release files for pysandbox-wasi 1.6.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pysandbox-wasi 1.6.8
File Size Uploaded Provenance Actions
pysandbox_wasi-1.6.8.tar.gz 11.4 MB With provenance Details for pysandbox_wasi-1.6.8.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pysandbox-wasi 1.6.8
File Interpreter ABI Platform Actions
pysandbox_wasi-1.6.8-py3-none-any.whl Python 3 none any Details for pysandbox_wasi-1.6.8-py3-none-any.whl

Total release size: 24.1 MB

Release files / pysandbox_wasi-1.6.8.tar.gz

Download URL pysandbox_wasi-1.6.8.tar.gz
Size 11.4 MB
Tags Source
SHA-256 checksum
How to use checksums
2e897a704fd2e6c4025b979e58ba3eeff5ee60dfd06e32c5adc29d5f86051d0e
BLAKE2b-256 checksum
How to use checksums
d2e90880d835c259312a18686e93cf8ca34ae21b7a5268ca8cb995f060d7cf1b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / pysandbox_wasi-1.6.8-py3-none-any.whl

Download URL pysandbox_wasi-1.6.8-py3-none-any.whl
Size 12.8 MB
Tags Python 3
SHA-256 checksum
How to use checksums
64dda8f439642a7c8d262fb797b9d18585c09ea5f0c60d7165b96fea94c9399e
BLAKE2b-256 checksum
How to use checksums
24f48ab8b625264e1ec167129cb04a99afdcd70e72dc699b3b52e63634726654
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for pysandbox-wasi 1.6.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pysandbox_wasi-1.6.8.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page