Skip to content
20 changes: 19 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,30 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
* Add ARM64 Linux MSHV support by @cshung in https://github.com/hyperlight-dev/hyperlight/pull/1626

### Changed
* Snapshot writers emit config v7 with provenance. Config v6 remains readable
without provenance; the guest ABI and memory-layer encoding are unchanged.
* Snapshot saving rejects detected memory-layer digest inconsistencies rather
than repairing them. Checked saves reject corrupted existing blobs; both
save modes reject wrong-length blobs and nonfiles without replacing them.
A detected layer hash mismatch also prevents subsequent shared-layer reuse.
* Compaction requires a supplied base to be declared in the target's provenance.
It replaces ancestry with the specified base's inherited list and ID,
or clears it without a base. This resets accumulated checkpoint history;
provenance inheritance copies the validated list in linear time.
* `Snapshot::load` retains declared memory-layer digests for ordinary saves
instead of hashing the loaded bytes on first save. Incorrect declarations
are preserved; use `checked_load` or `checked_save` for content consistency.
`base.load_overlay` and `base.checked_load_overlay` resolve matching layers from
a caller-authorized, declared whole-snapshot base, keeping declared and
verified digests separate. Persisted snapshot IDs and inherited base
declarations support both compacted and uncompacted descendants without
retaining unused base layers.
* `hyperlight-host` requires Rust 1.95.
* `Snapshot::save` caches memory-layer hashes and trusts existing same-length
regular blobs by their content-addressed filenames without verifying their
contents. Callers must keep blobs immutable. Use the new
`Snapshot::checked_save` to recompute hashes, verify existing blobs, and
atomically repair mismatched contents.
reject mismatched contents without modifying existing memory blobs or the index.
* **Breaking:** Snapshots use ABI 12. Guests must be rebuilt and existing
snapshots regenerated. Capture and restore provide full H2G bootstrap
capacity before guest entry, independent of retained buffers. Snapshot
Expand Down
83 changes: 76 additions & 7 deletions docs/snapshot-oci-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Three blob kinds per tag:
* **manifest** (`application/vnd.oci.image.manifest.v1+json`). Tiny JSON
pointer record selected via `index.json`. References one config and the
snapshot blobs by digest.
* **config** (`application/vnd.hyperlight.snapshot.config.v6+json`). The
* **config** (`application/vnd.hyperlight.snapshot.config.v7+json`). The
snapshot descriptor: arch, hypervisor, CPU vendor, ABI version,
resume address and captured registers, memory and transport layout,
registered host functions, the start address, data length, and page-table
Expand All @@ -76,10 +76,74 @@ across tags are stored once.
`Snapshot::save` caches each shared memory layer's SHA-256. Existing regular
blob files with the expected length are trusted by their content-addressed
filenames without reading or hashing their contents, even at a new destination.
There is no backing-file cache. Missing blobs are written atomically; symlinks
and wrong-length files are replaced.
`Snapshot::checked_load` seeds the digest cache during verification; unchecked
`load` does not. Metadata blobs retain their normal write path.
There is no backing-file cache. Missing blobs are written atomically without
overwriting a concurrently published blob. Symlinks, other nonfiles, and
wrong-length files are rejected in both save modes.
`Snapshot::checked_load` seeds the verified digest cache; ordinary `load`
retains declared digests separately for reuse on save without hashing memory.
Metadata blobs retain their normal write path.

`base.checked_load_overlay(path, reference)` resolves memory layers from an existing base
when their cached SHA-256, size, GPA and data/page-table geometry match. It shares
the base's layer objects without opening or reading those files from the new
layout; the matching files may be omitted. Other blobs are verified normally.
This is explicit content resolution from the supplied base, not validation of
an on-disk copy of a reused blob. Retaining the same objects through restore,
capture and base-preserving compaction avoids both byte comparisons and repeated
hashing of immutable base memory.

`Snapshot::load` trusts declared memory digests without reading memory to verify
them. Ordinary saves preserve those declarations, and
`base.load_overlay(path, reference)` resolves matching layers
by digest and geometry. `BlobHash` stores one immutable digest with an atomic
status. `get()` reconstructs `Unknown`, `Declared(&str)`, or `Verified(&str)`;
permanent invalidation is returned as an error.
`HashState::as_digest()` returns an owned digest for declared or verified states,
or `None` for unknown.
Constructors are `unknown()`,
`declared(digest)`, and `verified(digest)`; the caller must have computed or verified
the digest against the blob's bytes before using `verified`. `Default` initializes
unknown. `verify_bytes(bytes)`
and `verify_file(file)` always hash the supplied bytes or open file before
checking and updating the state. Recording a computed digest is private.
Computing a hash that differs
from the declaration or a previous computation is an error, not a correction.
Once such a mismatch is detected, all later hash access through that shared
layer fails, including ordinary saves and overlay matching. Checked base loading
never reuses a mere declaration, and
checked saving still hashes every layer. This changes prior ordinary
`load`-then-`save` behavior: it preserves declared digests instead of computing
them from actual bytes, including when the declared digest is incorrect.
Structural validation remains enabled in all modes. A declaration is neither
content authentication nor permission to read another actor's memory; callers
must restrict base sharing to authorized, immutable objects. Incorrect digests
can substitute guest state or publish bytes under an incorrect name.

Both overlay methods require persisted provenance declaring the supplied whole
snapshot as a base; a matching memory layer alone is insufficient. Each new VM
snapshot has a stable UUID stored as `snapshot_id` in the OCI config, with
ancestor IDs in `bases`. Metadata-only copies retain the VM snapshot's ID.
Restore/capture inherits the restored snapshot and its bases, including without
compaction. `compact(Some(base))` requires that base's ID to already appear in
the target's `bases`; matching memory alone is insufficient, and the target
cannot use itself as a base. It replaces the target's history with the specified
base's inherited bases plus the base itself; `compact(None)` clears all bases.
Once cleared, compaction cannot reintroduce a discarded base.
Neither operation retains unused layers merely to establish provenance.
Provenance is carried by the whole `SnapshotMemory` object, not individual
blobs, so capture inherits it directly from the existing memory backing.

Uncompacted captures can grow ancestry even without adding memory layers.
Periodically compact without a base to reset it, or compact against a fixed
base with a short ancestry list to retain that base without accumulating the
target's checkpoint history. Both operations can recover save capacity after
ancestry exceeds the config JSON size limit.

These IDs are trusted declarations, not content digests or cryptographic proofs
of ancestry, even with checked loading. Legacy v6 configs without provenance still
load standalone, receiving a new in-memory ID. Save that base to persist its ID
before relying on independently loaded copies for overlay. A layout without a
matching base declaration cannot be overlaid.

Callers must keep loaded and published memory blobs immutable for the lifetime
of these snapshots and outside writable guest mounts. Host-side mutation and
Expand All @@ -89,8 +153,11 @@ persisted contents explicitly.

`Snapshot::checked_save` takes the fully verifying path: it recomputes all
memory-layer digests without using the cache and hashes existing memory blob
files before reusing them. Mismatched contents are atomically replaced from
the snapshot's memory. It otherwise has the same layout and tag semantics as
files before reusing them. Digest or existing-content mismatches are errors;
neither copy is presumed trustworthy. Existing memory blobs and the published
index remain unchanged on these errors, though earlier newly written blobs
may remain unreferenced. Recovery requires a trusted source or a fresh capture,
not automatic repair. It otherwise has the same layout and tag semantics as
`save`. This is not protection against concurrent modification of loaded
backing files, which must remain immutable while snapshots use them.

Expand Down Expand Up @@ -175,6 +242,8 @@ podman), `go-containerregistry` (crane), and `regclient`.

`Snapshot::load(path, reference)` reads a snapshot. It does not check
the manifest, config, or data blobs against their sha256 digests.
It retains declared memory digests for ordinary saves; `load_overlay` also
shares matching layers from an explicitly supplied, authorized base.
`reference` is an
[`OciReference`], either a tag that matches the
`org.opencontainers.image.ref.name` annotation or the manifest
Expand Down
10 changes: 8 additions & 2 deletions docs/snapshot-versioning.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ A snapshot carries three independently evolvable version markers:
`MT_SNAPSHOT_CURRENT`. This is the on-wire format of the snapshot
blob: framing, section ordering, alignment, dirty/zero-page elision,
anything about how the bytes are packed inside the OCI layer.
* **Config schema**, `MT_CONFIG_V6`
(`application/vnd.hyperlight.snapshot.config.v6+json`), aliased as
* **Config schema**, `MT_CONFIG_V7`
(`application/vnd.hyperlight.snapshot.config.v7+json`), aliased as
`MT_CONFIG_CURRENT`. This is the JSON shape of the config blob:
field names, types, required vs optional, the descriptors the loader
needs in order to reconstruct the sandbox (memory sizes, buffer
Expand All @@ -33,6 +33,9 @@ A snapshot carries three independently evolvable version markers:
bumps this constant. Version 4 describes snapshot blobs, the blob with
the page tables, and transport geometry. Version 5 drops the heap size.
Version 6 contains code and scratch geometry without init-data fields.
Version 7 adds a required snapshot ID and optional inherited base IDs.
Version 6 remains readable without provenance; existing v6 readers reject
v7 by media type rather than interpreting a changed v6 schema.
Config v1 to v5 are incompatible with the current ABI.

ABI 6 requires checkpoint readiness after guest initialization and permits
Expand Down Expand Up @@ -81,6 +84,9 @@ Writers omit an empty map, and readers treat a missing field as empty.
Record compatibility paths here when a future hard snapshot break can remove
them.

Config v6 loading supplies no base provenance and assigns an in-memory snapshot
ID. The next hard snapshot break may remove this compatibility path.

## Enforcement

The format is large and easy to change by accident. Three mechanisms
Expand Down
69 changes: 64 additions & 5 deletions src/hyperlight_host/src/sandbox/snapshot/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,19 @@ impl Snapshot {
/// layers and unreferenced pages in merged layers are discarded, except
/// for minimal padding required by the snapshot format. Retained base
/// layers are kept whole.
/// A supplied base must already appear in this snapshot's provenance.
/// With a base, the result inherits that base's declared ancestors and records
/// the base itself for [`Snapshot::load_overlay`], discarding this snapshot's
/// previous ancestry. Without a base, the result clears all base provenance.
/// Provenance does not require retaining any otherwise unused layer.
///
/// Registers, metadata, transport state, generation, and page-table roots
/// are preserved. The result uses the existing snapshot file format.
///
/// # Errors
///
/// Returns an error if the base has a different memory layout, allocation
/// Returns an error if the base is not declared in this snapshot's provenance,
/// the base has a different memory layout, allocation
/// fails, or the compacted memory cannot fit within the address-space or
/// layer limits.
#[instrument(err(Debug), skip_all, parent = Span::current(), level = "Trace")]
Expand All @@ -36,6 +42,13 @@ impl Snapshot {
"compaction base has an incompatible memory layout"
));
}
if let Some(base) = base
&& !self.state.memory.bases.contains(&base.state.memory.id)
{
return Err(crate::new_error!(
"snapshot does not declare the supplied snapshot as a compaction base"
));
}

let memory = &self.state.memory;
let preserve: Vec<bool> = memory
Expand Down Expand Up @@ -158,9 +171,13 @@ impl Snapshot {
if data_len > 0 {
layers.push(blob.clone());
}
let mut memory = SnapshotMemory::new(layers.into_boxed_slice(), blob)?;
if let Some(base) = base {
memory.inherit_base(base.snapshot_memory());
}
Ok(Arc::new(Self {
state: Arc::new(SnapshotState {
memory: Arc::new(SnapshotMemory::new(layers.into_boxed_slice(), blob)?),
memory: Arc::new(memory),
..(*self.state).clone()
}),
metadata: self.metadata.clone(),
Expand Down Expand Up @@ -255,12 +272,49 @@ mod tests {
}
}

fn descendant(base: &Snapshot) -> Snapshot {
let mut memory = SnapshotMemory::new(
base.state.memory.layers().to_vec().into_boxed_slice(),
base.state.memory.page_table_blob().clone(),
)
.unwrap();
memory.inherit_base(base.snapshot_memory());
Snapshot {
state: Arc::new(SnapshotState {
memory: Arc::new(memory),
..(*base.state).clone()
}),
metadata: base.metadata.clone(),
}
}

#[test]
fn compact_requires_declared_base_even_with_identical_memory() {
let base = layered_snapshot();
let unrelated = layered_snapshot();
for target in [&unrelated, &base] {
let error = target.compact(Some(&base)).err().unwrap();
assert!(error.to_string().contains("does not declare"), "{error}");
}
unrelated.compact(None).unwrap();

let child = descendant(&base);
let grandchild = descendant(&child);
grandchild.compact(Some(&base)).unwrap();
grandchild.compact(Some(&child)).unwrap();

let cleared = grandchild.compact(None).unwrap();
let error = cleared.compact(Some(&base)).err().unwrap();
assert!(error.to_string().contains("does not declare"), "{error}");
}

#[test]
fn compact_packs_live_pages_and_preserves_aliases_and_permissions() {
let original = layered_snapshot();
let base = layered_snapshot();
let original = descendant(&base);
let start = SandboxMemoryLayout::BASE_ADDRESS as u64;
for preserve in [false, true] {
let compacted = original.compact(preserve.then_some(&original)).unwrap();
let compacted = original.compact(preserve.then_some(&base)).unwrap();
let memory = &compacted.state.memory;
assert_eq!(memory.layers().len(), if preserve { 2 } else { 1 });
assert_eq!(
Expand Down Expand Up @@ -315,8 +369,10 @@ mod tests {
.unwrap(),
..(*original.state).clone()
});
let base = original;
let original = descendant(&base);
for preserve in [false, true] {
let compacted = original.compact(preserve.then_some(&original)).unwrap();
let compacted = original.compact(preserve.then_some(&base)).unwrap();
let memory = &compacted.state.memory;
assert_eq!(memory.layers().len(), if preserve { 3 } else { 1 });
assert!(memory.gpa_span_len() >= 10 * alignment);
Expand Down Expand Up @@ -391,6 +447,9 @@ mod tests {
),
..(*current.state).clone()
});
Arc::get_mut(&mut Arc::get_mut(&mut current.state).unwrap().memory)
.unwrap()
.inherit_base(base.snapshot_memory());
let compacted = current.compact(Some(&base)).unwrap();
let layers = compacted.state.memory.layers();
assert_eq!(layers.len(), 2);
Expand Down
35 changes: 32 additions & 3 deletions src/hyperlight_host/src/sandbox/snapshot/file/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ impl CpuVendor {

/// Top-level Hyperlight snapshot config JSON. Lives at
/// `blobs/sha256/<config-digest>` with media type
/// `application/vnd.hyperlight.snapshot.config.v6+json`.
/// `application/vnd.hyperlight.snapshot.config.v7+json`, with defaults for v6.
///
/// In OCI terms this is the "image config" blob that the manifest's
/// `config` descriptor points to. It describes the accompanying
Expand Down Expand Up @@ -213,6 +213,15 @@ pub(super) struct OciSnapshotConfig {
/// `SCRATCH_TOP_SNAPSHOT_GENERATION_OFFSET` is continuous across
/// save/load.
pub(super) snapshot_generation: u64,
/// Persisted UUID of the whole snapshot, required in v7 and absent in v6.
/// Overlay loading uses this identity rather than matching memory blobs alone.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) snapshot_id: Option<String>,
/// Trusted ancestor snapshot UUIDs eligible as overlay bases.
/// Capture inherits the source history; compaction replaces it with the
/// chosen base's history and ID, or clears it when no base is chosen.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) bases: Vec<String>,
Comment thread
jprendes marked this conversation as resolved.
Resolved
Comment thread
jprendes marked this conversation as resolved.
Resolved
/// Application-owned metadata keyed by namespace.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) metadata: BTreeMap<String, serde_json::Value>,
Expand Down Expand Up @@ -430,6 +439,20 @@ impl OciSnapshotConfig {
}

pub(super) fn validate_for_load(&self) -> crate::Result<()> {
if self.snapshot_id.is_none() && !self.bases.is_empty() {
return Err(crate::new_error!("snapshot bases require a snapshot ID"));
}
let mut ids = std::collections::HashSet::new();
for id in self.snapshot_id.iter().chain(&self.bases) {
let id = uuid::Uuid::parse_str(id)
.map_err(|e| crate::new_error!("invalid snapshot provenance ID: {}", e))?;
if id.is_nil() {
return Err(crate::new_error!("snapshot provenance ID must not be nil"));
}
if !ids.insert(id) {
return Err(crate::new_error!("duplicate snapshot provenance ID"));
}
Comment thread
jprendes marked this conversation as resolved.
Resolved
}
if self.arch != Arch::current() {
return Err(crate::new_error!(
"snapshot architecture mismatch: file is {:?}, current host is {:?} \
Expand Down Expand Up @@ -808,6 +831,8 @@ mod tests {
/// gating checks under test short-circuit before reading it.
fn gating_config() -> OciSnapshotConfig {
OciSnapshotConfig {
snapshot_id: None,
bases: Vec::new(),
hyperlight_version: "test".to_string(),
arch: Arch::current(),
abi_version: SNAPSHOT_ABI_VERSION,
Expand Down Expand Up @@ -1110,7 +1135,9 @@ mod schema_pin {
"return_type": "void"
}
],
"snapshot_generation": 42
"snapshot_generation": 42,
"snapshot_id": "00000000-0000-0000-0000-000000000001",
"bases": ["00000000-0000-0000-0000-000000000002"]
}"#;

#[cfg(target_arch = "aarch64")]
Expand Down Expand Up @@ -1160,7 +1187,9 @@ mod schema_pin {
"return_type": "void"
}
],
"snapshot_generation": 42
"snapshot_generation": 42,
"snapshot_id": "00000000-0000-0000-0000-000000000001",
"bases": ["00000000-0000-0000-0000-000000000002"]
}"#;

const PINNED_ARCH: &str = r#"[
Expand Down
Loading
Loading