Observability and metrics
Microsandbox provides local operational metrics for each sandbox and for the metrics pipeline itself. A runtime samples resource use, a host-local registry holds the latest coherent sample, and readers expose that data to applications, the CLI, or an external observability system. For the timing, buffering, retry, and transport rules, see Metrics collection and delivery. The metrics describe runtime state during the sandbox lifecycle and support diagnosis of runtime execution.
Metrics lifecycle
The metrics path moves data from the sandbox runtime to one or more diagnostic views. All views use the same latest-sample data, so an application read and a continuous export describe the same runtime state.
This diagram shows how runtime observations become local reports or external telemetry.
flowchart LR
R[Sandbox runtime] --> S[Periodic resource sample]
S --> G[Host-local metrics registry]
G --> A[SDK snapshot and stream]
G --> C[CLI reports]
G --> K[Metrics collector]
K --> E[Exporter]
E --> O[Observability backend]
Runtime sampling
The runtime runs a background sampler for each sandbox. It writes an initial sample and then repeats at the configured interval without writing to the catalog database on the sample path. The sample combines VMM, guest, network, and writable filesystem signals.
CPU use comes from guest vCPU time over the measured wall-time window. The sampler rejects a window when the counter and clock reads were badly delayed, keeps the last trusted CPU value, and caps the result at the sandbox's vCPU ceiling. Live memory state can refresh the memory limit and the used-memory value. Guest memory reports are accepted only when they are complete and fresh against the host-wide monotonic receipt clock; an unavailable report does not become zero. Protected writable filesystem values are omitted when their source is missing or too old.
References: crates/…/metrics.rs• L27-37 crates/…/metrics.rs• L99-201 crates/…/metrics.rs• L246-307 crates/…/metrics.rs• L342-410 crates/…/guest_memory.rs• L9-49
Shared metrics registry
The host-local metrics registry is the shared handoff between runtime writers and readers. Each sandbox run owns one slot with identity data, sample time, lifecycle state, and resource values. The registry holds the latest sample instead of creating a database write for every interval.
The registry publishes a sample only when its fields form one coherent view. Slot generations protect a new sandbox from an old writer. A released or dead-owner slot can retain its final sample for diagnosis, while readers can demote a dead active slot to that terminal state.
The registry has a versioned layout. Writers use the current layout, while a read-only compatibility path can read the supported older layout without changing it. The current layout carries optional network policy counters and guest-memory receipt and lifecycle data. Older layouts do not gain fields that they did not store, so those values remain unavailable until a newer runtime publishes them. A bounded file-backed registry snapshot provides an isolated diagnostic view when a one-slot registry is supplied as a file; it validates a coherent copy before readers use it.
References: crates/…/lib.rs• L21-30 crates/…/layout.rs• L90-108 crates/…/layout.rs• L140-185 crates/…/layout.rs• L218-323 crates/…/registry.rs• L129-192 crates/…/registry.rs• L390-468 crates/…/registry.rs• L581-645 crates/…/registry.rs• L717-739 crates/…/registry.rs• L782-952 crates/…/compatibility.rs• L29-40 crates/…/compatibility.rs• L105-127
Collection and enrichment
The collector reads active samples on a regular schedule and groups them into one collection for all sandboxes. When more than one registry version is present, it keeps the newest view of the same sandbox run. It can also join catalog labels to each sandbox so downstream views can group data by user or tenant.
The collector treats labels as extra context rather than a requirement for metrics. If label lookup fails, the resource sample still moves forward without labels. It also stops exporting a sample that is older than the allowed age, which prevents a stopped sampler from producing a frozen value forever.
References: crates/…/reader.rs• L32-75 crates/…/reader.rs• L79-106 crates/…/reader.rs• L109-175 crates/…/builder.rs• L16-33
Collection delivery
The collector sends each collection to separate exporter workers. Each worker has its own bounded buffer and export schedule, so one slow destination does not block the other destinations. A full buffer drops the oldest collections and carries the drop count to the exporter.
An explicit flush asks all workers to export at once. Shutdown closes the collection path, gives each worker one final export, and then closes exporter-owned resources. A failed export is retried with backoff while the collector continues to collect new samples.
References: crates/…/driver.rs• L135-218 crates/…/worker.rs• L65-127 crates/…/worker.rs• L176-257 crates/…/types.rs• L21-59
Metric model
The metric model separates a sample's identity from its resource values. This lets a reader match data to a sandbox while allowing an exporter to choose which identity fields become labels.
Resource values
Each sandbox sample describes current or cumulative use. CPU use, memory use, memory limits, and uptime describe the current state. Disk, network traffic, and network policy counters are cumulative totals since the run began. Memory limits can start from the boot allocation and later reflect live VM memory state. Guest-reported total and available memory are present only while the complete report is valid and fresh. Optional memory, residency, network policy, and writable filesystem values appear only when their source reports a valid value.
The main resource groups are:
- CPU utilization and cumulative vCPU time.
- Used, available, resident, and limited memory.
- Fresh guest-reported usable memory total.
- Cumulative disk bytes read and written.
- Cumulative network bytes received and sent.
- Cumulative network admission and session-cap events.
- Guest-visible and host-allocated writable filesystem space.
- Sample time and sandbox uptime.
References: crates/…/snapshot.rs• L19-85 crates/…/snapshot.rs• L88-136 crates/…/layout.rs• L239-290 crates/…/guest_memory.rs• L30-49
Identity and labels
Every snapshot carries sandbox name, sandbox ID, run ID, and runtime process ID. These fields make it possible to distinguish a restart from the earlier run and to reject a stale slot after sandbox deletion and ID reuse.
Registry identity-aware reads add the slot number, allocation generation, registry creation time, and runtime activation time to a coherent metric. These values support cache validation without changing the shared metric layout. External metric points use sandbox name and sandbox ID by default. Run ID and process ID are opt-in because they create a new time series after each restart. Catalog labels are added as per-sandbox data point attributes rather than shared service attributes, so one sandbox's labels do not affect another sandbox's series.
References: crates/…/snapshot.rs• L19-40 crates/…/registry.rs• L148-162 crates/…/registry.rs• L626-645 crates/…/registry.rs• L717-739 crates/…/otel.rs• L33-41 crates/…/otel.rs• L111-132 crates/…/otel.rs• L774-804
Sample states
Metrics consumers must distinguish a live sample from a preserved terminal sample. An active sample belongs to a runtime that still owns its slot. A stale sample is retained for diagnosis after release or owner death and is not a current reading.
The Rust report view adds a stalled state when a runtime is still alive but has not produced a fresh sample within its sampling window. This state helps operators separate a quiet sampler from a sandbox that exited.
| State | Meaning | Typical use |
|---|---|---|
Active or Running | The runtime owns the slot and the sample is current. | Live dashboards and exports |
Stale or Exited | The runtime ended and the last sample remains available. | Post-exit diagnosis |
Stalled | The runtime is alive but the sample is too old. | Sampler or host health diagnosis |
References: crates/…/snapshot.rs• L9-17 sdk/…/metrics.rs• L74-109 sdk/…/metrics.rs• L485-507
Exposure surfaces
Microsandbox exposes the same local metric state through three main paths. The SDK is for application logic, the CLI is for human and script use, and the collector is for long-term storage and alerting.
SDK reads and streams
SDK calls return a point-in-time SandboxMetrics value or a stream of values at a requested interval. Fleet reads return the latest value for each running sandbox. These APIs are local-backend features because they read the host-local registry; cloud routes report that the operation is not supported.
The SDK values include nullable fields for data that a kernel, filesystem, network policy, or runtime source may not provide. Guest-derived memory values also carry their original receipt and lifecycle validity, so callers can treat an expired or invalid report as unavailable data rather than zero use.
References: sdk/…/metrics.rs• L39-72 sdk/…/metrics.rs• L115-141 sdk/…/metrics.rs• L233-260 sdk/…/metrics.ts• L1-18 sdk/…/metrics-stream.ts• L7-37 crates/…/snapshot.rs• L157-177
CLI reports
The msb metrics command reads local reports for one sandbox or for the fleet. It can show a table, print JSON, refresh a terminal view, or emit JSON Lines for a stream consumer. Reports join samples with active catalog configuration so resource denominators reflect accepted live changes.
The CLI derives disk and network rates from two samples. It keys the rate window by run ID, so a sandbox restart starts a new window instead of producing a false negative delta. Exited rows show totals rather than live rates, and stalled rows show that fresh samples are missing.
References: crates/…/metrics.rs• L1-9 crates/…/metrics.rs• L41-70 crates/…/metrics.rs• L107-154 crates/…/metrics.rs• L265-355 crates/…/metrics.rs• L494-531
Continuous export
The separate msb-metrics collector reads the registry on each collection tick and sends metric points through registered exporters. The OTLP exporter publishes sandbox gauges and collector health metrics to an OpenTelemetry-compatible backend. A stdout exporter provides a human-readable local view for diagnosis and is not a stable machine interface.
The OTLP names use the microsandbox.* namespace. Cumulative disk, network, and network policy values remain gauges with their absolute totals, so a backend can calculate change from successive samples. The exporter also publishes success, failure, dropped-collection, and last-success signals for the health of the delivery path.
See Metrics collection and delivery for exporter configuration and delivery behavior.
References: crates/…/otel.rs• L1-24 crates/…/otel.rs• L154-182 crates/…/otel.rs• L388-437 crates/…/otel.rs• L578-769 crates/…/stdout.rs• L1-18
Operational contracts
The metric path favors a current, coherent view over an unbounded history. Operators must read sample age, run identity, and collector health together when they assess whether a value is useful.
Cumulative counters
Disk and network values are absolute totals for one sandbox run. A restart begins a new run and resets those totals. Consumers that need a per-second rate must compare samples from the same run and handle the run boundary as a reset.
References: crates/…/otel.rs• L18-24 crates/…/metrics.rs• L91-101 crates/…/metrics.rs• L494-531
Guest memory freshness
Guest-derived memory values are tied to the original host receipt of a guest report. Collector buffering, export retries, and repeated publication do not renew that receipt. When the report expires or the lifecycle changes, readers remove the guest-derived values while retaining independent metrics. A buffered snapshot can also check that its report still belongs to the same active slot allocation; invalidation or slot reuse makes that check fail.
References: crates/…/guest_memory.rs• L30-49 crates/…/registry.rs• L289-316 crates/…/registry.rs• L965-1024 crates/…/registry.rs• L1046-1115 crates/…/snapshot.rs• L157-177
Delivery loss
Collection and export are deliberately bounded. When a destination cannot keep up, its worker drops old collections after the buffer limit. The exporter receives the number of dropped collections, and the OTLP self-metrics make that loss visible.
This means an external backend can have gaps during an outage even though the collector remains running. A successful later export confirms transport recovery but does not restore collections that were already dropped.
References: crates/…/types.rs• L36-44 crates/…/worker.rs• L176-185 crates/…/worker.rs• L218-235 crates/…/otel.rs• L390-405
Local access boundary
The registry is host-local and protected by the runtime's local access boundary. The collector and local SDK or CLI reader must use the same local runtime context to see the same registry. A missing registry means that no local samples are available; it does not mean that a remote sandbox has zero resource use.
References: docs/…/msb-metrics.mdx• L8-16 docs/…/msb-metrics.mdx• L54-63 sdk/…/metrics.rs• L115-141 sdk/…/metrics.rs• L398-413
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the runtime sample fields, shared registry layout, snapshot types, and exporter metric names aligned when adding or removing a resource value.
- Treat a change to the registry layout as an ABI change. Update the readable-version path and the collector's merge rule together.
- Preserve run ID boundaries in every rate calculation so counter resets do not become negative or inflated rates.
- Keep optional source values absent when their source is unavailable. Do not turn an unavailable measurement into a valid zero.
- Keep per-sandbox labels on datapoints rather than shared resource attributes. Otherwise labels can leak between sandbox series.
- Keep collector health signals aligned with buffer drop and export outcomes so a backend can show delivery loss.
- Preserve slot generation and registry identity when readers cache samples or validate a reused registry slot.
- Keep CPU sample validity tied to the counter and clock window. Do not publish a rate from a badly delayed pair of reads.
- Keep live memory limits and memory-use validity separate. A changed limit must not turn unavailable guest memory into a valid zero.
- Keep optional network policy counters behind their presence flags so older runtimes remain distinguishable from zero-valued counters.
- Keep guest report receipt time and lifecycle stamps unchanged by buffering or repeated publication. Expiry must remove guest-derived fields without removing independent metrics.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Runtime and reader use different local runtime contexts | The reader cannot open the registry or sees no sandboxes. | Use the same host context and local home setting. |
| A sampler stops while its slot remains active | A frozen sample can look like a live value. | Apply sample-age filtering and use the stalled state in reports. |
| A sandbox restarts and counters reset | A rate based on the old run can be wrong. | Key rate windows by run ID. |
| A CPU counter and its clock are read across a long host delay | CPU use can be greatly overstated for that window. | Reject the window, retain the last trusted value, and enforce the vCPU ceiling. |
| An exporter stays unavailable until its buffer fills | Old collections are dropped and cannot be recovered. | Monitor dropped-collection and export health metrics. |
| A reader cannot interpret the registry ABI | Metrics from that registry are skipped or rejected. | Keep supported reader versions and runtime rollout compatibility aligned. |
| A cached sample outlives the registry slot or registry that produced it | A reader can associate current data with an old sandbox run. | Validate slot generation and registry identity before reusing cached data. |
| Optional guest, residency, filesystem, or network policy reporting is unavailable or stale | Some metric fields have no value. | Treat nullable fields as unavailable rather than zero. |
| Guest report receipt time is renewed by buffering or repeated publication | An expired report can appear current. | Preserve the original receipt time and recheck lifecycle validity before export. |
Key files
| File | Why to read it |
|---|---|
| crates/…/metrics.rs | Defines the runtime sample sources, CPU validity rules, live memory values, and freshness rules. |
| crates/…/lib.rs | Defines the public metrics registry types and identity-aware read exports. |
| crates/…/layout.rs | Describes the versioned registry shape, sample validity flags, slot states, and guest-memory extension. |
| crates/…/registry.rs | Explains how writers publish samples, readers obtain coherent snapshots, and diagnostic file snapshots preserve a safe view. |
| crates/…/compatibility.rs | Shows how readers consume an older registry layout without mutating it. |
| crates/…/guest_memory.rs | Defines host receipt-time validation for guest memory reports. |
| crates/…/snapshot.rs | Defines the shared metric, identity, lifecycle, and optional-value model. |
| crates/…/reader.rs | Shows how registry snapshots are collected, merged, enriched, and filtered. |
| crates/…/driver.rs | Shows the collector lifecycle and the separation between collection and exporters. |
| crates/…/worker.rs | Shows per-exporter buffering, loss reporting, retry, and shutdown behavior. |
| crates/…/otel.rs | Defines the external metric names, attributes, and collector health signals. |
| sdk/…/metrics.rs | Defines local SDK snapshots, fleet reports, and live or stalled state. |
| crates/…/metrics.rs | Defines human, JSON, watch, and follow views for local diagnostics. |
| docs/…/msb-metrics.mdx | Provides the user-facing operational view of continuous export. |