Introducing a new way to review your PRs.

Read the announcement

superradcompany / microsandbox

🧱 easy, fast, programmable and local-first microVM runtime and library

View on GitHub

27 documents · Updated Nov 23, 2026

docs / rust-sdk

Rust SDK implementation

The Rust SDK gives applications one async API for isolated sandboxes on a local host or in Microsandbox Cloud. A retained Context selects the destination, while the same sandbox, volume, snapshot, log, and agent concepts work across both backends. See SDK bindings for the shared binding model, language binding adapters for other languages, and service management APIs for cloud services.

Context model

Context destinations

Context is the SDK term for a retained execution destination. It owns the settings and transport state for one local catalog or cloud account. Resource collections keep that context, so later calls do not switch destination because ambient settings changed.

Local and remote contexts expose the same resource surfaces. Backend limits remain visible through typed unsupported errors instead of changing the selected destination.

References: sdk/…/mod.rs• L1-36 sdk/…/mod.rs• L50-68 sdk/…/dispatch.rs• L22-131

Local context

LocalContext runs microVM sandboxes on the caller's host. It captures resolved paths, policy, registry settings, and database settings when it is built. The local catalog opens on first use unless the caller asks for eager startup.

The catalog is the durable record for sandboxes, volumes, runs, and snapshots. Startup coordinates schema migration, artifact reconciliation, and maintenance leases before local operations use that state. Multiple explicit contexts can therefore keep separate homes and policies.

Incomplete creates also have durable ownership. Cleanup removes files before it releases catalog ownership, and recovery keeps the record when cleanup cannot prove that removal finished.

References: sdk/…/mod.rs• L71-105 sdk/…/mod.rs• L118-205 sdk/…/mod.rs• L490-507 sdk/…/creation.rs• L127-228

Remote context

RemoteContext sends resource and lifecycle work to a cloud-compatible HTTP API. It captures the endpoint, credentials, request settings, compute choice, and policy at construction time. The same model supports the hosted service and compatible self-hosted endpoints.

Cloud lifecycle calls use HTTP. Cloud logs use server-sent events (SSE), and guest work uses an authenticated agent WebSocket. The cloud service owns sandbox and volume identity, so the SDK uses server IDs for receiver operations after a name lookup.

References: sdk/…/http.rs• L110-135 sdk/…/http.rs• L138-264 sdk/…/http.rs• L505-632 sdk/…/mod.rs• L26-36

Configuration error context

An invalid explicit backend selection becomes a fail-closed context. It remembers the original configuration error and returns that error for later resource calls instead of falling back to local execution.

This preserves the caller's deployment intent. A failed cloud selection cannot silently create a local sandbox with different isolation or data placement.

References: sdk/…/misconfigured.rs• L29-63 sdk/…/misconfigured.rs• L69-108 sdk/…/misconfigured.rs• L110-245

Runtime setup

Runtime pair

Local execution needs a matching msb executable and libkrunfw firmware library. Runtime setup treats them as one usable pair. It refuses a partial or incompatible selection instead of choosing another file without the caller's knowledge.

Resolution is read-only. Explicit setup can install and verify a complete pair so later local starts use the selected runtime.

References: sdk/…/runtime.rs• L48-102 sdk/…/runtime.rs• L124-199 sdk/…/runtime.rs• L225-328

Launch contract

The launch contract states what a selected runtime can honor. The SDK checks requested resources, mounts, network policy, security settings, restore state, and other launch intent before it starts or replaces a local sandbox.

This check prevents an older runtime from silently dropping a requested setting. The same admission rule is used again when a stopped sandbox starts with a different installed runtime.

References: sdk/…/launch_contract.rs• L53-62 sdk/…/launch_contract.rs• L228-307 sdk/…/launch_contract.rs• L508-614 sdk/…/spawn.rs• L310-364

Sandbox process

Local spawning turns a prepared sandbox into an owned runtime process and an agent relay endpoint. It prepares guest files and storage, resolves the runtime pair, checks launch capabilities, starts msb machine, reads startup identity, and returns only after the startup contract is met.

The main flow is:

flowchart TD
    A[Sandbox request] --> B[Resolve backend and storage]
    B --> C[Prepare rootfs mounts scripts and logs]
    C --> D[Resolve runtime and launch contract]
    D --> E[Start runtime process]
    E --> F[Read startup identity]
    F --> G[Connect agent relay]
    G --> H[Publish usable sandbox]

Attached mode ties the process to the creating process. Detached mode transfers survival to the runtime. A full snapshot restore uses detached ownership because it resumes an already captured workload rather than starting a new foreground command.

References: sdk/…/spawn.rs• L192-261 sdk/…/spawn.rs• L263-305 sdk/…/spawn.rs• L417-479 sdk/…/spawn.rs• L808-944 sdk/…/mod.rs• L1125-1136

Sandbox resources

Sandbox builder

SandboxBuilder collects the requested image, guest resources, command defaults, environment, mounts, network rules, lifecycle mode, registry choices, patches, and snapshot source. It retains the context that created it, so deferred build work uses the same destination.

The backend finishes the request by applying image defaults and managed policy. Local creation resolves images and prepares host state. Cloud creation converts the result to the cloud request and rejects fields that the cloud cannot honor instead of dropping them.

Named volume creation also differs by backend. Local creation can provision inline named volumes. Cloud creation supports only the service's ensure-existing behavior and creates missing named volumes through the cloud API.

References: sdk/…/builder.rs• L57-92 sdk/…/create.rs• L173-284 sdk/…/sandbox.rs• L195-270 sdk/…/sandbox.rs• L665-766

Sandbox creation

Local creation protects image files while it prepares the rootfs, records durable ownership before starting the runtime, and keeps a recovery record until the sandbox is ready. A failed preparation removes or retains that record according to what cleanup can prove.

The local path supports OCI images, host bind roots, disk images, snapshot restores, named volumes, and rootfs patches. It validates the final configuration before the VM starts and records the image dependency so stopped sandboxes keep their backing files safe from pruning.

Cloud creation validates the shared configuration first, resolves environment-backed secrets at create time, provisions supported named volumes, and asks the service to create or create-and-start the sandbox. A successful start must report running; a response that is still starting is an error rather than a usable sandbox.

References: sdk/…/create.rs• L122-170 sdk/…/create.rs• L197-284 sdk/…/create.rs• L1124-1282 sdk/…/sandbox.rs• L195-270 sdk/…/sandbox.rs• L1090-1111

Sandbox handles

Sandbox is the live resource view. SandboxRecord is an inspection and lookup view that does not start the guest. Both retain the backend context and a stable identity.

The name is a lookup key, not the full identity. Local identity comes from the catalog. Cloud identity comes from the service. Receiver operations refresh by name and compare the captured identity, so a stale handle cannot act on a replacement that reused the name.

Live status is fetched from the backend. A record's status is only an observation captured at lookup time. Guest access is prepared lazily, while inspection and log reads can remain non-starting.

References: sdk/…/mod.rs• L312-331 sdk/…/handle.rs• L84-111 sdk/…/handle.rs• L187-203 sdk/…/handle.rs• L421-443 sdk/…/mod.rs• L810-819

Lifecycle operations

The unified lifecycle surface supports lookup, create, start, connect, stop, kill, drain, restart, destroy, refresh, and waits for state convergence. Local operations may own a host process. Cloud operations ask the service to manage the worker.

connect_or_start observes the current state and converges only when it is safe. It waits for Starting, starts terminal non-running states, and rejects Draining or Paused instead of guessing. Graceful stop and force termination are separate actions; a timeout does not imply that a kill occurred.

References: sdk/…/handle.rs• L532-647 sdk/…/handle.rs• L805-881 sdk/…/handle.rs• L915-979 sdk/…/mod.rs• L73-317 sdk/…/sandbox.rs• L141-193

Sandbox modifications

Sandbox changes use a plan-first contract. A dry run reports conflicts, warnings, and whether each change is live, restart-backed, next-start, or unsupported. Apply follows that plan.

Cloud planning can describe secret changes without sending secret values. The apply request sends a secret at most once after local validation. An uncertain response is reported as uncertain, so the caller must inspect the sandbox before retrying.

References: sdk/…/mod.rs• L254-263 sdk/…/patch.rs• L728-789 sdk/…/http.rs• L316-348

Rootfs patches

Patches describe guest filesystem changes such as writes, copies, directory creation, links, removal, and append. Local bind-root patches apply through a confined host view. OCI patches become a private rootfs result before boot.

Optional source staging turns host copy inputs into bounded, private inputs before a patch worker consumes them. The staging policy can limit bytes, entries, depth, and concurrent batches. This keeps a changing host source from changing the meaning of an admitted patch and prevents special files from becoming patch inputs.

References: sdk/…/patch.rs• L61-76 sdk/…/patch.rs• L728-789 sdk/…/patch_sources.rs• L36-62 sdk/…/patch_sources.rs• L99-196 sdk/…/files.rs• L66-135

Agent bridge

Agent transport

The agent is the common guest control path for command execution, interactive attach, filesystem work, ping, touch, and lifecycle requests. Local sandboxes reach it through the relay endpoint. Cloud sandboxes open an authenticated WebSocket route tied to the cloud sandbox identity.

After connection, both backends use the same framed agent protocol. WebSocket chunks are only transport pieces; the protocol still owns message boundaries and flow control.

References: sdk/…/client.rs• L25-29 sdk/…/client.rs• L74-109 sdk/…/http.rs• L411-499 sdk/…/agent.rs• L63-147 sdk/…/ws_io.rs• L28-38

Binding bridge

AgentBridge is the binding-safe form of an agent connection. It exposes frame metadata and byte payloads without leaking Rust receivers, callbacks, or generic stream types across a language boundary.

Bindings must preserve frame order, stream completion, and backpressure. A bridge is therefore more than a byte pipe: it keeps the guest protocol's stream contract stable for each language adapter.

References: sdk/…/bridge.rs• L1-11 sdk/…/bridge.rs• L31-62 sdk/…/bridge.rs• L114-270

Logs

Log sources

The SDK exposes output as typed LogEntry values. Local entries come from retained runtime log files. Cloud entries come from the service's live SSE stream.

The shared model carries source, timestamp, data, and a cursor. Local reads can inspect retained history. Cloud currently supports live follow only.

References: sdk/…/mod.rs• L1-37 sdk/…/mod.rs• L98-143 sdk/…/http.rs• L411-499

Log history

Local history supports bounded reads, source and time filters, and a cursor handoff from a snapshot to a follow stream. If local rotation removes data before a consumer resumes, the SDK returns MissedRotation instead of skipping the missing range.

Cloud follow sends the cursor as Last-Event-ID and maps SSE events to the same log entries. Bounded cloud snapshots and bounded follow filters return typed unsupported errors because the cloud endpoint does not provide the local history contract.

References: sdk/…/mod.rs• L39-56 sdk/…/mod.rs• L166-199 sdk/…/http.rs• L433-499 sdk/…/http.rs• L824-977

Snapshots

Snapshot histories

Snapshot is an immutable captured state. A snapshot group is a named history that selects one member as its head. Capture returns the exact member and head result produced by that capture, so later head changes do not change the caller's result.

Local capture publishes a complete artifact from private staging. The group and ancestry commit happen after the artifact is valid. A source recovery problem remains visible even when the artifact was published, so callers can distinguish a usable artifact from a source that still needs attention.

References: sdk/…/group.rs• L19-64 sdk/…/group.rs• L212-250 sdk/…/create.rs• L218-365 sdk/…/create.rs• L1317-1355

Snapshot capture

Disk capture preserves writable disk state. Full capture also records memory and execution state for a resumed workload. Full capture requires a running OCI-rooted sandbox; disk capture can use a stopped or live source under the backend's consistency rules.

The source remains protected while the capture worker reads it. The SDK validates the checkpoint identity, image identity, disk layout, and captured owned-volume inventory before it publishes the result.

References: sdk/…/create.rs• L423-640 sdk/…/create.rs• L642-797 sdk/…/create.rs• L1109-1300

Snapshot archives

Local archives export snapshot state without requiring the destination to install an intermediate artifact. The archive can contain a disk snapshot or a full checkpoint and can include parents and image data when requested.

Archive load validates the inventory, descriptor identity, dependencies, payload integrity, and restore requirements before it produces child-owned state. Sparse disk data stays sparse, and archive publication uses a temporary file before the final output becomes visible.

References: sdk/…/archive.rs• L1-10 sdk/…/archive.rs• L255-615 sdk/…/archive.rs• L804-1055 sdk/…/copy.rs• L128-173

Snapshot restores

Restore creates a new child from captured state. It validates the checkpoint against its descriptor, copies or links the needed disk layers into child-owned staging, and adds a fresh writable head. Full restore also prepares memory and execution state for resume. Disk-only restore uses the disk closure and performs a new boot.

Captured sandbox-owned volumes are restored as child-owned backing. Explicit mappings cannot replace that captured ownership. External mounts remain destination choices and must be admitted separately.

The child owns all sources needed after publication. The original snapshot or archive can therefore be removed after restore without breaking the new sandbox.

References: sdk/…/restore.rs• L32-47 sdk/…/restore.rs• L53-120 sdk/…/restore.rs• L123-168 sdk/…/owned.rs• L19-133

Volumes

Volume resources

Volume is persistent storage that can outlive a sandbox. The public resource type works with local and cloud contexts, and its identity remains tied to the context that opened it.

Local volumes are host-managed. Cloud volumes are service-managed and have server identity and capacity. Cloud also provides a service-owned default volume; local does not invent an equivalent resource.

References: sdk/…/mod.rs• L1-22 sdk/…/volume.rs• L31-105 sdk/…/volume.rs• L107-153 sdk/…/http.rs• L505-577

Volume filesystem

VolumeFs provides direct file access without a running sandbox. Local access stays inside the selected volume root. Cloud access uses authenticated volume file requests, so cloud bytes do not become an implicit host path.

The shared model covers reads, writes, streams, directories, metadata, copy, rename, and removal. The backend keeps volume identity and path boundaries part of each request.

References: sdk/…/fs.rs• L1-10 sdk/…/fs.rs• L45-65 sdk/…/fs.rs• L168-277 sdk/…/http.rs• L579-632

Volume mounts

Sandbox configuration can mount named, owned, temporary, bind, or disk storage into the guest. The mount is guest-facing state, while the volume remains a separately owned resource.

Local creation tracks newly made named volumes under the in-progress sandbox until publication or cleanup. This prevents an interrupted create from leaving volume ownership unclear.

References: sdk/…/create.rs• L1079-1093 sdk/…/creation.rs• L141-225 sdk/…/builder.rs• L1224-1257

Integration contracts

Public Rust surface

The crate root is the stable Rust entry point for applications and language adapters. It re-exports contexts, sandbox builders and handles, agent types, logs, snapshots, volumes, setup, progress, and typed errors without requiring callers to depend on private module layout.

Cargo features select build-time capabilities. The public surface must remain coherent when a binding enables only local, cloud, networking, SSH, or another subset.

References: sdk/…/lib.rs• L16-35 sdk/…/lib.rs• L37-128 sdk/…/api_boundary.rs• L1-95 sdk/…/Cargo.toml• L19-60

Binding boundary

Language adapters need stable entry points for context creation, resource identity, async completion, streams, progress, and errors. Context option JSON is explicit and rejects unknown fields. Credentials remain inside Rust.

The boundary must preserve whether a result is live or a snapshot, whether an operation is local-only or cloud-only, and whether an uncertain mutation is safe to retry.

References: sdk/…/options.rs• L16-41 sdk/…/options.rs• L47-121 sdk/…/api_boundary.rs• L31-71 sdk/…/misconfigured.rs• L69-108

Resource contract

Resource traits connect one public resource surface to the context that owns its implementation. Returned sandboxes, volumes, snapshots, checkpoints, and services retain that context. Names select resources for lookup; stable identities protect receiver operations from replacement.

Local and cloud operations share types and meanings where the backends can provide the same contract. Backend-specific limits remain typed and visible.

References: sdk/…/sandbox.rs• L167-209 sdk/…/volume.rs• L107-153 sdk/…/service.rs• L23-27 sdk/…/handle.rs• L1099-1116

Protocol contract

The agent protocol carries guest requests and streamed events. The SDK maps it to execution, filesystem, attach, lifecycle, and binding-bridge results. Cloud WebSockets provide transport only; they do not replace the agent protocol.

Flow control is part of the contract. Input admission, output consumption, transport backpressure, and binding stream handling must stay aligned or guest work can stall.

References: sdk/…/client.rs• L35-55 sdk/…/ws_io.rs• L59-133 sdk/…/sandbox.rs• L351-395 sdk/…/bridge.rs• L31-62

Error contract

Typed errors describe invalid configuration, missing or replaced resources, unsupported backend operations, runtime incompatibility, snapshot integrity failures, lost log history, command outcomes, and uncertain control work.

The SDK fails closed when it cannot prove the requested meaning. It does not accept a partial runtime pair, drop a cloud-unsupported field, follow a stale identity, hide missed log history, or retry a change whose outcome is unknown.

References: sdk/…/error.rs• L118-161 sdk/…/error.rs• L195-242 sdk/…/http.rs• L670-817 sdk/…/misconfigured.rs• L40-63

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep context capture, resource ownership, default routing, and fail-closed configuration errors aligned. A resource must not resolve through a new ambient context after creation.
  • Keep runtime pair resolution, launch capability checks, startup identity, agent readiness, and attached or detached ownership aligned.
  • Keep local creation recovery records, image dependencies, named-volume ownership, runtime handoff, and cleanup ordering aligned.
  • Keep cloud request conversion, readiness waits, server identity routes, named-volume provisioning, and unsupported-field checks aligned.
  • Keep builder field presence, managed policy, snapshot restore intent, and persisted active configuration aligned.
  • Keep sandbox names, stable identities, refresh checks, local run generations, and cloud IDs aligned.
  • Keep rootfs patch admission, host source staging limits, bind-root confinement, OCI baking, and snapshot editing aligned.
  • Keep log cursors, local rotation errors, cloud SSE IDs, source filters, and cloud follow limits aligned.
  • Keep snapshot descriptors, group heads, source recovery outcomes, archive inventories, child-owned restore state, and owned-volume bindings aligned.
  • Keep volume identity, root confinement, active mounts, cloud volume IDs, and streaming transfer timeouts aligned.
  • Keep public re-exports, Cargo feature gates, binding option fields, agent frame handling, and typed error mappings aligned.

Important failure modes

TriggerConsequenceGuard
The runtime executable and firmware do not form a valid pairLocal start cannot safely select a runtimeResolve and verify the pair before launch
A cloud create request contains a field the cloud cannot honorThe service could create a sandbox different from the requestReject unsupported fields at the cloud boundary
A create or cleanup stops before durable ownership is publishedFiles or named volumes can remain without a safe ownerKeep the recovery record and retry cleanup under ownership locks
Startup returns before identity or agent readiness is provenThe caller receives a sandbox that cannot safely accept guest workValidate startup identity and complete the agent readiness step before publication
A stale handle addresses a reused nameLifecycle or guest work can reach a different sandboxCompare the captured local or cloud identity
A cloud response is lost after a mutation requestRetrying can apply the change twiceReport the outcome as unknown and refresh before retrying
A local log consumer falls behind file rotationThe stream loses part of its historyReturn MissedRotation and require a new cursor choice
A snapshot archive or checkpoint changes after admissionRestore can use the wrong captured stateVerify descriptor, payload, checkpoint, and source identity before publication
A restore publishes captured backing as shared mutable stateA later source removal or child write can corrupt another resourceMaterialize child-owned layers, writable heads, and owned volumes
A patch source is a special file, oversized tree, or unsafe pathPatch work can block, exceed policy, or escape the intended rootPin regular files and directories, enforce budgets, and keep destinations root-scoped

Key files

FileWhy to read it
sdk/…/mod.rsPublic context types and backend selection surface
sdk/…/mod.rsLocal configuration capture, catalog startup, and ownership
sdk/…/creation.rsDurable ownership and cleanup of incomplete local creates
sdk/…/create.rsLocal image, storage, snapshot, patch, and launch flow
sdk/…/mod.rsLocal lifecycle, state reconciliation, and backend dispatch
sdk/…/sandbox.rsCloud request conversion, readiness, identity, and lifecycle behavior
sdk/…/http.rsCloud HTTP routes, SSE logs, volume transfers, and error mapping
sdk/…/spawn.rsRuntime preparation, process ownership, launch handoff, and readiness
sdk/…/mod.rsUnified sandbox resource and guest operation surface
sdk/…/handle.rsInspection handles, identity checks, lifecycle convergence, and reconnect behavior
sdk/…/patch.rsRootfs patch meaning and confined local application
sdk/…/patch_sources.rsBounded staging policy for host copy inputs
sdk/…/create.rsDisk and full capture plus publication and recovery outcomes
sdk/…/archive.rsSnapshot archive export, validation, and direct restore materialization
sdk/…/restore.rsChild-owned disk and checkpoint restore state
sdk/…/owned.rsRestoration of sandbox-owned volume backing
sdk/…/client.rsCommon guest transport and protocol connection
sdk/…/bridge.rsBinding-safe agent frame and stream boundary
sdk/…/mod.rsShared log entries, cursors, rotation, and follow semantics
sdk/…/fs.rsShared direct-volume filesystem model
sdk/…/error.rsTyped failure and retry-certainty contract
sdk/…/api_boundary.rsCompile-time checks for the stable public API