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

Persistent sandbox state

The local persistence system is a SQLite catalog that gives sandboxes a durable identity beyond one process run. It keeps the configuration, execution history, storage links, image metadata, resource promises, labels, snapshots, and maintenance state that the host and runtime need to create, resume, inspect, and clean up sandboxes. It also protects the catalog from other local accounts and can publish verified private copies for backup. See Sandbox lifecycle for the state transitions that use this catalog, Images and snapshots for the image and snapshot flows, Persistence schema and migrations for schema entities and migration evolution, and Persistent storage backup and access for backup and private-storage rules.

Persistence model

The catalog connects product state with host-local state. A sandbox is the central record. Its related records describe what should run, what did run, which storage and image data it uses, and which host resources are reserved for that run.

This diagram shows how the main forms of state relate to one sandbox and its image data.

flowchart TD
    Config[Sandbox configuration] --> Sandbox[Sandbox identity]
    Sandbox --> Run[Run history]
    Sandbox --> Rootfs[Root filesystem choice]
    Sandbox --> Labels[Label projection]
    Run --> Control[Verified runtime control session]
    Rootfs --> Manifest[Image manifest]
    Manifest --> Image[Image references and layers]
    Sandbox --> Volume[Named volumes]
    Run --> Allocation[Resource allocations]
    Allocation --> Host[Host capacity promises]
    Snapshot[Snapshot artifact] -. indexed by .-> SnapshotIndex[Snapshot index]
    Lease[Maintenance state] -. coordinates .-> Sandbox
    Catalog[Catalog file identity] -. guards .-> Control

The catalog is shared by the host command process and the in-VM runtime. This shared view lets the host plan a sandbox and lets the runtime record run and resource state against the same durable identity. crates/…/lib.rs• L1-22

Sandbox identity and run history

The sandbox record stores the stable name, desired configuration, current lifecycle state, and the configuration used by an active VM. Its status shows whether the sandbox is being created or started, running, draining, paused, stopped, or crashed. A separate run record preserves each execution attempt with its process identity, result, timing, and reason for termination. This split lets configuration changes and execution history remain distinct.

References: crates/…/sandbox.rs• L9-93 crates/…/run.rs• L9-124

The desired configuration answers what the next start should use. The active configuration answers what the current VM actually uses. The ephemeral marker gives lifecycle maintenance a direct way to find terminal sandboxes that can be removed without parsing every saved configuration. The sandbox record can also hold the network address-pool slot leased to its current run; inactive rows should not retain that slot.

References: crates/…/sandbox.rs• L48-87 crates/…/m20260621_000001_add_sandbox_ephemeral.rs• L32-67 crates/…/m20260703_000001_add_sandbox_active_config.rs• L25-41

Runtime control sessions

Runtime control sessions provide a safe bridge from SDK operations to the VM selected by a run row. A session is valid only while the catalog file, sandbox run, recorded process identity, and connected peer still identify the same runtime. The process identity includes the process birth marker, so a reused PID does not count as the same runtime. A replacement catalog file also invalidates old sessions before they can send a request.

The local backend shares one verified session for concurrent operations on the same run. It retires dead or changed entries without evicting a live session, and it bounds the number of retained sessions. A delayed lookup for an old run cannot cancel the current run’s session or its in-progress setup. This prevents a stale SDK handle from sending work to a successor VM that reused the same endpoint or process ID.

References: sdk/…/identity.rs• L34-55 sdk/…/identity.rs• L61-178 sdk/…/identity.rs• L180-230 sdk/…/registry.rs• L19-30 sdk/…/registry.rs• L63-181 sdk/…/tests.rs• L382-471 sdk/…/tests.rs• L824-860

Image and rootfs metadata

The image catalog maps an image reference to a content-addressed manifest. Each manifest points to its image configuration and ordered reusable layers. This gives the system one durable place to resolve image names and to share layer data across sandboxes.

References: crates/…/image_ref.rs• L9-52 crates/…/manifest.rs• L9-83 crates/…/config.rs• L9-55 crates/…/layer.rs• L9-60 crates/…/manifest_layer.rs• L9-62

The rootfs record binds one sandbox to its selected root filesystem source. It records whether the source is an image-based filesystem, a host bind, or a disk image. For image-based roots it can pin the manifest, while host-backed roots retain their local source information. Flat rootfs records track reusable merged images and their use state.

References: crates/…/sandbox_rootfs.rs• L11-107 crates/…/flat_rootfs.rs• L11-62 crates/…/m20260410_000001_erofs_image_schema.rs• L368-405 crates/…/m20260710_000001_migrate_root_disk.rs• L40-89

Volumes and snapshot state

Named volumes represent storage that can outlive a sandbox. Their records describe the volume kind, quota or capacity, disk format, file-system type, labels, and timestamps. The local backend pairs this metadata with the volume data on the host.

References: crates/…/volume.rs• L9-40 sdk/…/mod.rs• L1-15 crates/…/m20260606_000001_named_volume_kinds.rs• L46-145

Snapshots use a different trust model. The snapshot artifact on disk is the source of truth. The snapshot index is a rebuildable view for lookup and parent-child bookkeeping. It identifies an artifact by its path and shared digest, then records its stable identity, group, parent, scope, state kind, image identity, storage binding, size, availability, and migration state.

References: crates/…/snapshot.rs• L1-66 sdk/…/store.rs• L23-105 sdk/…/store.rs• L108-220

Snapshot records form a parent graph. A child points to its parent snapshot identity and the index keeps a child count so the system can understand which snapshot state is still in use. The index also distinguishes disk and full scope from file and checkpoint state. This lets the catalog describe different snapshot payloads while keeping the artifact independent of the database.

References: crates/…/snapshot.rs• L17-65 sdk/…/store.rs• L158-218

Resource allocations

Resource allocation records make host capacity promises durable for the life of a run. A CPU allocation belongs to one run and describes the requested and resolved policy. Its child rows map guest vCPUs to host logical CPUs. Memory rows add boot and maximum memory promises for each guest NUMA node. The sandbox record also carries the network address-pool slot leased to its current run.

References: crates/…/cpu_allocation.rs• L9-57 crates/…/cpu_allocation_cpu.rs• L9-48 crates/…/memory_allocation_node.rs• L9-50 crates/…/sandbox.rs• L74-84

Writeback allocation records represent membership in a host-wide dirty-data budget. They keep enough host identity and lease data for recovery after a runtime crash. They do not depend on the run row, so cleanup of run history cannot hide a stale host reservation before recovery sees it.

References: crates/…/writeback_allocation.rs• L9-47 crates/…/m20260803_000001_create_writeback_allocations.rs• L30-109

Labels and maintenance state

Sandbox labels are stored as key and value pairs for fast selection and metrics attribution. The sandbox configuration remains the canonical source for those labels. The separate label rows are a query projection, so a rebuild can repair missing or stale rows without changing the user-facing configuration.

References: crates/…/sandbox_label.rs• L9-48 crates/…/m20260531_000001_create_sandbox_labels.rs• L33-78 crates/…/m20260810_000001_rebuild_sandbox_labels.rs• L1-91

Maintenance state coordinates work that can be attempted by many sandbox starts. Named lease rows record the holder, expiry, and last successful completion. The lifecycle sweep uses this state to avoid duplicate scans, while the install lease prevents schema and artifact changes from racing with another install operation.

References: crates/…/maintenance_lease.rs• L1-59 crates/…/maintenance.rs• L1-19 crates/…/maintenance.rs• L652-678 sdk/…/mod.rs• L665-710

Catalog lifecycle

The catalog lifecycle has two linked concerns: safe access to one local database and repair of durable state that spans the database and the file system. Startup opens the catalog, checks that its migration history is known, upgrades a recognized older catalog in one transaction, and reconciles managed snapshot artifacts before normal local work continues. Running VMs remain active while the catalog representation changes. References: sdk/…/database.rs• L35-104, sdk/…/database.rs• L164-203, sdk/…/mod.rs• L665-712, sdk/…/migration.rs• L95-178

Shared database access

The host and runtime use one SQLite file through a shared connection policy. The read pool supports concurrent WAL reads, while each process sends its writes through one connection so local writers queue before they reach SQLite. Every connection enables WAL, foreign keys, and normal synchronous writes. Busy timeouts and application retries absorb lock conflicts with the other process, and multi-record changes use a retried transaction so related state commits or rolls back as one unit.

The write pool opens before the read pool so WAL is established before readers connect. Pool setup retries transient SQLite lock errors within the connection deadline, and a failed setup does not create a catalog for read-only consumers. crates/…/connection.rs• L1-45, crates/…/connection.rs• L104-161, crates/…/pool.rs• L23-115, crates/…/retry.rs• L11-113

References: crates/…/connection.rs• L1-45 crates/…/connection.rs• L104-161 crates/…/pool.rs• L23-115 crates/…/retry.rs• L11-113 sdk/…/identity.rs• L46-55 sdk/…/database_tests.rs• L87-148

Read consumers do not create a missing catalog or change its journal mode. They can inspect an existing catalog without taking ownership of it, and they tighten legacy catalog and journal-file permissions when needed. A secure read-only catalog is inspected without changing its permissions. The write connection is the path that can create the database and apply durable changes. The pool hardens the catalog and its SQLite sidecars after it connects.

References: crates/…/connection.rs• L47-100 crates/…/connection.rs• L244-335 crates/…/pool.rs• L68-115 crates/…/storage.rs• L36-72

Private catalog storage

Private catalog storage keeps the database, SQLite sidecars, and backup files readable only by the owning account. Before SQLite sees a path, the storage boundary checks ownership, rejects unsafe path ancestors, and creates new files privately. It repairs permissions only inside the catalog’s known namespace, so shared or unrelated files are not changed. Read-only consumers can use an existing secure catalog without creating it or changing its permissions.

On macOS, file mode checks are not enough because ACLs can grant access outside those modes. The storage boundary removes unsafe ACL grants from owned catalog storage, preserves harmless owner and deny rules, and refuses ancestor ACLs that could let another account mutate the path.

References: crates/…/storage.rs• L16-72 crates/…/storage.rs• L80-123 crates/…/storage.rs• L126-207 crates/…/storage.rs• L213-245 crates/…/macos_acl.rs• L119-173 crates/…/tests.rs• L25-106 crates/…/macos_acl_tests.rs• L162-224

Verified private backups

Backups are published only after SQLite creates a complete copy and a read-only quick_check confirms that the copy is valid and non-empty. The copy is first written to an exclusive private staging file. Publication does not replace an existing backup, so an interrupted or failed copy cannot appear as the current backup. The file and its parent are synced after publication so the completed name survives a host restart.

The staging file stays private while SQLite writes sensitive data. If the process stops during the copy, the completed backup name remains absent and a later attempt can create a new copy. The destination is protected from replacement and symlink substitution by the private storage boundary. Validation opens the copy read-only and does not create files or change the catalog’s journal mode.

References: crates/…/backup.rs• L1-93 crates/…/backup_tests.rs• L33-134 crates/…/backup_tests.rs• L154-195 crates/…/backup_tests.rs• L247-330

Schema-aware catalog access

Some SDK processes can run while an older or newer CLI changes the shared catalog. The catalog helpers inspect table and column presence at query time, then select only fields that exist and supply safe defaults for fields introduced later. They do not migrate the schema, so schema ownership remains with the migration process.

References: crates/…/catalog.rs• L1-12 crates/…/catalog.rs• L18-112

This boundary lets older readers continue to load sandbox and rootfs records during a rolling upgrade. Runtime-only fields are cleared only when the owning schema contains them, which avoids writing an older process’s assumptions into a newer catalog.

References: crates/…/catalog.rs• L49-87 crates/…/catalog.rs• L124-170

Startup reconciliation

Startup reconciliation keeps database projections and snapshot artifacts aligned. It discovers indexed and visible artifacts, converts legacy descriptors when needed, records blocked work, and publishes the canonical index only after the artifact checks pass. A separate lease protects this install-time state from concurrent mutation.

References: sdk/…/mod.rs• L694-710 sdk/…/migration.rs• L185-274 sdk/…/migration.rs• L729-849

Schema evolution

Schema evolution is an ordered history of changes to both tables and persisted data. The migration system starts with image, sandbox, run, and storage records. Later changes add rootfs modes, snapshots, labels, leases, active configuration, and resource allocation state. Read Persistence schema and migrations for the entity relationships, full migration order, downgrade rules, and connection policy.

Data shape transitions

Some releases only add records. Others rewrite saved configuration or rebuild a projection. OCI, bind, and root-disk changes update both desired and active configuration where both forms exist. Snapshot changes add scope and recovery state. Label repair rebuilds all label rows from the canonical sandbox configuration in one transaction.

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 crates/…/m20260810_000001_rebuild_sandbox_labels.rs• L31-91

Compatibility boundaries

Migration history is append-only and has an explicit supported floor. A downgrade is safe only when the newer state can be represented by the target release. Snapshot artifacts may need reverse conversion first. Newer root-disk kinds can block a downgrade because an older runtime would interpret them incorrectly. The catalog also refuses an unknown or gapped migration history instead of treating an equal migration count as current.

References: crates/…/lib.rs• L40-75 crates/…/schema_metadata.rs• L14-18 crates/…/schema_metadata.rs• L71-117 crates/…/schema_metadata.rs• L193-258 sdk/…/database.rs• L111-161

Change checklist

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

  • Change a persisted sandbox configuration shape in both the desired and active configuration paths.
  • Change sandbox lifecycle states together with the rules that classify active runtime state and release network slots.
  • Change a canonical label field together with the label projection and its rebuild behavior.
  • Change snapshot metadata together with the on-disk artifact format, index projection, and recovery journal.
  • Change resource ownership with the cleanup and crash-recovery rules for its allocation rows.
  • Add each schema change to both the executable migration order and its downgrade metadata.
  • Change database access policy in the shared pool and connection layer because the host and runtime use the same file.
  • Keep the single-writer pool, WAL setup order, busy timeout, and retry policy aligned when changing shared database access.
  • Add or remove shared columns together with schema-aware catalog queries and their defaults for older processes.
  • Change run identity or control endpoints together with process birth checks, catalog-file identity checks, session invalidation, and replacement-run behavior.
  • Change control-session capacity or replacement rules together with the guarantee that valid current sessions are not evicted by delayed old-run lookups.
  • Change catalog upgrade rules together with migration-history checks, the install lease, and the transaction that fences other writers.
  • Change catalog or backup paths together with ownership checks, sidecar permissions, ACL handling, staging names, and no-replace publication.

Important failure modes

TriggerConsequenceGuard
Desired and active configuration use different data shapesA running sandbox or its next start can be read with the wrong rootfs or policyMigrate both configuration forms when both columns exist.
An inactive sandbox retains its network slotAddress-pool capacity remains falsely leased to a sandbox that no longer runsRelease slots when a sandbox becomes inactive and let maintenance repair stale leases.
Snapshot index data is treated as the artifact source of truthA stale row can hide a changed or missing snapshot artifactValidate the artifact and rebuild or upsert the index from it.
A label projection is rebuilt while one saved configuration is invalidValid label rows can be lost or the projection can become partialParse all configurations before replacing rows and use one transaction.
A reader assumes a column exists during a rolling catalog upgradeAn older or newer process cannot load the sandbox or rootfs rowUse schema-aware catalog queries and defaults instead of a fixed column set.
A runtime dies while holding a resource or maintenance leaseLater work can see capacity as busy or skip needed cleanupStore expiry and host identity so stale state can be reclaimed safely.
A PID, runtime endpoint, or catalog path is reused after a run or file replacementAn SDK operation can target a successor runtime or an unrelated databaseVerify the run row, process birth identity, connected peer, and catalog file identity before dispatch.
A delayed lookup for an old run arrives while the current run is activeThe old caller can cancel the current session or consume its setup capacityCompare complete runtime keys and invalidate only the verified old entry.
A migration is applied out of order or a downgrade crosses an unsupported data shapeThe catalog or user data cannot be read by the target releaseRequire a complete migration prefix and block unrepresentable reverse changes.
A catalog has an unknown history with the expected number of rowsA writer can apply changes to a schema it does not understandCompare migration identities, not only migration counts.
Concurrent processes exhaust SQLite busy retries or the connection deadlineThe catalog write or pool setup fails and the related durable state is not committedUse the shared write path, its transaction boundary, and the bounded retry policy.
Catalog storage is owned by another account or has an unsafe path ancestorThe process can expose private state or alter an unrelated fileRequire a trusted owner, private boundary, and safe ancestor chain before SQLite opens the file.
A backup is interrupted before validation and publicationA partial or invalid copy can be mistaken for a usable backupKeep the copy under a private staging name and publish only after validation without replacement.
An unsafe macOS ACL grants access through a catalog directory or ancestorAnother account can read the catalog or replace a path componentClear unsafe owned-directory ACLs and reject mutation-granting ancestor ACLs.

Key files

FileWhy to read it
crates/…/mod.rsStarting point for the current persistence model.
crates/…/sandbox.rsStable sandbox identity, lifecycle state, desired-versus-active state, and network slot.
crates/…/run.rsDurable execution history and termination state.
crates/…/manifest.rsCenter of image and layer metadata.
crates/…/sandbox_rootfs.rsLink between a sandbox and its root filesystem source.
crates/…/volume.rsNamed storage metadata.
crates/…/snapshot.rsRebuildable snapshot index, stable identities, artifact scope, and migration status.
crates/…/cpu_allocation.rsParent record for active CPU and memory promises.
crates/…/writeback_allocation.rsCrash-recoverable host writeback state.
crates/…/sandbox_label.rsQuery projection for sandbox labels.
crates/…/maintenance_lease.rsCoordination state for cleanup and installation.
crates/…/catalog.rsSchema-aware reads that bridge supported catalog shapes.
crates/…/connection.rsTyped read and write access, transaction boundaries, and busy handling.
crates/…/pool.rsShared SQLite access policy, WAL setup, and private-file setup.
crates/…/retry.rsSQLite lock classification and bounded retry behavior.
crates/…/storage.rsCatalog ownership, path safety, permissions, sidecars, and legacy repair.
crates/…/macos_acl.rsmacOS ACL checks for private catalog access.
crates/…/backup.rsVerified private backup creation, validation, and publication.
sdk/…/database.rsCatalog readiness checks, upgrade fencing, migration transactions, and lease recovery.
sdk/…/identity.rsOS identity checks that bind cached control sessions to one process and one catalog file.
sdk/…/owner.rsLink between persisted run identity and a verified runtime peer.
sdk/…/registry.rsShared runtime-session lifetime, replacement handling, delayed-lookup protection, and capacity.
sdk/…/session.rsRequest validity and invalidation for a selected run.
sdk/…/database_tests.rsCross-process catalog durability and lock-ownership guarantees.
sdk/…/tests.rsGuarantees for replacement detection, session safety, and atomic active-state updates.
sdk/…/mod.rsCatalog startup and migration boundary.
sdk/…/migration.rsSnapshot artifact reconciliation and recovery journal.
crates/…/lib.rsAuthoritative migration order.
crates/…/schema_metadata.rsCompatibility and downgrade rules.