Skip to content

An open-source, faster Devin alternative

TypeScript

fix migration issue

Brian Reardonf8bb8a69c0d9
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 33a4a504..226cbf4c 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/controlplane"
@@ -422,6 +423,15 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID
// The UUID is plumbed back to CreateSandboxSession so sandbox_sessions.
// secret_store_id gets populated — required for the secret-refresh fanout
// (ListRunningSandboxesByStore filters on this column).
+// ErrSecretStoreNotFound is returned by resolveSecretStoreInto when the named
+// secret store genuinely does not exist — as opposed to a transient lookup or
+// decrypt failure. The fork path matches it with errors.Is to skip a
+// checkpoint-inherited store that has since been deleted, rather than failing
+// the whole fork (see layerSecretStores). Its message is kept as the bare
+// "secret store not found" so the "%w: <name>" wrap reproduces the existing
+// public API error string for a genuinely-missing store.
+var ErrSecretStoreNotFound = errors.New("secret store not found")
+
func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig) (*uuid.UUID, error) {
if cfg.SecretStore == "" {
return nil, nil
@@ -435,7 +445,7 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg
bundle, err := s.edge.LookupSecretStore(ctx, uuid.UUID(orgID), cfg.SecretStore, s.store.Encryptor())
if err != nil {
if errors.Is(err, edgeclient.ErrNotFound) {
- return nil, fmt.Errorf("secret store not found: %s", cfg.SecretStore)
+ return nil, fmt.Errorf("%w: %s", ErrSecretStoreNotFound, cfg.SecretStore)
}
return nil, fmt.Errorf("edge lookup secret store %q: %w", cfg.SecretStore, err)
}
@@ -451,7 +461,13 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg
}
store, err := s.store.GetSecretStoreByName(ctx, orgID, cfg.SecretStore)
if err != nil {
- return nil, fmt.Errorf("secret store not found: %s", cfg.SecretStore)
+ // Only a genuine no-rows result is "not found" — a transient DB error
+ // must stay loud, not be misread as a deleted store (which the fork
+ // path would then silently skip, dropping the store's secrets).
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, fmt.Errorf("%w: %s", ErrSecretStoreNotFound, cfg.SecretStore)
+ }
+ return nil, fmt.Errorf("resolve secret store %q: %w", cfg.SecretStore, err)
}
cfg.EgressAllowlist = store.EgressAllowlist
@@ -478,6 +494,94 @@ func (s *Server) resolveSecretStoreInto(ctx context.Context, orgID [16]byte, cfg
return &store.ID, nil
}
+// layerForkSecretStores resolves the secret stores a fork should apply, in
+// layering order: the checkpoint-inherited base store, the checkpoint-inherited
+// child store, then the caller-supplied store. Later layers win on env
+// collisions and egress allowlists aggregate. It decrypts each store into cfg
+// (SecretEnvs/EgressAllowlist/SecretAllowedHosts) and returns the UUID of the
+// winning (last surviving) store for sandbox_sessions.secret_store_id.
+//
+// A checkpoint-inherited store that no longer exists is skipped rather than
+// failing the fork: a checkpoint is an immutable image and must not be bricked
+// by the deletion of an ephemeral build-time secret store. A store the CALLER
+// named in this request must still exist — a missing user-supplied store is a
+// hard error, honoring explicit intent. cfg.SecretStore/BaseSecretStore are
+// rewritten to the surviving stores so the forked child's persisted config no
+// longer references a deleted store (the binding self-heals forward).
+func (s *Server) layerForkSecretStores(ctx context.Context, orgID [16]byte, cfg *types.SandboxConfig, userStore string) (*uuid.UUID, error) {
+ // Capture the inherited layers before the resolver mutates cfg.SecretStore.
+ return layerSecretStores(cfg, cfg.BaseSecretStore, cfg.SecretStore, userStore,
+ func(name string) (*uuid.UUID, error) {
+ cfg.SecretStore = name
+ return s.resolveSecretStoreInto(ctx, orgID, cfg)
+ })
+}
+
+// layerSecretStores holds the ordering/dedup/skip/re-persist logic, decoupled
+// from how a single store is resolved (via resolve) so it is unit-testable
+// without an edge or DB. resolve must decrypt the named store into cfg and
+// return its UUID (or nil), or an error — an ErrSecretStoreNotFound error marks
+// a genuinely-missing store, which is skipped only for inherited layers.
+func layerSecretStores(cfg *types.SandboxConfig, inheritedBase, inheritedChild, userStore string, resolve func(name string) (*uuid.UUID, error)) (*uuid.UUID, error) {
+ // Ordered layers with empties dropped, deduped preserving first position.
+ seen := make(map[string]bool)
+ var layers []string
+ for _, n := range []string{inheritedBase, inheritedChild, userStore} {
+ if n != "" && !seen[n] {
+ seen[n] = true
+ layers = append(layers, n)
+ }
+ }
+ if len(layers) == 0 {
+ return nil, nil // no stores anywhere — leave cfg untouched (as before)
+ }
+
+ var secretStoreID *uuid.UUID
+ var resolved []string
+ var allEgress []string
+ for _, name := range layers {
+ // A name the caller explicitly passed must exist even if it also happens
+ // to match an inherited layer; only purely-inherited layers are skippable.
+ userNamed := userStore != "" && name == userStore
+ id, err := resolve(name)
+ if err != nil {
+ if errors.Is(err, ErrSecretStoreNotFound) && !userNamed {
+ log.Printf("api: fork: inherited secret store %q no longer exists — skipping (fork continues without it)", name)
+ continue
+ }
+ return nil, err
+ }
+ resolved = append(resolved, name)
+ if id != nil {
+ secretStoreID = id
+ }
+ allEgress = append(allEgress, cfg.EgressAllowlist...)
+ }
+
+ // Aggregate egress across the surviving stores, deduped.
+ egressSeen := make(map[string]bool)
+ var merged []string
+ for _, h := range allEgress {
+ if !egressSeen[h] {
+ egressSeen[h] = true
+ merged = append(merged, h)
+ }
+ }
+ cfg.EgressAllowlist = merged
+
+ // Persist only the surviving stores: last = winning child, prior = base.
+ // Empty when every layer was skipped (fork boots with no store bound).
+ cfg.SecretStore = ""
+ cfg.BaseSecretStore = ""
+ if n := len(resolved); n > 0 {
+ cfg.SecretStore = resolved[n-1]
+ if n > 1 {
+ cfg.BaseSecretStore = resolved[n-2]
+ }
+ }
+ return secretStoreID, nil
+}
+
// resolveTemplate is the edge-first equivalent of the inline
// `s.store.GetTemplateByName` call createSandbox used to do. Same return
// shape (the existing db.DBTemplate); same semantics (org-scoped first,
@@ -3007,60 +3111,13 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
// Egress allowlists aggregate (union of all layers).
// We collect all unique store names, resolve them in order, then persist
// the last two as SecretStore (child) and BaseSecretStore (parent).
- var stores []string
- if originalCfg.BaseSecretStore != "" {
- stores = append(stores, originalCfg.BaseSecretStore)
- }
- if originalCfg.SecretStore != "" {
- stores = append(stores, originalCfg.SecretStore)
- }
- if userSecretStore != "" {
- stores = append(stores, userSecretStore)
- }
- // Deduplicate preserving order
- seen := make(map[string]bool)
- var uniqueStores []string
- for _, name := range stores {
- if !seen[name] {
- seen[name] = true
- uniqueStores = append(uniqueStores, name)
- }
- }
- // secretStoreID tracks the resolved store of the LAST (winning) layer in
- // uniqueStores — that's the one we want recorded on the sandbox row, since
- // later layers shadow earlier ones for env collisions. Plumbed back to
- // CreateSandboxSessionWithStatus below so secret_store_id is populated for
- // the refresh fanout.
- var secretStoreID *uuid.UUID
- if len(uniqueStores) > 0 {
- var allEgress []string
- for _, storeName := range uniqueStores {
- originalCfg.SecretStore = storeName
- storeID, err := s.resolveSecretStoreInto(ctx, orgID, &originalCfg)
- if err != nil {
- return nil, http.StatusBadRequest, err
- }
- if storeID != nil {
- secretStoreID = storeID
- }
- allEgress = append(allEgress, originalCfg.EgressAllowlist...)
- }
- // Deduplicate egress
- egressSeen := make(map[string]bool)
- var merged []string
- for _, h := range allEgress {
- if !egressSeen[h] {
- egressSeen[h] = true
- merged = append(merged, h)
- }
- }
- originalCfg.EgressAllowlist = merged
- // Persist: last store = SecretStore, second-to-last = BaseSecretStore
- originalCfg.SecretStore = uniqueStores[len(uniqueStores)-1]
- originalCfg.BaseSecretStore = ""
- if len(uniqueStores) > 1 {
- originalCfg.BaseSecretStore = uniqueStores[len(uniqueStores)-2]
- }
+ // secretStoreID tracks the resolved store of the winning (last surviving)
+ // layer — recorded on the sandbox row so the secret-refresh fanout can find
+ // it. A checkpoint-inherited store that has since been deleted is skipped so
+ // the fork still boots; a store the caller named in THIS request must exist.
+ secretStoreID, err := s.layerForkSecretStores(ctx, orgID, &originalCfg, userSecretStore)
+ if err != nil {
+ return nil, http.StatusBadRequest, err
}
// Merge user-supplied envs over the checkpoint's envs. User keys win.
diff --git a/internal/api/secret_store_fork_test.go b/internal/api/secret_store_fork_test.go
new file mode 100644
index 00000000..37dd47e3
--- /dev/null
+++ b/internal/api/secret_store_fork_test.go
@@ -0,0 +1,176 @@
+package api
+
+import (
+ "errors"
+ "fmt"
+ "reflect"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// fakeSecretStore is a stand-in for a resolvable secret store in the resolver
+// below: its egress and envs are layered into cfg exactly as
+// resolveSecretStoreInto would.
+type fakeSecretStore struct {
+ id uuid.UUID
+ egress []string
+ envs map[string]string
+}
+
+func uid(n byte) uuid.UUID {
+ var u uuid.UUID
+ u[15] = n
+ return u
+}
+
+// fakeResolver mirrors resolveSecretStoreInto against an in-memory set of
+// stores: a present store overwrites cfg.EgressAllowlist and merges its envs
+// (later layer wins), a missing store returns ErrSecretStoreNotFound, and a
+// name prefixed "ERR-" returns a non-not-found error (transient failure). It
+// records the order of names it was asked to resolve.
+func fakeResolver(cfg *types.SandboxConfig, existing map[string]fakeSecretStore, calls *[]string) func(string) (*uuid.UUID, error) {
+ return func(name string) (*uuid.UUID, error) {
+ *calls = append(*calls, name)
+ if len(name) >= 4 && name[:4] == "ERR-" {
+ return nil, fmt.Errorf("edge lookup secret store %q: boom", name)
+ }
+ st, ok := existing[name]
+ if !ok {
+ return nil, fmt.Errorf("%w: %s", ErrSecretStoreNotFound, name)
+ }
+ cfg.EgressAllowlist = st.egress
+ if cfg.SecretEnvs == nil {
+ cfg.SecretEnvs = map[string]string{}
+ }
+ for k, v := range st.envs {
+ cfg.SecretEnvs[k] = v
+ }
+ id := st.id
+ return &id, nil
+ }
+}
+
+// TestLayerSecretStores_ColeRepro is the regression guard for the reported bug:
+// a checkpoint whose creation-time store (S1) was deleted must still fork when
+// the caller supplies a valid replacement (S2). Before (b), resolving the
+// inherited S1 hard-failed the fork; now it is skipped and S2 wins.
+func TestLayerSecretStores_ColeRepro(t *testing.T) {
+ cfg := &types.SandboxConfig{SecretStore: "S1"} // inherited child = deleted S1
+ existing := map[string]fakeSecretStore{
+ "S2": {id: uid(2), egress: []string{"*"}, envs: map[string]string{"K": "s2"}},
+ }
+ var calls []string
+ id, err := layerSecretStores(cfg, "", "S1", "S2", fakeResolver(cfg, existing, &calls))
+ if err != nil {
+ t.Fatalf("fork should succeed with replacement store, got error: %v", err)
+ }
+ if id == nil || *id != uid(2) {
+ t.Fatalf("winning store id = %v, want S2 (%v)", id, uid(2))
+ }
+ if cfg.SecretStore != "S2" || cfg.BaseSecretStore != "" {
+ t.Fatalf("persisted stores = (child %q, base %q), want (S2, \"\") — deleted S1 must not persist",
+ cfg.SecretStore, cfg.BaseSecretStore)
+ }
+ if !reflect.DeepEqual(cfg.EgressAllowlist, []string{"*"}) {
+ t.Fatalf("egress = %v, want S2's [\"*\"]", cfg.EgressAllowlist)
+ }
+ if want := []string{"S1", "S2"}; !reflect.DeepEqual(calls, want) {
+ t.Fatalf("resolve order = %v, want %v (S1 attempted then skipped)", calls, want)
+ }
+}
+
+// TestLayerSecretStores_MissingUserStoreIsHardError proves the intent split: a
+// store the CALLER named in the fork request must exist, even though inherited
+// stores are now skippable.
+func TestLayerSecretStores_MissingUserStoreIsHardError(t *testing.T) {
+ cfg := &types.SandboxConfig{}
+ var calls []string
+ _, err := layerSecretStores(cfg, "", "", "S2", fakeResolver(cfg, map[string]fakeSecretStore{}, &calls))
+ if err == nil {
+ t.Fatal("expected hard error for a missing user-supplied store, got nil")
+ }
+ if !errors.Is(err, ErrSecretStoreNotFound) {
+ t.Fatalf("error = %v, want ErrSecretStoreNotFound", err)
+ }
+}
+
+// TestLayerSecretStores_UserEqualsInheritedMissing: when the caller names the
+// very store that was inherited-and-deleted, honor the explicit request (hard
+// error), don't silently skip it.
+func TestLayerSecretStores_UserEqualsInheritedMissing(t *testing.T) {
+ cfg := &types.SandboxConfig{SecretStore: "S1"}
+ var calls []string
+ _, err := layerSecretStores(cfg, "", "S1", "S1", fakeResolver(cfg, map[string]fakeSecretStore{}, &calls))
+ if !errors.Is(err, ErrSecretStoreNotFound) {
+ t.Fatalf("error = %v, want ErrSecretStoreNotFound (user explicitly named S1)", err)
+ }
+ if want := []string{"S1"}; !reflect.DeepEqual(calls, want) {
+ t.Fatalf("resolve order = %v, want %v (deduped to one)", calls, want)
+ }
+}
+
+// TestLayerSecretStores_AllInheritedDeletedBootsBare: an inherited store gone
+// with no replacement leaves the fork with no store bound, rather than failing.
+func TestLayerSecretStores_AllInheritedDeletedBootsBare(t *testing.T) {
+ cfg := &types.SandboxConfig{BaseSecretStore: "B1", SecretStore: "S1"}
+ var calls []string
+ id, err := layerSecretStores(cfg, "B1", "S1", "", fakeResolver(cfg, map[string]fakeSecretStore{}, &calls))
+ if err != nil {
+ t.Fatalf("all-inherited-deleted should boot bare, got error: %v", err)
+ }
+ if id != nil {
+ t.Fatalf("secretStoreID = %v, want nil (no store bound)", id)
+ }
+ if cfg.SecretStore != "" || cfg.BaseSecretStore != "" {
+ t.Fatalf("persisted stores = (%q, %q), want empty", cfg.SecretStore, cfg.BaseSecretStore)
+ }
+}
+
+// TestLayerSecretStores_TransientErrorPropagates: a non-not-found failure (e.g.
+// edge/DB blip) on an inherited store must NOT be swallowed as a skip — it
+// fails the fork so we never silently drop a store's secrets.
+func TestLayerSecretStores_TransientErrorPropagates(t *testing.T) {
+ cfg := &types.SandboxConfig{SecretStore: "ERR-flaky"}
+ var calls []string
+ _, err := layerSecretStores(cfg, "", "ERR-flaky", "", fakeResolver(cfg, map[string]fakeSecretStore{}, &calls))
+ if err == nil {
+ t.Fatal("expected transient error to propagate, got nil")
+ }
+ if errors.Is(err, ErrSecretStoreNotFound) {
+ t.Fatalf("error = %v, should NOT be classified as not-found", err)
+ }
+}
+
+// TestLayerSecretStores_HappyLayeringUnchanged: with every layer present the
+// behavior is the pre-fix layering — order preserved, last wins as child,
+// second-to-last as base, envs merged (later wins), egress unioned.
+func TestLayerSecretStores_HappyLayeringUnchanged(t *testing.T) {
+ cfg := &types.SandboxConfig{BaseSecretStore: "B1", SecretStore: "C1"}
+ existing := map[string]fakeSecretStore{
+ "B1": {id: uid(1), egress: []string{"a", "b"}, envs: map[string]string{"K": "base", "B": "1"}},
+ "C1": {id: uid(2), egress: []string{"b", "c"}, envs: map[string]string{"K": "child", "C": "1"}},
+ "U1": {id: uid(3), egress: []string{"c", "d"}, envs: map[string]string{"K": "user", "U": "1"}},
+ }
+ var calls []string
+ id, err := layerSecretStores(cfg, "B1", "C1", "U1", fakeResolver(cfg, existing, &calls))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if id == nil || *id != uid(3) {
+ t.Fatalf("winning id = %v, want U1 (%v)", id, uid(3))
+ }
+ if cfg.SecretStore != "U1" || cfg.BaseSecretStore != "C1" {
+ t.Fatalf("persisted = (child %q, base %q), want (U1, C1)", cfg.SecretStore, cfg.BaseSecretStore)
+ }
+ if cfg.SecretEnvs["K"] != "user" {
+ t.Fatalf("env K = %q, want last-layer wins (user)", cfg.SecretEnvs["K"])
+ }
+ if want := []string{"a", "b", "c", "d"}; !reflect.DeepEqual(cfg.EgressAllowlist, want) {
+ t.Fatalf("egress = %v, want unioned %v", cfg.EgressAllowlist, want)
+ }
+ if want := []string{"B1", "C1", "U1"}; !reflect.DeepEqual(calls, want) {
+ t.Fatalf("resolve order = %v, want %v", calls, want)
+ }
+}
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 43691f29..fceac0c1 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -913,7 +913,11 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
log.Printf("qemu: cold-boot-local %s: sandbox-meta.json absent — recovered config from snapshot-meta.json (template=%q, mem=%dMB, cpu=%d)",
sandboxID, meta.Template, meta.MemoryMB, meta.CpuCount)
}
- if meta.Template == "" {
+ // Normalize "base" (the default template alias) to "default" so cold-boot
+ // recovery resolves the on-disk base (default.ext4) — matching
+ // createFromGolden. Without the "base" case, ResolveBaseImage looked for a
+ // nonexistent base.ext4 and this recovery hard-failed the wake.
+ if meta.Template == "" || meta.Template == "base" {
meta.Template = "default"
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 36e78297..62460a7f 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -1504,7 +1504,16 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa
hostPort int
err error
)
- if req.RootfsS3Key != "" && req.WorkspaceS3Key != "" {
+ // Route to the S3 path whenever the source pre-copied a rootfs. A MERGED
+ // (single-disk) sandbox has no workspace, so WorkspaceS3Key is legitimately
+ // empty — gating on it too (the old `&& WorkspaceS3Key != ""`) sent every
+ // merged box to the direct path below, which has no S3 keys/local paths for
+ // a cross-worker move and so rebuilt a BLANK rootfs from the template base
+ // (and then failed ResolveBaseImage). PrepareIncomingMigrationWithS3 already
+ // handles the merged case (merged := workspaceS3Key == ""), pulling the real
+ // rootfs from S3, so merged boxes migrate correctly here. The direct path
+ // remains only for a genuine no-S3 migration (RootfsS3Key == "").
+ if req.RootfsS3Key != "" {
addr, hostPort, err = s.migrator.PrepareIncomingMigrationWithS3(ctx,
req.SandboxId, req.RootfsS3Key, req.WorkspaceS3Key,
int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, s.checkpointStore, req.OverlayMode, req.SourceGoldenVersion, secrets)
diff --git a/internal/worker/migration_gate_test.go b/internal/worker/migration_gate_test.go
new file mode 100644
index 00000000..854b7f46
--- /dev/null
+++ b/internal/worker/migration_gate_test.go
@@ -0,0 +1,93 @@
+package worker
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// recordingMigrator implements LiveMigrator and records which prepare path the
+// PrepareMigrationIncoming handler chose. Both prepare methods return an error
+// so the handler returns right after the gate, before the router/store code.
+type recordingMigrator struct {
+ withS3 bool
+ direct bool
+ gotWorkspace string
+ gotRootfsPath string
+}
+
+func (m *recordingMigrator) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (string, int, error) {
+ m.direct = true
+ m.gotRootfsPath = rootfsPath
+ return "", 0, fmt.Errorf("stub: direct path")
+}
+
+func (m *recordingMigrator) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, cs *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string, secrets sandbox.MigrationSecrets) (string, int, error) {
+ m.withS3 = true
+ m.gotWorkspace = workspaceS3Key
+ return "", 0, fmt.Errorf("stub: s3 path")
+}
+
+func (m *recordingMigrator) PreCopyDrives(ctx context.Context, sandboxID string, cs *storage.CheckpointStore) (string, string, string, int, int, int, sandbox.MigrationSecrets, error) {
+ return "", "", "", 0, 0, 0, sandbox.MigrationSecrets{}, nil
+}
+func (m *recordingMigrator) CompleteIncomingMigration(ctx context.Context, sandboxID string) error {
+ return nil
+}
+func (m *recordingMigrator) LiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error {
+ return nil
+}
+
+// TestPrepareMigrationIncoming_MergedRoutesToS3 is the regression guard for the
+// stranded-merged-box incident: a MERGED sandbox has no workspace, so its
+// WorkspaceS3Key is empty, but its rootfs IS in S3. It must route to the S3
+// path (which carries the real disk), NOT the direct path (which would rebuild
+// a blank rootfs from the template base and lose the box's disk). The old gate
+// `RootfsS3Key != "" && WorkspaceS3Key != ""` sent merged boxes to the direct
+// path — this test would then fail.
+func TestPrepareMigrationIncoming_MergedRoutesToS3(t *testing.T) {
+ cases := []struct {
+ name string
+ rootfsS3 string
+ workspaceS3 string
+ wantWithS3 bool
+ }{
+ {"merged (rootfs in S3, no workspace)", "migrations/sb/rootfs.qcow2", "", true},
+ {"split (both drives in S3)", "migrations/sb/rootfs.qcow2", "migrations/sb/workspace.qcow2.zst", true},
+ {"no S3 keys (genuine direct/local migration)", "", "", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ m := &recordingMigrator{}
+ s := &GRPCServer{migrator: m}
+ req := &pb.PrepareMigrationIncomingRequest{
+ SandboxId: "sb-test",
+ RootfsS3Key: tc.rootfsS3,
+ WorkspaceS3Key: tc.workspaceS3,
+ TargetMemoryMb: 0, // 0 skips the capacity guard (no manager set)
+ }
+ // Migrator stubs return an error, so the handler returns right after
+ // the gate — we assert on which path it took, not on success.
+ _, _ = s.PrepareMigrationIncoming(context.Background(), req)
+
+ if m.withS3 != tc.wantWithS3 {
+ t.Fatalf("withS3=%v, want %v (direct=%v)", m.withS3, tc.wantWithS3, m.direct)
+ }
+ if tc.wantWithS3 && m.direct {
+ t.Fatal("took BOTH paths; expected only the S3 path")
+ }
+ if !tc.wantWithS3 && !m.direct {
+ t.Fatal("expected the direct path, but it was not taken")
+ }
+ // The merged case specifically must forward the empty workspace key
+ // (WithS3 keys `merged := workspaceS3Key == ""` off it).
+ if tc.name == "merged (rootfs in S3, no workspace)" && m.gotWorkspace != "" {
+ t.Fatalf("merged box forwarded non-empty workspace key %q", m.gotWorkspace)
+ }
+ })
+ }
+}