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 / metrics-collection-and-delivery

Metrics collection and delivery

The metrics collector is a host-local service that reads live sandbox measurements from shared memory and delivers them to an observability system. It keeps metric sampling separate from the runtime, adds optional sandbox labels, and sends each exporter its own bounded stream so a slow or broken destination does not stop collection for the other destinations. See the parent page, Observability and metrics, for the wider observability model.

Collector lifecycle

The collector has a build stage and a running stage. Configuration is checked before start, then one driver loop reads collections while one worker handles each registered exporter.

The main lifecycle is:

  1. Resolve the host home directory and the readable registry names.
  2. Build an exporter and set the collection and delivery rules.
  3. Start the collector and read the registries at the collection interval.
  4. Buffer collections per exporter and flush them on schedule or on demand.
  5. On shutdown, flush pending data and close each exporter.

This diagram shows the path from sandbox sampling to an external metrics backend.

flowchart LR
    R[Sandbox runtime] -->|writes samples| S[(Shared-memory registry)]
    S --> C[Collector reader]
    C --> L[Optional catalog labels]
    L --> D[Collector driver]
    D --> W1[Exporter worker]
    D --> W2[Exporter worker]
    W1 --> O[OTLP backend]
    W2 --> T[Stdout or custom sink]

The collector uses one worker per exporter. Each worker has its own queue, schedule, timeout, and failure state. This split makes delivery policy local to the destination while the reader continues to produce a common collection.

Runtime sampling

The runtime owns the write side of the metrics path. It reserves a registry slot for a sandbox, activates the slot when the runtime is ready, and starts a background sampler that writes CPU, memory, storage, network, uptime, and writable filesystem values. The sampler stops when the slot is reclaimed, so a stale writer cannot publish into a later sandbox run.

The registry avoids a database write for every sample. Lifecycle data still uses the catalog, but the high-rate measurement path uses the shared-memory slot instead. The collector therefore reads a current snapshot without making a request to each sandbox. A memory limit is set at reservation time and can be refreshed by later samples when the runtime reports a live value.

References: crates/…/metrics.rs• L1-6 crates/…/metrics.rs• L97-197 crates/…/vm.rs• L1311-1333 crates/…/registry.rs• L54-120 crates/…/registry.rs• L821-918

Collector control

The collector exposes a running handle with two control actions. flush asks all workers to try an export without waiting for completion. shutdown stops new reads, drains workers, and returns the first worker or driver error.

The data path is intentionally lossy under pressure. A worker drops its oldest queued collections when its limit is reached and carries the drop count into the next export batch. This bounds memory use and makes loss visible to exporters instead of allowing an outage to grow without limit.

References: crates/…/driver.rs• L47-69 crates/…/driver.rs• L135-218 crates/…/worker.rs• L86-127 crates/…/worker.rs• L176-215

Collector configuration

Configuration has two scopes. Collection settings apply to the shared read loop. Export settings apply to each destination and can use builder defaults or an explicit per-exporter override.

SettingPurposeDefault
Collection intervalControls how often the registry is read.1s
Flush intervalControls scheduled delivery for one exporter.10s
Buffer limitSets the number of collections held for one exporter.60
Export timeoutBounds one exporter call.30s
Maximum sample ageStops emitting a snapshot that has not been refreshed.30s

The builder rejects zero intervals, zero timeouts, and a zero buffer limit. A custom exporter configuration overrides the builder defaults for that exporter only. Label enrichment and the stale-sample filter are applied to the collection function before the driver starts.

The msb-metrics binary takes the same settings for both otel and stdout. It resolves --msb-home first, then $MSB_HOME, then ~/.microsandbox. The resolved home determines both the shared-memory registry names and the catalog path used for labels.

References: crates/…/builder.rs• L16-33 crates/…/builder.rs• L39-61 crates/…/builder.rs• L127-169 crates/…/builder.rs• L236-283 crates/…/main.rs• L120-166 crates/…/main.rs• L356-402

Registry readers

The reader opens each configured shared-memory registry on every collection tick and takes its active snapshot. A missing registry means that no sandbox is using that registry yet, so the tick continues with an empty result. The reader converts registry records into a common MetricsCollection containing a timestamp, sandbox snapshots, and optional labels.

The registry gives the reader a coherent view of each slot. A writer publishes a sample through a sequence check, and the reader retries when a write or slot reuse overlaps its read. The reader also checks the owner process when it sees an active slot. A dead owner is treated as stale, which prevents a crashed runtime from appearing live forever.

File snapshots

On Unix, the registry can also copy a one-slot file into independent memory before the reader inspects it. The copy checks the source size, waits for a coherent sequence, validates the current layout, and then stays safe if the source file is truncated or replaced. This is a separate file-backed read path; named registries and their older ABI support keep their existing behavior.

The file path accepts only a ready current-ABI registry. It rejects malformed, incomplete, or busy sources instead of returning a partial measurement. The copied registry remains local to the reader, so later reads or lifecycle actions do not change the source file.

References: crates/…/registry.rs• L390-469

Snapshot identity

The collector identifies one sandbox run by the pair (sandbox_id, run_id). When the same run appears in more than one readable registry, the snapshot from the higher ABI version replaces the older one. The final list is sorted by sandbox identity and name so delivery order is stable.

A snapshot carries both identity and measurements. Identity includes the sandbox name, catalog ID, run ID, and runtime process ID. Measurements include CPU use, memory, cumulative disk and network bytes, uptime, and optional writable filesystem values. The memory limit starts with the boot value and can carry a later live update; the snapshot also records whether memory and the limit were reported by the current sample. The registry exposes its slot allocation generation and creation times for local consumers that must verify that a cached slot still belongs to the same run.

References: crates/…/reader.rs• L32-75 crates/…/reader.rs• L79-107 crates/…/snapshot.rs• L19-67 crates/…/snapshot.rs• L104-149 crates/…/registry.rs• L128-145 crates/…/registry.rs• L501-567 crates/…/registry.rs• L779-815

Stale sample filtering

The collector can omit a sandbox when its newest sample is older than the configured maximum age. This handles a runtime that stopped before it released its slot. The filter only stops emission; it does not reclaim the slot. A live sandbox whose sampler pauses can return when fresh samples resume, while slot ownership remains the job of the registry and runtime lifecycle paths.

The runtime also marks optional writable filesystem values absent when their own source sample is too old. This keeps old storage values from looking current while other measurements continue to flow.

References: crates/…/reader.rs• L135-175 crates/…/builder.rs• L25-30 crates/…/metrics.rs• L306-345

Compatibility handling

Registry data has an ABI version because the shared-memory layout is a cross-process contract. The current reader can read the current layout and a supported older layout through a read-only compatibility path. The compatibility reader cannot reserve, activate, release, or write slots in the legacy registry.

At startup, msb-metrics derives one registry name for each readable ABI version. A missing legacy registry is ignored. An unreadable legacy registry is skipped with a warning, while an error from the current registry stops the collection tick. If the same sandbox run is present in both versions, the merge rule keeps the newer ABI snapshot.

Older layouts do not provide fields that were added later. The reader maps those fields to absent values instead of guessing them. This lets old runtimes continue to contribute the measurements they know how to publish without changing the meaning of newer fields.

References: crates/…/compatibility.rs• L22-38 crates/…/compatibility.rs• L104-127 crates/…/compatibility.rs• L239-275 crates/…/reader.rs• L42-68 crates/…/main.rs• L365-380

Label integration

Labels are optional enrichment from the catalog. After the reader has a set of sandbox IDs, the label source looks up the effective configuration for those sandboxes and attaches the resulting key-value pairs to the collection. The active configuration wins over the desired configuration because it describes the running VM.

Catalog access is lazy and recoverable. If the database does not exist or a query fails, the collector emits the measurements without labels and retries on the next tick. A small cache avoids parsing unchanged configurations again. Operators can disable all labels or exclude selected keys at emission time to control series cardinality without removing metadata from the catalog.

Labels are attached to each sandbox datapoint rather than to the shared OTel resource. The resource describes the collector process and host; datapoint attributes describe the sandbox. This separation prevents one sandbox's labels from leaking into another sandbox's series.

References: crates/…/label_source.rs• L41-71 crates/…/label_source.rs• L113-172 crates/…/label_source.rs• L179-226 crates/…/otel.rs• L774-804

Export drivers

The driver broadcasts each successful collection to all exporter workers. Each worker drains its own queue into a MetricsExportBatch, then calls its exporter on a schedule or after an explicit flush. A failed export restores the batch and retries later with capped exponential backoff. Scheduled retries pause during backoff, but an explicit flush can force an immediate retry.

The default error policy logs scheduled export failures and keeps collection running. A final flush and exporter shutdown still run during an orderly stop. The driver reports worker failures after it has drained all workers, so one failed destination does not prevent other destinations from receiving their pending data.

References: crates/…/driver.rs• L144-218 crates/…/worker.rs• L121-174 crates/…/worker.rs• L218-256 crates/…/types.rs• L36-59

OTLP delivery

The OTLP exporter turns each sandbox snapshot into observable gauges and sends the result to an OpenTelemetry-compatible endpoint. It supports gRPC and HTTP Protobuf transport. gRPC also supports gzip and an additional PEM CA certificate; incompatible combinations are rejected before the exporter starts.

The exporter uses cumulative byte values as gauges. A downstream rate query can calculate throughput from successive values, while a sandbox restart naturally begins a new cumulative sequence. Default resource attributes identify the service and host. Sandbox name and sandbox ID identify each datapoint; run ID and process ID are opt-in because they create new series after restarts.

The exporter sends its own health measurements through the same OTLP path. Successful exports, failed exports, dropped collections, and the latest successful export time show whether the collector is reading and delivering data.

References: crates/…/otel.rs• L1-41 crates/…/otel.rs• L87-109 crates/…/otel.rs• L259-380 crates/…/otel.rs• L388-439 crates/…/otel.rs• L446-525 crates/…/otel.rs• L578-605

Stdout delivery

The stdout exporter is a local inspection path. It writes one human-readable line for each sandbox snapshot and marks empty collections explicitly. It is useful for checking that the registry is populated without an OTLP receiver, but its output is not a stable machine contract.

References: crates/…/stdout.rs• L1-17 crates/…/stdout.rs• L36-63 crates/…/stdout.rs• L69-116

Runtime and registry integration

The runtime and collector share a host-local registry rather than a request path. During sandbox startup, the host reserves a slot and passes its identity to the runtime. The runtime activates the reservation after the guest is ready, then samples into the slot. The collector opens the registry as a reader and never needs to contact the sandbox process.

Each slot has an allocation generation that changes when ownership changes. Writers and release paths check that generation, so a late sampler cannot write into a slot reused by a later sandbox. Identity-aware readers can also verify the slot, registry creation, generation, and activation times before trusting a cached match.

The registry preserves stale samples when a run ends in a way that requires later inspection, but it prefers active ownership for lookups and can match a sandbox by run ID or by sandbox ID and name. This prevents a stale slot from being mistaken for a new sandbox after catalog ID reuse.

The registry is owner-readable on Unix. The collector must run as the same user and use the same home directory as the runtime. One collector is expected per host because each registry represents that host's sandboxes.

This boundary reduces catalog load and keeps the collection rate independent of sandbox RPC availability. It also means that registry permissions, registry names, ABI compatibility, slot generations, and slot lifecycle are part of the delivery contract.

References: crates/…/registry.rs• L119-153 crates/…/registry.rs• L229-355 crates/…/registry.rs• L358-499 crates/…/registry.rs• L501-673 crates/…/registry.rs• L702-818 crates/…/registry.rs• L821-933 crates/…/main.rs• L1-11 crates/…/main.rs• L365-380

Change checklist

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

  • When the shared-memory slot layout or ABI changes, update the current reader, every supported legacy reader, the readable ABI list, and snapshot field mapping together.
  • When a metric field changes, align runtime sampling, registry flags, snapshot conversion, OTLP instruments, and any custom exporter contract.
  • When sandbox identity changes, review registry merge keys, catalog label lookup keys, and the default OTLP attributes together.
  • When slot reuse or lookup identity changes, preserve generation checks and update cached-match validation for slot, registry, activation, and catalog identity.
  • When collection or buffer rules change, keep the drop count and collector health measurements consistent with worker behavior.
  • When MSB_HOME or registry naming changes, update runtime creation, collector discovery, catalog label lookup, and same-user deployment guidance together.
  • When OTLP transport options change, preserve the validation rules for protocol, compression, TLS, headers, and endpoint shape.
  • When memory reporting changes, keep the boot limit, live limit flag, reported memory state, snapshot mapping, compatibility defaults, and exporter meaning aligned.
  • When a file-backed registry source changes, preserve its one-slot size check, coherent copy check, current-ABI validation, and independent-memory guarantee.

Important failure modes

TriggerConsequenceGuard
Collector runs under a different user or home directoryIt cannot open the runtime's owner-only registry or reads no sandboxes.Use the same Unix user and resolve the same MSB_HOME for both processes.
Registry is missingThe current tick produces no sandbox snapshots.Missing registries are treated as empty and checked again on the next tick.
Registry ABI is unsupported or malformedThat registry is skipped or the current collection fails.Header validation and explicit readable ABI versions prevent unsafe layout reads.
File-backed registry is truncated, malformed, or being writtenNo independent snapshot is returned from that file.Require the exact one-slot size, compare sequence bytes before and after the copy, and validate a ready current layout.
Runtime dies before releasing its slotA frozen sample could be emitted as live data.Dead-owner demotion and maximum sample age stop continued emission.
A slot is reused while a late writer or cached lookup still refers to its old ownerA stale writer could corrupt the new sample or a cached lookup could select the wrong run.Generation checks protect writes, and identity checks validate slot, registry, activation, and catalog identity.
Exporter is slower than collectionIts queue drops old collections when full.Per-exporter caps bound memory and report the drop count.
Backend export fails or times outThe batch remains pending and scheduled retries back off.Failed batches are restored, export calls have timeouts, and health metrics record failure.
Catalog is absent or unavailableMetrics continue without sandbox labels.Label lookup is best-effort and retries on later ticks.
HTTP OTLP is combined with gzip or a custom CAExporter construction fails before collection starts.Protocol-specific configuration validation rejects unsupported combinations.
A runtime changes its memory limit but the sample does not report the new limitThe collector continues to show the last known limit.Treat the live-limit marker as the authority for whether the current sample refreshed the limit.

Key files

FileWhy to read it
crates/…/main.rsShows the msb-metrics commands, operator settings, home and registry discovery, and shutdown flow.
crates/…/builder.rsDefines collector-wide and per-exporter configuration and validation.
crates/…/driver.rsExplains the collector lifecycle, collection loop, exporter fan-out, and shutdown result handling.
crates/…/reader.rsShows registry reads, ABI merge behavior, label enrichment, and stale-sample filtering.
crates/…/worker.rsShows buffering, scheduled and forced flushes, retries, drop accounting, and final delivery.
crates/…/label_source.rsShows catalog-backed label lookup, cache use, exclusions, and degraded operation.
crates/…/otel.rsDefines OTLP transport, metric identity, sandbox gauges, and collector health measurements.
crates/…/registry.rsDefines the shared-memory registry contract, file-backed snapshot reads, slot ownership and generations, live memory-limit updates, identity-aware lookup, coherent reads, and stale-owner handling.
crates/…/compatibility.rsDefines read-only support for the older registry ABI.
crates/…/metrics.rsShows how runtime measurements are sampled and published into registry slots.