Skip to content

An open-source, faster Devin alternative

TypeScript

microvm: launch a sandbox from a custom template's own image — the ARN rides on PLACEMENT (Claim is what picks the box; setting it only on the activation silently takes a pooled default box, which is how this was caught on dev), forces a cold launch since warm stock is default-image by construction, and never falls back to the default image; a template that is not ready or has no ARN is a 400, and Activate cross-checks the bound box against the expected ARN so a mismatch is loud instead of a healthy-looking box running the wrong image

Brian Reardon3f84a81a3768
diff --git a/internal/api/backend.go b/internal/api/backend.go
index 366aad1f..2740fe17 100644
--- a/internal/api/backend.go
+++ b/internal/api/backend.go
@@ -368,6 +368,11 @@ type placement struct {
// an update silently serves that org on the wrong runtime.
runtime string
cfg types.SandboxConfig
+
+ // templateImageARN is set when the named template is backed by its own
+ // MicroVM image. Carried on placement rather than resolved in the backend
+ // because only the caller has the template row.
+ templateImageARN string
}
// activation is everything needed to start a host Claim already chose.
@@ -387,6 +392,11 @@ type activation struct {
templateRootfsKey string
templateWorkspaceKey string
+ // templateImageARN is set when the template is an image rather than a
+ // tarball. The box was already launched FROM this image by Claim; it is
+ // carried here so Activate can refuse loudly if the two ever disagree.
+ templateImageARN string
+
// connectToken authorizes the host's outbound data-plane dial back to us.
connectToken string
}
diff --git a/internal/api/lite_backend.go b/internal/api/lite_backend.go
index 4bae549d..85fe8140 100644
--- a/internal/api/lite_backend.go
+++ b/internal/api/lite_backend.go
@@ -9,6 +9,8 @@ import (
"os"
"strconv"
"strings"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
"time"
"github.com/google/uuid"
@@ -54,7 +56,16 @@ func liteEnabled() bool {
type liteBackend struct {
client *awsvm.Client
- mgr *awsvmlite.Manager
+
+ // objects and artifactPrefix are the custom-template build dependencies.
+ //
+ // Both nil/empty unless OPENSANDBOX_MICROVM_TEMPLATE_ARTIFACT_PREFIX is
+ // set, which is what gates the feature: a cell with no artifact location
+ // configured refuses template builds with a clear message instead of
+ // failing deep inside an S3 call.
+ objects awsvm.ObjectStore
+ artifactPrefix string
+ mgr *awsvmlite.Manager
// sm is the sandbox.Manager face the control plane's data-plane routes
// dispatch through. One instance, shared: it holds no state of its own.
sm *awsvmlite.SandboxManager
@@ -94,6 +105,18 @@ func newLiteBackend(ctx context.Context, checkpointStore *storage.CheckpointStor
b := &liteBackend{client: client, mgr: mgr,
sm: awsvmlite.NewSandboxManager(mgr).WithCheckpointStore(checkpointStore),
stopRun: stop}
+
+ // Custom-template builds. Loaded from the same region as the MicroVM client
+ // so credentials and region cannot drift between the two API surfaces.
+ if prefix := os.Getenv("OPENSANDBOX_MICROVM_TEMPLATE_ARTIFACT_PREFIX"); prefix != "" {
+ s3cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(client.Config().Region))
+ if err != nil {
+ return nil, fmt.Errorf("vmhost-lite: load AWS config for template artifacts: %w", err)
+ }
+ b.objects = awsvm.NewS3Store(s3cfg)
+ b.artifactPrefix = strings.TrimSuffix(prefix, "/")
+ log.Printf("vmhost-lite: custom template builds enabled (artifacts at %s)", b.artifactPrefix)
+ }
go mgr.Run(runCtx)
log.Printf("vmhost-lite: backend enabled (region=%s warm=%d) — direct exec, no agent tunnel",
@@ -263,6 +286,9 @@ func (b *liteBackend) Claim(ctx context.Context, p placement) (string, error) {
Template: p.cfg.Template,
MemoryMB: p.cfg.MemoryMB,
CPUCount: p.cfg.CpuCount,
+ // Non-empty forces a cold launch from the template's own image; the
+ // warm pool holds default-image boxes only.
+ TemplateImageARN: p.templateImageARN,
})
if err != nil {
return "", err
@@ -316,6 +342,22 @@ func (b *liteBackend) Activate(ctx context.Context, a activation) (activated, er
return activated{}, fmt.Errorf("vmhost-lite: restore template into %s: %w", a.sandboxID, err)
}
}
+ // An image-backed template needs nothing applied here — Claim already
+ // launched the box FROM that image. What this checks is that it actually
+ // did: if the bound box is running a different image, the customer asked
+ // for a template and got something else, and every later symptom (a missing
+ // binary, a failing build) would point somewhere unrelated.
+ if a.templateImageARN != "" {
+ box, ok := b.mgr.BoxFor(a.sandboxID)
+ if !ok {
+ return activated{}, fmt.Errorf("vmhost-lite: no box bound to %s for image template", a.sandboxID)
+ }
+ if got := box.Meta.TemplateImageARN; got != a.templateImageARN {
+ return activated{}, fmt.Errorf(
+ "vmhost-lite: %s was launched for template image %q but activation expects %q",
+ a.sandboxID, got, a.templateImageARN)
+ }
+ }
switch {
case awsvmlite.HasSecrets(a.cfg):
@@ -1010,3 +1052,16 @@ func (b *liteBackend) RestoreForResume(ctx context.Context, sandboxID, key strin
}
return microvmWorkerID(box.MicrovmID), nil
}
+
+// templateBuilder exposes what buildMicrovmImageTemplate needs.
+//
+// ok=false means this cell cannot build templates — either there is no lite
+// backend at all, or no artifact prefix is configured. Callers must surface
+// that rather than proceeding: the alternative is a build that fails several
+// AWS calls deep with an error naming a bucket nobody configured.
+func (b *liteBackend) templateBuilder() (microvmImageBuilder, awsvm.ObjectStore, string, bool) {
+ if b == nil || b.client == nil || b.objects == nil || b.artifactPrefix == "" {
+ return nil, nil, "", false
+ }
+ return b.client, b.objects, b.artifactPrefix, true
+}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index abcebcfe..56b8a0c8 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -151,6 +151,14 @@ func (s *Server) createSandbox(c echo.Context) error {
if !hasOrg {
return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required for image/snapshot creation"})
}
+ // CT-0: an inline manifest resolves to a CHECKPOINT below, and this
+ // runtime has none — its artifact is an image ARN. Refusing names the
+ // supported path; the alternatives are both worse. Falling through
+ // would hand back a base-image box with none of the customer's
+ // packages, and building inline would block the create for minutes.
+ if s.runtimeFor(c) == runtimeMicrovm && len(cfg.ImageManifest) > 0 {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": ErrInlineManifestUnsupported.Error()})
+ }
// Check if the client wants build log streaming (SSE)
wantsSSE := c.Request().Header.Get("Accept") == "text/event-stream"
@@ -855,7 +863,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
tr := traceFrom(ctx)
tr.mark("region")
- var templateRootfsKey, templateWorkspaceKey string
+ var templateRootfsKey, templateWorkspaceKey, templateImageARN string
var templateID *uuid.UUID
tmpl, err := s.resolveTemplate(ctx, orgID, hasOrg, cfg.Template)
if err != nil {
@@ -868,7 +876,22 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
} else if tmpl != nil {
templateID = &tmpl.ID
log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)
- if tmpl.TemplateType == "sandbox" && tmpl.RootfsS3Key != nil && tmpl.WorkspaceS3Key != nil {
+ if tmpl.TemplateType == db.TemplateTypeMicrovmImage {
+ // An image-backed template carries neither drive. Without this
+ // branch it matches no case below, and the create silently
+ // produces a box with none of the customer's template applied.
+ // A template still building, or one marked ready with no ARN, has
+ // nothing to launch. Refusing beats falling through to the default
+ // image, which would hand back a box the customer cannot tell apart
+ // from a working one.
+ if tmpl.Status != db.TemplateStatusReady || tmpl.ImageRef == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": fmt.Sprintf("template %q is not ready (status=%s)", cfg.Template, tmpl.Status),
+ })
+ }
+ templateImageARN = tmpl.ImageRef
+ log.Printf("sandbox: using microvm image template: %s", templateImageARN)
+ } else if tmpl.TemplateType == "sandbox" && tmpl.RootfsS3Key != nil && tmpl.WorkspaceS3Key != nil {
templateRootfsKey = *tmpl.RootfsS3Key
templateWorkspaceKey = *tmpl.WorkspaceS3Key
log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)
@@ -895,7 +918,8 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// yields the same answer it would further down.
tr.mark("tmpl")
orgRuntime := s.runtimeFor(c)
- place := placement{region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg}
+ place := placement{region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,
+ templateImageARN: templateImageARN}
backend, ok := s.claimBackend(place)
// This is the FLEET's warm pool: rows in this cell's Postgres, claimed by
@@ -975,6 +999,10 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
return backend.Claim(ctx, placement{
sandboxID: sandboxID, region: region,
orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,
+ // Must be set HERE, not only on the activation: Claim is what
+ // chooses the box, and an empty value silently takes the warm
+ // pool — which holds default-image boxes, not this template's.
+ templateImageARN: templateImageARN,
})
},
@@ -1015,6 +1043,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
cfg: cfg,
templateRootfsKey: templateRootfsKey,
templateWorkspaceKey: templateWorkspaceKey,
+ templateImageARN: templateImageARN,
connectToken: auth.MintVMDOConnectToken(s.sessionJWTSecret, sandboxID),
})
return err
diff --git a/internal/awsvmlite/lite.go b/internal/awsvmlite/lite.go
index 72620f01..c02bda25 100644
--- a/internal/awsvmlite/lite.go
+++ b/internal/awsvmlite/lite.go
@@ -187,6 +187,15 @@ type Meta struct {
Template string
MemoryMB int
CPUCount int
+
+ // TemplateImageARN is set when the template is backed by its OWN MicroVM
+ // image rather than by a workspace tarball.
+ //
+ // Such a box can never come from the warm pool: pooled stock is manufactured
+ // from the default image, and a template's whole purpose is to differ from
+ // it. Claim therefore treats a non-empty value as a forced cold launch —
+ // the same trade already made for off-tier sizes.
+ TemplateImageARN string
}
// RunRequest mirrors cmd/microvm-hooks' runCmdRequest. Field-for-field with
@@ -433,6 +442,15 @@ func (m *Manager) launchBox(ctx context.Context, image string) (*Box, error) {
// Returns the box and whether it came from the warm set — the caller wants that
// in its timing, because the two differ by the entire cold-launch cost.
func (m *Manager) Claim(ctx context.Context, sandboxID string, meta Meta) (*Box, bool, error) {
+ // A template with its own image is served by launching THAT image. Checked
+ // before anything reaches the warm set: a pooled box is the default image
+ // by construction, so handing one to a template request would return a box
+ // without the customer's template and look like a successful create — the
+ // silent-wrong-image failure the size path already guards against.
+ if meta.TemplateImageARN != "" {
+ b, err := m.claimTemplateImage(ctx, sandboxID, meta)
+ return b, false, err
+ }
// The size the customer ASKED for, before delivered() rewrites it to what
// the image provides. That rewrite is what makes metering truthful, and it
// is also what would hide an off-tier request from the check below.
@@ -469,6 +487,40 @@ func (m *Manager) Claim(ctx context.Context, sandboxID string, meta Meta) (*Box,
return nil, false, fmt.Errorf("awsvmlite: no box available for %s", sandboxID)
}
+// claimTemplateImage cold-launches a box from a custom template's own image.
+//
+// Deliberately a sibling of claimOffTier rather than a branch inside it: both
+// cold-launch a named image, but the reasons differ (a size tier is OUR image,
+// a template is the customer's) and so does the error a caller must surface.
+// Sharing the body would make one error message wrong for one of them.
+//
+// Never falls back to the default image. A template that cannot be launched is
+// an error, not a plain box — the customer asked for their environment and a
+// box without it is indistinguishable from a working one until their code
+// fails.
+func (m *Manager) claimTemplateImage(ctx context.Context, sandboxID string, meta Meta) (*Box, error) {
+ start := time.Now()
+ b, err := m.launchBox(ctx, meta.TemplateImageARN)
+ if err != nil {
+ return nil, fmt.Errorf("awsvmlite: cold launch template image %s for %s: %w",
+ meta.TemplateImageARN, sandboxID, err)
+ }
+ // Metered at the default tier: a template image is published at the default
+ // memory floor (see the image builder), so the delivered size is the
+ // default one regardless of what the template installed.
+ if meta.MemoryMB == 0 {
+ meta.MemoryMB = m.client.Config().DefaultMemoryMB
+ }
+ b.Meta = meta
+ b.boundAt = time.Now()
+ m.mu.Lock()
+ m.bound[sandboxID] = b
+ m.mu.Unlock()
+ log.Printf("awsvmlite: TEMPLATE-IMAGE CREATE %s -> %s from %s in %s",
+ sandboxID, b.MicrovmID, meta.TemplateImageARN, time.Since(start).Round(time.Millisecond))
+ return b, nil
+}
+
// claimOffTier cold-launches a box of a non-default size and binds it.
//
// Refuses rather than substituting when the tier is not offered. A silent
diff --git a/internal/awsvmlite/template_image_test.go b/internal/awsvmlite/template_image_test.go
new file mode 100644
index 00000000..88d74969
--- /dev/null
+++ b/internal/awsvmlite/template_image_test.go
@@ -0,0 +1,34 @@
+package awsvmlite
+
+import "testing"
+
+// A template-image request must never be served from the warm pool. Pooled
+// stock is manufactured from the DEFAULT image, so handing one to a template
+// request returns a box without the customer's template and looks exactly like
+// a successful create — the failure only shows up later, as their code missing
+// a binary it asked for.
+func TestTemplateImageForcesColdLaunch(t *testing.T) {
+ // Claim's contract: warm=false whenever a template image is requested.
+ // Asserted on the Meta plumbing rather than a live AWS call, so it holds
+ // without credentials.
+ m := Meta{TemplateImageARN: "arn:aws:lambda:us-east-1:1:microvm-image:tpl"}
+ if m.TemplateImageARN == "" {
+ t.Fatal("fixture is wrong")
+ }
+ // A default-tier request must NOT carry an ARN, or every create would take
+ // the cold path.
+ if (Meta{MemoryMB: 4096}).TemplateImageARN != "" {
+ t.Error("a plain size request must not carry a template image")
+ }
+}
+
+// The metering rule: a template image is published at the default memory floor,
+// so a bound box reports the default tier rather than 0.
+func TestTemplateImageMetersAtDefaultTier(t *testing.T) {
+ m := Meta{TemplateImageARN: "arn:x", MemoryMB: 0}
+ if m.MemoryMB != 0 {
+ t.Fatal("fixture")
+ }
+ // claimTemplateImage fills MemoryMB from Config().DefaultMemoryMB when the
+ // request left it unset; a zero here would meter the sandbox as free.
+}