Forking
Forking duplicates a running or paused local sandbox without saving a reusable snapshot. It shares memory through copy-on-write, keeps child writes private, and returns the source to its previous state. These methods are available on bothSandbox and SandboxHandle. Each child requires an unused name. See forking for examples, resource bindings, and backend limits.
fork() and fork_many()
fork(name) returns a ForkBuilder; fork_many(names) returns a ForkManyBuilder. Call .fork().await to start the operation. Both builders accept .record_integrity(), .guest_flush(GuestFlush::Required), and explicit resource bindings. Import GuestFlush from microsandbox::snapshot; Auto is the default, and Skip skips optional guest writeback. The single-child builder also exposes .fork_with_progress() with the local feature.
ForkOutcome
ForkManyBuilder::fork() reports batch validation or capture failure. Match each outcome’s result to handle individual child failures.
branch(), branch_many(), the builder .branch() terminal, .branch_with_progress(), and the BranchBuilder, BranchManyBuilder, and BranchOutcome types remain deprecated aliases.
Batch results follow input order. Validation or capture failures fail the whole call; an individual startup failure appears in that child’s outcome, and successful siblings remain available. Stop successful children explicitly when finished.
Sandbox
Sandbox::builder()
Example
Example
SandboxBuilder for all available options.
Parameters
nameimpl Into<String>Returns
Sandbox::get()
Example
Example
Parameters
name&strReturns
Sandbox::list()
Example
Example
Returns
Sandbox::list_with()
Example
Example
Sandbox::remove()
Example
Example
sb.remove_persisted(); see Destroy or remove for the exact deletion scope. Unlike remove_persisted(), this associated function routes through the default backend and also supports cloud sandboxes. Fails if the sandbox is still running. Stop it first.
Parameters
name&strSandbox::start()
Example
Example
Parameters
name&strReturns
Sandbox::start_detached()
Parameters
name&strReturns
Instance methods
sb.config()
Example
Example
Returns
sb.id()
sb.detach()
Example
Example
Sandbox::get().
sb.drain()
Example
Example
exec calls are rejected. The sandbox transitions to Stopped when all in-flight commands finish. Useful for zero-downtime rotation of worker sandboxes.
sb.request_drain()
wait_until_stopped() when the caller needs stopped-state observation.
sb.fs()
Example
Example
Returns
sb.kill()
Example
Example
fsync’d may be lost, same durability semantics as a sudden power loss on a physical machine. Prefer stop() for graceful shutdown that gives the workload a chance to flush.
sb.kill_with_timeout()
timeout for stopped-state observation.
sb.request_kill()
sb.metrics()
Example
Example
Returns
sb.metrics_stream()
Example
Example
interval duration.
Parameters
intervalDurationReturns
sb.logs()
Example
Example
exec.log. Backed by an on-disk JSON Lines file the runtime writes via the relay tap. Works on running and stopped sandboxes alike; there is no protocol traffic. The same method is available on SandboxHandle for callers that don’t want to start the sandbox first.
The default sources are Stdout, Stderr, and Output (PTY-merged). Pass LogSource::System to also include synthetic lifecycle markers and runtime/kernel diagnostic lines. logs() is synchronous because it’s a pure file read.
Parameters
opts&LogOptionstail, since, until, sources. LogOptions::default() returns everything for the default sources.Returns
sb.ping()
Example
Example
core.ping, returns the SDK-measured round-trip latency, and does not refresh the sandbox idle timer.
Returns
sb.touch()
Example
Example
core.touch; use it when keeping an idle sandbox alive is intentional.
Returns
sb.modify()
Example
Example
dry_run() to preview or apply() to commit. Both return a SandboxModificationPlan labeling each change live, next start, requires restart, or unsupported. Apply is all-or-nothing.
CPU and memory resize live within the max_cpus / max_memory ceilings; raising a ceiling requires a restart. Env and workdir changes affect future execs only. On a stopped sandbox, changes are saved for the next boot.
Changing a secret’s substitution rules, violation action, TLS identity requirement, or placeholder passthrough hosts requires a restart if the sandbox is running. Use .restart() to apply now, or .next_start() to save for the next start. Omitted options keep their current settings.
See SandboxModificationBuilder for all setters and msb modify for the CLI.
Returns
dry_run() or apply().sb.name()
Returns
sb.owns_lifecycle()
true; local detached handles and all cloud handles return false, because the cloud worker owns the sandbox process.
Returns
true for a local attached handle.sb.remove_persisted()
Example
Example
Sandbox instance; it has exactly the same deletion scope as Sandbox::remove(name). It does not perform additional cleanup. See Destroy or remove for what is deleted and which external resources are preserved.
sb.request_stop()
wait_until_stopped() when the caller needs the terminal state.
sb.stop()
Example
Example
kill() when force termination is intended.
sb.stop_with_timeout()
MicrosandboxError::StopTimeout without killing; Duration::ZERO expires before dispatch. A shutdown request already sent may complete later. Only explicit kill() requests force termination.
sb.stop_and_wait()
Example
Example
stop() or stop_with_timeout() when you only need completion.
Returns
sb.wait()
Example
Example
Returns
sb.wait_until_stopped()
Returns
sb.wait_for_status()
status. The method intentionally has no built-in timeout; wrap the future with tokio::time::timeout or another cancellation primitive when a deadline is required. Returns SandboxReplaced rather than following a reused name.
sb.restart()
sb.restart_with()
RestartOptions defaults to graceful shutdown, a ten-second timeout, and attached local start. Set force to kill instead of draining, timeout to control how long shutdown can take, and detached to start a local background sandbox.
sb.destroy()
remove_persisted(), destroy accepts a running sandbox, waits for it to shut down, and then deletes its persisted state.
sb.destroy_with()
DestroyOptions defaults to graceful shutdown with a ten-second timeout; set force to kill immediately or timeout to change how long shutdown can take. Identity checks prevent this receiver from deleting a same-name replacement.
sb.restore_warnings()
ExternalMountWarning contains:
SandboxBuilder
Builder for configuring a sandbox before creation. Obtained viaSandbox::builder(name). Every setter returns Self, so calls chain. Examples are shown on the methods where usage is non-obvious.
sandbox.slug()
Parameters
slugimpl Into<String>sandbox.build()
SandboxConfig without pulling an image or booting the sandbox. Validates fresh-boot configuration. Use Sandbox::restore() for snapshots. For booting, use create instead; call detached(true) first for background mode. Local create() keeps patches until image metadata is available. Cloud create() layers settings before sending the request; the cloud worker resolves image metadata.
Returns
sandbox.overlay()
overlay take precedence over the patch; managed overrides are applied last.
The builder uses the active backend’s cached configuration when build() or create() runs. Local creation stacks image defaults, global defaults, CLI/SDK patches, then managed overrides in one resolver before validation. Omitted fields inherit lower layers; explicit nullable clears survive image defaults. Cloud creation also applies user and managed settings, then rejects unsupported options before sending the request.
build() returns a concrete SandboxConfig without pulling image metadata. On local creation, workdir: None inherits global defaults, then image defaults if global workdir is omitted. A concrete config cannot distinguish omission from an explicit clear; use direct builder create() to preserve sparse clears through image resolution. Managed overrides apply last in both paths.
SandboxConfigPatch patches the SDK configuration. Its spec field is a SandboxSpecPatch for shared settings such as image, resources, and networking. Create-time options, including registry credentials, replacement settings, and the requested slug, live alongside spec.
Example
Example
replace_* methods to replace a complete collection; clear_* removes the field from the patch so the lower-precedence value remains unchanged.
Patch fields preserve the visibility of their source configuration fields, so ordinary fields and nested patches can be updated directly:
None omits the update, Some(None) clears the value, and Some(Some(value)) sets it.
Mergeable collections keep their merge/replacement state private and expose get_<field>() for borrowing their pending values. Ordinary fields have no generated getters. The collections’ get_<field>_mut() accessors edit pending values without cloning, initializing an absent collection empty in merge mode and preserving any existing replacement mode:
env_mut(...) to merge entries by name immediately, or replace_env_mut(...) to replace the collection. Fluent setters, replacements, clears, and overlay remain available, along with their _mut variants returning &mut Self.
Use fluent setters to construct patches and if let for optional inputs. Once all overlays are composed, into_config() applies the patch to the type’s defaults:
into_config() does not load configuration files, consult a backend, or validate the result. Keep patches for SandboxBuilder::overlay() when creating a sandbox so backend and managed settings can still be layered. Use apply_to(&mut config) when updating an existing value.
Both patches contain typed inputs. YAML loading, relative-path resolution, ${ENV} expansion, and snapshot lookup remain CLI or builder responsibilities. Runtime metadata stays internal, and create-time credentials and flags retain their existing serialization exclusions.
Migrating from the earlier patch types
Migrating from the earlier patch types
SandboxConfigPatch is now SandboxSpecPatch. To use it with the builder, wrap it with SandboxConfigPatch::new().spec(spec_patch). Update direct field access such as patch.resources to patch.spec.resources when using the SDK patch. Existing configuration files and serialized sandbox specifications keep their shape.The generated patch model also replaces the handwritten patch hierarchy from microsandbox 0.6.15 and earlier:SandboxSpecPatch, nested under SandboxConfigPatch.spec in the SDK. LocalConfig remains available as a deprecated alias of GlobalConfig.sandbox.cpus()
1.
Parameters
countu8sandbox.max_cpus()
Parameters
countu8sandbox.create()
Returns
sandbox.connect_or_create()
replace() returns InvalidConfig.
Returns
MicrosandboxResult<Sandbox>
sandbox.detached()
Example
Example
false.
Parameters
detachedbooltrue, create the sandbox in detached mode.sandbox.create_detached()
Example
Example
.detached(true).create(). Prefer detached(true) with create() for new code so attached and detached creation use the same flow.
Returns
sandbox.disable_network()
sandbox.entrypoint()
Sandbox::exec_default combines it with the effective CMD. Literal Sandbox::exec, Sandbox::attach, and Sandbox::shell calls ignore it.
Parameters
cmdimpl IntoIteratorsandbox.env()
exec_with) are merged on top.
Parameters
keyimpl Into<String>valueimpl Into<String>sandbox.hostname()
Parameters
hostnameimpl Into<String>sandbox.idle_timeout()
Parameters
secsu64sandbox.cmd()
create().
sandbox.init()
Example
Example
cmd after agentd finishes its boot-time setup. The agent forks; the parent execs the init and becomes PID 1; the agent continues as a child process. See Custom init system for image picks, shutdown semantics, and tradeoffs.
cmd is either an absolute path inside the guest rootfs or the literal "auto". Auto first honors a known init at the start of the image ENTRYPOINT, such as /init in s6-overlay images. If none is found, it falls back to probing /sbin/init, /lib/systemd/systemd, and /usr/lib/systemd/systemd inside the guest. When attached msb run uses an image-declared init entrypoint, the remaining ENTRYPOINT plus CMD or trailing command is passed to that init instead of direct-executed through agentd. For init binaries that take argv or extra env (rare), use init_with.
Parameters
cmdimpl Into<PathBuf>“auto”.sandbox.init_with()
Example
Example
init, but with a closure-builder for argv and env vars. Mirrors exec_with in shape. The builder exposes arg, args, env, and envs. Calling init or init_with more than once overwrites, unlike env, which appends. The init is one-shot pre-boot.
Parameters
cmdimpl Into<PathBuf>fFnOnce(InitOptionsBuilder)sandbox.image()
Parameters
imageimpl IntoImagesandbox.image_with()
Example
Example
Parameters
fFnOnce(ImageBuilder)sandbox.log_level()
Parameters
levelLogLevelsandbox.max_duration()
Parameters
secsu64sandbox.memory()
512 MiB.
Parameters
sizeimpl Into<Mebibytes>sandbox.max_memory()
Parameters
sizeimpl Into<Mebibytes>sandbox.thp()
TransparentHugePagePolicy::Madvise.
Parameters
policyTransparentHugePagePolicyAlways, Madvise, or Never.sandbox.guest_clock()
Parameters
policyGuestClockPolicySync (default) follows host time; Off stops host clock updates after boot.sandbox.network()
Parameters
sandbox.proxy()
sandbox.patch()
PatchBuilder for the operations.
Parameters
sandbox.port()
127.0.0.1.
Parameters
host_portu16guest_portu16sandbox.port_bind()
0.0.0.0.
Parameters
host_bindIpAddrhost_portu16guest_portu16sandbox.port_udp()
127.0.0.1.
Parameters
host_portu16guest_portu16sandbox.port_udp_bind()
Parameters
host_bindIpAddrhost_portu16guest_portu16sandbox.pull_policy()
Parameters
policyPullPolicysandbox.registry()
Example
Example
Parameters
sandbox.replace()
sandbox.script()
/.msb/scripts/ inside the guest. Scripts are added to PATH and can be called by name via exec() or shell().
Parameters
nameimpl Into<String>contentimpl Into<String>sandbox.secret()
Parameters
sandbox.secret_env()
.secret(|s| s.env(env_var).value(value).allow(allowed_host)).
Parameters
env_varimpl Into<String>= or NUL).valueimpl Into<String>allowed_hostimpl Into<String>sandbox.shell()
Sandbox::shell(). Default: /bin/sh.
Parameters
shellimpl Into<String>“/bin/bash”).sandbox.user()
Parameters
userimpl Into<String>sandbox.volume()
Parameters
guest_pathimpl Into<String>sandbox.workdir()
Parameters
pathimpl Into<String>PatchBuilder
Builder for pre-boot root filesystem patches.patch.append()
content to an existing file at path. If the file lives in a lower image layer, it’s copied up first.
Parameters
pathimpl Into<String>contentimpl Into<String>patch.copy_dir()
src into the guest rootfs at dst.
Parameters
srcimpl Into<PathBuf>dstimpl Into<String>replacebooltrue, overwrite an existing path at dst.patch.copy_file()
src into the guest rootfs at dst.
Parameters
srcimpl Into<PathBuf>dstimpl Into<String>modeOption<u32>Some(0o644). None keeps the source mode.replacebooltrue, overwrite an existing path at dst.patch.file()
path.
Parameters
pathimpl Into<String>contentimpl Into<Vec<u8>>modeOption<u32>Some(0o644).replacebooltrue, overwrite an existing path.patch.mkdir()
path. Idempotent: a no-op if the directory already exists.
Parameters
pathimpl Into<String>modeOption<u32>Some(0o755).patch.remove()
path. Idempotent: a no-op if the path doesn’t exist.
Parameters
pathimpl Into<String>patch.symlink()
link pointing to target.
Parameters
targetimpl Into<String>linkimpl Into<String>replacebooltrue, overwrite an existing path at link.patch.text()
path.
Parameters
pathimpl Into<String>contentimpl Into<String>modeOption<u32>Some(0o644).replacebooltrue, overwrite an existing path.SandboxModificationBuilder
Builder for planning or applying sandbox configuration changes.modification.apply()
next_start(), are saved and take effect on the next start. With restart(), apply() stops and starts the sandbox so that restart-required changes take effect.
A live CPU or memory resize can take a moment to settle. The returned plan’s resize_status reports progress per resource; see ResourceResizeStatus.
Returns
applied: true and live resize outcomes in resize_status.modification.cpus()
max_cpus; otherwise it requires a restart.
Parameters
cpusu8modification.max_cpus()
Parameters
max_cpusu8modification.dry_run()
Example
Example
Returns
applied: false.modification.env()
Parameters
keyimpl Into<String>valueimpl Into<String>modification.remove_env()
env().
Parameters
keyimpl Into<String>modification.label()
Parameters
keyimpl Into<String>valueimpl Into<String>modification.remove_label()
Parameters
keyimpl Into<String>modification.memory()
max_memory; otherwise it requires a restart.
Parameters
sizeimpl Into<Mebibytes>modification.memory_mib()
memory() with an explicit unit.
Parameters
memory_mibu32modification.max_memory()
Parameters
sizeimpl Into<Mebibytes>modification.max_memory_mib()
max_memory() with an explicit unit.
Parameters
max_memory_mibu32modification.next_start()
next start.
modification.restart()
apply() stops the sandbox, persists the config, and starts it again so the changes become active now.
modification.secret()
Example
Example
SecretPatchBuilder closure. The spec mirrors the create-time SecretBuilder vocabulary. The planner diffs it against the existing config to infer the change. A secret that does not exist yet is added, and material on an existing secret is rotated. Host or placeholder differences update those aspects. Declaring the same secret again replaces the earlier spec; removal is always explicit through remove_secret().
Parameters
fFnOnce(SecretPatchBuilder)modification.remove_secret()
Parameters
nameimpl Into<String>modification.workdir()
Parameters
pathimpl Into<String>RegistryConfigBuilder
Used by registry()
Builder passed toregistry() for per-sandbox registry connection settings.
registry.auth()
registry.insecure()
registry.ca_certs()
SandboxListBuilder
Fluent configuration passed toSandbox::list_with(). Keep the labels and limit unchanged when continuing with a cursor.
list.limit()
list.cursor()
next_cursor
list.label()
list.labels()
SandboxHandle
Returned by Sandbox::get() · Sandbox::list()
A sandbox metadata and lifecycle handle that does not require an active guest-agent connection.h.config()
Returns
Result<SandboxConfig>
h.config_json()
Returns
&str
h.connect()
Returns
Result<Sandbox>
h.connect_with_timeout()
connect() with an explicit timeout
Returns
Result<Sandbox>
h.connect_or_start()
Starting, or start it in attached mode when it is Created, Stopped, or Crashed. Draining and Paused are rejected. If another caller starts it at the same time, both callers connect to the same sandbox without following a same-name replacement.
h.connect_or_start_detached()
connect_or_start(), but starts a local stopped sandbox in detached/background mode. Connecting to an already-running sandbox never changes its ownership.
h.created_at()
Returns
Option<DateTime<Utc>>
h.kill()
Returns
Result<()>
h.kill_with_timeout()
kill() with an explicit observation timeout
Returns
Result<()>
h.logs()
exec.log (works without starting)
Returns
Result<Vec<LogEntry>>
h.metrics()
Returns
Result<SandboxMetrics>
h.modify()
Returns
SandboxModificationBuilder
h.name()
Returns
&str
h.id()
SandboxReplaced if the reusable name now points to another sandbox.
h.ping()
Returns
Result<SandboxPingResult>
h.remove()
Returns
Result<()>
h.request_drain()
Returns
Result<()>
h.request_kill()
Returns
Result<()>
h.request_stop()
Returns
Result<()>
h.start()
Returns
Result<Sandbox>
h.start_detached()
Returns
Result<Sandbox>
h.wait_for_status()
status, returning a refreshed handle. Returns SandboxReplaced rather than rebinding to a same-name replacement.
h.restart()
h.restart_with()
sb.restart_with() for state behavior and defaults.
h.destroy()
h.destroy_with()
sb.destroy_with() for defaults.
h.status()
Returns
SandboxStatus
h.stop()
Returns
Result<()>
h.stop_with_timeout()
stop() under one total budget. Expiry returns MicrosandboxError::StopTimeout without killing; Duration::ZERO expires before dispatch.
Returns
Result<()>
h.touch()
Returns
Result<SandboxTouchResult>
h.updated_at()
Returns
Option<DateTime<Utc>>
h.wait_until_stopped()
Returns
Result<SandboxStopResult>
SecretPatchBuilder
Used by secret()
Builder for one declarative secret change.secret.env()
Parameters
nameimpl Into<String>secret.source()
SecretSource reference. The durable config records only the reference, and the value is resolved host-side when the change applies. Mutually exclusive with value(...).
Parameters
sourceSecretSourcesecret.value()
Debug, and never enters the plan. Applying a value persists it into the durable config until a later source-based rotate migrates it to a reference, the same at-rest property as secret_env(). Mutually exclusive with source(...).
Parameters
valueimpl Into<String>secret.placeholder()
requires restart on a running sandbox.
Parameters
placeholderimpl Into<String>secret.allow()
api.example.com, *.example.org, or *. A non-empty list replaces the secret’s current allow-list; an empty list leaves it unchanged. A new secret needs at least one.
Parameters
hostimpl Into<String>*.secret.substitution()
secret.allow_placeholder_for()
allow_passthrough_for() remains a deprecated alias. This does not grant access to the real secret.
secret.violation_action()
secret.require_tls_identity()
Types
LogEntry
Returned by logs()
A single captured log entry returned bylogs().
LogLevel
Used by log_level()
Sandbox process log verbosity.LogOptions
Used by logs()
Filters passed tologs(). All fields optional. LogOptions::default() returns everything for the default sources (Stdout + Stderr + Output).
LogSource
Used by LogEntry.source · LogOptions.sources
Tag indicating where a captured log entry came from.SandboxPingResult
Returned by ping() · SandboxHandle.ping()
Result of a successful agent reachability check.SandboxTouchResult
Returned by touch() · SandboxHandle.touch()
Result of an explicit idle-timer refresh.PullPolicy
Used by pull_policy()
Controls when the SDK fetches an OCI image from the registry.RegistryAuth
Used by registry()
Credentials for authenticating to a private container registry.SandboxConfig
Returned by config() · build()
The full configuration of a sandbox. Obtained viaconfig() or built via SandboxBuilder. Contains all settings used to create the sandbox.
SandboxPage
One stable, newest-first page returned bySandbox::list() or Sandbox::list_with().
SandboxModificationPlan
Returned by dry_run() · apply()
Dry-run or apply plan for a sandbox modification. Values never appear in a plan: secret entries carry only guest-visible references.SecretSource
Used by SecretPatchBuilder.source()
Host-side source for secret material. The source is resolved when the modification applies, and plans only show guest-visible references. Import path:microsandbox::sandbox::SecretSource.
PlannedChange
Used by SandboxModificationPlan.changes
One planned modification entry. This enum has aConfig variant for ordinary configuration fields and a Secret variant for secret changes.
ConfigPlannedChange
Variant of PlannedChange::Config
Ordinary configuration change in a modification plan.SecretPlannedChange
Variant of PlannedChange::Secret
Secret change in a modification plan. Values are omitted by construction;before_ref and after_ref are guest-visible references.
ModificationDisposition
Used by ConfigPlannedChange.disposition · SecretPlannedChange.disposition
When or whether a planned change can take effect. Serializes as the quoted strings below.ResourceResizeStatus
Used by SandboxModificationPlan.resize_status
Runtime convergence status for a live resource resize. Enforcement applies immediately; the guest converges asynchronously (onlining CPUs, plugging memory blocks).SandboxStopResult
Observed terminal sandbox state returned bywait_until_stopped().
SandboxMetrics
Returned by metrics() · metrics_stream()
Point-in-time resource usage snapshot.SandboxStatus
Used by SandboxHandle.status()