Guest agent session handling
The guest agent daemon is the control point inside each Linux microVM. It prepares the guest, accepts framed commands through the host relay, runs guest work, exposes file and network access, coordinates checkpoint boundaries, reports liveness, and shuts the guest down in a clean way. The host runtime owns the relay and VM process, while the daemon owns guest state and guest resources. See Sandbox lifecycle for the full sandbox flow and Runtime execution orchestration for host-side VM control.
System role
The daemon joins the host and guest through one named virtio-serial channel. It turns host protocol messages into guest actions and sends results back with the same correlation ID, so command output and stream data stay attached to the request that created them.
The daemon has two roles:
- It acts as the first guest process during boot. It mounts the guest view, applies policy, and makes the guest usable.
- It acts as a long-lived agent. It owns active exec, filesystem, TCP, and checkpoint sessions until they finish or the guest stops.
Guest boot
Bootstrap context
The host places one core.bootstrap frame on the agent console before the VM starts. The daemon accepts it only as the first frame with correlation ID 0, no flags, and a supported protocol generation. The frame carries the one-shot guest setup plan and the runtime values that survive into later exec requests. crates/…/main.rs• L21-58, crates/…/agent.rs• L385-429, crates/…/config.rs• L41-144
The daemon keeps the console open across all boot phases. This matters because one device read can contain both the bootstrap frame and the later init acknowledgement. The shared input buffer prevents the second frame from being lost between phases. crates/…/agent.rs• L80-87
References: crates/…/main.rs• L21-58 crates/…/agent.rs• L385-429 crates/…/config.rs• L41-144
Guest preparation
Initialization changes the minimal boot environment into the guest environment used by workloads. The daemon applies resource limits first, mounts essential and user filesystems, prepares /run/microsandbox, configures the network, installs available trust material, and adds the guest scripts path to shell environments. A restricted security profile also adds mount limits and removes mount-admin privilege from later exec processes. crates/…/init.rs• L19-60, crates/…/config.rs• L135-144
The order protects dependencies between these actions. The daemon first mounts enough of /dev and /sys to find the console. It then mounts the final root and runtime share, resolves the default user, waits for host-dependent setup, and only then attaches user mounts. User mount paths are planned as one parent-first tree, which avoids a child mount being hidden by a later parent. crates/…/init.rs• L11-17, crates/…/init.rs• L162-167, crates/…/init.rs• L504-607
After the root is ready, the daemon sends core.init.resolved with the effective default user and waits up to 60 seconds for core.init.ack. The host can use this point to install host-to-guest identity mappings before the daemon mounts user volumes. The daemon does not send core.ready until this exchange and the remaining setup finish. crates/…/agent.rs• L431-456, crates/…/relay.rs• L296-367
The boot sequence is summarized below.
flowchart TD
A[Guest starts as agentd] --> B[Prepare console filesystems]
B --> C[Receive and validate bootstrap]
C --> D[Apply limits and mount guest root]
D --> E[Resolve default user]
E --> F[Host installs dependent setup]
F --> G[Send init acknowledgement request]
G --> H[Apply user mounts and guest hooks]
H --> I{PID 1 handoff configured?}
I -- Yes --> J[Parent execs new init]
I -- No --> K[Start agent loop as PID 1]
J --> L[Agent child starts loop]
K --> M[Send core.ready]
L --> M
References: crates/…/init.rs• L19-60 crates/…/agent.rs• L431-456 crates/…/relay.rs• L296-367
Session admission and handoff
Relay session admission
The host relay is the local gateway for SDK clients. It waits for the daemon's core.ready frame, then gives each connected client a non-overlapping correlation-ID range and forwards frames without changing their protocol headers. A client handshake contains that range and the cached ready frame. crates/…/relay.rs• L305-386, crates/…/relay.rs• L452-548
This range is the session's routing and ownership boundary. The relay rejects client frames outside the assigned range, and the daemon uses the same range to decide which filesystem handles and streams belong to a disconnected client. The guest protocol has no separate password exchange; when a remote transport needs authentication, that check belongs to the outer transport before it becomes a transparent byte stream to the relay. crates/…/relay.rs• L920-1023, packages/…/client.rs• L203-211, crates/…/fs.rs• L95-107
The client chooses between one-shot requests and streaming sessions. One-shot calls wait for one terminal response. Streaming calls keep the correlation ID so later input, signal, resize, or data frames can use the same session. packages/…/client.rs• L301-350
References: crates/…/relay.rs• L305-386 crates/…/relay.rs• L452-548 crates/…/relay.rs• L920-1023 packages/…/client.rs• L203-211
PID 1 handoff
An optional handoff lets a user-supplied init process become guest PID 1 after the daemon completes setup. The daemon checks the target and working directory before the fork. The parent keeps PID 1 and executes the target init, while the child leaves the init process group and continues to serve the host over the already-open console. crates/…/handoff.rs• L57-117
The handoff preserves a prepared root, mounts, network, and environment for the new init. The daemon child writes later diagnostics to run/…/agentd.log when possible so its output does not mix with the new init's console output. In handoff mode, shutdown asks the new PID 1 to stop instead of calling the guest reboot system call directly. crates/…/handoff.rs• L46-51, crates/…/handoff.rs• L286-317, crates/…/agent.rs• L1259-1292
References: crates/…/main.rs• L55-77 crates/…/handoff.rs• L57-117 crates/…/handoff.rs• L286-337 crates/…/agent.rs• L1259-1292
Workload sessions
Process execution
An exec session runs one guest command and streams its result to the host. The daemon supports interactive PTY sessions and non-interactive pipe sessions. Both modes report start, output, input errors, and exit through the session's correlation ID. crates/…/agent.rs• L2749-2831, crates/…/session.rs• L657-691
The command inherits the configured guest context unless the request overrides it. That context includes the working directory, environment, user, resource limits, security profile, and the scripts directory on PATH. Signals target the command's whole process group, so descendants do not remain after the session is stopped. When checkpoint support is available, the child joins the agent-owned workload boundary before it can run user code. crates/…/agent.rs• L2749-2795, crates/…/session.rs• L856-877, crates/…/session.rs• L962-1055
The process manager is the single owner of child exit status. A dedicated SIGCHLD watcher reaps children and sends exit codes to session readers. Generation data keeps a stale session from signalling a new process that reused the same PID. If the manager fails, the agent loop stops rather than continuing with unknown process state. crates/…/process.rs• L42-84, crates/…/process.rs• L162-196, crates/…/process.rs• L270-295
Session output is bounded before a reader allocates more data. Each output event also carries its attachment generation and client owner, so output from a restored or disconnected client is discarded instead of being sent to a new owner of the same correlation range. Spawn failures return a typed failure category when the guest can identify the cause. crates/…/session.rs• L42-55, crates/…/session.rs• L186-200, crates/…/session.rs• L551-625, crates/…/agent.rs• L1084-1139, crates/…/session.rs• L90-132
References: crates/…/agent.rs• L2749-2831 crates/…/session.rs• L657-691 crates/…/session.rs• L739-877 crates/…/session.rs• L959-1191 crates/…/process.rs• L42-84
Filesystem sessions
Filesystem access gives the host a guest-side file API that works on the mounted guest view. The daemon handles path operations such as stat, directory access, links, metadata changes, copy, rename, and removal. Open files and directories receive handles that remain valid across later operations. crates/…/fs.rs• L299-440
Large file transfers use separate read and write streams. Reads return data chunks in the background. Writes accept chunks until an empty data frame ends the stream and causes a flush. Each handle and stream belongs to the relay client that opened it, and the daemon limits the number of handles per client to prevent one client from consuming all guest file resources. crates/…/fs.rs• L41-89, crates/…/fs.rs• L443-500
References: crates/…/fs.rs• L41-89 crates/…/fs.rs• L95-151 crates/…/fs.rs• L299-440 crates/…/fs.rs• L443-500
TCP sessions
TCP forwarding opens a socket from inside the guest and presents it as a bidirectional host session. The connect runs in its own task, so a slow destination cannot block the daemon's console loop. The task reports connected, failed, data, EOF, and closed states on the session ID. crates/…/tcp.rs• L100-125, crates/…/tcp.rs• L131-186
The relay applies backpressure when a destination cannot accept data. A destination EOF closes only its read direction, so host-to-guest data can continue until the host sends its own EOF or close. An explicit close aborts the relay task and releases the guest socket without waiting behind queued data. crates/…/tcp.rs• L26-35, crates/…/tcp.rs• L57-93, crates/…/tcp.rs• L188-293
References: crates/…/agent.rs• L2999-3059 crates/…/tcp.rs• L100-125 crates/…/tcp.rs• L131-186 crates/…/tcp.rs• L188-293
Workload checkpoint controls
The workload checkpoint flow creates a safe boundary around agent-managed processes and their transport state. A workload latch is a guest cgroup freezer owned by one checkpoint attempt. If the guest cannot provide that freezer, ordinary exec remains available but full workload checkpointing is not.
When the host requests a freeze, the daemon first waits for the stated input cut. It then parks outgoing bulk records, freezes the workload, pauses the heartbeat checkpoint gate, and returns the transport cut and input credit that the host must drain or preserve. Optional external mount selectors ask the guest to prove writeback with syncfs; the proof is reported separately from the process freeze. crates/…/agent.rs• L2506-2647, crates/…/mount_checkpoint.rs• L47-71
The attempt ID owns the boundary. Repeating the same operation is safe, while another attempt cannot thaw or replace it. A continue thaw releases the same process and transport state. A restore thaw first drops old client-owned streams, detaches accepted process input, advances the output generation, and only then releases the workload so a new host attachment cannot receive stale output. crates/…/workload.rs• L123-213, crates/…/agent.rs• L2369-2427, crates/…/agent.rs• L2650-2746
The flow is summarized below.
flowchart TD
A[Host sends freeze with attempt and input cut] --> B[Guest waits for admitted input]
B --> C[Park outgoing bulk records]
C --> D[Freeze agent-managed workload]
D --> E{External mounts requested?}
E -- Yes --> F[Prove selected mount writeback]
E -- No --> G[Return frozen boundary]
F --> G
G --> H{Thaw mode}
H -- Continue --> I[Resume same clients and processes]
H -- Restore --> J[Drop old streams and advance output generation]
J --> I
References: crates/…/workload.rs• L24-38 crates/…/workload.rs• L84-213 crates/…/workload.rs• L235-332 crates/…/mount_checkpoint.rs• L22-71 crates/…/mount_checkpoint.rs• L74-142 crates/…/agent.rs• L2369-2427 crates/…/agent.rs• L2506-2746 crates/…/core.rs• L122-214
Guest hooks
Network setup
Networking is a boot hook rather than a per-session service. The daemon always brings up loopback. If network settings exist, it also applies the guest interface identity and MTU, adds IPv4 and IPv6 addresses and default routes, and writes DNS settings. It can add the guest hostname and a host alias to /etc/hosts, which gives guest processes a stable name for reaching the sandbox host. crates/…/network.rs• L15-73, crates/…/network.rs• L174-224
The daemon also installs available sandbox and host CA bundles during initialization. This makes guest TLS clients trust the sandbox's interception CA and host-side corporate CAs without adding network logic to each exec session. crates/…/tls.rs• L53-115
References: crates/…/init.rs• L48-58 crates/…/network.rs• L15-73 crates/…/network.rs• L174-224 crates/…/tls.rs• L53-115
Heartbeat and activity
The daemon writes a heartbeat to /.msb/heartbeat.json about once per second. The record contains liveness and activity sequences, the last meaningful activity time, active session counts, and cumulative byte counters. Writes use a temporary file and rename so the host sees a complete record. crates/…/agent.rs• L177-187, crates/…/agent.rs• L782-840, crates/…/heartbeat.rs• L10-39
The pulse runs outside the async runtime. Heavy command output or stream work therefore cannot starve the liveness update. The host uses the activity time for an optional idle timeout. Maintenance messages such as ping, clock sync, and their replies do not keep an idle sandbox alive, while real work and explicit touch messages do. crates/…/vm.rs• L1223-1277, crates/…/agent.rs• L751-780
References: crates/…/agent.rs• L782-860 crates/…/heartbeat.rs• L10-39 crates/…/vm.rs• L1223-1277 crates/…/agent.rs• L751-780
Teardown
Client disconnect cleanup
When a relay client disconnects, the host first stops its active exec sessions and then sends the client's ID range to the daemon. The daemon closes that client's filesystem handles, aborts its filesystem reads, drops its pending writes, and closes its TCP sessions. This keeps resources tied to a dead client from surviving until the whole sandbox stops. crates/…/relay.rs• L1025-1099, crates/…/agent.rs• L692-715
References: crates/…/relay.rs• L1025-1099 crates/…/agent.rs• L2314-2367
Guest shutdown
For a normal shutdown, the daemon sends SIGTERM to active exec process groups, clears stream state, and requests guest poweroff. When it is still PID 1, it quiesces remaining processes, syncs data, and reboots the guest. After a PID 1 handoff, it asks the new init to power off and uses a signal and host-side VM exit as fallbacks if that init does not respond. crates/…/agent.rs• L726-741, crates/…/agent.rs• L1259-1292
Filesystem teardown is best effort and time bounded. The daemon handles child mounts before parent mounts, remounts busy filesystems read-only, and gives the overlay upper filesystem a final read-only remount so its journal can reach a clean state. It always continues toward poweroff when a cleanup step fails. crates/…/teardown.rs• L21-31, crates/…/teardown.rs• L93-125, crates/…/teardown.rs• L175-220
References: crates/…/agent.rs• L726-741 crates/…/agent.rs• L1259-1292 crates/…/teardown.rs• L93-125 crates/…/teardown.rs• L175-220
Change checklist
When these files or sections are changed, remember to consider these:
- Bootstrap fields or their validation: update host frame creation, guest conversion, init ordering, and the
core.init.resolved/core.init.ackreadiness contract together. - Message types, flags, or protocol generations: update the protocol definitions, guest dispatch, relay routing, and client feature gating as one contract.
- Relay ID range rules: preserve the same range meaning in client admission, response routing, guest ownership checks, and disconnect cleanup.
- New session kinds or terminal states: add them to agent state, heartbeat counts, activity accounting, stream completion, and client disconnect cleanup.
- Exec process control: keep process registration, exit watching, PID-reuse protection, process-group signalling, and terminal teardown aligned.
- Session output ownership: preserve attachment generation and client-incarnation checks across control output, bulk scheduling, restore, and disconnect cleanup.
- Workload freeze and thaw messages: keep attempt ownership, transport input cuts, parked output, heartbeat gating, and cgroup state changes as one boundary.
- External mount checkpoint evidence: keep selector validation, mount inventory resolution, write-worker exclusion, sync completion, and the host's capture decision aligned.
- Handoff or shutdown behavior: check both the agent-as-PID-1 path and the child-after-handoff path, including the host flush window.
- Heartbeat fields or paths: update the guest writer, protocol shape, host idle reader, and runtime-directory setup together.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Bootstrap frame has the wrong type, ID, flags, or protocol generation | The daemon exits before guest setup and never becomes ready | Validate the first frame before converting or applying setup data |
| Init acknowledgement is missing for 60 seconds | Boot does not reach core.ready; the relay eventually reports a readiness timeout | Keep the host init-dependent work between core.init.resolved and core.init.ack |
| Client sends an ID outside its assigned range | The relay drops the client connection instead of forwarding an ambiguous request | Allocate non-overlapping ranges and use the same range for guest ownership cleanup |
| Process manager stops or loses child-status ownership | The agent loop fails and active process groups are killed by manager failure handling | Treat the manager as the only normal reaper and subscribe to its terminal failure signal |
| Exec command cannot be forked, entered, or started | The host receives ExecFailed with a typed cause when the guest can classify it | Keep pre-exec checks and the child error report tied to the session start reply |
| Filesystem handle is unknown or owned by another client | The operation returns an error and cannot affect another client's open resource | Check handle ownership on every handle operation and close owner ranges on disconnect |
| Guest TCP destination does not connect within 30 seconds | The TCP session ends with a terminal failure frame | Connect in a per-session task with a bounded timeout |
| Workload freezer is unavailable or the daemon is no longer PID 1 | Ordinary exec can continue but a full checkpoint cannot establish a guest process boundary | Advertise the capability state and reject freeze instead of claiming a partial boundary |
| Freeze or thaw uses a different or invalid attempt ID | The workload stays owned by the active attempt and the requested transition is rejected | Validate bounded attempt IDs and require matching ownership for every transition |
| External mount is absent, invalid, or still has an agent upload worker | The frozen reply cannot certify external mount writeback | Resolve complete mount selectors and require exclusive sync access before setting the evidence flag |
| Restore output is not drained before the new attachment resumes | Old output can corrupt the new transport or reach a recycled correlation owner | Park at complete records, advance the output generation, and keep the workload frozen until the barrier completes |
| Handoff init ignores the shutdown request | The guest may not power off through the normal init path | Sync filesystems, signal PID 1 again, and let the host VM exit path act as a backstop |
| Filesystem cleanup reaches its deadline or a mount stays busy | A mount can remain read-write and its journal may need recovery on the next use | Use bounded best-effort cleanup, child-before-parent order, and read-only remounts |
Key files
| File | Why to read it |
|---|---|
| crates/…/main.rs | Shows the complete guest boot order and the point where the daemon enters its long-lived loop. |
| crates/…/agent.rs | Shows console framing, message dispatch, session state, checkpoint barriers, heartbeat publication, and shutdown control. |
| crates/…/init.rs | Explains how the daemon turns bootstrap data into a usable guest root and mount tree. |
| crates/…/config.rs | Defines the split between one-shot boot values and runtime values used by later exec sessions. |
| crates/…/handoff.rs | Explains the parent/new-init and child/agent roles after PID 1 handoff. |
| crates/…/session.rs and crates/…/process.rs | Explain command I/O modes, output ownership, process groups, exit delivery, and PID-reuse safety. |
| crates/…/workload.rs | Explains the guest process boundary used for checkpoint freeze and thaw. |
| crates/…/mount_checkpoint.rs | Explains how the guest proves writeback for selected external mounts. |
| crates/…/fs.rs | Explains guest file operations, handle ownership, and streaming transfers. |
| crates/…/tcp.rs | Explains guest-originated TCP connections, half-close behavior, backpressure, and terminal states. |
| crates/…/network.rs and crates/…/tls.rs | Explain boot-time network identity, routes, DNS, host aliases, and guest trust setup. |
| crates/…/heartbeat.rs and crates/…/teardown.rs | Explain host-visible liveness data and bounded filesystem cleanup before poweroff. |
| crates/…/relay.rs | Explains the host relay handshake, client ID ownership, routing, and disconnect cleanup. |
| crates/…/message.rs, core.rs, bootstrap.rs, and heartbeat.rs | Define the wire messages, session flags, bootstrap contract, checkpoint boundary, and heartbeat shape shared by host and guest. |
| packages/…/client.rs | Explains how clients consume the relay handshake and use one-shot or streaming correlation IDs. |