Skip to content

Quickly sandbox your AI agent.

Python

Remove microvm, add runtime QEMU installer, fix overlay builds

Tyler Payne1ec754fa328b
diff --git a/README.md b/README.md
index eefd254..1152acc 100644
--- a/README.md
+++ b/README.md
@@ -272,7 +272,7 @@ uv run poe check # type-check, lint, and run tests
| Save and Rollback | [Checkpoints, reverts, persistent saves](docs/user-guide/05-save-and-rollback.md) | [qcow2 overlays, `savevm`, `blockdev-snapshot-sync`](docs/under-the-hood/05-save-and-rollback.md) |
| Desktop Control | [Screenshots, keyboard, mouse](docs/user-guide/06-desktop-control.md) | [VNC, GPU, USB tablet, QMP input injection](docs/under-the-hood/06-desktop-control.md) |
| Network and Isolation | [Network modes, port forwarding](docs/user-guide/07-network-and-isolation.md) | [SLIRP NAT, `restrict=on`, `guestfwd`](docs/under-the-hood/07-network-and-isolation.md) |
-| Performance | [What makes it fast](docs/user-guide/08-performance.md) | [`microvm`, `io_uring`, IOThreads, TCG vs KVM](docs/under-the-hood/08-performance.md) |
+| Performance | [What makes it fast](docs/user-guide/08-performance.md) | [`io_uring`, IOThreads, TCG vs KVM](docs/under-the-hood/08-performance.md) |
### Contributing
diff --git a/docs/contributor-guide/02-extending-the-sandbox.md b/docs/contributor-guide/02-extending-the-sandbox.md
index 66377da..3b6b4f7 100644
--- a/docs/contributor-guide/02-extending-the-sandbox.md
+++ b/docs/contributor-guide/02-extending-the-sandbox.md
@@ -31,7 +31,7 @@ Export from `quicksand_core` and the `quicksand` wrapper if it's public API.
## Add a new OS
1. Add `OS.FREEBSD` to the enum in `host/os_.py`
-2. Create `FreeBSDConfig(BaseOSConfig)` and implement `detect_accelerator()`, `disk_aio`, `supports_microvm`, etc.
+2. Create `FreeBSDConfig(BaseOSConfig)` and implement `detect_accelerator()`, `disk_aio`, etc.
3. Add the detection branch in `OSConfig.__new__()` and `_detect_os()`
4. If it needs unique QEMU flags, handle them in `build_qemu_command()` (`qemu/platform.py`)
diff --git a/docs/packages/quicksand-core.md b/docs/packages/quicksand-core.md
index 1370472..ce66121 100644
--- a/docs/packages/quicksand-core.md
+++ b/docs/packages/quicksand-core.md
@@ -74,7 +74,6 @@ asyncio.run(main())
- **Save and load**: Save VM disk state to a directory and load it on any machine
- **File sharing**: CIFS mounts via `quicksand-smb` (pure-Python SMB3 server, invoked as a subprocess via QEMU guestfwd)
- **Performance optimizations**:
- - microvm machine type (~4x faster boot on Linux x86_64 + KVM)
- io_uring disk AIO (~50% lower latency on Linux)
- IOThreads for better concurrent disk I/O (all platforms)
diff --git a/docs/packages/quicksand.md b/docs/packages/quicksand.md
index 89209c6..3f4c6e4 100644
--- a/docs/packages/quicksand.md
+++ b/docs/packages/quicksand.md
@@ -89,7 +89,7 @@ Each sandbox runs in a real virtual machine with hypervisor-level isolation:
| Platform | Accelerator | Machine | File Sharing | Performance |
|----------|-------------|---------|--------------|-------------|
-| Linux x86_64 | KVM | microvm | SMB/CIFS | io_uring + IOThreads |
+| Linux x86_64 | KVM | q35 | SMB/CIFS | io_uring + IOThreads |
| Linux ARM64 | KVM | virt | SMB/CIFS | io_uring + IOThreads |
| macOS | HVF | q35/virt | SMB/CIFS | IOThreads |
| Windows | WHPX | q35 | SMB/CIFS | IOThreads |
@@ -99,7 +99,7 @@ Key components:
- **Guest agent**: Lightweight TCP server for command execution
- **Disposable overlays**: Base image unchanged, writes go to temp overlay
- **SMB/CIFS mounts**: Mount host directories into the VM
-- **Platform optimizations**: microvm (~4x faster boot), io_uring (~50% lower disk latency), IOThreads
+- **Platform optimizations**: io_uring (~50% lower disk latency), IOThreads
## Requirements
diff --git a/docs/under-the-hood/02-sandbox-lifecycle.md b/docs/under-the-hood/02-sandbox-lifecycle.md
index a3c8dfc..e0dd962 100644
--- a/docs/under-the-hood/02-sandbox-lifecycle.md
+++ b/docs/under-the-hood/02-sandbox-lifecycle.md
@@ -41,10 +41,7 @@ The `-machine` flag is selected automatically based on architecture and platform
| Architecture | Platform | Machine | Why |
|---|---|---|---|
| ARM64 | Any | `virt` | ARM's standard virtual machine type |
-| x86_64 | Linux + KVM | `microvm` | Minimal machine, ~4x faster boot |
-| x86_64 | macOS / Windows / TCG | `q35` | Full-featured Intel chipset |
-
-`microvm` is only used on Linux x86_64 with KVM and when the firmware file `bios-microvm.bin` exists in the data directory. It skips PCI bus emulation entirely, using MMIO (memory-mapped) virtio devices instead.
+| x86_64 | Any | `q35` | Full-featured Intel chipset |
## Hardware acceleration
@@ -73,9 +70,8 @@ The machine type determines how virtio devices are attached:
|---|---|---|---|
| `virt` (ARM64) | `virtio-blk-device` | `virtio-net-device` | MMIO |
| `q35` (x86_64) | `virtio-blk-pci` | `virtio-net-pci` | PCI |
-| `microvm` (x86_64+KVM) | `virtio-blk-device` | `virtio-net-device` | MMIO |
-PCI devices have a small overhead from bus emulation. MMIO devices (used by `virt` and `microvm`) skip this entirely.
+PCI devices have a small overhead from bus emulation. MMIO devices (used by `virt`) skip this entirely.
## Full assembled command
diff --git a/docs/under-the-hood/04-file-exchange.md b/docs/under-the-hood/04-file-exchange.md
index 8722316..7ac5377 100644
--- a/docs/under-the-hood/04-file-exchange.md
+++ b/docs/under-the-hood/04-file-exchange.md
@@ -65,7 +65,7 @@ Sandbox(
| `-device virtio-9p-pci,...` | Attach the filesystem as a virtio device the guest can mount |
| `mount_tag=pb9p0` | Tag used by the guest `mount -t 9p pb9p0 /mnt/data` command |
-On MMIO machines such as `microvm` (x86_64+KVM) and `virt` (ARM64), the device type is `virtio-9p-device` instead of `virtio-9p-pci`.
+On MMIO machines such as `virt` (ARM64), the device type is `virtio-9p-device` instead of `virtio-9p-pci`.
Read-only 9p mounts add `,readonly=on` to the `-fsdev` flags.
diff --git a/docs/under-the-hood/07-network-and-isolation.md b/docs/under-the-hood/07-network-and-isolation.md
index 4b65742..38aecf0 100644
--- a/docs/under-the-hood/07-network-and-isolation.md
+++ b/docs/under-the-hood/07-network-and-isolation.md
@@ -33,7 +33,7 @@ Sandbox(image="ubuntu", network_mode=NetworkMode.NONE)
-nic none
```
-The only difference between `MOUNTS_ONLY` and `FULL` is `restrict=on` vs no restrict. On `microvm`, `NetworkMode.NONE` produces no network flags at all (microvm doesn't need `-nic none`).
+The only difference between `MOUNTS_ONLY` and `FULL` is `restrict=on` vs no restrict.
## How `restrict=on` works
@@ -71,9 +71,8 @@ The device type depends on machine type:
|---|---|---|
| `virt` (ARM64) | `virtio-net-device` | MMIO |
| `q35` (x86_64) | `virtio-net-pci` | PCI |
-| `microvm` (x86_64+KVM) | `virtio-net-device` | MMIO |
-On non-microvm x86_64 machines, an additional flag suppresses PXE boot:
+On x86_64 machines, an additional flag suppresses PXE boot:
```bash
-global virtio-net-pci.romfile=
diff --git a/docs/under-the-hood/08-performance.md b/docs/under-the-hood/08-performance.md
index 35b5c6d..ac188c2 100644
--- a/docs/under-the-hood/08-performance.md
+++ b/docs/under-the-hood/08-performance.md
@@ -4,26 +4,13 @@ Companion to [Performance](../user-guide/08-performance.md).
## Boot time: machine type
-The biggest boot-time win is the machine type:
+The machine type affects boot time:
| Machine | Boot time | Why |
|---|---|---|
-| `microvm` | < 1 second | No PCI bus, no firmware, no device enumeration |
| `q35` / `virt` | ~2-3 seconds | Full chipset emulation, firmware device scan |
-`microvm` is auto-selected on Linux x86_64 + KVM when `bios-microvm.bin` is present. It uses MMIO devices instead of PCI:
-
-```bash
-# microvm (fast):
--machine microvm \
--device virtio-blk-device,drive=drive0,iothread=iothread0 \
--device virtio-net-device,netdev=net0
-
-# q35 (standard):
--machine q35 \
--device virtio-blk-pci,drive=drive0,iothread=iothread0 \
--device virtio-net-pci,netdev=net0
-```
+Direct kernel boot (see below) is the primary boot-time optimization, skipping BIOS/UEFI entirely.
## Boot time: direct kernel boot
diff --git a/docs/under-the-hood/index.md b/docs/under-the-hood/index.md
index 76bbb6d..229ff2a 100644
--- a/docs/under-the-hood/index.md
+++ b/docs/under-the-hood/index.md
@@ -240,11 +240,11 @@ All mixins share state through flat typed attributes declared on `_SandboxProtoc
`host/os_.py` provides OS-level configuration including accelerator detection:
-| Class | Accelerator | Disk AIO | microvm |
-|-------|-------------|----------|---------|
-| `LinuxConfig` | KVM | io_uring | Yes |
-| `DarwinConfig` | HVF | default | No |
-| `WindowsConfig` | WHPX | default | No |
+| Class | Accelerator | Disk AIO |
+|-------|-------------|----------|
+| `LinuxConfig` | KVM | io_uring |
+| `DarwinConfig` | HVF | default |
+| `WindowsConfig` | WHPX | default |
### QEMU configuration (`qemu/`)
@@ -252,7 +252,7 @@ All mixins share state through flat typed attributes declared on `_SandboxProtoc
| Class | Default Machine | QEMU Binary | virtio Bus |
|-------|-----------------|-------------|------------|
-| `X86_64Config` | Q35 (or microvm with KVM) | qemu-system-x86_64 | PCI or MMIO |
+| `X86_64Config` | Q35 | qemu-system-x86_64 | PCI |
| `ARM64Config` | VIRT | qemu-system-aarch64 | MMIO |
`qemu/platform.py` composes arch + OS into `PlatformConfig` and provides:
@@ -531,15 +531,13 @@ The lifecycle mixin auto-unpacks `.quicksand` bundles during `start()`.
```
-nodefaults # blank slate — only explicitly configured devices
--machine {type} # microvm (Linux x86_64+KVM) or q35 (x86_64 other) or virt (ARM64)
+-machine {type} # q35 (x86_64) or virt (ARM64)
-m {memory} # guest RAM
-smp {cpus} # virtual CPU count
```
`-nodefaults` prevents QEMU from creating its usual set of default devices (floppy, CD-ROM, VGA, serial). Every device is explicit.
-`microvm` is an ultra-minimal machine type without PCI or ACPI. It boots ~4x faster than Q35 because there's no device enumeration overhead. It uses virtio-mmio devices instead of virtio-pci. Only available on Linux x86_64 + KVM.
-
### CPU and acceleration
```
@@ -563,7 +561,7 @@ Acceleration is auto-detected. KVM is found via `/dev/kvm`, HVF via `sysctl kern
`aio=io_uring` (Linux only) uses the modern io_uring kernel API instead of blocking threads for async I/O, reducing disk latency by ~50%. Falls back to `threads` on macOS and Windows.
-`virtio-blk-pci` (Q35/VIRT machines) or `virtio-blk-device` (microvm) is the paravirtualized block device. It is much faster than emulated IDE or SCSI.
+`virtio-blk-pci` (Q35) or `virtio-blk-device` (VIRT) is the paravirtualized block device. It is much faster than emulated IDE or SCSI.
### Display and console
@@ -618,13 +616,13 @@ Starts the QMP server on a random free port alongside QEMU. TCP transport is use
### Performance by platform
-| Platform | Machine | Disk AIO | IOThreads | Boot speedup |
-|----------|---------|----------|-----------|--------------|
-| Linux x86_64 + KVM | microvm | io_uring | Yes | ~4x |
-| Linux ARM64 + KVM | virt | io_uring | Yes | baseline |
-| macOS (HVF) | q35/virt | threads | Yes | baseline |
-| Windows (WHPX) | q35 | threads | Yes | baseline |
-| Any + TCG | q35/virt | varies | Yes | baseline |
+| Platform | Machine | Disk AIO | IOThreads |
+|----------|---------|----------|-----------|
+| Linux x86_64 + KVM | q35 | io_uring | Yes |
+| Linux ARM64 + KVM | virt | io_uring | Yes |
+| macOS (HVF) | q35/virt | threads | Yes |
+| Windows (WHPX) | q35 | threads | Yes |
+| Any + TCG | q35/virt | varies | Yes |
---
@@ -694,7 +692,7 @@ Starts the QMP server on a random free port alongside QEMU. TCP transport is use
| **Kernel cmdline** | Parameters passed to the Linux kernel via QEMU's `-append` flag; readable from `/proc/cmdline` inside the VM. Quicksand passes the agent token and port this way. |
| **[Hardware acceleration](https://www.qemu.org/docs/master/system/introduction.html#virtualisation-accelerators)** | Using CPU virtualization extensions for near-native VM performance: **KVM** (Linux), **HVF** (macOS), **WHPX** (Windows). |
| **[TCG](https://www.qemu.org/docs/master/devel/tcg.html)** | Tiny Code Generator — QEMU's software emulation fallback. ~10-50x slower but works everywhere. |
-| **[Machine type](https://www.qemu.org/docs/master/system/invocation.html#hxtool-1)** | Virtual hardware platform: **microvm** (ultra-minimal, ~4x faster boot, Linux x86_64+KVM only), **Q35** (modern Intel chipset, x86_64), **VIRT** (ARM64 paravirt). |
+| **[Machine type](https://www.qemu.org/docs/master/system/invocation.html#hxtool-1)** | Virtual hardware platform: **Q35** (modern Intel chipset, x86_64), **VIRT** (ARM64 paravirt). |
| **[virtio](https://www.qemu.org/docs/master/system/devices/virtio.html)** | Paravirtualized I/O — efficient virtual devices where the guest knows it's virtualized. Used for disk, network, and filesystem sharing. |
| **CIFS** | Common Internet File System — the protocol used by quicksand for host→guest file sharing. The host runs a pure-Python SMB3 server (`quicksand-smb`); the guest mounts via `mount -t cifs`. |
| **[User-mode networking](https://www.qemu.org/docs/master/system/devices/net.html#using-the-user-mode-network-stack)** | QEMU's built-in NAT (slirp). Guest gets a private IP (10.0.2.x), host gateway at 10.0.2.2. `restrict=on` blocks guest outbound but guestfwd tunnels still work; `restrict=off` allows full bidirectional. |
diff --git a/docs/user-guide/08-performance.md b/docs/user-guide/08-performance.md
index f220c5c..41643e2 100644
--- a/docs/user-guide/08-performance.md
+++ b/docs/user-guide/08-performance.md
@@ -15,7 +15,7 @@ Measured with `quicksand benchmark -n 5` on macOS ARM64 (Apple M3 Max, HVF):
| `aif-agent-sandbox` | 0.91s | 0.92s |
| `aif-cua-agent-sandbox` | 0.85s | 1.01s |
-Boot time is measured from `start()` to sandbox ready (agent connected, mounts configured). The two biggest factors are the machine type (microvm is ~4x faster on Linux) and hardware acceleration (TCG is 10-50x slower).
+Boot time is measured from `start()` to sandbox ready (agent connected, mounts configured). The biggest factor is hardware acceleration (TCG is 10-50x slower).
## CPU performance
@@ -65,11 +65,11 @@ Plus ~50-100MB of overhead for the QEMU process itself. Multiple sandboxes run c
| | Linux + KVM | macOS + HVF | Windows + WHPX | Any + TCG |
|---|---|---|---|---|
-| Boot (Alpine) | < 0.2s (microvm) | 0.37s | ~1-2s | ~10-30s |
-| Boot (Ubuntu) | < 0.5s (microvm) | 0.88s | ~2-3s | ~10-30s |
+| Boot (Alpine) | < 0.5s | 0.37s | ~1-2s | ~10-30s |
+| Boot (Ubuntu) | < 1s | 0.88s | ~2-3s | ~10-30s |
| CPU performance | Near-native | Near-native | Near-native | 10-50x slower |
| Disk AIO | io_uring | threads | threads | threads |
-| Machine type | microvm | Q35/VIRT | Q35 | Q35/VIRT |
+| Machine type | Q35/VIRT | Q35/VIRT | Q35 | Q35/VIRT |
## Tips
diff --git a/examples/accelerator_config.py b/examples/accelerator_config.py
index 7e11fba..ec46552 100644
--- a/examples/accelerator_config.py
+++ b/examples/accelerator_config.py
@@ -8,7 +8,6 @@ By default, quicksand auto-detects the best accelerator:
Falls back to TCG (software emulation) when hardware accel unavailable.
Performance optimizations are applied automatically based on platform:
-- Linux x86_64 + KVM: Uses 'microvm' machine type (~4x faster boot)
- Linux: Uses io_uring for disk I/O (~50% lower latency)
- All platforms: Uses IOThreads for better concurrent disk I/O
"""
diff --git a/packages/quicksand-core/README.md b/packages/quicksand-core/README.md
index 1370472..ce66121 100644
--- a/packages/quicksand-core/README.md
+++ b/packages/quicksand-core/README.md
@@ -74,7 +74,6 @@ asyncio.run(main())
- **Save and load**: Save VM disk state to a directory and load it on any machine
- **File sharing**: CIFS mounts via `quicksand-smb` (pure-Python SMB3 server, invoked as a subprocess via QEMU guestfwd)
- **Performance optimizations**:
- - microvm machine type (~4x faster boot on Linux x86_64 + KVM)
- io_uring disk AIO (~50% lower latency on Linux)
- IOThreads for better concurrent disk I/O (all platforms)
diff --git a/packages/quicksand-core/quicksand_core/__init__.py b/packages/quicksand-core/quicksand_core/__init__.py
index fe42186..2701b1c 100644
--- a/packages/quicksand-core/quicksand_core/__init__.py
+++ b/packages/quicksand-core/quicksand_core/__init__.py
@@ -41,6 +41,7 @@ from .qemu.arch import (
MachineType,
X86_64Config,
)
+from .qemu.installer import ensure_runtime, install_qemu
from .qemu.platform import (
PlatformConfig,
RuntimeInfo,
@@ -74,6 +75,8 @@ __all__ = [ # noqa: RUF022
"RuntimeInfo",
"is_runtime_available",
"get_machine_type",
+ "ensure_runtime",
+ "install_qemu",
# Accelerator
"get_accelerator",
"detect_accelerator",
diff --git a/packages/quicksand-core/quicksand_core/host/os_.py b/packages/quicksand-core/quicksand_core/host/os_.py
index 2361338..7bfe3d2 100644
--- a/packages/quicksand-core/quicksand_core/host/os_.py
+++ b/packages/quicksand-core/quicksand_core/host/os_.py
@@ -4,7 +4,7 @@ This module provides OS-specific values (accelerator, paths, kernel params, etc.
through a class hierarchy. Each OS has its own subclass.
OS-specific features:
-- Linux: KVM acceleration, io_uring disk AIO, microvm support
+- Linux: KVM acceleration, io_uring disk AIO
- macOS: HVF acceleration
- Windows: WHPX acceleration, noapic kernel param
"""
@@ -107,15 +107,6 @@ class BaseOSConfig(ABC):
"""
...
- @property
- @abstractmethod
- def supports_microvm(self) -> bool:
- """Whether this OS supports the microvm machine type.
-
- microvm provides ~4x faster boot but requires KVM (Linux only).
- """
- ...
-
@abstractmethod
def detect_accelerator(self) -> AcceleratorStatus:
"""Detect if hardware acceleration is available."""
@@ -162,11 +153,6 @@ class LinuxConfig(BaseOSConfig):
# io_uring provides ~50% lower disk latency on Linux (kernel 5.8+)
return "io_uring"
- @property
- def supports_microvm(self) -> bool:
- # microvm is a Linux-only machine type that provides ~4x faster boot
- return True
-
def detect_accelerator(self) -> AcceleratorStatus:
"""Detect KVM on Linux."""
kvm_path = self.kvm_device
@@ -227,11 +213,6 @@ class DarwinConfig(BaseOSConfig):
# io_uring is Linux-only; macOS uses QEMU's default (threads)
return None
- @property
- def supports_microvm(self) -> bool:
- # microvm requires KVM (Linux only)
- return False
-
def detect_accelerator(self) -> AcceleratorStatus:
"""Detect Hypervisor.framework on macOS."""
try:
@@ -301,11 +282,6 @@ class WindowsConfig(BaseOSConfig):
# io_uring is Linux-only; Windows uses QEMU's default
return None
- @property
- def supports_microvm(self) -> bool:
- # microvm requires KVM (Linux only)
- return False
-
def detect_accelerator(self) -> AcceleratorStatus:
"""Detect Windows Hypervisor Platform."""
try:
@@ -425,9 +401,5 @@ class OSConfig(BaseOSConfig):
def disk_aio(self) -> str | None:
raise NotImplementedError
- @property
- def supports_microvm(self) -> bool:
- raise NotImplementedError
-
def detect_accelerator(self) -> AcceleratorStatus:
raise NotImplementedError
diff --git a/packages/quicksand-core/quicksand_core/qemu/__init__.py b/packages/quicksand-core/quicksand_core/qemu/__init__.py
index 08754a2..e53c1f4 100644
--- a/packages/quicksand-core/quicksand_core/qemu/__init__.py
+++ b/packages/quicksand-core/quicksand_core/qemu/__init__.py
@@ -1,5 +1,6 @@
"""QEMU-specific subsystems: overlay, process, save, and platform configuration."""
+from .installer import ensure_runtime, install_qemu
from .overlay import OverlayManager
from .process import VMProcessManager
from .qmp import QMPClient
@@ -8,4 +9,6 @@ __all__ = [
"OverlayManager",
"QMPClient",
"VMProcessManager",
+ "ensure_runtime",
+ "install_qemu",
]
diff --git a/packages/quicksand-core/quicksand_core/qemu/arch.py b/packages/quicksand-core/quicksand_core/qemu/arch.py
index 0d174dd..c758699 100644
--- a/packages/quicksand-core/quicksand_core/qemu/arch.py
+++ b/packages/quicksand-core/quicksand_core/qemu/arch.py
@@ -3,12 +3,12 @@
Provides machine types and virtio device names for each supported CPU architecture.
Machine types:
-- x86_64: q35 (default) or microvm (with KVM for ~4x faster boot)
+- x86_64: q35
- ARM64: virt
Device types vary by machine:
- PCI machines (q35): virtio-blk-pci, virtio-net-pci
-- MMIO machines (virt, microvm): virtio-blk-device, virtio-net-device
+- MMIO machines (virt): virtio-blk-device, virtio-net-device
"""
from __future__ import annotations
@@ -24,7 +24,6 @@ class MachineType(StrEnum):
VIRT = "virt"
Q35 = "q35"
- MICROVM = "microvm"
class BaseArchitectureConfig(ABC):
diff --git a/packages/quicksand-core/quicksand_core/qemu/installer.py b/packages/quicksand-core/quicksand_core/qemu/installer.py
new file mode 100644
index 0000000..9d1e9ba
--- /dev/null
+++ b/packages/quicksand-core/quicksand_core/qemu/installer.py
@@ -0,0 +1,156 @@
+"""Runtime QEMU installation fallback.
+
+Provides ``install_qemu()`` to install QEMU via the system package manager
+and ``ensure_runtime()`` to resolve QEMU with automatic installation as a
+last resort. The bundled ``quicksand-qemu`` wheel remains the primary path;
+this module is a fallback for environments where the bundled wheel is
+unavailable or doesn't match the host platform.
+
+NOTE: The platform-specific install logic is shared with
+``quicksand-qemu/hatch_build.py`` (build-time hook). Keep in sync.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import platform as _platform
+import shutil
+import subprocess
+from pathlib import Path
+
+from ..host.arch import Architecture, _detect_architecture
+
+logger = logging.getLogger("quicksand.qemu.installer")
+
+# Stefan Weil Windows installer — update URL when upgrading QEMU.
+WINDOWS_QEMU_INSTALLER = "qemu-w64-setup-20260324.exe"
+WINDOWS_QEMU_URL = f"https://qemu.weilnetz.de/w64/2026/{WINDOWS_QEMU_INSTALLER}"
+
+WINDOWS_ARM64_QEMU_INSTALLER = "qemu-arm-setup-20260401.exe"
+WINDOWS_ARM64_QEMU_URL = f"https://qemu.weilnetz.de/aarch64/{WINDOWS_ARM64_QEMU_INSTALLER}"
+
+
+def install_qemu() -> None:
+ """Install QEMU via the system package manager.
+
+ Supports macOS (Homebrew), Linux (apt-get/dnf), and Windows (Stefan Weil
+ installer). On Linux, expects passwordless ``sudo``.
+
+ Raises:
+ RuntimeError: If the platform is unsupported or installation fails.
+ """
+ arch = _detect_architecture()
+ system = _platform.system().lower()
+
+ qemu_name = "qemu-system-x86_64" if arch == Architecture.X86_64 else "qemu-system-aarch64"
+
+ if shutil.which(qemu_name):
+ logger.info("Found %s on PATH", qemu_name)
+ return
+
+ logger.info("QEMU not found — installing for %s...", system)
+
+ if system == "darwin":
+ _install_qemu_macos()
+ elif system == "linux":
+ _install_qemu_linux(arch)
+ elif system == "windows":
+ _install_qemu_windows(arch)
+ else:
+ raise RuntimeError(f"Unsupported platform for automatic QEMU install: {system}")
+
+
+def ensure_runtime():
+ """Resolve QEMU runtime, auto-installing if needed.
+
+ Tries the standard resolution chain (bundled wheel → system PATH).
+ If neither is found, installs QEMU via the system package manager
+ and retries.
+
+ Returns:
+ RuntimeInfo: Resolved QEMU runtime paths.
+
+ Raises:
+ RuntimeError: If QEMU cannot be found or installed.
+ """
+ from .platform import _WrongArchError, get_runtime
+
+ try:
+ return get_runtime()
+ except _WrongArchError:
+ raise # Don't install over a misconfigured bundled package
+ except RuntimeError:
+ logger.info("QEMU not found, attempting automatic installation...")
+ install_qemu()
+ return get_runtime() # Retry; let any error propagate
+
+
+def _install_qemu_macos() -> None:
+ """Install QEMU via Homebrew."""
+ if not shutil.which("brew"):
+ raise RuntimeError(
+ "Homebrew is required to install QEMU on macOS.\nInstall it from https://brew.sh"
+ )
+ subprocess.run(["brew", "install", "qemu"], check=True)
+ logger.info("Installed QEMU via Homebrew")
+
+
+def _install_qemu_linux(arch: Architecture) -> None:
+ """Install QEMU via apt-get or dnf."""
+ pkg = "qemu-system-x86" if arch == Architecture.X86_64 else "qemu-system-arm"
+
+ if shutil.which("apt-get"):
+ env = {**os.environ, "DEBIAN_FRONTEND": "noninteractive"}
+ subprocess.run(
+ ["sudo", "apt-get", "update", "-qq"],
+ check=True,
+ env=env,
+ )
+ subprocess.run(
+ ["sudo", "apt-get", "install", "-y", "-qq", pkg, "qemu-utils"],
+ check=True,
+ env=env,
+ )
+ logger.info("Installed %s and qemu-utils via apt", pkg)
+ elif shutil.which("dnf"):
+ subprocess.run(
+ ["sudo", "dnf", "install", "-y", "qemu-system-x86-core", "qemu-img"],
+ check=True,
+ )
+ logger.info("Installed QEMU via dnf")
+ else:
+ raise RuntimeError(
+ "No supported package manager found (apt-get or dnf).\nPlease install QEMU manually."
+ )
+
+
+def _install_qemu_windows(arch: Architecture) -> None:
+ """Install QEMU via the Stefan Weil Windows installer."""
+ import urllib.request
+
+ if arch == Architecture.ARM64:
+ installer_name = WINDOWS_ARM64_QEMU_INSTALLER
+ installer_url = WINDOWS_ARM64_QEMU_URL
+ else:
+ installer_name = WINDOWS_QEMU_INSTALLER
+ installer_url = WINDOWS_QEMU_URL
+
+ installer = Path(installer_name)
+ if not installer.exists():
+ logger.info("Downloading %s...", installer_url)
+ urllib.request.urlretrieve(installer_url, installer)
+
+ logger.info("Running QEMU installer (silent)...")
+ subprocess.run([str(installer), "/S"], check=True)
+
+ # Add to PATH for this process
+ qemu_dir = Path(r"C:\Program Files\qemu")
+ if qemu_dir.exists():
+ os.environ["PATH"] = str(qemu_dir) + os.pathsep + os.environ.get("PATH", "")
+ logger.info("Installed QEMU to %s", qemu_dir)
+ else:
+ raise RuntimeError(
+ f"QEMU installer completed but {qemu_dir} not found.\n"
+ "The installer may have failed silently."
+ )
diff --git a/packages/quicksand-core/quicksand_core/qemu/platform.py b/packages/quicksand-core/quicksand_core/qemu/platform.py
index 03ad4c3..91b34d3 100644
--- a/packages/quicksand-core/quicksand_core/qemu/platform.py
+++ b/packages/quicksand-core/quicksand_core/qemu/platform.py
@@ -4,7 +4,6 @@ Provides PlatformConfig which composes architecture + OS configuration to produc
QEMU command lines. Also provides runtime discovery (get_runtime, get_accelerator).
Performance optimizations applied automatically:
-- microvm machine type: ~4x faster boot (Linux x86_64 + KVM only)
- io_uring disk AIO: ~50% lower disk latency (Linux only)
- IOThreads: Better concurrent disk I/O (all platforms)
"""
@@ -17,7 +16,6 @@ from pathlib import Path
from typing import TYPE_CHECKING
from .._types import KernelParams, NetworkConstants, NetworkMode
-from ..host.arch import Architecture
from ..host.os_ import (
Accelerator,
AcceleratorStatus,
@@ -116,34 +114,13 @@ class PlatformConfig:
def disk_aio(self) -> str | None:
return self.os.disk_aio
- def _use_microvm(self, accelerator: Accelerator | None, data_dir: Path | None = None) -> bool:
- if not (
- self.os.supports_microvm
- and self.arch.arch_type == Architecture.X86_64
- and accelerator == Accelerator.KVM
- ):
- return False
- return not (data_dir and not (data_dir / "bios-microvm.bin").exists())
-
- def _get_effective_machine_type(
- self, accelerator: Accelerator | None, data_dir: Path | None = None
- ) -> MachineType:
- if self._use_microvm(accelerator, data_dir):
- return MachineType.MICROVM
+ def _get_effective_machine_type(self) -> MachineType:
return self.arch.machine_type
- def _get_virtio_blk_device(
- self, accelerator: Accelerator | None, data_dir: Path | None = None
- ) -> str:
- if self._use_microvm(accelerator, data_dir):
- return "virtio-blk-device"
+ def _get_virtio_blk_device(self) -> str:
return self.arch.virtio_blk_device
- def _get_virtio_net_device(
- self, accelerator: Accelerator | None, data_dir: Path | None = None
- ) -> str:
- if self._use_microvm(accelerator, data_dir):
- return "virtio-net-device"
+ def _get_virtio_net_device(self) -> str:
return self.arch.virtio_net_device
# =========================================================================
@@ -169,9 +146,8 @@ class PlatformConfig:
) -> list[str]:
"""Build the complete QEMU command line."""
data_dir = runtime_info.data_dir
- use_microvm = self._use_microvm(accelerator, data_dir)
- effective_machine = self._get_effective_machine_type(accelerator, data_dir)
- virtio_blk = self._get_virtio_blk_device(accelerator, data_dir)
+ effective_machine = self._get_effective_machine_type()
+ virtio_blk = self._get_virtio_blk_device()
drive_opts = (
f"file={overlay_path},format=qcow2,if=none,id=drive0,"
@@ -238,7 +214,7 @@ class PlatformConfig:
else:
cmd.extend(["-nographic", "-vga", "none"])
- if not use_microvm:
+ if effective_machine != MachineType.VIRT:
cmd.extend(["-global", "virtio-net-pci.romfile="])
has_hw_accel = accelerator in (Accelerator.KVM, Accelerator.HVF)
@@ -254,17 +230,13 @@ class PlatformConfig:
cmd.extend(["-qmp", f"tcp:127.0.0.1:{qmp_port},server,nowait"])
if agent_socket_path is not None:
- cmd.extend(self._build_virtio_serial_args(agent_socket_path, accelerator, data_dir))
+ cmd.extend(self._build_virtio_serial_args(agent_socket_path))
cmd.extend(
self._build_kernel_args(config, kernel_path, initrd_path, agent_port, agent_token)
)
- cmd.extend(
- self._build_network_args(
- config, agent_port, accelerator, data_dir, smb_port, smb_server
- )
- )
- cmd.extend(self._build_9p_args(config, accelerator, data_dir))
+ cmd.extend(self._build_network_args(config, agent_port, smb_port, smb_server))
+ cmd.extend(self._build_9p_args(config))
cmd.extend(config.extra_qemu_args)
return cmd
@@ -302,12 +274,10 @@ class PlatformConfig:
def _build_virtio_serial_args(
self,
socket_path: Path,
- accelerator: Accelerator | None = None,
- data_dir: Path | None = None,
) -> list[str]:
"""Build QEMU args for virtio-serial agent channel."""
- use_microvm = self._use_microvm(accelerator, data_dir)
- serial_device = "virtio-serial-device" if use_microvm else "virtio-serial-pci"
+ use_mmio = self.arch.machine_type == MachineType.VIRT
+ serial_device = "virtio-serial-device" if use_mmio else "virtio-serial-pci"
return [
"-device",
@@ -321,8 +291,6 @@ class PlatformConfig:
def _build_9p_args(
self,
config: SandboxConfig,
- accelerator: Accelerator | None = None,
- data_dir: Path | None = None,
) -> list[str]:
"""Build QEMU args for virtio-9p (Plan 9) mounts.
@@ -334,9 +302,8 @@ class PlatformConfig:
if not plan9_mounts:
return []
- use_microvm = self._use_microvm(accelerator, data_dir)
- # MMIO machines (virt, microvm) use virtio-*-device; PCI machines (q35) use virtio-*-pci
- use_mmio = use_microvm or self.arch.machine_type == MachineType.VIRT
+ # MMIO machines (virt/ARM64) use virtio-*-device; PCI machines (q35) use virtio-*-pci
+ use_mmio = self.arch.machine_type == MachineType.VIRT
device_type = "virtio-9p-device" if use_mmio else "virtio-9p-pci"
cmd: list[str] = []
@@ -357,16 +324,10 @@ class PlatformConfig:
self,
config: SandboxConfig,
agent_port: int,
- accelerator: Accelerator | None = None,
- data_dir: Path | None = None,
smb_port: int | None = None,
smb_server: SMBServer | None = None,
) -> list[str]:
- use_microvm = self._use_microvm(accelerator, data_dir)
-
if config.network_mode is NetworkMode.NONE:
- if use_microvm:
- return []
return ["-nic", "none"]
hostfwd = f"hostfwd=tcp:127.0.0.1:{agent_port}-:{agent_port}"
@@ -385,11 +346,8 @@ class PlatformConfig:
guestfwd_cmd = smb_server.get_guestfwd_cmd() if smb_server is not None else None
if guestfwd_cmd is not None:
- # QuicksandSMBServer: spawn the pure-Python SMB server directly.
- # Works in both MOUNTS_ONLY and FULL modes — no TCP port needed.
guestfwd = f",guestfwd=tcp:{guestfwd_ip}:{guestfwd_port}-cmd:{guestfwd_cmd}"
elif config.network_mode is NetworkMode.MOUNTS_ONLY and smb_port is not None:
- # SambaSMBServer fallback: relay to external smbd via TCP.
import sys
relay_script = str(Path(__file__).resolve().parent.parent / "_tcp_relay.py")
@@ -400,16 +358,8 @@ class PlatformConfig:
)
netdev_opts = f"user,id=net0,restrict={restrict},{hostfwd}{guestfwd}"
+ virtio_net = self._get_virtio_net_device()
- if use_microvm:
- return [
- "-netdev",
- netdev_opts,
- "-device",
- "virtio-net-device,netdev=net0",
- ]
-
- virtio_net = self._get_virtio_net_device(accelerator, data_dir)
return [
"-netdev",
netdev_opts,
@@ -496,7 +446,8 @@ def get_runtime(config: PlatformConfig | None = None) -> RuntimeInfo:
raise RuntimeError(
"QEMU not found. Either:\n"
" - Install bundled: pip install quicksand-qemu\n"
- " - Or install system QEMU and ensure it's in PATH"
+ " - Or install system QEMU and ensure it's in PATH\n"
+ " - Or auto-install: quicksand.ensure_runtime()"
)
diff --git a/packages/quicksand-qemu/hatch_build.py b/packages/quicksand-qemu/hatch_build.py
index 15d0d7c..cd61bbd 100644
--- a/packages/quicksand-qemu/hatch_build.py
+++ b/packages/quicksand-qemu/hatch_build.py
@@ -122,28 +122,6 @@ class RuntimeBuildHook(BuildHookInterface):
"Ensure QEMU and seabios/ipxe-qemu are installed."
)
- # Optional files for performance optimizations
- # These enable faster boot with microvm machine type on Linux x86_64 + KVM
- optional_files = {
- "bios-microvm.bin": [
- qemu_share_dir_windows / "bios-microvm.bin", # Windows (Stefan Weil)
- qemu_share_dir_linux / "bios-microvm.bin", # macOS/Linux
- Path("/usr/share/qemu/bios-microvm.bin"), # Standard Linux
- Path("/usr/share/seabios/bios-microvm.bin"), # Ubuntu seabios
- ],
- }
-
- for filename, search_paths in optional_files.items():
- for src in search_paths:
- if src.exists():
- shutil.copy2(src, data_dir / filename)
- self.app.display_info(f"Bundled (optional): {filename} (from {src})")
- break
- else:
- self.app.display_warning(
- f"Optional file not found: {filename} - microvm optimization disabled"
- )
-
def _find_qemu_install_dir(self, qemu_path: Path) -> Path:
"""Find the QEMU installation directory from a binary path."""
system = platform.system().lower()
@@ -868,6 +846,8 @@ class RuntimeBuildHook(BuildHookInterface):
# -----------------------------------------------------------------
# QEMU installation
+ # NOTE: This logic is shared with quicksand_core.qemu.installer.
+ # Keep both in sync when updating installers or package names.
# -----------------------------------------------------------------
# Stefan Weil Windows installer — update URL when upgrading QEMU.
diff --git a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network
index dc83b95..d94d368 100644
--- a/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network
+++ b/packages/quicksand-ubuntu/quicksand_ubuntu/docker/80-dhcp.network
@@ -1,6 +1,5 @@
[Match]
# Match both predictable names (en*: ens3, enp0s3) and classic names (eth0)
-# Classic names are used by virtio-mmio devices (microvm machine type)
Name=e*
[Network]
diff --git a/packages/quicksand/README.md b/packages/quicksand/README.md
index 0ec6cd9..bb48d10 100644
--- a/packages/quicksand/README.md
+++ b/packages/quicksand/README.md
@@ -89,7 +89,7 @@ Each sandbox runs in a real virtual machine with hypervisor-level isolation:
| Platform | Accelerator | Machine | File Sharing | Performance |
|----------|-------------|---------|--------------|-------------|
-| Linux x86_64 | KVM | microvm | SMB/CIFS | io_uring + IOThreads |
+| Linux x86_64 | KVM | q35 | SMB/CIFS | io_uring + IOThreads |
| Linux ARM64 | KVM | virt | SMB/CIFS | io_uring + IOThreads |
| macOS | HVF | q35/virt | SMB/CIFS | IOThreads |
| Windows | WHPX | q35 | SMB/CIFS | IOThreads |
@@ -99,7 +99,7 @@ Key components:
- **Guest agent**: Lightweight TCP server for command execution
- **Disposable overlays**: Base image unchanged, writes go to temp overlay
- **SMB/CIFS mounts**: Mount host directories into the VM
-- **Platform optimizations**: microvm (~4x faster boot), io_uring (~50% lower disk latency), IOThreads
+- **Platform optimizations**: io_uring (~50% lower disk latency), IOThreads
## Requirements
diff --git a/packages/quicksand/quicksand/__init__.py b/packages/quicksand/quicksand/__init__.py
index 9337ff9..9632d19 100644
--- a/packages/quicksand/quicksand/__init__.py
+++ b/packages/quicksand/quicksand/__init__.py
@@ -54,10 +54,12 @@ from quicksand_core import (
SandboxConfigParams,
SaveManifest,
detect_accelerator,
+ ensure_runtime,
get_accelerator,
get_machine_type,
get_platform_config,
get_runtime,
+ install_qemu,
is_runtime_available,
)
@@ -120,6 +122,8 @@ __all__ = [ # noqa: RUF022
"RuntimeInfo",
"is_runtime_available",
"get_machine_type",
+ "ensure_runtime",
+ "install_qemu",
# Accelerator
"get_accelerator",
"detect_accelerator",
diff --git a/packages/quicksand/quicksand/cli/qemu.py b/packages/quicksand/quicksand/cli/qemu.py
index 413e5d0..ad3d7a9 100644
--- a/packages/quicksand/quicksand/cli/qemu.py
+++ b/packages/quicksand/quicksand/cli/qemu.py
@@ -1,4 +1,4 @@
-"""QEMU status command."""
+"""QEMU status and install commands."""
from __future__ import annotations
@@ -8,13 +8,22 @@ import subprocess
def register(subparsers: argparse._SubParsersAction) -> None:
"""Register the qemu subcommand."""
- subparsers.add_parser(
+ qemu_parser = subparsers.add_parser(
"qemu",
- help="Show QEMU installation info",
+ help="Show QEMU installation info or install QEMU",
)
+ qemu_sub = qemu_parser.add_subparsers(dest="qemu_command")
+ qemu_sub.add_parser("install", help="Install QEMU via system package manager")
def cmd(args: argparse.Namespace) -> int:
+ """Show QEMU installation info, or install QEMU."""
+ if getattr(args, "qemu_command", None) == "install":
+ return _cmd_install()
+ return _cmd_status()
+
+
+def _cmd_status() -> int:
"""Show QEMU installation info."""
from quicksand_core.qemu.platform import get_runtime
@@ -53,3 +62,17 @@ def cmd(args: argparse.Namespace) -> int:
pass
return 0
+
+
+def _cmd_install() -> int:
+ """Install QEMU via system package manager."""
+ from quicksand_core.qemu.installer import install_qemu
+
+ try:
+ install_qemu()
+ except RuntimeError as e:
+ print(f"Failed to install QEMU: {e}")
+ return 1
+
+ print("QEMU installed successfully.")
+ return _cmd_status()
diff --git a/tests/unit/test_qemu_installer.py b/tests/unit/test_qemu_installer.py
new file mode 100644
index 0000000..3d4670f
--- /dev/null
+++ b/tests/unit/test_qemu_installer.py
@@ -0,0 +1,97 @@
+"""Tests for quicksand_core.qemu.installer."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+from quicksand_core.host.arch import Architecture
+from quicksand_core.qemu.installer import (
+ ensure_runtime,
+ install_qemu,
+)
+
+
+class TestInstallQemu:
+ """Tests for install_qemu() platform dispatch."""
+
+ @patch("quicksand_core.qemu.installer.shutil.which", return_value="/usr/bin/qemu-system-x86_64")
+ @patch("quicksand_core.qemu.installer._detect_architecture", return_value=Architecture.X86_64)
+ def test_skips_if_already_on_path(self, _mock_arch, _mock_which):
+ """Should return early if QEMU is already on PATH."""
+ install_qemu() # Should not raise
+
+ @patch("quicksand_core.qemu.installer._install_qemu_macos")
+ @patch("quicksand_core.qemu.installer.shutil.which", return_value=None)
+ @patch("quicksand_core.qemu.installer._platform.system", return_value="Darwin")
+ @patch("quicksand_core.qemu.installer._detect_architecture", return_value=Architecture.ARM64)
+ def test_dispatches_macos(self, _arch, _sys, _which, mock_install):
+ install_qemu()
+ mock_install.assert_called_once()
+
+ @patch("quicksand_core.qemu.installer._install_qemu_linux")
+ @patch("quicksand_core.qemu.installer.shutil.which", return_value=None)
+ @patch("quicksand_core.qemu.installer._platform.system", return_value="Linux")
+ @patch("quicksand_core.qemu.installer._detect_architecture", return_value=Architecture.X86_64)
+ def test_dispatches_linux(self, _arch, _sys, _which, mock_install):
+ install_qemu()
+ mock_install.assert_called_once_with(Architecture.X86_64)
+
+ @patch("quicksand_core.qemu.installer._install_qemu_windows")
+ @patch("quicksand_core.qemu.installer.shutil.which", return_value=None)
+ @patch("quicksand_core.qemu.installer._platform.system", return_value="Windows")
+ @patch("quicksand_core.qemu.installer._detect_architecture", return_value=Architecture.X86_64)
+ def test_dispatches_windows(self, _arch, _sys, _which, mock_install):
+ install_qemu()
+ mock_install.assert_called_once_with(Architecture.X86_64)
+
+ @patch("quicksand_core.qemu.installer.shutil.which", return_value=None)
+ @patch("quicksand_core.qemu.installer._platform.system", return_value="FreeBSD")
+ @patch("quicksand_core.qemu.installer._detect_architecture", return_value=Architecture.X86_64)
+ def test_raises_on_unsupported_platform(self, _arch, _sys, _which):
+ with pytest.raises(RuntimeError, match="Unsupported platform"):
+ install_qemu()
+
+
+class TestEnsureRuntime:
+ """Tests for ensure_runtime() resolve-or-install logic."""
+
+ @patch("quicksand_core.qemu.platform.get_runtime")
+ def test_returns_without_installing_when_found(self, mock_get_runtime):
+ """Should return RuntimeInfo without calling install_qemu."""
+ mock_runtime = MagicMock()
+ mock_get_runtime.return_value = mock_runtime
+
+ result = ensure_runtime()
+
+ assert result is mock_runtime
+ mock_get_runtime.assert_called_once()
+
+ @patch("quicksand_core.qemu.platform.get_runtime")
+ @patch("quicksand_core.qemu.installer.install_qemu")
+ def test_installs_on_runtime_error(self, mock_install, mock_get_runtime):
+ """Should call install_qemu and retry when get_runtime raises."""
+ mock_runtime = MagicMock()
+ mock_get_runtime.side_effect = [RuntimeError("not found"), mock_runtime]
+
+ result = ensure_runtime()
+
+ assert result is mock_runtime
+ mock_install.assert_called_once()
+ assert mock_get_runtime.call_count == 2
+
+ @patch("quicksand_core.qemu.installer.install_qemu")
+ def test_propagates_wrong_arch_error(self, mock_install):
+ """Should re-raise _WrongArchError without attempting install."""
+ from quicksand_core.qemu.platform import _WrongArchError
+
+ with (
+ patch(
+ "quicksand_core.qemu.platform.get_runtime",
+ side_effect=_WrongArchError("wrong arch"),
+ ),
+ pytest.raises(_WrongArchError),
+ ):
+ ensure_runtime()
+
+ mock_install.assert_not_called()