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 / persistence-schema-and-migrations

Persistence schema and migrations

The persistence layer is a SQLite catalog shared by the host CLI and the in-VM runtime. It records image metadata, sandbox and run state, storage indexes, resource reservations, labels, and coordination leases while ordered migrations keep old catalogs readable by newer releases. See the parent page Persistence for the wider persistence model.

Persistence model

The catalog joins durable product state with host-local projections. A sandbox points to its desired configuration and runtime state. Related rows connect it to a root filesystem, runs, labels, snapshots, and resource reservations.

The main relationships are:

flowchart TD
    Ref[Image reference] --> Manifest[Image manifest]
    Manifest --> Config[Image config]
    Manifest --> Layer[Image layers]
    Sandbox[Sandbox] --> Run[Sandbox runs]
    Sandbox --> Rootfs[Root filesystem]
    Rootfs --> Manifest
    Sandbox --> Labels[Labels]
    Sandbox --> Snapshot[Snapshot index]
    Run --> CPU[CPU allocation]
    CPU --> Memory[NUMA memory promises]
    Run --> Writeback[Writeback allocation]
    Lease[Maintenance lease] -. coordinates .-> Sandbox

Entity model

The entity model expresses the durable relationships that other subsystems use. It also marks which records are authoritative and which records are projections or short-lived coordination state.

Image catalog

The image catalog resolves a human image reference to one manifest. The manifest owns one image configuration and an ordered set of reusable layers. Layer identity uses the uncompressed content digest so different images can share stored layer data. The catalog also keeps metadata needed to build an EROFS-backed root filesystem. References: crates/…/image_ref.rs• L1-52, crates/…/manifest.rs• L1-83, crates/…/config.rs• L1-55, crates/…/layer.rs• L1-60, crates/…/manifest_layer.rs• L1-62

Sandbox lifecycle

The sandbox row is the stable identity for a named sandbox. It stores the desired configuration, the configuration used by an active VM, lifecycle status, and the ephemeral flag used by cleanup. Each sandbox can have many run records, which preserve process identity and the result of each execution. References: crates/…/sandbox.rs• L9-93, crates/…/run.rs• L9-124

The root filesystem row gives each sandbox one selected image or host storage source. Its mode distinguishes EROFS, bind, and disk-image roots. A root filesystem may point to an image manifest, while bind and disk-image roots can use host-local data instead. References: crates/…/sandbox_rootfs.rs• L1-107

Storage state

Volumes represent named storage with its kind, capacity, format, and file-system information. The snapshot index is a digest-keyed local view of snapshot artifacts on disk. The artifact remains the source of truth; the index supports fast lookup and records parent links, state type, availability, and artifact transition status. References: crates/…/volume.rs• L1-40, crates/…/snapshot.rs• L1-71

Resource allocations

Allocation rows make host resource promises visible while a sandbox run is active. A CPU allocation belongs to one run and has child rows for guest vCPU assignments. Memory rows attach per-guest-node boot and maximum promises to that allocation. Writeback rows record host-global dirty-data capacity and intentionally do not depend on the run row, so crash recovery can inspect stale membership after lifecycle cleanup. References: crates/…/cpu_allocation.rs• L1-57, crates/…/cpu_allocation_cpu.rs• L1-48, crates/…/memory_allocation_node.rs• L1-50, crates/…/writeback_allocation.rs• L1-47

Labels and leases

Labels are a query-friendly projection of the labels stored in sandbox configuration. The (sandbox_id, key) identity permits one value per key for each sandbox. Maintenance leases use named rows to coordinate work such as lifecycle cleanup or exclusive installation, and an expired lease can be claimed by a later process. References: crates/…/sandbox_label.rs• L1-48, crates/…/maintenance_lease.rs• L1-59

Connection pools and retries

The database uses a shared SQLite connection policy so every process sees the same locking and durability behavior. Reads use a multi-connection pool. Writes use one connection per process, which queues local writers before SQLite must arbitrate with another process.

SQLite connection policy

The paired pools open the write side first. All connections use WAL mode, foreign-key checks, normal synchronous mode, and a configurable busy timeout. The write side may create the catalog. A read-only consumer must find an existing file and never creates one. References: crates/…/pool.rs• L1-99, crates/…/connection.rs• L23-97

WAL lets readers continue while a writer changes the catalog. The single write connection removes most same-process writer contention. Cross-process contention still occurs because the host and runtime can open the same file.

Busy retry behavior

Write operations retry transient SQLite BUSY and BUSY_SNAPSHOT errors after the connection-level busy timeout expires. The retry loop uses exponential backoff from 10 milliseconds to a 500 millisecond cap and stops after eight attempts. Other database errors return at once. References: crates/…/retry.rs• L11-108

Single-statement writes receive this policy through the write connection. A group of writes that must commit together uses a transaction helper, which opens a fresh transaction and retries the whole operation. Callers must therefore make transaction work safe to run more than once. References: crates/…/connection.rs• L104-132, crates/…/connection.rs• L167-208

Migration evolution

The migration crate defines one append-only executable order. Each migration changes schema or persisted data from the state produced by the previous entry. The migration metadata mirrors that order and supplies downgrade information.

Ordered migration stages

The following table shows the current executable order. The order comes from Migrator::migrations() and is not reconstructed by sorting the timestamp-like names.

OrderSchema concernMigration
1Initial image catalogm20260305_000001_create_image_tables
2Sandboxes and runsm20260305_000002_create_sandbox_tables
3Initial volumes and snapshot storagem20260305_000003_create_storage_tables
4Sandbox image referencesm20260305_000004_create_sandbox_images_table
5EROFS image and rootfs modelm20260410_000001_erofs_image_schema
6File-first snapshot indexm20260501_000001_create_snapshot_index
7Removal of catalog metrics rowsm20260517_000001_drop_sandbox_metric
8OCI rootfs config shapem20260527_000001_migrate_oci_rootfs_source
9Sandbox label projectionm20260531_000001_create_sandbox_labels
10Label selector indexm20260531_000002_index_sandbox_labels_key_value
11Named volume kinds and attachmentsm20260606_000001_named_volume_kinds
12Ephemeral sandbox statem20260621_000001_add_sandbox_ephemeral
13Maintenance leasesm20260621_000002_create_maintenance_lease
14Desired and active sandbox configm20260703_000001_add_sandbox_active_config
15Bind rootfs config shapem20260708_000001_migrate_bind_rootfs_source
16Structured root disk statem20260710_000001_migrate_root_disk
17Snapshot payload scopem20260714_000001_add_snapshot_scope
18Snapshot artifact transition statem20260723_000001_snapshot_artifact_transition
19Cooperative CPU allocationsm20260719_000001_create_cpu_allocations
20Host-global writeback allocationsm20260803_000001_create_writeback_allocations
21NUMA memory promisesm20260808_000001_create_memory_allocation_nodes
22Label projection rebuildm20260810_000001_rebuild_sandbox_labels
23Shareable logical-CPU assignmentsm20260813_000001_share_cpu_allocations
24Recyclable sandbox network address-pool slotsm20260818_000001_sandbox_network_slot
25Mount ownership compatibility boundarym20260824_000001_mount_owner_config

References: crates/…/lib.rs• L1-80

Persisted data transitions

Several migrations change data shape as well as tables. Sandbox configuration is rewritten from legacy OCI and bind forms to structured forms. Root disk data moves from a single upper-size field to a kind-aware record. These changes apply to active configuration when that column exists, so the desired and running views remain readable by the same release. References: crates/…/m20260527_000001_migrate_oci_rootfs_source.rs• L37-100, crates/…/m20260708_000001_migrate_bind_rootfs_source.rs• L34-107, crates/…/m20260710_000001_migrate_root_disk.rs• L40-137

Snapshot evolution adds scope and then expands the index to describe file and checkpoint state. It also creates a journal for artifact conversion and records whether each indexed artifact is canonical or needs recovery. Label repair rebuilds the full projection from sandbox configuration in one transaction, rather than trying to guess which rows are stale. References: crates/…/m20260714_000001_add_snapshot_scope.rs• L31-62, crates/…/m20260723_000001_snapshot_artifact_transition.rs• L23-117, crates/…/m20260810_000001_rebuild_sandbox_labels.rs• L31-91

Allocation evolution also changes row meaning. CPU assignments move from exclusive logical-CPU ownership to per-allocation vCPU assignments, which permits several allocations to share a logical processor. The memory and writeback migrations add the host capacity state needed to plan and recover those allocations. References: crates/…/m20260719_000001_create_cpu_allocations.rs• L44-158, crates/…/m20260803_000001_create_writeback_allocations.rs• L30-109, crates/…/m20260808_000001_create_memory_allocation_nodes.rs• L31-103, crates/…/m20260813_000001_share_cpu_allocations.rs• L53-131

Later migrations extend active sandbox state without changing the main relationship model. The network-slot migration persists a recyclable address-pool slot for active sandboxes and clears slots from terminal rows. The mount-owner migration is a compatibility marker: it prevents an older binary from silently dropping mount ownership settings from desired or active sandbox configuration. References: crates/…/m20260818_000001_sandbox_network_slot.rs• L1-10, crates/…/m20260824_000001_mount_owner_config.rs• L1-5

Downgrade boundaries

Downgrade metadata states whether a migration can restore a target-compatible schema and whether it can affect cached images or user data. The migration history has a floor at release 0.6.0; newer targets report their own schema baseline. The downgrade planner treats applied migration names as a set and accepts them only when they form a complete prefix of the known order. References: crates/…/schema_metadata.rs• L14-72, crates/…/schema_metadata.rs• L240-316

Some reverse paths are deliberately blocked or incomplete. A snapshot downgrade requires all managed artifacts to reach a reverse-complete state. A root disk downgrade rejects kinds that the older release cannot represent. The old metrics table is not restored because live metrics no longer belong in the catalog. Network-slot rollback keeps its compatible column in place. Mount-owner rollback checks both desired and active configuration and refuses to remove the compatibility marker when an older binary would discard ownership settings. References: crates/…/m20260723_000001_snapshot_artifact_transition.rs• L122-190, crates/…/m20260710_000001_migrate_root_disk.rs• L179-228, crates/…/m20260517_000001_drop_sandbox_metric.rs• L34-51, crates/…/m20260818_000001_sandbox_network_slot.rs• L90-108, crates/…/m20260824_000001_mount_owner_config.rs• L28-60, crates/…/schema_metadata.rs• L71-255

Change checklist

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

  • Add a new schema change to both the executable migration order and MIGRATION_METADATA; keep the order append-only and preserve the supported baseline.
  • Treat a persisted network slot and a mount ownership compatibility marker as migration contracts. Keep their metadata entries aligned with the executable order and with downgrade checks.
  • Change both the SeaORM entity model and the migration that creates or alters its table. Check foreign-key delete behavior and indexes as part of the same contract.
  • Change sandbox configuration serialization in both config and active_config migration paths when both columns can contain the old shape.
  • Change snapshot fields together with the on-disk artifact transition journal and its downgrade preflight.
  • Change label storage or the canonical configuration shape together with the full projection rebuild path.
  • Change allocation ownership or cleanup with the intended cascade rules; keep writeback rows independent of run-row deletion when crash recovery needs them.
  • Change SQLite tuning or write routing in the shared pool builder because both the host and runtime depend on that policy.

Important failure modes

TriggerConsequenceGuard
A read-only consumer opens a missing catalogOpen fails and the consumer does not create a competing database fileOnly the write side opens with creation enabled.
Another process holds the SQLite writer lock through the busy timeout and all retriesThe write returns a database error after eight attemptsUse the shared write connection and keep multi-write changes inside its retrying transaction helper.
A migration set has a gap, unknown name, or duplicate rowThe applied state cannot be treated as a valid schema prefixResolve the set against the canonical migration metadata order.
A sandbox config is malformed during a data migrationMigration stops instead of writing an uncertain config shapeParse and validate persisted JSON before accepting the new form.
A label config has a non-string label value during projection rebuildThe rebuild fails; the transaction preserves the prior projectionFix the canonical config before retrying the migration.
A snapshot still needs forward artifact recovery during downgradeDowngrade is refused because the older schema cannot safely describe the artifactComplete artifact reversal until every row is reverse_complete.
A newer root disk kind is present during downgradeThe old release cannot safely start the sandbox and the downgrade failsUse a target-compatible managed root disk or keep the newer schema.
A network slot is retained on a terminal sandboxThe address-pool slot stays occupied and later runs can lose a recyclable slotClear the slot when the sandbox reaches a terminal state.
Mount ownership exists in desired or active config during downgradeAn older binary could load the sandbox while silently dropping ownership policyKeep the compatibility marker until both config forms are free of ownership settings.

Key files

FileWhy to read it
crates/…/mod.rsEntry point for the current database entity model.
crates/…/sandbox.rsCore sandbox identity, desired-versus-active configuration, and lifecycle state.
crates/…/manifest.rsCenter of the image relationship graph.
crates/…/sandbox_rootfs.rsLink between sandbox storage mode and image or host rootfs state.
crates/…/snapshot.rsLocal snapshot index and its file-first relationship to disk artifacts.
crates/…/cpu_allocation.rsParent record for active host CPU reservations.
crates/…/pool.rsShared SQLite pool policy for all processes.
crates/…/connection.rsRead/write pool split and transaction retry boundary.
crates/…/retry.rsSQLite lock classification and backoff policy.
crates/…/lib.rsAuthoritative executable migration order.
crates/…/schema_metadata.rsDowngrade floor, baseline, migration impact, and prefix validation.
crates/…/m20260723_000001_snapshot_artifact_transition.rsMost important snapshot schema and recovery transition.
crates/…/m20260810_000001_rebuild_sandbox_labels.rsExample of rebuilding a derived projection from canonical state.
crates/…/m20260818_000001_sandbox_network_slot.rsCurrent example of persisted, recyclable sandbox resource state and safe re-upgrade behavior.
crates/…/m20260824_000001_mount_owner_config.rsCompatibility boundary for persisted mount ownership in desired and active configuration.