Skip to content

An open-source, faster Devin alternative

TypeScript

make multistage built, add adjustable mb

Brian Reardon38903f42715b
diff --git a/docs/sandboxes/templates.mdx b/docs/sandboxes/templates.mdx
index 67fea5f7..44976f5e 100644
--- a/docs/sandboxes/templates.mdx
+++ b/docs/sandboxes/templates.mdx
@@ -90,6 +90,36 @@ When you pass an `image` to `Sandbox.create()`, the server:
2. If cached, creates the sandbox from the existing checkpoint instantly
3. If not cached, boots a build sandbox, executes each step, checkpoints the result, then creates your sandbox from it
+### Build vs. runtime memory
+
+Two independent, optional knobs control the memory used while *building* the image versus the memory *floor* of the resulting image:
+
+- **`.builderMemory(mb)` / `.builder_memory(mb)`** — RAM for the build phase. Raise it when a build OOMs (heavy `apt`/`pip`/`npm`). It does **not** pin the output: the builder cold-boots a fresh VM from the built disk at the runtime floor and snapshots that, so a large build still forks down cheaply.
+- **`.runtimeMemory(mb)` / `.runtime_memory(mb)`** — the memory **floor** of the image (the [fork floor](#sizing-a-forks-memory) described above). Defaults to 1 GB. Forks can run at this or higher; raise it only for images whose services auto-start heavy at boot.
+
+<CodeGroup>
+
+```typescript TypeScript
+// 8 GB to build (compiles a big toolchain) but a normal 1 GB floor for forks
+const image = Image.base()
+ .aptInstall(['build-essential', 'cmake'])
+ .runCommands('make -j')
+ .builderMemory(8192);
+```
+
+```python Python
+image = (
+ Image.base()
+ .apt_install(["build-essential", "cmake"])
+ .run_commands("make -j")
+ .builder_memory(8192)
+)
+```
+
+</CodeGroup>
+
+Neither knob changes the cache key — they're resource parameters, not image content.
+
## Creating pre-built snapshots
Create named snapshots that persist permanently and can be shared across sandboxes. Snapshots are visible in the dashboard and don't need to be rebuilt.
@@ -285,6 +315,8 @@ The `Image` class provides a fluent, immutable API for defining sandbox environm
| `.addFile(path, content)` / `.add_file(path, content)` | Embed a file with inline content |
| `.addLocalFile(local, remote)` / `.add_local_file(local, remote)` | Read a local file into the image |
| `.addLocalDir(local, remote)` / `.add_local_dir(local, remote)` | Read a local directory into the image |
+| `.builderMemory(mb)` / `.builder_memory(mb)` | RAM for the build phase (does not pin the output floor) |
+| `.runtimeMemory(mb)` / `.runtime_memory(mb)` | Memory floor of the resulting image (default 1 GB) |
| `.toJSON()` / `.to_dict()` | Return the image manifest |
| `.cacheKey()` / `.cache_key()` | Compute SHA-256 content hash |
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index af6e2b2b..999591a8 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -23,8 +23,32 @@ type ImageManifest struct {
Base string `json:"base"`
Steps []ImageStep `json:"steps"`
Name string `json:"name,omitempty"` // optional — makes image addressable as a snapshot (for patches, etc.)
+
+ // BuilderMemoryMB is the RAM given to the build VM while it runs the steps
+ // (apt/pip can be memory-hungry; the old 1 GB default OOM'd large builds).
+ // It does NOT pin the output: the finalize pass re-snapshots at
+ // RuntimeMemoryMB. Default defaultBuilderMemoryMB.
+ BuilderMemoryMB int `json:"builderMemoryMB,omitempty"`
+
+ // RuntimeMemoryMB is the memory floor of the OUTPUT image — the RAM the
+ // finalize VM is cold-booted + savevm'd at. Forks of this image can't run
+ // below it (a warm savevm can't shrink past its running size) but can hotplug
+ // up. Default defaultRuntimeMemoryMB (= today's behavior). Raise it only for
+ // images whose services auto-start heavy at boot.
+ RuntimeMemoryMB int `json:"runtimeMemoryMB,omitempty"`
}
+const (
+ // defaultBuilderMemoryMB is the build-phase RAM. Generous so common
+ // apt/pip/npm builds don't OOM; safe because it never pins the output (see
+ // the finalize pass in buildImage).
+ defaultBuilderMemoryMB = 8192
+
+ // defaultRuntimeMemoryMB is the output image's memory floor. Kept at the
+ // historical 1 GB so existing fork behavior is unchanged.
+ defaultRuntimeMemoryMB = 1024
+)
+
// ImageStep is a single build step in an image manifest.
type ImageStep struct {
Type string `json:"type"`
@@ -380,15 +404,36 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
base = "base"
}
+ // Build-phase RAM (apt/pip), and the output image's memory floor. Both
+ // settable per-manifest; defaults preserve "builds get headroom, floor stays
+ // at the historical 1 GB" (the finalize pass below re-snapshots at the floor).
+ builderMem := manifest.BuilderMemoryMB
+ if builderMem <= 0 {
+ builderMem = defaultBuilderMemoryMB
+ }
+ runtimeMem := manifest.RuntimeMemoryMB
+ if runtimeMem <= 0 {
+ runtimeMem = defaultRuntimeMemoryMB
+ }
+ // Only run the cold-boot finalize pass when it actually lowers the floor.
+ // If runtime >= builder there's nothing to gain (the in-place savevm already
+ // floors at builderMem ≤ runtimeMem), so snapshot in place (finalizeMem = 0).
+ finalizeMem := 0
+ if runtimeMem < builderMem {
+ finalizeMem = runtimeMem
+ }
+
// Create a throwaway sandbox
buildSandboxID := "sb-build-" + uuid.New().String()[:8]
cfg := types.SandboxConfig{
Template: base,
Timeout: 600, // 10 min max for builds
SandboxID: buildSandboxID,
+ MemoryMB: builderMem,
}
- log.Printf("image-builder: creating build sandbox %s (base=%s, steps=%d)", buildSandboxID, base, len(manifest.Steps))
+ log.Printf("image-builder: creating build sandbox %s (base=%s, steps=%d, builderMem=%dMB, runtimeMem=%dMB)",
+ buildSandboxID, base, len(manifest.Steps), builderMem, runtimeMem)
var grpcClient pb.SandboxWorkerClient
var workerID string
@@ -414,6 +459,7 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
Timeout: int32(cfg.Timeout),
NetworkEnabled: true, // Need network for apt/pip
SandboxId: buildSandboxID,
+ MemoryMb: int32(builderMem),
})
if err != nil {
return uuid.Nil, fmt.Errorf("failed to create build sandbox: %w", err)
@@ -512,10 +558,10 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
if s.store != nil {
cfgJSON, _ := json.Marshal(cfg)
cp := &db.Checkpoint{
- ID: checkpointID,
- SandboxID: buildSandboxID,
- OrgID: orgID,
- Name: fmt.Sprintf("_image_build_%s", checkpointID.String()[:8]),
+ ID: checkpointID,
+ SandboxID: buildSandboxID,
+ OrgID: orgID,
+ Name: fmt.Sprintf("_image_build_%s", checkpointID.String()[:8]),
SandboxConfig: cfgJSON,
}
if err := s.store.CreateCheckpoint(ctx, cp); err != nil {
@@ -533,9 +579,10 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
defer cancel()
resp, err := grpcClient.CreateCheckpoint(cpCtx, &pb.CreateCheckpointRequest{
- SandboxId: buildSandboxID,
- CheckpointId: checkpointID.String(),
- PrepareGolden: true, // prepare golden snapshot for instant template creates
+ SandboxId: buildSandboxID,
+ CheckpointId: checkpointID.String(),
+ PrepareGolden: true, // prepare golden snapshot for instant template creates
+ FinalizeMemoryMb: int32(finalizeMem), // 0 = snapshot in place; >0 = cold-boot finalize at this floor
})
if err != nil {
return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)
@@ -557,7 +604,17 @@ func (s *Server) buildImage(ctx context.Context, orgID uuid.UUID, manifest *Imag
return uuid.Nil, fmt.Errorf("manager does not support checkpoints")
}
- rootfsKey, workspaceKey, sizeBytes, err := cpMgr.CreateCheckpoint(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ var rootfsKey, workspaceKey string
+ var sizeBytes int64
+ var err error
+ type finalizer interface {
+ CreateCheckpointFinalized(ctx context.Context, buildSandboxID, checkpointID string, store *storage.CheckpointStore, finalizeMemMB int, onReady func()) (string, string, int64, error)
+ }
+ if fz, ok := s.manager.(finalizer); ok && finalizeMem > 0 {
+ rootfsKey, workspaceKey, sizeBytes, err = fz.CreateCheckpointFinalized(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, finalizeMem, func() {})
+ } else {
+ rootfsKey, workspaceKey, sizeBytes, err = cpMgr.CreateCheckpoint(ctx, buildSandboxID, checkpointID.String(), s.checkpointStore, func() {})
+ }
if err != nil {
return uuid.Nil, fmt.Errorf("failed to checkpoint build sandbox: %w", err)
}
@@ -693,4 +750,3 @@ func stepDescription(step ImageStep) string {
return step.Type
}
}
-
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index c3ec0f1c..18c6b1b7 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -332,7 +332,7 @@ type Manager struct {
goldenVersion string // hash of base image — used for overlay-based migration
// Metadata service callbacks (set via SetMetadataCallbacks)
- onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
+ onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
onSandboxDestroy func(sandboxID string)
onMigrationOutgoing func(sandboxID string)
@@ -2845,6 +2845,67 @@ func (m *Manager) CheckpointCachePath(checkpointID, filename string) string {
// checkpoint actually is. Upload failures now propagate as an error rather
// than being silently logged — the control plane gets the reason and
// persists it via SetCheckpointFailed (migration 039 added error_msg).
+// CreateCheckpointFinalized produces an image checkpoint whose memory floor is
+// finalizeMemMB, decoupled from the build VM's (larger) build-phase RAM. The
+// image builder uses this so a build can run at, say, 8 GB (apt/pip don't OOM)
+// while the resulting image still forks down to a 1 GB floor.
+//
+// Why two VMs: a savevm captures the *running* memory, and ForkFromCheckpoint
+// floors every fork at that size (shrinking past it would OOM restored
+// processes). So the only way to get a low floor from a high-memory build is to
+// cold-boot a fresh VM from the built disks at the target floor and snapshot
+// THAT. The cold-boot machinery already exists (Create with TemplateRootfsKey).
+//
+// Sequence: sync the build guest's FS → cold-boot a finalize VM from a copy of
+// the build disks at finalizeMemMB → snapshot the finalize VM (the output) →
+// tear the finalize VM down. The build VM is left running for its caller to
+// destroy (Kill would delete the disks we copy from). Cold-boot replays the
+// ext4 journal, so a post-sync disk copy restores cleanly.
+//
+// NOTE: the disk-consistency of the live-disk copy and the finalize cold-boot's
+// agent bring-up are the things to validate on dev before prod.
+func (m *Manager) CreateCheckpointFinalized(ctx context.Context, buildSandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, finalizeMemMB int, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error) {
+ // 1. Flush the build guest's filesystem so the on-disk qcow2 is consistent
+ // before we copy it. Best-effort: the cold-boot journal-replays regardless.
+ if syncErr := m.SyncFS(ctx, buildSandboxID); syncErr != nil {
+ log.Printf("qemu: finalize %s: SyncFS warning: %v (continuing)", buildSandboxID, syncErr)
+ }
+
+ buildDir := filepath.Join(m.cfg.DataDir, "sandboxes", buildSandboxID)
+ buildRootfs := filepath.Join(buildDir, "rootfs.qcow2")
+ buildWorkspace := filepath.Join(buildDir, "workspace.qcow2")
+ if !fileExists(buildRootfs) || !fileExists(buildWorkspace) {
+ return "", "", 0, fmt.Errorf("finalize: build disks not found for %s", buildSandboxID)
+ }
+
+ // 2. Cold-boot a fresh finalize VM from a copy of the build disks at the
+ // target floor. Create() copies the disks (reflink) via TemplateRootfsKey
+ // and cold-boots — no savevm restore, so no memory floor inherited.
+ finalizeID := buildSandboxID + "-fin"
+ netEnabled := true
+ finCfg := types.SandboxConfig{
+ SandboxID: finalizeID,
+ MemoryMB: finalizeMemMB,
+ NetworkEnabled: &netEnabled,
+ TemplateRootfsKey: "local://" + buildRootfs,
+ TemplateWorkspaceKey: "local://" + buildWorkspace,
+ }
+ log.Printf("qemu: finalize: cold-booting %s from %s disks at %dMB", finalizeID, buildSandboxID, finalizeMemMB)
+ if _, err := m.Create(ctx, finCfg); err != nil {
+ return "", "", 0, fmt.Errorf("finalize: cold-boot at %dMB: %w", finalizeMemMB, err)
+ }
+ // Tear down the ephemeral finalize VM after we snapshot it.
+ defer func() {
+ if kErr := m.Kill(context.Background(), finalizeID); kErr != nil {
+ log.Printf("qemu: finalize %s: cleanup Kill failed: %v", finalizeID, kErr)
+ }
+ }()
+
+ // 3. Snapshot the finalize VM → the output checkpoint (floor = finalizeMemMB).
+ log.Printf("qemu: finalize %s → checkpoint %s (floor %dMB)", finalizeID, checkpointID, finalizeMemMB)
+ return m.CreateCheckpoint(ctx, finalizeID, checkpointID, checkpointStore, onReady)
+}
+
func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, sizeBytes int64, err error) {
tStart := time.Now()
// failureReason is updated at each error site below so the defer can attribute
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 52e096c3..91d023cc 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -882,7 +882,25 @@ func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpo
// it's marked "ready" — forks poll for "ready" before downloading.
// The gRPC call returns immediately with the S3 keys — the CP's fork path
// polls for checkpoint readiness and blocks until onReady fires.
- rootfsKey, workspaceKey, sizeBytes, err := s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)
+ // Finalize: when finalize_memory_mb is set (image builder), produce the
+ // checkpoint at that memory floor by cold-booting a fresh VM from the build
+ // disks and snapshotting it — decoupling the image's floor from the build's
+ // (larger) RAM. Otherwise snapshot the sandbox in place.
+ var rootfsKey, workspaceKey string
+ var sizeBytes int64
+ var err error
+ if req.FinalizeMemoryMb > 0 {
+ type finalizer interface {
+ CreateCheckpointFinalized(ctx context.Context, buildSandboxID, checkpointID string, store *storage.CheckpointStore, finalizeMemMB int, onReady func()) (string, string, int64, error)
+ }
+ fz, ok := s.manager.(finalizer)
+ if !ok {
+ return nil, fmt.Errorf("manager does not support finalized checkpoints")
+ }
+ rootfsKey, workspaceKey, sizeBytes, err = fz.CreateCheckpointFinalized(ctx, req.SandboxId, checkpointID, s.checkpointStore, int(req.FinalizeMemoryMb), onReady)
+ } else {
+ rootfsKey, workspaceKey, sizeBytes, err = s.manager.CreateCheckpoint(ctx, req.SandboxId, checkpointID, s.checkpointStore, onReady)
+ }
if err != nil {
return nil, fmt.Errorf("create checkpoint failed: %w", err)
}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 78b6ce0b..1514e3a6 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -2598,8 +2598,13 @@ type CreateCheckpointRequest struct {
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // UUID assigned by control plane
PrepareGolden bool `protobuf:"varint,3,opt,name=prepare_golden,json=prepareGolden,proto3" json:"prepare_golden,omitempty"` // If true, prepare a golden snapshot from this checkpoint
- unknownFields protoimpl.UnknownFields
- sizeCache protoimpl.SizeCache
+ // If > 0, finalize the checkpoint at this memory: the worker stops the build VM,
+ // cold-boots a fresh VM from its disks at finalize_memory_mb, and snapshots THAT
+ // — so the image's memory floor is finalize_memory_mb, decoupled from the
+ // (larger) build-phase RAM. Used by the image builder. 0 = snapshot in place.
+ FinalizeMemoryMb int32 `protobuf:"varint,4,opt,name=finalize_memory_mb,json=finalizeMemoryMb,proto3" json:"finalize_memory_mb,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *CreateCheckpointRequest) Reset() {
@@ -2653,6 +2658,13 @@ func (x *CreateCheckpointRequest) GetPrepareGolden() bool {
return false
}
+func (x *CreateCheckpointRequest) GetFinalizeMemoryMb() int32 {
+ if x != nil {
+ return x.FinalizeMemoryMb
+ }
+ return 0
+}
+
type CreateCheckpointResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
RootfsS3Key string `protobuf:"bytes,1,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"`
@@ -3950,12 +3962,13 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +
"\n" +
"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +
- "\x04pids\x18\x06 \x01(\x05R\x04pids\"\x84\x01\n" +
+ "\x04pids\x18\x06 \x01(\x05R\x04pids\"\xb2\x01\n" +
"\x17CreateCheckpointRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12#\n" +
"\rcheckpoint_id\x18\x02 \x01(\tR\fcheckpointId\x12%\n" +
- "\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\"\x87\x01\n" +
+ "\x0eprepare_golden\x18\x03 \x01(\bR\rprepareGolden\x12,\n" +
+ "\x12finalize_memory_mb\x18\x04 \x01(\x05R\x10finalizeMemoryMb\"\x87\x01\n" +
"\x18CreateCheckpointResponse\x12\"\n" +
"\rrootfs_s3_key\x18\x01 \x01(\tR\vrootfsS3Key\x12(\n" +
"\x10workspace_s3_key\x18\x02 \x01(\tR\x0eworkspaceS3Key\x12\x1d\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 67cb7504..18bc58b3 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -338,6 +338,11 @@ message CreateCheckpointRequest {
string sandbox_id = 1;
string checkpoint_id = 2; // UUID assigned by control plane
bool prepare_golden = 3; // If true, prepare a golden snapshot from this checkpoint
+ // If > 0, finalize the checkpoint at this memory: the worker stops the build VM,
+ // cold-boots a fresh VM from its disks at finalize_memory_mb, and snapshots THAT
+ // — so the image's memory floor is finalize_memory_mb, decoupled from the
+ // (larger) build-phase RAM. Used by the image builder. 0 = snapshot in place.
+ int32 finalize_memory_mb = 4;
}
message CreateCheckpointResponse {
diff --git a/sdks/python/opencomputer/image.py b/sdks/python/opencomputer/image.py
index 92fb16bd..6a69e4a5 100644
--- a/sdks/python/opencomputer/image.py
+++ b/sdks/python/opencomputer/image.py
@@ -6,7 +6,7 @@ import base64
import hashlib
import json
import os
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from typing import Any
@@ -47,6 +47,12 @@ class Image:
_base: str = "base"
_steps: tuple[ImageStep, ...] = field(default_factory=tuple)
+ # RAM for the build phase (apt/pip). 0 = server default (generous). Does not
+ # pin the output image — the server re-snapshots at the runtime floor.
+ _builder_memory_mb: int = 0
+ # Memory floor of the OUTPUT image. 0 = server default (1 GB). Forks can't run
+ # below this but can scale up. Raise only for images with heavy boot services.
+ _runtime_memory_mb: int = 0
@classmethod
def base(cls) -> Image:
@@ -60,36 +66,36 @@ class Image:
def apt_install(self, packages: list[str]) -> Image:
"""Install system packages via apt-get."""
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("apt_install", {"packages": packages})),
)
def pip_install(self, packages: list[str]) -> Image:
"""Install Python packages via pip."""
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("pip_install", {"packages": packages})),
)
def run_commands(self, *commands: str) -> Image:
"""Run one or more shell commands."""
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("run", {"commands": list(commands)})),
)
def env(self, vars: dict[str, str]) -> Image:
"""Set environment variables (written to /etc/environment)."""
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("env", {"vars": vars})),
)
def workdir(self, path: str) -> Image:
"""Set the default working directory."""
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("workdir", {"path": path})),
)
@@ -101,8 +107,8 @@ class Image:
content: String content of the file.
"""
encoded = base64.b64encode(content.encode()).decode()
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("add_file", {
"path": remote_path,
"content": encoded,
@@ -121,8 +127,8 @@ class Image:
"""
with open(local_path, "rb") as f:
encoded = base64.b64encode(f.read()).decode()
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("add_file", {
"path": remote_path,
"content": encoded,
@@ -147,22 +153,39 @@ class Image:
with open(full, "rb") as f:
encoded = base64.b64encode(f.read()).decode()
files.append({"relativePath": rel, "content": encoded})
- return Image(
- _base=self._base,
+ return replace(
+ self,
_steps=(*self._steps, ImageStep("add_dir", {
"path": remote_path,
"files": files,
})),
)
+ def builder_memory(self, mb: int) -> Image:
+ """Set the RAM (MB) for the build phase. Use this when a build OOMs at the
+ default (e.g. heavy ``apt``/``pip``). Does not affect the output's floor."""
+ return replace(self, _builder_memory_mb=mb)
+
+ def runtime_memory(self, mb: int) -> Image:
+ """Set the memory floor (MB) of the resulting image. Forks can't run below
+ it. Defaults to 1 GB; raise only for images whose services auto-start heavy."""
+ return replace(self, _runtime_memory_mb=mb)
+
def to_dict(self) -> dict[str, Any]:
"""Returns the manifest as a plain dict (for JSON serialization)."""
- return {
+ d: dict[str, Any] = {
"base": self._base,
"steps": [s.to_dict() for s in self._steps],
}
+ if self._builder_memory_mb > 0:
+ d["builderMemoryMB"] = self._builder_memory_mb
+ if self._runtime_memory_mb > 0:
+ d["runtimeMemoryMB"] = self._runtime_memory_mb
+ return d
def cache_key(self) -> str:
- """Compute a deterministic content hash for caching."""
- canonical = json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"))
+ """Deterministic content hash for caching. Memory knobs are resource
+ params, not image content, so they're excluded (matches the server)."""
+ content = {"base": self._base, "steps": [s.to_dict() for s in self._steps]}
+ canonical = json.dumps(content, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()
diff --git a/sdks/typescript/src/image.ts b/sdks/typescript/src/image.ts
index e580bea9..745c3cf5 100644
--- a/sdks/typescript/src/image.ts
+++ b/sdks/typescript/src/image.ts
@@ -10,6 +10,13 @@ export interface ImageStep {
export interface ImageManifest {
base: string;
steps: ImageStep[];
+ /** RAM (MB) for the build phase (apt/pip). Omit for the server default
+ * (generous). Does NOT pin the output — the server re-snapshots at the floor. */
+ builderMemoryMB?: number;
+ /** Memory floor (MB) of the output image. Omit for the server default (1 GB).
+ * Forks can't run below it but can scale up. Raise only for images with heavy
+ * boot-time services. */
+ runtimeMemoryMB?: number;
}
/**
@@ -28,6 +35,9 @@ export interface ImageManifest {
* .env({ PROJECT_ROOT: '/workspace' })
* .workdir('/workspace')
*
+ * // Heavy build that should still fork down to the default floor:
+ * const big = Image.base().aptInstall(['build-essential']).builderMemory(8192)
+ *
* // On-demand: cached by content hash
* const sandbox = await Sandbox.create({ image })
*
@@ -39,8 +49,8 @@ export interface ImageManifest {
export class Image {
private readonly manifest: ImageManifest;
- private constructor(steps: ImageStep[] = []) {
- this.manifest = { base: "base", steps };
+ private constructor(manifest: ImageManifest) {
+ this.manifest = manifest;
}
/**
@@ -49,57 +59,47 @@ export class Image {
* Customize by chaining steps like `.aptInstall()`, `.pipInstall()`, `.runCommands()`, etc.
*/
static base(): Image {
- return new Image();
+ return new Image({ base: "base", steps: [] });
+ }
+
+ /** Append a step, preserving base + memory settings. */
+ private withStep(step: ImageStep): Image {
+ return new Image({ ...this.manifest, steps: [...this.manifest.steps, step] });
}
/**
* Install system packages via apt-get.
*/
aptInstall(packages: string[]): Image {
- return new Image([
- ...this.manifest.steps,
- { type: "apt_install", args: { packages } },
- ]);
+ return this.withStep({ type: "apt_install", args: { packages } });
}
/**
* Install Python packages via pip.
*/
pipInstall(packages: string[]): Image {
- return new Image([
- ...this.manifest.steps,
- { type: "pip_install", args: { packages } },
- ]);
+ return this.withStep({ type: "pip_install", args: { packages } });
}
/**
* Run one or more shell commands.
*/
runCommands(...commands: string[]): Image {
- return new Image([
- ...this.manifest.steps,
- { type: "run", args: { commands } },
- ]);
+ return this.withStep({ type: "run", args: { commands } });
}
/**
* Set environment variables (written to /etc/environment).
*/
env(vars: Record<string, string>): Image {
- return new Image([
- ...this.manifest.steps,
- { type: "env", args: { vars } },
- ]);
+ return this.withStep({ type: "env", args: { vars } });
}
/**
* Set the default working directory.
*/
workdir(path: string): Image {
- return new Image([
- ...this.manifest.steps,
- { type: "workdir", args: { path } },
- ]);
+ return this.withStep({ type: "workdir", args: { path } });
}
/**
@@ -109,10 +109,7 @@ export class Image {
*/
addFile(remotePath: string, content: string): Image {
const encoded = Buffer.from(content).toString("base64");
- return new Image([
- ...this.manifest.steps,
- { type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } },
- ]);
+ return this.withStep({ type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } });
}
/**
@@ -124,10 +121,7 @@ export class Image {
addLocalFile(localPath: string, remotePath: string): Image {
const content = readFileSync(localPath);
const encoded = content.toString("base64");
- return new Image([
- ...this.manifest.steps,
- { type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } },
- ]);
+ return this.withStep({ type: "add_file", args: { path: remotePath, content: encoded, encoding: "base64" } });
}
/**
@@ -139,10 +133,23 @@ export class Image {
addLocalDir(localPath: string, remotePath: string): Image {
const files: Array<{ relativePath: string; content: string }> = [];
collectFiles(localPath, localPath, files);
- return new Image([
- ...this.manifest.steps,
- { type: "add_dir", args: { path: remotePath, files } },
- ]);
+ return this.withStep({ type: "add_dir", args: { path: remotePath, files } });
+ }
+
+ /**
+ * Set the RAM (MB) for the build phase. Use this when a build OOMs at the
+ * default (e.g. heavy `apt`/`pip`). Does not affect the output image's floor.
+ */
+ builderMemory(mb: number): Image {
+ return new Image({ ...this.manifest, builderMemoryMB: mb });
+ }
+
+ /**
+ * Set the memory floor (MB) of the resulting image. Forks can't run below it.
+ * Defaults to 1 GB; raise only for images whose services auto-start heavy.
+ */
+ runtimeMemory(mb: number): Image {
+ return new Image({ ...this.manifest, runtimeMemoryMB: mb });
}
/**
@@ -153,10 +160,11 @@ export class Image {
}
/**
- * Compute a deterministic content hash for caching.
+ * Compute a deterministic content hash for caching. Memory knobs are resource
+ * params, not image content, so they're excluded (matches the server).
*/
cacheKey(): string {
- const canonical = JSON.stringify(this.manifest);
+ const canonical = JSON.stringify({ base: this.manifest.base, steps: this.manifest.steps });
return createHash("sha256").update(canonical).digest("hex");
}
}