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 / managed-jobs

Managed jobs

Managed jobs are sandbox-scoped commands that the runtime owns after launch. They let an application or operator start a command without keeping the launching process open, inspect its state, replay its output, attach input later, and end it with an explicit signal while the sandbox keeps its own lifecycle. See sandbox lifecycle for the parent state model, runtime execution for guest process orchestration, CLI sandbox operations for operator flows, and SDK bindings for the wider language API model.

Managed-job model

The managed-job model separates command identity from the host connection that starts or observes it. A job has a stable ID inside one sandbox and durable metadata, while temporary clients can connect and disconnect without stopping the process.

ConcernManaged-job behavior
IdentityA client-generated job ID identifies one admitted command. It is not a guest PID or a connection ID.
OwnershipThe runtime owns the command. Dropping an SDK job object or detaching a client does not terminate it.
ScopeThe job belongs to the sandbox and retains that sandbox's identity. A name reuse cannot redirect an old job reference.
HistoryMetadata and captured output remain available after a confirmed exit and, when possible, after sandbox shutdown.
InputPipe input can remain open for a later attachment. PTY input follows terminal rules.

The launch is accepted only when the sandbox is running and the guest can support bounded input and execution control. The runtime confirms guest spawn before the SDK treats the launch as complete. If the transport fails during that boundary, the client keeps the job ID so it can inspect the result instead of starting an uncertain duplicate.

References: crates/…/jobs.rs• L35-90 crates/…/executor.rs• L230-277 sdk/…/execution.rs• L30-167 sdk/…/client.rs• L24-40

Job lifecycle

The lifecycle records what the runtime has confirmed about the command. Starting means admission is durable but guest spawn is not confirmed. Running means the guest reported spawn. Exited carries a guest exit code, Failed means the command did not start, and Lost means ownership or transport ended without a confirmed exit.

The following flow shows the main confirmed transitions and the paths that do not produce a known process result.

flowchart LR
    A[Start request] --> B[Starting]
    B -->|guest spawn confirmed| C[Running]
    B -->|guest rejects command| D[Failed]
    C -->|guest reports exit| E[Exited]
    B -->|runtime or transport loss| F[Lost]
    C -->|runtime or transport loss| F
    C -->|signal or deadline| E

Pause is a sandbox state, not a job state. A running job stays Running while the sandbox is paused, but it does not make guest progress until the sandbox resumes. A job cannot be launched while the sandbox is paused or stopped. A wait timeout only stops the caller's wait; it does not signal or terminate the job.

The runtime keeps the confirmed exit code distinct from a loss diagnostic. Therefore a nonzero exit is a known process result, while Lost requires the caller to treat completion as unknown. A deadline sets the timeout marker and requests termination; callers still observe the final job state separately.

References: crates/…/jobs.rs• L40-90 crates/…/jobs.rs• L110-171 crates/…/jobs.rs• L466-621 crates/…/jobs.rs• L799-917 crates/…/executor.rs• L250-277 sdk/…/client.rs• L200-231 scripts/…/managed-jobs.py• L56-80

Observation and retained output

Observation is independent from process control. A caller can inspect metadata, wait for a confirmed result, read retained output, or follow new output without consuming the command's input or owning its termination.

Output records preserve bytes and identify their source as stdout, stderr, merged PTY output, or stdin_error. Each record has a monotonic job cursor. Readers can filter by time or source, request a tail, resume after a cursor, or follow after reading the retained history.

The runtime bounds live output retention. When older records are pruned, a reader receives an explicit gap rather than a false claim that the history is complete. Terminal history is read from durable storage after the sandbox stops. If output capture fails during execution, the job remains observable but reports that later output is live-only.

The observer path moves from retained history to live events without taking control of the process.

sequenceDiagram
    participant O as Observer
    participant R as Runtime job manager
    participant H as Job history
    participant P as Guest process
    O->>R: Inspect or read after cursor
    R-->>O: Metadata and retained output
    P-->>R: Output and terminal result
    R->>H: Append output and final metadata
    O->>R: Follow from returned cursor
    R-->>O: New output, gap, or completion

References: crates/…/jobs.rs• L93-126 crates/…/jobs.rs• L79-107 crates/…/jobs.rs• L250-313 crates/…/jobs.rs• L623-665 crates/…/jobs.rs• L839-917 sdk/…/client.rs• L255-361

Attachments

An attachment is a temporary connection to an existing job. It carries output events and may own input, resize a PTY, or detach. The attachment lease protects input ownership across process and network boundaries without making the attachment the owner of the job.

One attachment can own writable input at a time. Other attachments can use read-only observation. Detach releases only the connection and leaves guest stdin open. If a client disappears without detaching, the runtime releases its lease after the bounded lease period. Explicit EOF is different: it permanently closes pipe input and does not terminate the process.

An unexpired attachment to an active job also counts as caller activity for the sandbox idle monitor. A detached job's own runtime connection does not count as an attached client session, so an active job without an attachment does not block idle reclamation when the sandbox otherwise meets its idle policy.

Attachment replay starts at admission, from a bounded recent byte range, or after a job cursor. The attachment then follows live output until all output is delivered and the job reaches a terminal state. A read-only attachment cannot write or resize, and only one receiver may read attachment events at a time.

References: crates/…/jobs.rs• L174-238 crates/…/jobs.rs• L241-247 crates/…/jobs.rs• L314-461 crates/…/vm.rs• L1580-1585 crates/…/relay.rs• L570-597 sdk/…/attachment.rs• L24-159 sdk/…/attachment.rs• L162-323 sdk/…/types.rs• L93-137

Terminal interaction

Terminal interaction is an adapter over the attachment contract. It connects a host terminal to the job's input and output, changes the host terminal to a suitable mode, forwards window size for PTY jobs, and restores the host terminal when the session ends.

For a PTY, output is a merged stream and input uses terminal behavior. The default detach shortcut is Ctrl-] so the operator can leave the job running. Host EOF or the shortcut stops local input admission but does not close guest stdin or terminate the job. The adapter drains already accepted input for a bounded time. If it cannot confirm that drain, it reports input_not_flushed and does not advise automatic replay.

The adapter keeps shortcut detection active under input backpressure. If its bounded lookahead fills, it reports input loss, discards later input, and stays attached until the operator detaches or the job completes. This prevents an incomplete paste from being returned to the host shell as if it were unused input.

References: sdk/…/terminal.rs• L16-20 sdk/…/terminal.rs• L50-152 sdk/…/terminal.rs• L144-274 crates/…/jobs.rs• L165-238 scripts/…/managed-job-terminal.py• L46-145

Control protocol

Managed jobs use an additive host-control extension named control.jobs. A client first checks support and receives the selected job protocol version plus the runtime boot identity. Every later operation carries that boot identity, so a request from an earlier runtime generation cannot control a new execution.

Signals use a separate host-only control path when the normal agent input stream is backpressured. This path is advertised only for the active agent connection and uses an ephemeral connection capability. It waits for the target execution to reach the guest-start boundary before queueing the signal. A response confirms physical delivery to the guest transport, not signal handling or process exit. If the three-second delivery deadline expires, the result is uncertain and the caller must inspect the job rather than assume that a retry is safe.

The runtime registers its discovered managed connection before it starts the guest execution stream. The idle monitor can then distinguish runtime-owned job traffic from caller-owned attached execution sessions, while still tracking active job attachments as caller activity.

The protocol exposes bounded operations rather than a long-lived process stream. Start admits a command, list and inspect report state, read returns output pages, attach and detach manage temporary leases, write and resize control input, signal requests process-group action, and EOF closes pipe input. The control dispatcher admits these requests while independent runtime tasks handle guest input and output.

flowchart LR
    C[SDK or CLI] -->|Hello| R[Sandbox runtime]
    R -->|Version and boot identity| C
    C -->|Start, inspect, read, attach, signal, EOF| R
    R -->|Fenced result or output page| C
    R -->|Exec request and input/control| G[Guest agent]
    G -->|Output and exit events| R

The runtime fences launch admission by job ID and command fingerprint. Repeating the same admitted launch is safe to inspect, while reusing the ID for another command is rejected. A lost response is not treated as a safe replay case; the caller must inspect the retained job using the preserved ID.

References: crates/…/jobs.rs• L129-282 crates/…/exec_control.rs• L1-101 crates/…/exec_control.rs• L27-225 crates/…/executor.rs• L230-296 crates/…/jobs.rs• L173-245 crates/…/jobs.rs• L466-620 crates/…/jobs.rs• L771-777 crates/…/relay.rs• L570-597 sdk/…/client.rs• L76-132 sdk/…/execution.rs• L104-166

SDK and CLI integration

The Rust SDK defines the common managed-job surface. A Sandbox starts, finds, and lists jobs. A SandboxHandle finds and lists retained jobs without starting a stopped sandbox. A Job inspects, waits, signals, kills, closes pipe input, reads logs, and creates attachments. The language bindings expose the same model as native job objects, typed metadata, byte-preserving log entries, attachment events, and stable error codes. See SDK bindings for the shared language boundary.

The CLI maps the model to separate commands so lifecycle control does not depend on an attached terminal:

  • msb exec -d starts a job in an already running sandbox and prints its ID without consuming host stdin.
  • msb jobs lists active or retained jobs.
  • msb inspect NAME --job ID reads job metadata.
  • msb logs NAME --job ID reads or follows retained output.
  • msb attach NAME --job ID connects terminal or redirected I/O. --read-only observes without input ownership.
  • msb wait NAME --job ID waits for the result. A CLI timeout does not terminate the job.
  • msb signal, msb kill, and msb eof send explicit process or input controls.

msb run -d is a separate background-start path. It starts the sandbox's configured workload rather than creating a later managed-job handle. A supplied command becomes the background workload for a new sandbox while an empty command uses the image default. An unnamed detached run is ephemeral and is removed after the sandbox reaches a terminal state. A named detached run remains persistent; when that sandbox already exists, the command is ignored unless the caller uses replacement.

Sandbox lifetime flags such as --max-duration and --idle-timeout govern the owning sandbox. They do not replace job-level wait, signal, or kill operations. Managed jobs also block full snapshot and fork capture while active because those operations need a stable execution boundary; callers must wait for or terminate active jobs first.

References: sdk/…/mod.rs• L1-20 sdk/…/execution.rs• L30-284 sdk/…/jobs.py• L9-89 sdk/…/jobs.ts• L3-135 sdk/…/jobs.go• L16-163 sdk/…/jobs.rb• L5-104 crates/…/jobs.rs• L13-259 crates/…/exec.rs• L17-149 crates/…/run.rs• L119-200 crates/…/common.rs• L345-352 sdk/…/builder.rs• L583-605 sdk/…/config.rs• L93-112 sdk/…/config.rs• L482-502 sdk/…/config.rs• L671-756 scripts/…/managed-jobs.py• L138-170

Change checklist

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

  • Keep the job state meanings aligned across protocol records, runtime recovery, SDK result types, and CLI exit behavior.
  • Keep runtime boot fencing and job-ID fingerprint checks aligned so retries cannot start or control a different command.
  • Keep the host-only signal path aligned with guest capability discovery, per-connection authority, execution-start ordering, and delivery-uncertainty errors.
  • Keep attachment lease, single writable owner, detach, renew, EOF, and read-only rules aligned across protocol, SDK, and CLI adapters.
  • Keep output cursor, pruning-gap, replay, follow, and terminal-history behavior aligned across durable storage and every language binding.
  • Keep PTY input, resize, detach shortcut, host-terminal restoration, and bounded-drain behavior aligned across Unix and Windows terminal adapters.
  • Keep detached launch refusal aligned with sandbox paused, stopped, runtime-generation, and stopping states.
  • Keep the distinction between one-shot foreground launch, detached sandbox workload launch, and managed exec -d jobs aligned across CLI launch intent, persisted command configuration, and inspect output.
  • Keep sandbox lifetime policy separate from job control so idle or maximum-duration shutdown does not get reported as a job wait or signal result.
  • Keep active-job safeguards aligned with full snapshot and fork admission.
  • Keep uncertain launch, unconfirmed signal delivery, and unconfirmed exit errors distinct from confirmed process failures. Do not add automatic replay after an ambiguous control result.

Important failure modes

TriggerConsequenceGuard
A launch response is lost after admissionThe caller cannot know whether a new process exists.Preserve the returned job ID when available and inspect it before retrying.
A signal arrives before guest spawn is confirmedThe signal could overtake process creation or target no process.Wait for the execution-start boundary before queueing the signal.
Signal delivery exceeds its deadlineThe caller cannot know if the queued signal reached the guest.Return delivery_unconfirmed and inspect the job instead of replaying automatically.
A request uses an old runtime boot identityIt could act on a new runtime generation.Fence every post-Hello operation with the selected boot identity.
A second writable attachment connectsTwo clients could interleave guest input.Allow one input owner and use read-only attachments for observers.
A client drops without detachInput ownership could remain stuck.Use a bounded attachment lease with renewal.
A reader resumes before retained outputEarlier records may already be pruned.Emit a gap event and resume from the available cursor.
A wait timeout is treated as terminationThe process can continue while the caller assumes it ended.Treat wait timeout as local observation failure and signal or kill explicitly.
A sandbox stops while a job is activeThe job has no confirmed process exit.Mark it Lost and keep the exit code unset.
Terminal input cannot drain before detachSome input delivery is uncertain.Return input_not_flushed; do not close stdin or resend automatically.
A detached msb exec targets a stopped sandboxNo managed job is started.Start the sandbox first; detached execution requires a running sandbox.
A named existing sandbox receives msb run -d COMMAND without replacementThe sandbox starts or remains running but the supplied command is ignored.Use msb exec -d for a managed job or pass --replace to recreate the sandbox.
A full capture starts with active jobsCaptured state could omit or change live command execution.Refuse snapshot or fork until jobs are completed or terminated.

Key files

FileWhy to read it
crates/…/jobs.rsDefines the managed-job identity, state, output, attachment, control, and result contract.
crates/…/exec_control.rsDefines the optional host-only signal capability and its physical-delivery result.
crates/…/jobs.rsShows runtime ownership, guest execution, output retention, attachment leases, recovery, managed connection tracking, and terminal updates.
crates/…/exec_control.rsShows signal ordering, per-connection authority, execution leases, and delivery deadlines.
crates/…/relay.rsShows how runtime-owned managed connections stay distinct from caller sessions for idle tracking.
crates/…/vm.rsShows how active job attachments participate in sandbox idle decisions.
crates/…/executor.rsShows capability checks, stopping-state admission, and the runtime entry point for job requests and signals.
sdk/…/execution.rsShows detached launch, sandbox checks, job lookup, and active or retained listing.
sdk/…/client.rsShows identity validation, inspection, waiting, signals, output replay, and runtime-fenced requests.
sdk/…/attachment.rsShows temporary input ownership, replay setup, lease renewal, output events, and detach semantics.
sdk/…/terminal.rsShows the host-terminal bridge, detach handling, PTY resize, backpressure, and input-loss reporting.
crates/…/jobs.rsShows CLI listing, inspection, waiting, attachment, signal, kill, and EOF flows.
crates/…/exec.rsShows how detached msb exec -d starts a managed job and prints its ID.
crates/…/run.rsShows the separate attached and detached sandbox workload paths, ephemeral unnamed runs, and named-sandbox reuse.
crates/…/common.rsShows how sandbox lifetime options become maximum-duration and idle-timeout policy.
sdk/…/builder.rsShows the SDK boundary for one-shot foreground commands and background workload commands.
sdk/…/config.rsShows launch intent, background command resolution, and removal of transient launch state before persistence.
sdk/…/jobs.py, sdk/…/jobs.ts, sdk/…/jobs.go, sdk/…/jobs.rbShow how the shared job contract is represented in the supported language SDKs.
scripts/…/managed-jobs.pyDemonstrates lifecycle, output, input, pause, restart, capture safeguards, and CLI integration.
scripts/…/managed-job-terminal.pyDemonstrates real terminal behavior, backpressure, detach, PTY input, and host mode restoration.