Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(runner): plumb full checkpoint kind and memorySizeBytes through export, upload, and restore (#3106)

lfld28745e0f1e755d0
diff --git a/apps/runner/README.md b/apps/runner/README.md
index 0006f0bfd..0ff6d1b91 100644
--- a/apps/runner/README.md
+++ b/apps/runner/README.md
@@ -927,9 +927,11 @@ The [checkpoint design](https://github.com/boxlite-ai/boxlite/issues/2367)
defines the capture, transfer and recovery contracts; the transfer helper alone
does not provide target recovery ownership.
-Checkpoint creation requires an idle, stopped source; running and transitional
-sources are refused without stopping them. The runner rechecks `stopped` while
-holding the source operation lease, so a concurrent start cannot race export.
+`EXPORT_CHECKPOINT` accepts an optional `kind`: `disk` (the default when omitted)
+requires a stopped source, and `full` requires a running source and native support
+for exporting memory. The runner checks the state under the source operation
+lease; it does not start or stop the source to make it eligible. The runner does
+not yet advertise the `memory_checkpoint` capability.
Checkpoint capture separates native export from upload. `EXPORT_CHECKPOINT`
owns the source `BOX` job slot; it reports an immutable archive record and never
@@ -939,7 +941,11 @@ operation lease, so a later source start can proceed independently.
Each capture uses `<BOXLITE_HOME_DIR>/work/checkpoints/<checkpoint-id>/<export-job-id>/`.
Its record pins the image digest that built the source disk, archive size,
-SHA-256 and object URI. Redelivery reuses that capture; it never substitutes a
+SHA-256 and object URI. The result carries `kind` when supplied, and for `full`
+it also carries `memorySizeBytes` from the archive manifest (a nonnegative
+integer, including zero). Disk results omit `memorySizeBytes`. Pass the export
+result unchanged to `UPLOAD_CHECKPOINT`; upload returns the same metadata.
+Redelivery reuses that capture; it never substitutes a
fresh source export if the published file is missing or corrupt. Fixed lock
files serialize duplicate deliveries across processes sharing the work directory.
@@ -960,14 +966,20 @@ policy; native runtime has no checkpoint-specific archive preparer.
`IMPORT_CHECKPOINT` downloads and verifies SHA-256, imports a candidate under an
operation-specific native name, publishes its public-to-native identity mapping,
-and only then removes the predecessor. Import failures retain the original Box.
+and only then removes the predecessor. The candidate must be `stopped` with PID
+zero; recovery requires a `stopped` or `failed` predecessor with PID zero.
+Import failures retain the original Box. The request's `archive` carries the
+upload result, including `kind` and `memorySizeBytes` for a full checkpoint. An
+optional request-level `kind` must match `archive.kind` (which defaults to `disk`
+when omitted).
Runner streams the archive to a temporary plain tar, changing only the first
manifest member's pinned image and six platform environment keys. It copies
-the remaining tar bytes unchanged, preserving GNU sparse members. It performs
-no separate disk validation or startup preflight; the existing native import
-owns archive extraction and validation. This adds one stream read and temporary
-write, without extracting disk files or recompressing them.
+the remaining tar bytes unchanged, preserving GNU sparse members and full
+checkpoint memory data. The manifest's `memory_checkpoint` metadata is retained.
+Runner performs no separate disk validation or startup preflight; the existing
+native import owns archive extraction and validation. This adds one stream read
+and temporary write, without extracting disk files or recompressing them.
The download and adapted tar stay owned until native import finishes. The
request carries a stable operation and monotonically increasing target sequence,
diff --git a/apps/runner/pkg/backend/backend.go b/apps/runner/pkg/backend/backend.go
index cd2dd8480..471832b1e 100644
--- a/apps/runner/pkg/backend/backend.go
+++ b/apps/runner/pkg/backend/backend.go
@@ -40,7 +40,7 @@ type BoxBackend interface {
// CheckpointExporter captures a disk archive and the source's original OCI
// build without extending the existing migration export contract.
type CheckpointExporter interface {
- ExportCheckpoint(ctx context.Context, boxId, destDir string) (archivePath, pinnedImage string, err error)
+ ExportCheckpoint(ctx context.Context, boxId, destDir, kind string) (checkpoint.CaptureResult, error)
}
type CheckpointRestorer interface {
diff --git a/apps/runner/pkg/backend/boxlite_adapter.go b/apps/runner/pkg/backend/boxlite_adapter.go
index de6b0279c..8ff379341 100644
--- a/apps/runner/pkg/backend/boxlite_adapter.go
+++ b/apps/runner/pkg/backend/boxlite_adapter.go
@@ -68,8 +68,8 @@ func (a *BoxliteAdapter) ImportBox(ctx context.Context, boxId, archivePath strin
return a.client.ImportBox(ctx, boxId, archivePath)
}
-func (a *BoxliteAdapter) ExportCheckpoint(ctx context.Context, boxId, destDir string) (string, string, error) {
- return a.client.ExportCheckpoint(ctx, boxId, destDir)
+func (a *BoxliteAdapter) ExportCheckpoint(ctx context.Context, boxId, destDir, kind string) (checkpoint.CaptureResult, error) {
+ return a.client.ExportCheckpoint(ctx, boxId, destDir, kind)
}
func (a *BoxliteAdapter) RestoreCheckpoint(ctx context.Context, request checkpoint.RestoreRequest, attemptID string, artifacts checkpoint.Artifacts, store storage.ArchiveStore) (checkpoint.RestoreResult, error) {
diff --git a/apps/runner/pkg/backend/boxlite_adapter_test.go b/apps/runner/pkg/backend/boxlite_adapter_test.go
new file mode 100644
index 000000000..3b3a737c1
--- /dev/null
+++ b/apps/runner/pkg/backend/boxlite_adapter_test.go
@@ -0,0 +1,133 @@
+// Copyright 2026 BoxLite AI
+// SPDX-License-Identifier: AGPL-3.0
+
+package backend
+
+import (
+ "archive/tar"
+ "context"
+ "crypto/sha256"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ sdk "github.com/boxlite-ai/boxlite/sdks/go"
+ blclient "github.com/boxlite-ai/runner/pkg/boxlite"
+ "github.com/boxlite-ai/runner/pkg/checkpoint"
+)
+
+func TestBoxliteAdapterExportCheckpoint(t *testing.T) {
+ client, err := blclient.NewClient(t.Context(), blclient.ClientConfig{HomeDir: t.TempDir()})
+ var runtimeErr *sdk.Error
+ if errors.As(err, &runtimeErr) && runtimeErr.Code == sdk.ErrUnsupported {
+ t.Skipf("runtime could not start (infrastructure prerequisite): %v", err)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = client.Close() })
+ var adapter CheckpointExporter = NewBoxliteAdapter(client)
+
+ const boxID = "checkpoint-source"
+ image := "example.invalid/app@sha256:" + strings.Repeat("a", 64)
+ if err := client.ImportBox(t.Context(), boxID, writeStoppedBoxArchive(t, image)); err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("disk export", func(t *testing.T) {
+ dest := filepath.Join(t.TempDir(), "capture")
+ result, err := adapter.ExportCheckpoint(t.Context(), boxID, dest, checkpoint.KindDisk)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if filepath.Dir(result.ArchivePath) != dest || result.PinnedImage != image || result.MemorySizeBytes != nil {
+ t.Fatalf("unexpected capture result: %+v", result)
+ }
+ info, err := os.Stat(result.ArchivePath)
+ if err != nil || !info.Mode().IsRegular() || info.Size() == 0 {
+ t.Fatalf("expected a nonempty archive at %q, got %v, %v", result.ArchivePath, info, err)
+ }
+ })
+
+ t.Run("native lookup error", func(t *testing.T) {
+ result, err := adapter.ExportCheckpoint(t.Context(), "missing-box", t.TempDir(), checkpoint.KindDisk)
+ if !sdk.IsNotFound(err) || result != (checkpoint.CaptureResult{}) {
+ t.Fatalf("expected not-found from client with no result, got %+v, %v", result, err)
+ }
+ })
+
+ t.Run("full kind requires running source", func(t *testing.T) {
+ result, err := adapter.ExportCheckpoint(t.Context(), boxID, t.TempDir(), checkpoint.KindFull)
+ if err == nil || !strings.Contains(err.Error(), "must be running (got stopped)") || result != (checkpoint.CaptureResult{}) {
+ t.Fatalf("expected full export to reject stopped source, got %+v, %v", result, err)
+ }
+ })
+
+ t.Run("cancelled context", func(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ result, err := adapter.ExportCheckpoint(ctx, boxID, t.TempDir(), checkpoint.KindDisk)
+ if !errors.Is(err, context.Canceled) || result != (checkpoint.CaptureResult{}) {
+ t.Fatalf("expected cancellation with no result, got %+v, %v", result, err)
+ }
+ })
+}
+
+func TestBoxliteAdapterExportCheckpointRejectsInvalidKindWithoutRuntime(t *testing.T) {
+ adapter := NewBoxliteAdapter(&blclient.Client{})
+ res, err := adapter.ExportCheckpoint(t.Context(), "checkpoint-source", t.TempDir(), "invalid")
+ if err == nil {
+ t.Fatal("expected error for invalid checkpoint kind, got nil")
+ }
+ if res != (checkpoint.CaptureResult{}) {
+ t.Fatalf("expected empty CaptureResult, got %+v", res)
+ }
+}
+
+// An empty standalone QCOW2 v2 lets the real runtime import a stopped box
+// without pulling an image or booting a VM.
+func writeStoppedBoxArchive(t *testing.T, image string) string {
+ t.Helper()
+ const cluster = 1 << 16
+ disk := make([]byte, 4*cluster)
+ binary.BigEndian.PutUint32(disk[0:4], 0x514649fb)
+ binary.BigEndian.PutUint32(disk[4:8], 2)
+ binary.BigEndian.PutUint32(disk[20:24], 16)
+ binary.BigEndian.PutUint64(disk[24:32], 1<<20)
+ binary.BigEndian.PutUint32(disk[36:40], 1)
+ binary.BigEndian.PutUint64(disk[40:48], 3*cluster)
+ binary.BigEndian.PutUint64(disk[48:56], cluster)
+ binary.BigEndian.PutUint32(disk[56:60], 1)
+ binary.BigEndian.PutUint64(disk[cluster:cluster+8], 2*cluster)
+ for i := range 4 {
+ binary.BigEndian.PutUint16(disk[2*cluster+2*i:], 1)
+ }
+ manifest := fmt.Appendf(nil, `{"version":3,"box_name":"source","image":%q,"box_options":{"rootfs":{"Image":%q},"cpus":1,"memory_mib":128,"detach":true,"auto_delete":0},"guest_disk_checksum":"","container_disk_checksum":"sha256:%x","exported_at":"2026-01-01T00:00:00Z"}`, image, image, sha256.Sum256(disk))
+
+ path := filepath.Join(t.TempDir(), "source.boxlite")
+ file, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer file.Close()
+ archive := tar.NewWriter(file)
+ for _, member := range []struct {
+ name string
+ data []byte
+ }{{"manifest.json", manifest}, {"disk.qcow2", disk}} {
+ if err := archive.WriteHeader(&tar.Header{Name: member.name, Mode: 0600, Size: int64(len(member.data))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := archive.Write(member.data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := archive.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
diff --git a/apps/runner/pkg/boxlite/archive.go b/apps/runner/pkg/boxlite/archive.go
index 2d6f2ae76..0606bb7a8 100644
--- a/apps/runner/pkg/boxlite/archive.go
+++ b/apps/runner/pkg/boxlite/archive.go
@@ -12,19 +12,27 @@ import (
"github.com/boxlite-ai/runner/pkg/checkpoint"
)
-func (c *Client) ExportCheckpoint(ctx context.Context, boxId, destDir string) (string, string, error) {
+func (c *Client) ExportCheckpoint(ctx context.Context, boxId, destDir, kind string) (checkpoint.CaptureResult, error) {
+ requiredState, options := boxlite.StateStopped, boxlite.ExportOptions{}
+ switch kind {
+ case "", checkpoint.KindDisk:
+ case checkpoint.KindFull:
+ requiredState, options.IncludeMemory = boxlite.StateRunning, true
+ default:
+ return checkpoint.CaptureResult{}, fmt.Errorf("invalid checkpoint kind %q", kind)
+ }
operation, err := c.lockCheckpointTarget(ctx, boxId)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
defer operation.Close()
ctx = context.WithoutCancel(ctx)
info, err := c.nativeBoxInfo(ctx, boxId)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
- if info.State != boxlite.StateStopped {
- return "", "", fmt.Errorf("checkpoint source must be stopped; stop the Box before creating a checkpoint")
+ if info.State != requiredState {
+ return checkpoint.CaptureResult{}, fmt.Errorf("checkpoint source must be %s (got %s)", requiredState, info.State)
}
digest := ""
if info.ResolvedImage != nil {
@@ -32,10 +40,20 @@ func (c *Client) ExportCheckpoint(ctx context.Context, boxId, destDir string) (s
}
pinned, err := checkpoint.PinImage(info.Image, digest)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
+ }
+ archive, err := c.exportBoxWithOptions(ctx, boxId, destDir, options)
+ if err != nil {
+ return checkpoint.CaptureResult{}, err
+ }
+ result := checkpoint.CaptureResult{ArchivePath: archive, PinnedImage: pinned}
+ if options.IncludeMemory {
+ result.MemorySizeBytes, err = readExportedCheckpointMemorySizeBytes(destDir, archive)
+ if err != nil {
+ return checkpoint.CaptureResult{}, err
+ }
}
- archive, err := c.exportBox(ctx, boxId, destDir)
- return archive, pinned, err
+ return result, nil
}
// ExportBox packs a box into a portable .boxlite archive inside destDir and
@@ -47,10 +65,10 @@ func (c *Client) ExportBox(ctx context.Context, boxId, destDir string) (string,
return "", err
}
defer operation.Close()
- return c.exportBox(context.WithoutCancel(ctx), boxId, destDir)
+ return c.exportBoxWithOptions(context.WithoutCancel(ctx), boxId, destDir, boxlite.ExportOptions{})
}
-func (c *Client) exportBox(ctx context.Context, boxId, destDir string) (string, error) {
+func (c *Client) exportBoxWithOptions(ctx context.Context, boxId, destDir string, options boxlite.ExportOptions) (string, error) {
if err := os.MkdirAll(destDir, 0755); err != nil {
return "", fmt.Errorf("failed to create export directory %s: %w", destDir, err)
}
@@ -60,7 +78,7 @@ func (c *Client) exportBox(ctx context.Context, boxId, destDir string) (string,
return "", err
}
- archivePath, err := bx.Export(ctx, destDir)
+ archivePath, err := bx.ExportWithOptions(ctx, destDir, options)
if err != nil {
return "", fmt.Errorf("failed to export box %s: %w", boxId, err)
}
diff --git a/apps/runner/pkg/boxlite/checkpoint_archive.go b/apps/runner/pkg/boxlite/checkpoint_archive.go
index d1e78a18d..2bae1fe13 100644
--- a/apps/runner/pkg/boxlite/checkpoint_archive.go
+++ b/apps/runner/pkg/boxlite/checkpoint_archive.go
@@ -19,6 +19,7 @@ import (
"github.com/boxlite-ai/runner/pkg/checkpoint"
"github.com/klauspost/compress/zstd"
+ "golang.org/x/sys/unix"
)
var checkpointPlatformEnvKeys = []string{
@@ -26,46 +27,164 @@ var checkpointPlatformEnvKeys = []string{
"BOXLITE_REGION_ID", "BOXLITE_TRACEPARENT", "BOXLITE_TRACESTATE",
}
-// Native export writes manifest.json first. Replace only that member, then copy
-// the raw tar tail unchanged: decoding/re-encoding disk members with Go's tar
-// writer would lose GNU sparse metadata. Native import owns all disk validation.
-// The plain tar stays beside the download until the restore worker releases it.
-func checkpointImportArchive(source *checkpoint.DownloadedArchive, env map[string]string) (_ string, err error) {
- file, err := os.Open(source.Path)
- if err != nil {
- return "", err
- }
- defer file.Close()
+// checkpointArchiveReader decodes the archive without taking ownership of file.
+func checkpointArchiveReader(file *os.File) (io.Reader, func(), error) {
reader := bufio.NewReader(file)
magic, err := reader.Peek(4)
if err != nil {
- return "", err
+ return nil, nil, err
}
- var input io.Reader = reader
if bytes.Equal(magic, []byte{0x28, 0xb5, 0x2f, 0xfd}) {
decoder, err := zstd.NewReader(reader, zstd.WithDecoderConcurrency(1))
if err != nil {
- return "", err
+ return nil, nil, err
}
- defer decoder.Close()
- input = decoder
+ return decoder, decoder.Close, nil
}
+ return reader, func() {}, nil
+}
+
+// Read exactly the manifest member, leaving input positioned at the raw tar tail.
+func readCheckpointManifest(input io.Reader) (*tar.Header, []byte, error) {
headerBytes := make([]byte, 512)
if _, err := io.ReadFull(input, headerBytes); err != nil {
- return "", err
+ return nil, nil, err
}
header, err := tar.NewReader(bytes.NewReader(headerBytes)).Next()
if err != nil {
- return "", err
+ return nil, nil, err
}
if header.Name != "manifest.json" || header.Typeflag != tar.TypeReg || header.Size < 0 || header.Size > 1<<20 {
- return "", fmt.Errorf("native checkpoint must begin with a manifest of at most 1 MiB")
+ return nil, nil, fmt.Errorf("native checkpoint must begin with a manifest of at most 1 MiB")
}
manifest := make([]byte, header.Size)
if _, err := io.ReadFull(input, manifest); err != nil {
- return "", err
+ return nil, nil, err
}
if _, err := io.CopyN(io.Discard, input, (512-header.Size%512)%512); err != nil {
+ return nil, nil, err
+ }
+ return header, manifest, nil
+}
+
+func readExportedCheckpointMemorySizeBytes(destDir, archive string) (*int64, error) {
+ // Rel cleans its inputs; reject traversal in the original archive path too.
+ relative, err := filepath.Rel(destDir, archive)
+ if err != nil || relative == "." || relative == ".." || filepath.Dir(relative) != "." || archive != filepath.Clean(archive) {
+ return nil, fmt.Errorf("checkpoint exporter returned an archive outside its private directory")
+ }
+ // Validate the opened file itself; opening a FIFO must not wait for a writer.
+ file, err := os.OpenFile(archive, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
+ if err != nil {
+ return nil, fmt.Errorf("open full checkpoint archive: %w", err)
+ }
+ defer file.Close()
+ info, err := file.Stat()
+ if err != nil {
+ return nil, fmt.Errorf("stat full checkpoint archive: %w", err)
+ }
+ if !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("full checkpoint archive must be a regular file")
+ }
+ size, err := readCheckpointMemorySizeBytes(file)
+ if err != nil {
+ return nil, fmt.Errorf("read full checkpoint memory size: %w", err)
+ }
+ return size, nil
+}
+
+func readCheckpointMemorySizeBytes(file *os.File) (*int64, error) {
+ input, closeArchive, err := checkpointArchiveReader(file)
+ if err != nil {
+ return nil, err
+ }
+ defer closeArchive()
+ _, data, err := readCheckpointManifest(input)
+ if err != nil {
+ return nil, err
+ }
+ var manifest map[string]json.RawMessage
+ if err := json.Unmarshal(data, &manifest); err != nil {
+ return nil, err
+ }
+ return checkpointMemorySizeBytes(manifest["memory_checkpoint"])
+}
+
+func checkpointMemorySizeBytes(memory json.RawMessage) (*int64, error) {
+ var metadata map[string]json.RawMessage
+ if len(memory) != 0 {
+ if err := json.Unmarshal(memory, &metadata); err != nil {
+ return nil, fmt.Errorf("invalid checkpoint manifest memory_checkpoint: %w", err)
+ }
+ }
+ var size *int64
+ if data := metadata["memory_size_bytes"]; len(data) != 0 {
+ if err := json.Unmarshal(data, &size); err != nil {
+ return nil, fmt.Errorf("invalid checkpoint manifest memory_checkpoint.memory_size_bytes: %w", err)
+ }
+ }
+ if size == nil || *size < 0 {
+ return nil, fmt.Errorf("checkpoint manifest requires a nonnegative memory_checkpoint.memory_size_bytes")
+ }
+ return size, nil
+}
+
+func validateCheckpointImportMemory(data []byte, artifact checkpoint.Artifact) error {
+ var manifest map[string]json.RawMessage
+ if err := json.Unmarshal(data, &manifest); err != nil {
+ return err
+ }
+ memory := manifest["memory_checkpoint"]
+ switch artifact.NormalizedKind() {
+ case checkpoint.KindDisk:
+ if len(memory) != 0 && !bytes.Equal(memory, []byte("null")) {
+ return fmt.Errorf("disk checkpoint manifest must not contain a non-null memory_checkpoint")
+ }
+ var version uint32
+ if raw, ok := manifest["version"]; ok {
+ if err := json.Unmarshal(raw, &version); err != nil {
+ return fmt.Errorf("invalid checkpoint manifest version: %w", err)
+ }
+ }
+ // Match MEMORY_CHECKPOINT_ARCHIVE_VERSION in the native importer.
+ if version == 8 {
+ return fmt.Errorf("disk checkpoint manifest must not use memory checkpoint archive version %d", version)
+ }
+ case checkpoint.KindFull:
+ size, err := checkpointMemorySizeBytes(memory)
+ if err != nil {
+ return err
+ }
+ if artifact.MemorySizeBytes == nil {
+ return fmt.Errorf("full checkpoint artifact is missing memorySizeBytes")
+ }
+ if *size != *artifact.MemorySizeBytes {
+ return fmt.Errorf("checkpoint manifest memory_size_bytes %d does not match artifact memorySizeBytes %d", *size, *artifact.MemorySizeBytes)
+ }
+ }
+ return nil
+}
+
+// Native export writes manifest.json first. Replace only that member, then copy
+// the raw tar tail unchanged: decoding/re-encoding disk members with Go's tar
+// writer would lose GNU sparse metadata. Native import owns all disk validation.
+// The plain tar stays beside the download until the restore worker releases it.
+func checkpointImportArchive(source *checkpoint.DownloadedArchive, env map[string]string) (_ string, err error) {
+ file, err := os.Open(source.Path)
+ if err != nil {
+ return "", err
+ }
+ defer file.Close()
+ input, closeArchive, err := checkpointArchiveReader(file)
+ if err != nil {
+ return "", err
+ }
+ defer closeArchive()
+ header, manifest, err := readCheckpointManifest(input)
+ if err != nil {
+ return "", err
+ }
+ if err := validateCheckpointImportMemory(manifest, source.Artifact); err != nil {
return "", err
}
manifest, err = checkpointImportManifest(manifest, source.Artifact.PinnedImage, env)
diff --git a/apps/runner/pkg/boxlite/checkpoint_boundary_test.go b/apps/runner/pkg/boxlite/checkpoint_boundary_test.go
index 7bf9428c4..1820adcd2 100644
--- a/apps/runner/pkg/boxlite/checkpoint_boundary_test.go
+++ b/apps/runner/pkg/boxlite/checkpoint_boundary_test.go
@@ -7,6 +7,7 @@ import (
"archive/tar"
"bytes"
"context"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -15,6 +16,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
sdk "github.com/boxlite-ai/boxlite/sdks/go"
@@ -68,7 +70,7 @@ func TestCheckpointClientLifecycleRefusesCorruptJournalAndCancelledAdmission(t *
"stop": func() error { return client.Stop(ctx, "target", false) },
"destroy": func() error { return client.Destroy(ctx, "target") },
"export": func() error { _, err := client.ExportBox(ctx, "target", t.TempDir()); return err },
- "capture": func() error { _, _, err := client.ExportCheckpoint(ctx, "target", t.TempDir()); return err },
+ "capture": func() error { _, err := client.ExportCheckpoint(ctx, "target", t.TempDir(), ""); return err },
"import": func() error { return client.ImportBox(ctx, "target", "missing.boxlite") },
}
if scenario == "cancelled" {
@@ -88,7 +90,7 @@ func TestCheckpointClientLifecycleRefusesCorruptJournalAndCancelledAdmission(t *
func TestCheckpointClientOrdinaryImportUsesNativePresenceAndCachesSuccess(t *testing.T) {
for _, scenario := range []string{"success", "already-present", "lookup-error", "import-error"} {
t.Run(scenario, func(t *testing.T) {
- imports := 0
+ var imports atomic.Int32
client := checkpointRESTClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/v1/config" {
@@ -107,7 +109,7 @@ func TestCheckpointClientOrdinaryImportUsesNativePresenceAndCachesSuccess(t *tes
}
return
}
- imports++
+ imports.Add(1)
if r.Method != http.MethodPost || r.URL.Path != "/v1/boxes/import" || r.URL.Query().Get("name") != "target" {
t.Errorf("unexpected import: %s %s", r.Method, r.URL)
}
@@ -133,12 +135,12 @@ func TestCheckpointClientOrdinaryImportUsesNativePresenceAndCachesSuccess(t *tes
if scenario == "success" && (client.boxes["target"] == nil || client.boxes["target"].ID() != "accepted") {
t.Fatal("accepted native handle was not cached")
}
- wantImports := 1
+ wantImports := int32(1)
if scenario == "already-present" || scenario == "lookup-error" {
wantImports = 0
}
- if imports != wantImports {
- t.Fatalf("native import count: got %d, want %d; result: %v", imports, wantImports, err)
+ if got := imports.Load(); got != wantImports {
+ t.Fatalf("native import count: got %d, want %d; result: %v", got, wantImports, err)
}
})
}
@@ -158,7 +160,7 @@ func TestCheckpointClientLifecycleUsesNativeRESTUnderTargetLease(t *testing.T) {
for _, action := range []string{"start", "stop", "export"} {
for _, scenario := range []string{"success", "lookup-error", "native-error"} {
t.Run(action+"/"+scenario, func(t *testing.T) {
- nativeCalls := 0
+ var nativeCalls atomic.Int32
client := checkpointRESTClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.URL.Path == "/v1/config" {
@@ -174,7 +176,7 @@ func TestCheckpointClientLifecycleUsesNativeRESTUnderTargetLease(t *testing.T) {
}
return
}
- nativeCalls++
+ nativeCalls.Add(1)
if r.Method != http.MethodPost || r.URL.Path != "/v1/boxes/target/"+action {
t.Errorf("unexpected lifecycle request: %s %s", r.Method, r.URL)
}
@@ -212,12 +214,12 @@ func TestCheckpointClientLifecycleUsesNativeRESTUnderTargetLease(t *testing.T) {
if (err == nil) != (scenario == "success") {
t.Fatalf("%s: %v", scenario, err)
}
- wantNative := 1
+ wantNative := int32(1)
if scenario == "lookup-error" {
wantNative = 0
}
- if nativeCalls != wantNative {
- t.Fatalf("native lifecycle calls: got %d, want %d; result: %v", nativeCalls, wantNative, err)
+ if got := nativeCalls.Load(); got != wantNative {
+ t.Fatalf("native lifecycle calls: got %d, want %d; result: %v", got, wantNative, err)
}
})
}
@@ -347,21 +349,64 @@ func TestCheckpointNativeAdapterImport(t *testing.T) {
}
}
+func TestCheckpointClientExportKindAndSourceState(t *testing.T) {
+ for _, tc := range []struct{ kind, state, wantError string }{
+ {checkpoint.KindDisk, "running", "must be stopped"},
+ {checkpoint.KindFull, "stopped", "must be running"},
+ {checkpoint.KindFull, "running", ""},
+ {"invalid", "running", "invalid checkpoint kind"},
+ } {
+ t.Run(tc.kind+"/"+tc.state, func(t *testing.T) {
+ client := checkpointRESTClient(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/v1/config" {
+ _, _ = io.WriteString(w, `{"capabilities":{"export_enabled":true}}`)
+ return
+ }
+ if r.Method != http.MethodGet || tc.kind == "invalid" {
+ t.Errorf("unexpected request: %s %s", r.Method, r.URL)
+ }
+ _, _ = io.WriteString(w, checkpointWireBox("source", "source", tc.state, "alpine@sha256:"+strings.Repeat("a", 64)))
+ })
+ _, err := client.ExportCheckpoint(t.Context(), "source", t.TempDir(), tc.kind)
+ if tc.wantError != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) {
+ t.Fatalf("want error containing %q, got %v", tc.wantError, err)
+ }
+ return
+ }
+ // REST rejects IncludeMemory before issuing an export request. A disk
+ // export would POST to the server instead.
+ var nativeErr *sdk.Error
+ if !errors.As(err, &nativeErr) || nativeErr.Code != sdk.ErrUnsupported {
+ t.Fatalf("expected SDK to reject IncludeMemory over REST, got %v", err)
+ }
+ })
+ }
+}
+
func TestCheckpointClientExportThroughNativeREST(t *testing.T) {
- for _, scenario := range []string{"success", "lookup-error", "unrecorded-image", "export-error", "invalid-destination"} {
- t.Run(scenario, func(t *testing.T) {
+ for _, tc := range []struct{ scenario, kind, wantError string }{
+ {"disk", checkpoint.KindDisk, ""},
+ {"default disk", "", ""},
+ {"lookup-error", checkpoint.KindDisk, "native operation rejected"},
+ {"unrecorded-image", checkpoint.KindDisk, "requires a recorded SHA-256 image build"},
+ {"export-error", checkpoint.KindDisk, "native operation rejected"},
+ {"invalid-destination", checkpoint.KindDisk, "failed to create export directory"},
+ } {
+ t.Run(tc.scenario, func(t *testing.T) {
image := "alpine@sha256:" + strings.Repeat("a", 64)
client := checkpointRESTClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/v1/config":
_, _ = io.WriteString(w, `{"capabilities":{"export_enabled":true}}`)
- case scenario == "lookup-error" || (scenario == "export-error" && r.Method == http.MethodPost):
+ case tc.scenario == "lookup-error" || (tc.scenario == "export-error" && r.Method == http.MethodPost):
w.WriteHeader(http.StatusConflict)
_, _ = io.WriteString(w, `{"error":{"code":"invalid_state","message":"native operation rejected"}}`)
case r.Method == http.MethodGet:
selected := image
- if scenario == "unrecorded-image" {
+ if tc.scenario == "unrecorded-image" {
selected = "alpine:latest"
}
_, _ = io.WriteString(w, checkpointWireBox("source", "source", "stopped", selected))
@@ -373,20 +418,22 @@ func TestCheckpointClientExportThroughNativeREST(t *testing.T) {
}
})
destination := t.TempDir()
- if scenario == "invalid-destination" {
+ if tc.scenario == "invalid-destination" {
destination = filepath.Join(destination, "file")
if err := os.WriteFile(destination, []byte("existing file"), 0600); err != nil {
t.Fatal(err)
}
}
- path, pinned, err := client.ExportCheckpoint(context.Background(), "source", destination)
- if scenario == "success" {
- data, readErr := os.ReadFile(path)
- if err != nil || readErr != nil || string(data) != "captured disk" || pinned != image {
- t.Fatalf("export: %q %q %v %v", path, pinned, err, readErr)
+ result, err := client.ExportCheckpoint(t.Context(), "source", destination, tc.kind)
+ if tc.wantError != "" {
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) || result != (checkpoint.CaptureResult{}) {
+ t.Fatalf("expected %q and no result, got %+v, %v", tc.wantError, result, err)
}
- } else if err == nil {
- t.Fatal("native export failure was swallowed")
+ return
+ }
+ data, readErr := os.ReadFile(result.ArchivePath)
+ if err != nil || readErr != nil || filepath.Dir(result.ArchivePath) != destination || string(data) != "captured disk" || result.PinnedImage != image || result.MemorySizeBytes != nil {
+ t.Fatalf("export: %+v %v %v", result, err, readErr)
}
})
}
diff --git a/apps/runner/pkg/boxlite/checkpoint_import_test.go b/apps/runner/pkg/boxlite/checkpoint_import_test.go
index 67238b87d..010b9fa12 100644
--- a/apps/runner/pkg/boxlite/checkpoint_import_test.go
+++ b/apps/runner/pkg/boxlite/checkpoint_import_test.go
@@ -7,14 +7,17 @@ import (
"archive/tar"
"bytes"
"encoding/json"
+ "errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
+ "time"
"github.com/boxlite-ai/runner/pkg/checkpoint"
"github.com/klauspost/compress/zstd"
+ "golang.org/x/sys/unix"
)
func TestCheckpointImportManifestReplacesOnlyCloudIdentity(t *testing.T) {
@@ -65,22 +68,25 @@ func TestCheckpointImportManifestReplacesOnlyCloudIdentity(t *testing.T) {
}
func TestCheckpointImportCopiesTheOriginalTarTail(t *testing.T) {
+ const memory = `{"memory_size_bytes":4096,"directory":"memory"}`
for _, compressed := range []bool{false, true} {
t.Run(map[bool]string{false: "tar", true: "zstd"}[compressed], func(t *testing.T) {
var original bytes.Buffer
writer := tar.NewWriter(&original)
- manifest := []byte(`{"version":3,"image":"alpine:old","box_options":{"env":[],"rootfs":{"Image":"alpine:old"}}}`)
+ manifest := []byte(`{"version":8,"image":"alpine:old","box_options":{"env":[],"rootfs":{"Image":"alpine:old"}},"memory_checkpoint":` + memory + `}`)
if err := writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(manifest))}); err != nil {
t.Fatal(err)
}
if _, err := writer.Write(manifest); err != nil {
t.Fatal(err)
}
- if err := writer.WriteHeader(&tar.Header{Name: "disk.qcow2", Mode: 0600, Size: 4}); err != nil {
- t.Fatal(err)
- }
- if _, err := writer.Write([]byte("disk")); err != nil {
- t.Fatal(err)
+ for _, name := range []string{"disk.qcow2", "memory/vm-memory"} {
+ if err := writer.WriteHeader(&tar.Header{Name: name, Mode: 0600, Size: int64(len(name))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := writer.Write([]byte(name)); err != nil {
+ t.Fatal(err)
+ }
}
if err := writer.Close(); err != nil {
t.Fatal(err)
@@ -99,7 +105,15 @@ func TestCheckpointImportCopiesTheOriginalTarTail(t *testing.T) {
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
- source := &checkpoint.DownloadedArchive{Path: path, Artifact: checkpoint.Artifact{PinnedImage: "alpine@sha256:" + strings.Repeat("a", 64)}}
+ size, err := readExportedCheckpointMemorySizeBytes(filepath.Dir(path), path)
+ if err != nil || size == nil || *size != 4096 {
+ t.Fatalf("memory size: %v %v", size, err)
+ }
+ source := &checkpoint.DownloadedArchive{Path: path, Artifact: checkpoint.Artifact{
+ Reference: checkpoint.Reference{Kind: checkpoint.KindFull},
+ PinnedImage: "alpine@sha256:" + strings.Repeat("a", 64),
+ MemorySizeBytes: size,
+ }}
adapted, err := checkpointImportArchive(source, map[string]string{"BOXLITE_BOX_ID": "target"})
if err != nil {
t.Fatal(err)
@@ -114,9 +128,13 @@ func TestCheckpointImportCopiesTheOriginalTarTail(t *testing.T) {
if err != nil || header.Name != "manifest.json" {
t.Fatalf("adapted manifest: %#v %v", header, err)
}
- if _, err := io.Copy(io.Discard, reader); err != nil {
+ var adaptedManifest map[string]json.RawMessage
+ if err := json.NewDecoder(reader).Decode(&adaptedManifest); err != nil {
t.Fatal(err)
}
+ if string(adaptedManifest["version"]) != "8" || string(adaptedManifest["memory_checkpoint"]) != memory {
+ t.Fatalf("adapted manifest lost version or memory metadata: %v", adaptedManifest)
+ }
if _, err := file.Seek(512+(header.Size+511)/512*512, io.SeekStart); err != nil {
t.Fatal(err)
}
@@ -125,7 +143,7 @@ func TestCheckpointImportCopiesTheOriginalTarTail(t *testing.T) {
t.Fatal(err)
}
if !bytes.Equal(copied, tail) {
- t.Fatal("disk tar bytes were re-encoded")
+ t.Fatal("disk or memory tar bytes were re-encoded")
}
retained, err := os.ReadFile(path)
if err != nil || !bytes.Equal(retained, data) {
@@ -135,6 +153,193 @@ func TestCheckpointImportCopiesTheOriginalTarTail(t *testing.T) {
}
}
+func TestCheckpointImportArchiveValidatesMemoryMetadata(t *testing.T) {
+ const (
+ zeroMemory = `,"memory_checkpoint":{"memory_size_bytes":0}`
+ fullMemory = `,"memory_checkpoint":{"memory_size_bytes":4096}`
+ nullMemory = `,"memory_checkpoint": null`
+ version8 = `,"version":8`
+ )
+ zero, full := int64(0), int64(4096)
+ for _, tc := range []struct {
+ name, fields, kind string
+ size *int64
+ wantError string
+ }{
+ {"legacy disk", "", "", nil, ""},
+ {"explicit disk with null memory", nullMemory, checkpoint.KindDisk, nil, ""},
+ {"disk with invalid version", `,"version":"8"`, checkpoint.KindDisk, nil, "invalid checkpoint manifest version"},
+ {"v8 without memory declared legacy disk", version8, "", nil, "disk checkpoint manifest must not use memory checkpoint archive version 8"},
+ {"v8 without memory declared explicit disk", version8, checkpoint.KindDisk, nil, "disk checkpoint manifest must not use memory checkpoint archive version 8"},
+ {"full with zero size", zeroMemory, checkpoint.KindFull, &zero, ""},
+ {"full with positive size", fullMemory, checkpoint.KindFull, &full, ""},
+ {"disk declared full", "", checkpoint.KindFull, &zero, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"null memory declared full", nullMemory, checkpoint.KindFull, &zero, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"full declared legacy disk", fullMemory, "", nil, "disk checkpoint manifest must not contain a non-null memory_checkpoint"},
+ {"full declared explicit disk", zeroMemory, checkpoint.KindDisk, nil, "disk checkpoint manifest must not contain a non-null memory_checkpoint"},
+ {"full with mismatched size", fullMemory, checkpoint.KindFull, &zero, "memory_size_bytes 4096 does not match artifact memorySizeBytes 0"},
+ {"full with missing declared size", fullMemory, checkpoint.KindFull, nil, "artifact is missing memorySizeBytes"},
+ {"full with negative manifest size", `,"memory_checkpoint":{"memory_size_bytes":-1}`, checkpoint.KindFull, &zero, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ manifest := `{"box_options":{"env":[]}` + tc.fields + `}`
+ var archive bytes.Buffer
+ writer := tar.NewWriter(&archive)
+ if err := writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(manifest))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(writer, manifest); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ path := filepath.Join(dir, "source.boxlite")
+ if err := os.WriteFile(path, archive.Bytes(), 0600); err != nil {
+ t.Fatal(err)
+ }
+ source := &checkpoint.DownloadedArchive{Path: path, Artifact: checkpoint.Artifact{
+ Reference: checkpoint.Reference{Kind: tc.kind},
+ PinnedImage: "alpine@sha256:" + strings.Repeat("a", 64),
+ MemorySizeBytes: tc.size,
+ }}
+ output, err := checkpointImportArchive(source, map[string]string{"BOXLITE_BOX_ID": "target"})
+ if tc.wantError == "" {
+ if err != nil || output == "" {
+ t.Fatalf("valid archive rejected: %q %v", output, err)
+ }
+ return
+ }
+ if err == nil || !strings.Contains(err.Error(), tc.wantError) || output != "" {
+ t.Errorf("want error containing %q and no output, got %q %v", tc.wantError, output, err)
+ }
+ files, err := filepath.Glob(filepath.Join(dir, "import-*.tar"))
+ if err != nil || len(files) != 0 {
+ t.Fatalf("unexpected temporary import files: %v %v", files, err)
+ }
+ })
+ }
+}
+
+func TestCheckpointExportMemorySizeValidatesArchivePath(t *testing.T) {
+ root := t.TempDir()
+ destDir := filepath.Join(root, "stage")
+ subDir := filepath.Join(destDir, "nested")
+ if err := os.MkdirAll(subDir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ const manifest = `{"memory_checkpoint":{"memory_size_bytes":4096}}`
+ var archive bytes.Buffer
+ writer := tar.NewWriter(&archive)
+ if err := writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(manifest))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(writer, manifest); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ valid := filepath.Join(destDir, "archive.boxlite")
+ outside := filepath.Join(root, "outside.boxlite")
+ nested := filepath.Join(subDir, "archive.boxlite")
+ for _, path := range []string{valid, outside, nested} {
+ if err := os.WriteFile(path, archive.Bytes(), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ link := filepath.Join(destDir, "link.boxlite")
+ if err := os.Symlink(outside, link); err != nil {
+ t.Fatal(err)
+ }
+ if size, err := readExportedCheckpointMemorySizeBytes(destDir, valid); err != nil || size == nil || *size != 4096 {
+ t.Fatalf("valid archive memory size: %v, %v", size, err)
+ }
+ for _, tc := range []struct{ name, path, wantError string }{
+ {"outside", outside, "outside its private directory"},
+ {"parent traversal", destDir + "/../outside.boxlite", "outside its private directory"},
+ {"nested", nested, "outside its private directory"},
+ {"traversal back inside", subDir + "/../archive.boxlite", "outside its private directory"},
+ {"directory", subDir, "must be a regular file"},
+ {"destination itself", destDir, "outside its private directory"},
+ {"mixed path types", "relative.boxlite", "outside its private directory"},
+ {"missing", filepath.Join(destDir, "missing.boxlite"), "checkpoint archive"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if size, err := readExportedCheckpointMemorySizeBytes(destDir, tc.path); err == nil || !strings.Contains(err.Error(), tc.wantError) || size != nil {
+ t.Fatalf("want path rejection %q before reading memory size, got %v, %v", tc.wantError, size, err)
+ }
+ })
+ }
+ if size, err := readExportedCheckpointMemorySizeBytes(destDir, link); !errors.Is(err, unix.ELOOP) || size != nil {
+ t.Errorf("expected no-follow open to reject a symlink, got %v, %v", size, err)
+ }
+ if retained, err := os.ReadFile(outside); err != nil || !bytes.Equal(retained, archive.Bytes()) {
+ t.Fatalf("outside archive removed or changed: %v", err)
+ }
+}
+
+func TestCheckpointExportMemorySizeRejectsFIFOWithoutWriter(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "export.boxlite")
+ if err := unix.Mkfifo(path, 0600); err != nil {
+ t.Fatal(err)
+ }
+ type result struct {
+ size *int64
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ size, err := readExportedCheckpointMemorySizeBytes(dir, path)
+ done <- result{size, err}
+ }()
+ select {
+ case got := <-done:
+ if got.err == nil || !strings.Contains(got.err.Error(), "must be a regular file") || got.size != nil {
+ t.Fatalf("expected FIFO rejection, got %v, %v", got.size, got.err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("reading exported checkpoint blocked on a FIFO with no writer")
+ }
+}
+
+func TestReadCheckpointMemorySizeBytesRejectsInvalidMetadata(t *testing.T) {
+ for _, tc := range []struct{ name, data, wantError string }{
+ {"invalid JSON", `{`, "unexpected end of JSON input"},
+ {"missing metadata", `{}`, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"invalid metadata", `{"memory_checkpoint":false}`, "invalid checkpoint manifest memory_checkpoint:"},
+ {"missing size", `{"memory_checkpoint":{}}`, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"null size", `{"memory_checkpoint":{"memory_size_bytes":null}}`, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"negative size", `{"memory_checkpoint":{"memory_size_bytes":-1}}`, "requires a nonnegative memory_checkpoint.memory_size_bytes"},
+ {"string size", `{"memory_checkpoint":{"memory_size_bytes":"1"}}`, "invalid checkpoint manifest memory_checkpoint.memory_size_bytes:"},
+ {"fractional size", `{"memory_checkpoint":{"memory_size_bytes":1.5}}`, "invalid checkpoint manifest memory_checkpoint.memory_size_bytes:"},
+ {"size overflow", `{"memory_checkpoint":{"memory_size_bytes":9223372036854775808}}`, "invalid checkpoint manifest memory_checkpoint.memory_size_bytes:"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var archive bytes.Buffer
+ writer := tar.NewWriter(&archive)
+ if err := writer.WriteHeader(&tar.Header{Name: "manifest.json", Mode: 0600, Size: int64(len(tc.data))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.WriteString(writer, tc.data); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(t.TempDir(), "source.boxlite")
+ if err := os.WriteFile(path, archive.Bytes(), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if size, err := readExportedCheckpointMemorySizeBytes(filepath.Dir(path), path); err == nil || !strings.Contains(err.Error(), tc.wantError) || size != nil {
+ t.Fatalf("want error containing %q, got %v, %v", tc.wantError, size, err)
+ }
+ })
+ }
+}
+
func TestCheckpointImportArchiveRejectsDamagedPrefixAndCleansPartialOutput(t *testing.T) {
manifest := []byte(`{"box_options":{"env":[]}}`)
prefix := func(name string, size int64, data []byte) []byte {
@@ -180,6 +385,11 @@ func TestCheckpointImportArchiveRejectsDamagedPrefixAndCleansPartialOutput(t *te
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
+ if name == "short magic" || name == "short header" {
+ if size, err := readExportedCheckpointMemorySizeBytes(dir, path); size != nil || !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
+ t.Fatalf("expected truncated export error, got %v, %v", size, err)
+ }
+ }
source := &checkpoint.DownloadedArchive{Path: path, Artifact: checkpoint.Artifact{PinnedImage: "alpine@sha256:" + strings.Repeat("a", 64)}}
if output, err := checkpointImportArchive(source, map[string]string{"BOXLITE_BOX_ID": "target"}); err == nil || output != "" {
t.Fatalf("damaged archive accepted: %q %v", output, err)
diff --git a/apps/runner/pkg/boxlite/checkpoint_native_test.go b/apps/runner/pkg/boxlite/checkpoint_native_test.go
index 6fbdd9cb9..db62c02b1 100644
--- a/apps/runner/pkg/boxlite/checkpoint_native_test.go
+++ b/apps/runner/pkg/boxlite/checkpoint_native_test.go
@@ -140,52 +140,52 @@ func TestCheckpointNativeRestoreKeepsFailedImportAndPersistsReplacement(t *testi
artifacts := checkpoint.Artifacts{Root: filepath.Join(home, "work", "archives")}
ref := checkpoint.Reference{CheckpointID: uuid.NewString(), ExportJobID: uuid.NewString(), SourceBoxID: target, ArcPath: "gs://archives/" + uuid.NewString() + ".boxlite"}
store := &nativeArchiveStore{}
- artifact, err := artifacts.Export(ctx, ref, func(ctx context.Context, dir string) (string, string, error) {
+ artifact, err := artifacts.Export(ctx, ref, func(ctx context.Context, dir string) (checkpoint.CaptureResult, error) {
path, err := original.Export(ctx, dir)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
data, err := os.ReadFile(path)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
if corrupt {
decoder, err := zstd.NewReader(nil)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
raw, err := decoder.DecodeAll(data, nil)
decoder.Close()
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
reader := tar.NewReader(bytes.NewReader(raw))
if _, err := reader.Next(); err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
manifest, err := io.ReadAll(reader)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
var metadata struct {
Checksum string `json:"container_disk_checksum"`
}
if err := json.Unmarshal(manifest, &metadata); err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
raw = bytes.Replace(raw, []byte(metadata.Checksum), []byte("sha256:"+strings.Repeat("0", 64)), 1)
encoder, err := zstd.NewWriter(nil)
if err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
data = encoder.EncodeAll(raw, nil)
encoder.Close()
if err := os.WriteFile(path, data, 0600); err != nil {
- return "", "", err
+ return checkpoint.CaptureResult{}, err
}
}
store.data = data
- return path, image, nil
+ return checkpoint.CaptureResult{ArchivePath: path, PinnedImage: image}, nil
})
original.Close()
if err != nil {
diff --git a/apps/runner/pkg/boxlite/client_checkpoint_cancel_test.go b/apps/runner/pkg/boxlite/client_checkpoint_cancel_test.go
index 862a089f7..1b7824de4 100644
--- a/apps/runner/pkg/boxlite/client_checkpoint_cancel_test.go
+++ b/apps/runner/pkg/boxlite/client_checkpoint_cancel_test.go
@@ -49,7 +49,7 @@ func TestCheckpointExportRejectsRunningSourceBeforeNativeExport(t *testing.T) {
}
client := &Client{runtime: runtime, homeDir: t.TempDir(), logger: slog.Default(), boxes: make(map[string]*sdk.Box)}
defer client.Close()
- _, _, err = client.ExportCheckpoint(context.Background(), "source", t.TempDir())
+ _, err = client.ExportCheckpoint(context.Background(), "source", t.TempDir(), "")
if exports.Load() != 0 {
t.Fatal("running source reached native export")
}
diff --git a/apps/runner/pkg/checkpoint/artifact_boundaries_test.go b/apps/runner/pkg/checkpoint/artifact_boundaries_test.go
index ed55e0bf2..9eecd3fc3 100644
--- a/apps/runner/pkg/checkpoint/artifact_boundaries_test.go
+++ b/apps/runner/pkg/checkpoint/artifact_boundaries_test.go
@@ -22,7 +22,7 @@ func TestCheckpointArtifactCancelledWaiterPreservesCaptureOwnership(t *testing.T
t.Cleanup(func() { close(release) })
done := make(chan error, 1)
go func() {
- _, err := artifacts.Export(t.Context(), ref, func(ctx context.Context, stage string) (string, string, error) {
+ _, err := artifacts.Export(t.Context(), ref, func(ctx context.Context, stage string) (CaptureResult, error) {
close(started)
<-release
return captureBytes("original capture")(ctx, stage)
@@ -60,14 +60,15 @@ func TestCheckpointArtifactRejectsInvalidExporterOutputs(t *testing.T) {
t.Run(scenario, func(t *testing.T) {
artifacts := Artifacts{Root: t.TempDir()}
ref := reference()
- _, err := artifacts.Export(t.Context(), ref, func(ctx context.Context, stage string) (string, string, error) {
- path, image, err := captureBytes("captured disk")(ctx, stage)
+ _, err := artifacts.Export(t.Context(), ref, func(ctx context.Context, stage string) (CaptureResult, error) {
+ result, err := captureBytes("captured disk")(ctx, stage)
if err != nil {
- return "", "", err
+ return CaptureResult{}, err
}
+ path := result.ArchivePath
switch scenario {
case "unpinned":
- image = "alpine:latest"
+ result.PinnedImage = "alpine:latest"
case "outside":
path = filepath.Join(filepath.Dir(stage), "outside.boxlite")
if err := os.WriteFile(path, []byte("outside"), 0600); err != nil {
@@ -106,7 +107,8 @@ func TestCheckpointArtifactRejectsInvalidExporterOutputs(t *testing.T) {
t.Fatal(err)
}
}
- return path, image, nil
+ result.ArchivePath = path
+ return result, nil
})
if err == nil {
t.Fatal("invalid capture was published")
diff --git a/apps/runner/pkg/checkpoint/artifacts.go b/apps/runner/pkg/checkpoint/artifacts.go
index e4067dc97..b3c93372f 100644
--- a/apps/runner/pkg/checkpoint/artifacts.go
+++ b/apps/runner/pkg/checkpoint/artifacts.go
@@ -22,26 +22,74 @@ import (
"golang.org/x/sys/unix"
)
+const (
+ KindDisk = "disk"
+ KindFull = "full"
+)
+
+func validKind(kind string) bool {
+ return kind == "" || kind == KindDisk || kind == KindFull
+}
+
// Reference identifies one capture, independently of subsequent source changes.
type Reference struct {
CheckpointID string `json:"checkpointId"`
ExportJobID string `json:"exportJobId"`
SourceBoxID string `json:"sourceBoxId"`
ArcPath string `json:"arcPath"`
+ Kind string `json:"kind,omitempty"`
+}
+
+func (r Reference) NormalizedKind() string {
+ if r.Kind == "" {
+ return KindDisk
+ }
+ return r.Kind
}
type Artifact struct {
Reference
- SizeBytes int64 `json:"sizeBytes"`
- SHA256 string `json:"sha256"`
- PinnedImage string `json:"pinnedImage"`
+ SizeBytes int64 `json:"sizeBytes"`
+ SHA256 string `json:"sha256"`
+ PinnedImage string `json:"pinnedImage"`
+ MemorySizeBytes *int64 `json:"memorySizeBytes,omitempty"`
+}
+
+func validateMemorySize(kind string, size *int64) error {
+ if kind == KindFull && (size == nil || *size < 0) {
+ return fmt.Errorf("full checkpoint requires a nonnegative memorySizeBytes")
+ }
+ if kind == KindDisk && size != nil {
+ return fmt.Errorf("disk checkpoint must not include memorySizeBytes")
+ }
+ return nil
+}
+
+func referencesEqual(a, b Reference) bool {
+ a.Kind, b.Kind = a.NormalizedKind(), b.NormalizedKind()
+ return a == b
+}
+
+func artifactsEqual(a, b Artifact) bool {
+ if !referencesEqual(a.Reference, b.Reference) || a.SizeBytes != b.SizeBytes || a.SHA256 != b.SHA256 || a.PinnedImage != b.PinnedImage {
+ return false
+ }
+ if a.MemorySizeBytes == nil || b.MemorySizeBytes == nil {
+ return a.MemorySizeBytes == nil && b.MemorySizeBytes == nil
+ }
+ return *a.MemorySizeBytes == *b.MemorySizeBytes
}
type Artifacts struct{ Root string }
-// Capture writes into its private directory and returns the actual archive
-// path and the digest-pinned image associated with the source disk.
-type Capture func(context.Context, string) (archive, pinnedImage string, err error)
+type CaptureResult struct {
+ ArchivePath string
+ PinnedImage string
+ MemorySizeBytes *int64
+}
+
+// Capture writes an archive into its private directory and returns its metadata.
+type Capture func(context.Context, string) (CaptureResult, error)
func (a Artifacts) Export(ctx context.Context, ref Reference, capture Capture) (Artifact, error) {
directory, unlock, err := a.lock(ctx, ref)
@@ -79,10 +127,14 @@ func (a Artifacts) Export(ctx context.Context, ref Reference, capture Capture) (
return Artifact{}, err
}
defer os.RemoveAll(stage)
- archive, image, err := capture(ctx, stage)
+ result, err := capture(ctx, stage)
if err != nil {
return Artifact{}, err
}
+ if err := validateMemorySize(ref.NormalizedKind(), result.MemorySizeBytes); err != nil {
+ return Artifact{}, err
+ }
+ archive, image := result.ArchivePath, result.PinnedImage
if !pinnedImage(image) {
return Artifact{}, fmt.Errorf("checkpoint capture did not supply a SHA-256 pinned image")
}
@@ -111,7 +163,7 @@ func (a Artifacts) Export(ctx context.Context, ref Reference, capture Capture) (
if err != nil {
return Artifact{}, err
}
- record := Artifact{Reference: ref, SizeBytes: size, SHA256: digest, PinnedImage: image}
+ record := Artifact{Reference: ref, SizeBytes: size, SHA256: digest, PinnedImage: image, MemorySizeBytes: result.MemorySizeBytes}
if size == 0 {
return Artifact{}, fmt.Errorf("checkpoint archive is empty")
}
@@ -133,7 +185,7 @@ func (a Artifacts) Upload(ctx context.Context, expected Artifact, store storage.
if err != nil {
return Artifact{}, err
}
- if record != expected {
+ if !artifactsEqual(record, expected) {
return Artifact{}, fmt.Errorf("checkpoint upload metadata does not match its captured artifact")
}
if err := a.verify(directory, record); err != nil {
@@ -158,7 +210,7 @@ func (a Artifacts) Acknowledge(ctx context.Context, expected Artifact) error {
if err != nil {
return err
}
- if record != expected {
+ if !artifactsEqual(record, expected) {
return fmt.Errorf("checkpoint cleanup metadata does not match its captured artifact")
}
if err := os.Remove(filepath.Join(directory, "archive.boxlite")); err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -170,6 +222,9 @@ func (a Artifacts) Acknowledge(ctx context.Context, expected Artifact) error {
}
func validateReference(ref Reference) error {
+ if !validKind(ref.Kind) {
+ return fmt.Errorf("invalid checkpoint kind %q", ref.Kind)
+ }
for _, id := range []string{ref.CheckpointID, ref.ExportJobID} {
parsed, err := uuid.Parse(id)
if err != nil || parsed.String() != id {
@@ -294,9 +349,12 @@ func (a Artifacts) read(directory string, expected Reference) (Artifact, error)
if err := json.Unmarshal(bytes, &record); err != nil {
return Artifact{}, err
}
- if record.Reference != expected || record.SizeBytes <= 0 || !sha256Digest(record.SHA256) || !pinnedImage(record.PinnedImage) {
+ if !referencesEqual(record.Reference, expected) || record.SizeBytes <= 0 || !sha256Digest(record.SHA256) || !pinnedImage(record.PinnedImage) {
return Artifact{}, fmt.Errorf("checkpoint artifact metadata does not match its owner or format")
}
+ if err := validateMemorySize(record.NormalizedKind(), record.MemorySizeBytes); err != nil {
+ return Artifact{}, err
+ }
return record, nil
}
diff --git a/apps/runner/pkg/checkpoint/artifacts_test.go b/apps/runner/pkg/checkpoint/artifacts_test.go
index b009bc0fe..3afd66e67 100644
--- a/apps/runner/pkg/checkpoint/artifacts_test.go
+++ b/apps/runner/pkg/checkpoint/artifacts_test.go
@@ -38,7 +38,7 @@ func TestCheckpointArtifactDurabilityFailurePreventsCapture(t *testing.T) {
root = filepath.Join(parent, "new", "archives")
}
captured := false
- _, err := (Artifacts{Root: root}).Export(context.Background(), reference(), func(ctx context.Context, path string) (string, string, error) {
+ _, err := (Artifacts{Root: root}).Export(context.Background(), reference(), func(ctx context.Context, path string) (CaptureResult, error) {
captured = true
return captureBytes("must not capture before parent durability")(ctx, path)
})
@@ -53,9 +53,9 @@ func TestCheckpointArtifactDurabilityFailurePreventsCapture(t *testing.T) {
}
func captureBytes(data string) Capture {
- return func(_ context.Context, directory string) (string, string, error) {
+ return func(_ context.Context, directory string) (CaptureResult, error) {
path := filepath.Join(directory, "source.boxlite")
- return path, "registry:5000/app@sha256:" + strings.Repeat("a", 64), os.WriteFile(path, []byte(data), 0600)
+ return CaptureResult{ArchivePath: path, PinnedImage: "registry:5000/app@sha256:" + strings.Repeat("a", 64)}, os.WriteFile(path, []byte(data), 0600)
}
}
@@ -70,9 +70,9 @@ func mustExport(t *testing.T, artifacts Artifacts, ref Reference, capture Captur
func noCapture(t *testing.T) Capture {
t.Helper()
- return func(context.Context, string) (string, string, error) {
+ return func(context.Context, string) (CaptureResult, error) {
t.Error("source must not be captured again")
- return "", "", errors.New("unexpected capture")
+ return CaptureResult{}, errors.New("unexpected capture")
}
}
@@ -117,6 +117,7 @@ func TestCheckpointArtifactReplayDoesNotReadTheSource(t *testing.T) {
artifacts := Artifacts{Root: t.TempDir()}
ref := reference()
first := mustExport(t, artifacts, ref, captureBytes(t.Name()))
+ ref.Kind = KindDisk // Explicit disk and legacy omitted kind identify the same capture.
second := mustExport(t, Artifacts{Root: artifacts.Root}, ref, noCapture(t))
if second != first {
t.Fatalf("replay changed the artifact: %#v != %#v", second, first)
@@ -205,9 +206,9 @@ func TestCheckpointArtifactConcurrentRedeliveryCapturesOnlyOnce(t *testing.T) {
ref := reference()
entered, resume := make(chan struct{}), make(chan struct{})
var count atomic.Int32
- capture := func(ctx context.Context, path string) (string, string, error) {
+ capture := func(ctx context.Context, path string) (CaptureResult, error) {
if count.Add(1) != 1 {
- return "", "", errors.New("duplicate capture")
+ return CaptureResult{}, errors.New("duplicate capture")
}
close(entered)
<-resume
@@ -282,11 +283,11 @@ func TestCheckpointArtifactMissingOrCorruptFilesNeverRecaptureOrUpload(t *testin
func TestCheckpointArtifactFailedCaptureIsNotRepeatedAfterRestart(t *testing.T) {
artifacts := Artifacts{Root: t.TempDir()}
ref := reference()
- _, err := artifacts.Export(context.Background(), ref, func(_ context.Context, path string) (string, string, error) {
+ _, err := artifacts.Export(context.Background(), ref, func(_ context.Context, path string) (CaptureResult, error) {
if err := os.WriteFile(filepath.Join(path, "partial.boxlite"), []byte("partial"), 0600); err != nil {
t.Fatal(err)
}
- return "", "", errors.New("capture failed after writing")
+ return CaptureResult{}, errors.New("capture failed after writing")
})
if err == nil {
t.Fatal("capture unexpectedly succeeded")
@@ -335,6 +336,84 @@ func TestCheckpointPinsOnlyTheSourcesRecordedBuild(t *testing.T) {
}
}
+func TestFullCheckpointArtifactUploadAndAcknowledge(t *testing.T) {
+ for _, size := range []int64{0, 4096} {
+ t.Run(fmt.Sprint(size), func(t *testing.T) {
+ artifacts, ref := Artifacts{Root: t.TempDir()}, reference()
+ ref.Kind = KindFull
+ record := mustExport(t, artifacts, ref, func(ctx context.Context, dir string) (CaptureResult, error) {
+ result, err := captureBytes("archive")(ctx, dir)
+ result.MemorySizeBytes = &size
+ return result, err
+ })
+ if record.Kind != KindFull || record.MemorySizeBytes == nil || *record.MemorySizeBytes != size {
+ t.Fatalf("incorrect export metadata: %+v", record)
+ }
+ replayed := mustExport(t, Artifacts{Root: artifacts.Root}, ref, noCapture(t))
+ if replayed.MemorySizeBytes == record.MemorySizeBytes || !artifactsEqual(replayed, record) {
+ t.Fatalf("full replay should return equal metadata without recapturing: %+v != %+v", replayed, record)
+ }
+ store := &transferStore{}
+ wrong := record
+ other := size + 1
+ wrong.MemorySizeBytes = &other
+ if _, err := artifacts.Upload(t.Context(), wrong, store); err == nil {
+ t.Fatal("upload accepted a different memory size")
+ }
+ if err := artifacts.Acknowledge(t.Context(), wrong); err == nil {
+ t.Fatal("acknowledgment accepted a different memory size")
+ }
+ uploaded, err := artifacts.Upload(t.Context(), record, store)
+ if err != nil || uploaded.MemorySizeBytes == record.MemorySizeBytes || !artifactsEqual(uploaded, record) {
+ t.Fatalf("upload should compare memory size by value: %+v %v", uploaded, err)
+ }
+ if string(store.uploaded[ref.ArcPath]) != "archive" {
+ t.Fatal("upload did not transfer the captured bytes")
+ }
+ if err := artifacts.Acknowledge(t.Context(), record); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(artifacts.Root, ref.CheckpointID, ref.ExportJobID, "archive.boxlite")
+ if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("acknowledgment did not remove the archive: %v", err)
+ }
+ })
+ }
+}
+
+func TestCheckpointArtifactRejectsInvalidMemoryMetadata(t *testing.T) {
+ negative, zero := int64(-1), int64(0)
+ for _, tc := range []struct {
+ name, kind string
+ size *int64
+ }{
+ {"missing", KindFull, nil},
+ {"negative", KindFull, &negative},
+ {"disk", KindDisk, &zero},
+ {"legacy disk", "", &zero},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ artifacts, ref := Artifacts{Root: t.TempDir()}, reference()
+ ref.Kind = tc.kind
+ if _, err := artifacts.Export(t.Context(), ref, func(ctx context.Context, dir string) (CaptureResult, error) {
+ result, err := captureBytes("archive")(ctx, dir)
+ result.MemorySizeBytes = tc.size
+ return result, err
+ }); err == nil || !strings.Contains(err.Error(), "memorySizeBytes") {
+ t.Fatalf("export validation: %v", err)
+ }
+ directory := filepath.Join(artifacts.Root, ref.CheckpointID, ref.ExportJobID)
+ record := Artifact{Reference: ref, SizeBytes: 1, SHA256: strings.Repeat("a", 64), PinnedImage: "alpine@sha256:" + strings.Repeat("a", 64), MemorySizeBytes: tc.size}
+ if err := writeRecord(directory, record); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := artifacts.read(directory, ref); err == nil || !strings.Contains(err.Error(), "memorySizeBytes") {
+ t.Fatalf("record validation: %v", err)
+ }
+ })
+ }
+}
+
func TestCheckpointArtifactRefusesUploadOwnershipChanges(t *testing.T) {
artifacts := Artifacts{Root: t.TempDir()}
record := mustExport(t, artifacts, reference(), captureBytes(t.Name()))
diff --git a/apps/runner/pkg/checkpoint/restore.go b/apps/runner/pkg/checkpoint/restore.go
index dc1001acc..9ba8c9867 100644
--- a/apps/runner/pkg/checkpoint/restore.go
+++ b/apps/runner/pkg/checkpoint/restore.go
@@ -21,10 +21,19 @@ type RestoreRequest struct {
Sequence int64 `json:"targetSequence"`
Target string `json:"targetBoxId"`
Mode string `json:"mode"`
+ Kind string `json:"kind,omitempty"`
Archive Artifact `json:"archive"`
PlatformEnv map[string]string `json:"platformEnv"`
}
+func (r RestoreRequest) withNormalizedKinds() RestoreRequest {
+ r.Archive.Kind = r.Archive.NormalizedKind()
+ if r.Kind == "" {
+ r.Kind = r.Archive.Kind
+ }
+ return r
+}
+
func (r RestoreRequest) validate() error {
id, err := uuid.Parse(r.OperationID)
if err != nil || id.String() != r.OperationID || r.Sequence <= 0 || r.Sequence > 1<<53-1 || r.Target == "" {
@@ -36,6 +45,12 @@ func (r RestoreRequest) validate() error {
if err := validateReference(r.Archive.Reference); err != nil {
return err
}
+ if !validKind(r.Kind) || (r.Kind != "" && r.Kind != r.Archive.NormalizedKind()) {
+ return fmt.Errorf("invalid checkpoint restore kind %q for archive kind %q", r.Kind, r.Archive.Kind)
+ }
+ if err := validateMemorySize(r.Archive.NormalizedKind(), r.Archive.MemorySizeBytes); err != nil {
+ return err
+ }
if r.Archive.SizeBytes <= 0 || !sha256Digest(r.Archive.SHA256) || !pinnedImage(r.Archive.PinnedImage) {
return fmt.Errorf("invalid checkpoint operation archive")
}
@@ -135,7 +150,7 @@ func (r Restorer) restore(ctx context.Context, lease *TargetLease, request Resto
return RestoreResult{}, fmt.Errorf("stale checkpoint operation")
}
if request.OperationID == previous.OperationID {
- if !reflect.DeepEqual(request, previous) || record.Stage == "invalidated" {
+ if !reflect.DeepEqual(request.withNormalizedKinds(), previous.withNormalizedKinds()) || record.Stage == "invalidated" {
return RestoreResult{}, fmt.Errorf("checkpoint operation changed or was invalidated")
}
} else {
diff --git a/apps/runner/pkg/checkpoint/restore_test.go b/apps/runner/pkg/checkpoint/restore_test.go
index bf0acf67a..4f80eb78b 100644
--- a/apps/runner/pkg/checkpoint/restore_test.go
+++ b/apps/runner/pkg/checkpoint/restore_test.go
@@ -22,6 +22,7 @@ type recoveryNative struct {
current *NativeBox
importErr error
commitThenErr bool
+ importState string
removes int
imports int
candidates map[string]*NativeBox
@@ -99,7 +100,11 @@ func (n *recoveryNative) Import(ctx context.Context, source *DownloadedArchive,
if n.importErr != nil && !n.commitThenErr {
return "", n.importErr
}
- candidate := &NativeBox{ID: uuid.NewString(), State: "stopped"}
+ state := n.importState
+ if state == "" {
+ state = "stopped"
+ }
+ candidate := &NativeBox{ID: uuid.NewString(), State: state}
n.candidates[name] = candidate
if n.current == nil {
n.current = candidate
@@ -121,6 +126,120 @@ func recoveryHarness(t *testing.T) (Restorer, RestoreRequest, *recoveryNative, *
return Restorer{Operations: operations, Artifacts: artifacts, Store: store, Backend: native}, request, native, store
}
+func TestCheckpointRestoreKindValidation(t *testing.T) {
+ _, request, _, _ := recoveryHarness(t)
+ zero, negative := int64(0), int64(-1)
+ for _, tc := range []struct {
+ kind, archiveKind string
+ size *int64
+ valid bool
+ }{
+ {"", "", nil, true},
+ {KindDisk, "", nil, true},
+ {KindFull, KindFull, &zero, true},
+ {"", KindFull, &zero, true},
+ {"invalid", "", nil, false},
+ {"", "invalid", nil, false},
+ {KindDisk, KindFull, &zero, false},
+ {KindFull, KindDisk, nil, false},
+ {KindFull, "", nil, false},
+ {KindFull, KindFull, nil, false},
+ {KindFull, KindFull, &negative, false},
+ {"", KindDisk, &zero, false},
+ } {
+ request.Kind, request.Archive.Kind, request.Archive.MemorySizeBytes = tc.kind, tc.archiveKind, tc.size
+ if err := request.validate(); (err == nil) != tc.valid {
+ t.Errorf("validate(%+v): %v", tc, err)
+ }
+ }
+}
+
+func TestCheckpointRestoreRejectsConfiguredCandidateAndPredecessor(t *testing.T) {
+ t.Run("candidate after lost receipt", func(t *testing.T) {
+ r, request, native, _ := recoveryHarness(t)
+ predecessor := native.current.ID
+ native.importState, native.commitThenErr = "configured", true
+ native.importErr = errors.New("lost import receipt")
+ if _, err := r.Restore(t.Context(), request, uuid.NewString()); !errors.Is(err, native.importErr) {
+ t.Fatalf("expected first attempt to lose the import receipt, got %v", err)
+ }
+ if _, err := r.Restore(t.Context(), request, uuid.NewString()); err == nil || err.Error() != "checkpoint import returned an invalid native identity" {
+ t.Fatalf("expected retry to reject the configured candidate, got %v", err)
+ }
+ published, err := r.Operations.Resolve(request.Target)
+ if err != nil || published != request.Target {
+ t.Fatalf("retry changed the public mapping: %q, %v", published, err)
+ }
+ if native.imports != 1 || native.removes != 0 || native.current == nil || native.current.ID != predecessor {
+ t.Fatal("retry reimported the candidate or removed the predecessor")
+ }
+ })
+ t.Run("recovery predecessor", func(t *testing.T) {
+ r, request, native, _ := recoveryHarness(t)
+ predecessor := native.current
+ predecessor.State = "configured"
+ if _, err := r.Restore(t.Context(), request, uuid.NewString()); err == nil || err.Error() != "checkpoint recovery requires a stopped or failed target" {
+ t.Fatalf("expected recovery to reject the configured predecessor, got %v", err)
+ }
+ if native.imports != 0 || native.removes != 0 || native.current != predecessor {
+ t.Fatal("recovery imported a candidate or removed the predecessor")
+ }
+ })
+}
+
+func TestCheckpointRestoreRetryNormalizesDiskKinds(t *testing.T) {
+ for _, tc := range []struct {
+ name, firstKind, retryKind string
+ }{
+ {"legacy to explicit disk", "", KindDisk},
+ {"explicit disk to legacy", KindDisk, ""},
+ {"disk to full", KindDisk, KindFull},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r, request, native, _ := recoveryHarness(t)
+ request.Kind, request.Archive.Kind = tc.firstKind, tc.firstKind
+ first, err := r.Restore(t.Context(), request, uuid.NewString())
+ if err != nil {
+ t.Fatal(err)
+ }
+ retry := request
+ retry.Kind, retry.Archive.Kind = tc.retryKind, tc.retryKind
+ if tc.retryKind == KindFull {
+ zero := int64(0)
+ retry.Archive.MemorySizeBytes = &zero
+ }
+ got, err := r.Restore(t.Context(), retry, uuid.NewString())
+ if tc.retryKind == KindFull {
+ if err == nil || err.Error() != "checkpoint operation changed or was invalidated" {
+ t.Fatalf("retry changing disk to full: got %+v, %v", got, err)
+ }
+ } else if err != nil || got != first {
+ t.Fatalf("retry: got %+v, %v; want original result %+v", got, err, first)
+ }
+ if native.imports != 1 || native.removes != 1 {
+ t.Fatalf("retry repeated native work: %d imports, %d removals", native.imports, native.removes)
+ }
+ })
+ }
+}
+
+func TestCheckpointRestoreFullRetryComparesMemorySizeByValue(t *testing.T) {
+ r, request, native, _ := recoveryHarness(t)
+ size := int64(4096)
+ request.Kind, request.Archive.Kind, request.Archive.MemorySizeBytes = KindFull, KindFull, &size
+ native.importErr = errors.New("transient import failure")
+ if _, err := r.Restore(t.Context(), request, uuid.NewString()); err == nil {
+ t.Fatal("expected transient import failure")
+ }
+ retry := request
+ sameSize := int64(4096)
+ retry.Archive.MemorySizeBytes = &sameSize
+ native.importErr = nil
+ if _, err := r.Restore(t.Context(), retry, uuid.NewString()); err != nil {
+ t.Fatalf("full checkpoint retry with equal memorySizeBytes failed: %v", err)
+ }
+}
+
func TestCheckpointRestoreImportFailurePreservesPredecessor(t *testing.T) {
r, request, native, _ := recoveryHarness(t)
predecessor := native.current.ID
diff --git a/apps/runner/pkg/runner/v2/executor/checkpoint.go b/apps/runner/pkg/runner/v2/executor/checkpoint.go
index 4d810dd68..acce9f5f5 100644
--- a/apps/runner/pkg/runner/v2/executor/checkpoint.go
+++ b/apps/runner/pkg/runner/v2/executor/checkpoint.go
@@ -16,6 +16,7 @@ import (
type ExportCheckpointPayload struct {
CheckpointID string `json:"checkpointId"`
ArcPath string `json:"arcPath"`
+ Kind string `json:"kind,omitempty"`
}
func (e *Executor) checkpointSetup(arcPath string) (checkpoint.Artifacts, error) {
@@ -38,6 +39,11 @@ func (e *Executor) exportCheckpoint(ctx context.Context, job *apiclient.Job) (an
if err := e.parsePayload(job.Payload, &payload); err != nil {
return nil, err
}
+ ref := checkpoint.Reference{CheckpointID: payload.CheckpointID, ExportJobID: job.Id, SourceBoxID: job.ResourceId, ArcPath: payload.ArcPath, Kind: payload.Kind}
+ kind := ref.NormalizedKind()
+ if kind != checkpoint.KindDisk && kind != checkpoint.KindFull {
+ return nil, fmt.Errorf("invalid checkpoint kind %q", payload.Kind)
+ }
artifacts, err := e.checkpointSetup(payload.ArcPath)
if err != nil {
return nil, err
@@ -46,9 +52,8 @@ func (e *Executor) exportCheckpoint(ctx context.Context, job *apiclient.Job) (an
if !ok {
return nil, fmt.Errorf("backend does not support checkpoint export")
}
- ref := checkpoint.Reference{CheckpointID: payload.CheckpointID, ExportJobID: job.Id, SourceBoxID: job.ResourceId, ArcPath: payload.ArcPath}
- return artifacts.Export(ctx, ref, func(ctx context.Context, directory string) (string, string, error) {
- return exporter.ExportCheckpoint(ctx, job.ResourceId, directory)
+ return artifacts.Export(ctx, ref, func(ctx context.Context, directory string) (checkpoint.CaptureResult, error) {
+ return exporter.ExportCheckpoint(ctx, job.ResourceId, directory, kind)
})
}
diff --git a/apps/runner/pkg/runner/v2/executor/checkpoint_test.go b/apps/runner/pkg/runner/v2/executor/checkpoint_test.go
index 4dae407bc..3d30d7310 100644
--- a/apps/runner/pkg/runner/v2/executor/checkpoint_test.go
+++ b/apps/runner/pkg/runner/v2/executor/checkpoint_test.go
@@ -25,7 +25,7 @@ import (
type checkpointBackend struct {
*fakeBackend
- capture func(context.Context, string, string) (string, string, error)
+ capture func(context.Context, string, string, string) (checkpoint.CaptureResult, error)
restore func(context.Context, checkpoint.RestoreRequest, string, checkpoint.Artifacts, storage.ArchiveStore) (checkpoint.RestoreResult, error)
start func()
}
@@ -63,12 +63,12 @@ func TestCheckpointDeleteAcceptsAnAlreadyAbsentNativeTarget(t *testing.T) {
}
}
-func (b *checkpointBackend) ExportCheckpoint(ctx context.Context, boxID, directory string) (string, string, error) {
+func (b *checkpointBackend) ExportCheckpoint(ctx context.Context, boxID, directory, kind string) (checkpoint.CaptureResult, error) {
if b.capture != nil {
- return b.capture(ctx, boxID, directory)
+ return b.capture(ctx, boxID, directory, kind)
}
archive, err := b.fakeBackend.ExportBox(ctx, boxID, directory)
- return archive, "example/app@sha256:" + strings.Repeat("a", 64), err
+ return checkpoint.CaptureResult{ArchivePath: archive, PinnedImage: "example/app@sha256:" + strings.Repeat("a", 64)}, err
}
func (b *checkpointBackend) Start(context.Context, string, *string, map[string]string) (string, error) {
@@ -136,17 +136,53 @@ func TestCheckpointExportReportsAnArtifactWithoutUploadingOrStopping(t *testing.
}
}
+func TestCheckpointExportKind(t *testing.T) {
+ for _, kind := range []string{checkpoint.KindFull, "invalid"} {
+ t.Run(kind, func(t *testing.T) {
+ h, backend, job := checkpointHarness(t)
+ payload := ExportCheckpointPayload{CheckpointID: uuid.NewString(), ArcPath: "gs://bucket/checkpoints/full.boxlite", Kind: kind}
+ data, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ job.SetPayload(string(data))
+ backend.capture = func(ctx context.Context, source, directory, gotKind string) (checkpoint.CaptureResult, error) {
+ if source != job.ResourceId || gotKind != checkpoint.KindFull || kind != checkpoint.KindFull {
+ t.Fatalf("unexpected capture: %q %q", source, gotKind)
+ }
+ archive, err := backend.fakeBackend.ExportBox(ctx, source, directory)
+ zero := int64(0)
+ return checkpoint.CaptureResult{ArchivePath: archive, PinnedImage: "example/app@sha256:" + strings.Repeat("a", 64), MemorySizeBytes: &zero}, err
+ }
+ if kind != checkpoint.KindFull {
+ if _, err := h.executor.exportCheckpoint(t.Context(), job); err == nil || !strings.Contains(err.Error(), "invalid checkpoint kind") {
+ t.Fatalf("invalid kind: %v", err)
+ }
+ return
+ }
+ h.executor.Execute(t.Context(), job)
+ artifact := capturedArtifact(t, h, job)
+ if artifact.Kind != kind || artifact.MemorySizeBytes == nil || *artifact.MemorySizeBytes != 0 {
+ t.Fatalf("missing result metadata: %+v", artifact)
+ }
+ })
+ }
+}
+
func TestCheckpointExportCancellationBeforeLateNativeResultKeepsTheArchive(t *testing.T) {
h, backend, job := checkpointHarness(t)
entered, resume := make(chan struct{}), make(chan struct{})
- backend.capture = func(ctx context.Context, source, directory string) (string, string, error) {
+ backend.capture = func(ctx context.Context, source, directory, kind string) (checkpoint.CaptureResult, error) {
+ if kind != checkpoint.KindDisk {
+ t.Errorf("omitted kind was not normalized: %q", kind)
+ }
close(entered)
<-resume
if ctx.Err() != nil {
- return "", "", errors.New("native export received cancellation")
+ return checkpoint.CaptureResult{}, errors.New("native export received cancellation")
}
archive, err := backend.fakeBackend.ExportBox(ctx, source, directory)
- return archive, "example/app@sha256:" + strings.Repeat("b", 64), err
+ return checkpoint.CaptureResult{ArchivePath: archive, PinnedImage: "example/app@sha256:" + strings.Repeat("b", 64)}, err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()