Skip to main content
Image is the static namespace for two related things: configuring an explicit rootfs source for a sandbox (Image.oci, Image.bind, Image.disk), and managing the local OCI image cache that sandbox creation pulls into (get, list, inspect, remove, prune). Cache operations require a local backend. See Sandbox for the image= and pull_policy= creation kwargs.
from microsandbox import Image

Typical flow

from microsandbox import Image, Sandbox

# Pull happens implicitly on creation
async with await Sandbox.create("api", image="python:3.12") as sb:
    await sb.exec("python", ["-V"])

# Later, inspect and prune the local cache
for image in await Image.list():
    print(image.reference, image.layer_count)

report = await Image.prune()
print(f"reclaimed {report.bytes_reclaimed} bytes")

Source factory

These static methods return an ImageSource you can pass as the image= kwarg to Sandbox.create(). A plain string also works (image="python:3.12"); use the factory when you need OCI-only options like the writable upper size, or to be explicit about a bind or disk source.

Image.oci()

@staticmethod
def oci(reference: str, *, upper_size_mib: int | None = None) -> ImageSource
sb = await Sandbox.create(
    "api",
    image=Image.oci("python:3.12", upper_size_mib=8192),
)
Create an OCI image rootfs source. Use upper_size_mib to size the writable overlay upper layer; otherwise the default applies.

Parameters

referencestr
OCI image reference, e.g. “python:3.12”.
upper_size_mibint | None
Writable overlay upper size in MiB. None keeps the default.

Returns

Rootfs source for image=.

Image.bind()

@staticmethod
def bind(path: str) -> ImageSource
sb = await Sandbox.create("api", image=Image.bind("/srv/rootfs"))
Create a rootfs source that binds a host directory as the guest root filesystem.

Parameters

pathstr
Host directory to use as the rootfs.

Returns

Rootfs source for image=.

Image.disk()

@staticmethod
def disk(path: str, *, fstype: str | None = None) -> ImageSource
sb = await Sandbox.create(
    "api",
    image=Image.disk("/data/root.qcow2", fstype="ext4"),
)
Create a rootfs source backed by a disk image. The format is inferred from the file extension. Pass fstype when the filesystem type cannot be auto-detected.

Parameters

pathstr
Path to the disk image (e.g. .qcow2, .raw, .vmdk).
fstypestr | None
Filesystem type, e.g. “ext4”. None auto-detects.

Returns

Rootfs source for image=.

Cache management

These static methods inspect and prune images already pulled into the local OCI cache. They require a local backend; on a cloud backend they raise UnsupportedError.

Image.get()

@staticmethod
async def get(reference: str) -> ImageHandle
handle = await Image.get("python:3.12")
print(handle.reference, handle.layer_count)
Fetch one cached image by reference. Raises ImageNotFoundError when the image is not present in the local cache.

Parameters

referencestr
Image reference to look up.

Returns

Handle to the cached image.

Image.list()

@staticmethod
async def list() -> list[ImageHandle]
for image in await Image.list():
    print(image.reference, image.size_bytes)
Return every cached image.

Returns

All cached image handles.

Image.inspect()

@staticmethod
async def inspect(reference: str) -> ImageDetail
detail = await Image.inspect("python:3.12")
print(detail.handle.reference)
for layer in detail.layers:
    print(layer.position, layer.diff_id)
Return handle metadata plus the parsed OCI config and per-layer detail.

Parameters

referencestr
Image reference to inspect.

Returns

Handle, OCI config, and layers.

Image.remove()

@staticmethod
async def remove(reference: str, *, force: bool = False) -> None
await Image.remove("python:3.12", force=True)
Delete a cached image. When force is False, an image still referenced by one or more sandboxes raises ImageInUseError; pass force=True to remove it anyway.

Parameters

referencestr
Image reference to delete.
forcebool
Remove even if still referenced. Default False.

Image.prune()

@staticmethod
async def prune() -> ImagePruneReport
report = await Image.prune()
print(f"{report.layers_removed} layers, {report.bytes_reclaimed} bytes")
Remove cached image data that is not used by any sandbox or indexed snapshot. The returned report counts the removed refs, manifests, layers, fsmeta files, and VMDK files, plus any measured bytes reclaimed.

Returns

Counts of removed data and bytes reclaimed.

Types

ImageSource

Returned by oci() · bind() · disk()

Explicit rootfs image source. Build one with Image.oci(), Image.bind(), or Image.disk(), then pass it as the image= kwarg to Sandbox.create(). A frozen dataclass; treat its fields as opaque.
FieldTypeDescription
_typestrSource kind: "oci", "bind", or "disk"
_pathstr | NoneHost path for bind / disk sources
_referencestr | NoneOCI reference for oci sources
_upper_size_mibint | NoneWritable overlay upper size in MiB (OCI only)
_fstypestr | NoneFilesystem type for disk sources
_formatDiskImageFormat | NoneDisk image format (inferred from extension)

ImageHandle

Returned by get() · list()

A lightweight handle to a cached OCI image, returned by Image.get() and Image.list(). Properties are read-only attributes; the two methods are async.
Property / MethodTypeDescription
referencestrImage reference
size_bytesint | NoneTotal size in bytes, or None when unknown
manifest_digeststr | NoneContent-addressable manifest digest
architecturestr | NoneResolved architecture
osstr | NoneResolved operating system
layer_countintNumber of layers
last_used_atfloat | NoneLast referenced time, milliseconds since epoch
created_atfloat | NoneFirst-pulled time, milliseconds since epoch
await inspect()ImageDetailFetch full detail for this image
await remove(*, force=False)NoneDelete this image (raises ImageInUseError unless force)

ImageDetail

Returned by inspect() · ImageHandle.inspect()

Full detail for a cached image: the core handle, the parsed OCI config block, and per-layer metadata.
PropertyTypeDescription
handleImageHandleCore cached image metadata
configImageConfigDetail | NoneParsed OCI config block
layerslist[ImageLayerDetail]Layers in bottom-to-top order

ImageConfigDetail

Used by ImageDetail.config

OCI image config fields extracted from the local cache.
PropertyTypeDescription
digeststrConfig blob digest
envlist[str]Environment variables (KEY=value)
cmdlist[str] | NoneDefault command
entrypointlist[str] | NoneImage entrypoint
working_dirstr | NoneDefault working directory
userstr | NoneDefault user
labelsdict[str, Any] | NoneOCI labels
stop_signalstr | NoneConfigured stop signal

ImageLayerDetail

Used by ImageDetail.layers

Metadata for a single image layer.
PropertyTypeDescription
diff_idstrUncompressed layer diff id
blob_digeststrCompressed blob digest
media_typestr | NoneLayer media type
compressed_size_bytesint | NoneCompressed size in bytes
erofs_size_bytesint | NoneSize of the generated EROFS sidecar in bytes
positionintLayer position (bottom to top)

ImagePruneReport

Returned by prune()

Summary of cached image data removed by Image.prune().
PropertyTypeDescription
image_refs_removedintNumber of image refs removed
manifests_removedintNumber of manifests removed
layers_removedintNumber of layer blobs removed
fsmeta_removedintNumber of fsmeta sidecar files removed
vmdk_removedintNumber of VMDK files removed
bytes_reclaimedint | NoneMeasured bytes reclaimed, or None when not measured

DiskImageFormat

Used by ImageSource._format

Disk image container format. A StrEnum, so the string values are accepted directly.
ValueDescription
"qcow2"QEMU copy-on-write v2
"raw"Raw block image
"vmdk"VMware disk image

Errors

Image operations raise these typed exceptions, all subclasses of MicrosandboxError.
ExceptionRaised when
ImageNotFoundErrorThe image reference could not be resolved in the local cache
ImageInUseErrorThe image is still referenced by one or more sandboxes (and force was not set)
ImagePullFailedErrorAn image pull failed
UnsupportedErrorCache operations were attempted on a backend that lacks a local cache