Skip to content

An open-source, faster Devin alternative

TypeScript

various fixes,tests

Brian Reardonccad0f5fde7c
diff --git a/.claude/skills/openqemu/SKILL.md b/.claude/skills/openqemu/SKILL.md
index 89842f7b..ff600306 100644
--- a/.claude/skills/openqemu/SKILL.md
+++ b/.claude/skills/openqemu/SKILL.md
@@ -121,7 +121,7 @@ Pricing model: 1 vCPU per 1GB RAM (linear scaling). Setting memoryMB auto-calcul
curl -s -X PUT $API_URL/api/sandboxes/{SANDBOX_ID}/limits \
-H 'Content-Type: application/json' \
-H "X-API-Key: $API_KEY" \
- -d '{"maxMemoryMB": 2048, "cpuPercent": 200, "maxPids": 256}'
+ -d '{"memoryMB": 2048}'
```
#### Internal API (from inside the sandbox — 169.254.169.254)
@@ -134,7 +134,7 @@ curl -s http://169.254.169.254/v1/limits
# → {"cpuPercent":100,"memUsage":52428800,"memLimit":907051008,"pids":3}
curl -s -X POST http://169.254.169.254/v1/scale -d '{"memoryMB": 4096}'
-# → {"ok":true,"memoryMB":4096,"cpuPercent":400,"maxPids":0}
+# → {"ok":true,"memoryMB":4096,"cpuPercent":400}
# Auto-calculates: 4GB RAM → 400% CPU (4 vCPUs)
curl -s http://169.254.169.254/v1/metadata
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index cf684ff0..77229c40 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -99,37 +99,41 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {
}
l.mu.Lock()
- if !l.active {
+ if l.active {
l.mu.Unlock()
+ time.Sleep(100 * time.Millisecond)
+ continue
+ }
+ l.mu.Unlock()
- // Drain any stale data from the previous gRPC session.
- // After a gRPC connection drops, the serial port may have leftover
- // bytes (GOAWAY frames, partial HTTP/2 frames). If we hand these to
- // the new gRPC session, it gets a protocol error and closes immediately.
- drainStaleData(l.f)
+ // Drain any stale data from the previous gRPC session.
+ // After a gRPC connection drops, the serial port may have leftover
+ // bytes (GOAWAY frames, partial HTTP/2 frames). If we hand these to
+ // the new gRPC session, it gets a protocol error and closes immediately.
+ drainStaleData(l.f)
- // Wait for the host to connect (port becomes readable with fresh data)
- if waitForReadable(l.f, 500*time.Millisecond) {
- l.mu.Lock()
- if !l.active {
- l.active = true
- l.mu.Unlock()
- log.Printf("agent: virtio-serial Accept: port readable, accepting connection")
- return &virtioSerialConn{
- f: l.f,
- onClose: func() {
- l.mu.Lock()
- l.active = false
- l.mu.Unlock()
- },
- }, nil
- }
- l.mu.Unlock()
- }
+ // Wait for the host to connect (port becomes readable with fresh data)
+ if !waitForReadable(l.f, 500*time.Millisecond) {
continue
}
+
+ // Re-check and set active atomically under a single lock hold
+ l.mu.Lock()
+ if l.active {
+ l.mu.Unlock()
+ continue
+ }
+ l.active = true
l.mu.Unlock()
- time.Sleep(100 * time.Millisecond)
+ log.Printf("agent: virtio-serial Accept: port readable, accepting connection")
+ return &virtioSerialConn{
+ f: l.f,
+ onClose: func() {
+ l.mu.Lock()
+ l.active = false
+ l.mu.Unlock()
+ },
+ }, nil
}
}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 0731435c..7bc9cef7 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -129,9 +129,21 @@ func main() {
return
}
log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))
- shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ shutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
results := qmMgr.HibernateAll(shutCtx, checkpointStore)
cancel()
+
+ // Log which VMs were NOT hibernated
+ var failed []string
+ for _, r := range results {
+ if r.Err != nil {
+ failed = append(failed, r.SandboxID)
+ }
+ }
+ if len(failed) > 0 {
+ log.Printf("opensandbox-worker: %d VMs failed to hibernate: %v", len(failed), failed)
+ }
+
processHibernateResults(results, store, func(r interface{}) (string, string, error) {
hr := r.(qm.HibernateAllResult)
return hr.SandboxID, hr.HibernationKey, hr.Err
diff --git a/internal/agent/exec.go b/internal/agent/exec.go
index a0177025..b06be827 100644
--- a/internal/agent/exec.go
+++ b/internal/agent/exec.go
@@ -283,6 +283,16 @@ func killCgroup() {
syscall.Kill(pid, syscall.SIGKILL)
}
}
+
+ // Brief wait, then check for survivors (e.g., D-state processes immune to SIGKILL)
+ time.Sleep(100 * time.Millisecond)
+ if remaining, err := os.ReadFile(sandboxCgroupProcs); err == nil {
+ lines := strings.TrimSpace(string(remaining))
+ if lines != "" {
+ fmt.Fprintf(os.Stderr, "agent: WARNING: %d PIDs remain in sandbox cgroup after SIGKILL: %s\n",
+ len(strings.Split(lines, "\n")), lines)
+ }
+ }
}
// SetResourceLimits adjusts the sandbox cgroup limits at runtime.
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index f4fb74e2..bb482065 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -612,9 +612,8 @@ func (s *Server) setLimits(c echo.Context) error {
ctx := c.Request().Context()
var req struct {
- MaxPids int `json:"maxPids"`
- MaxMemoryMB int `json:"maxMemoryMB"`
- CPUPercent int `json:"cpuPercent"`
+ MemoryMB int `json:"memoryMB"`
+ CPUPercent int `json:"cpuPercent"`
}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
@@ -622,14 +621,22 @@ func (s *Server) setLimits(c echo.Context) error {
})
}
+ // Auto-calculate CPU from memory: 1 vCPU per 1GB
+ if req.MemoryMB > 0 && req.CPUPercent == 0 {
+ req.CPUPercent = (req.MemoryMB * 100) / 1024
+ if req.CPUPercent < 100 {
+ req.CPUPercent = 100
+ }
+ }
+
// Convert to cgroup values
- maxMemoryBytes := int64(req.MaxMemoryMB) * 1024 * 1024
+ maxMemoryBytes := int64(req.MemoryMB) * 1024 * 1024
cpuMaxUsec := int64(req.CPUPercent) * 1000
cpuPeriodUsec := int64(100000)
// Server mode: dispatch to worker via gRPC
if s.workerRegistry != nil {
- return s.setLimitsRemote(c, id, int32(req.MaxPids), maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)
+ return s.setLimitsRemote(c, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)
}
// Combined mode: apply locally
@@ -637,30 +644,29 @@ func (s *Server) setLimits(c echo.Context) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
- if err := s.manager.SetResourceLimits(ctx, id, int32(req.MaxPids), maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
+ if err := s.manager.SetResourceLimits(ctx, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
- "sandboxID": id,
- "maxPids": req.MaxPids,
- "maxMemoryMB": req.MaxMemoryMB,
- "cpuPercent": req.CPUPercent,
+ "sandboxID": id,
+ "memoryMB": req.MemoryMB,
+ "cpuPercent": req.CPUPercent,
})
}
// scaleSandbox is a simplified scaling endpoint: POST /sandboxes/:id/scale
-// Accepts {"memory_mb": 2048} and auto-calculates CPU (1 vCPU per 1GB).
+// Accepts {"memoryMB": 2048} and auto-calculates CPU (1 vCPU per 1GB).
func (s *Server) scaleSandbox(c echo.Context) error {
id := c.Param("id")
var req struct {
- MemoryMB int `json:"memory_mb"`
+ MemoryMB int `json:"memoryMB"`
}
if err := c.Bind(&req); err != nil || req.MemoryMB <= 0 {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "memory_mb is required and must be positive"})
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "memoryMB is required and must be positive"})
}
// Auto-calculate: 1 vCPU per 1GB = 100% CPU per 1024MB
@@ -725,11 +731,8 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
}
return c.JSON(http.StatusOK, map[string]interface{}{
- "sandboxID": sandboxID,
- "maxPids": maxPids,
- "maxMemoryBytes": maxMemoryBytes,
- "cpuMaxUsec": cpuMaxUsec,
- "cpuPeriodUsec": cpuPeriodUsec,
+ "sandboxID": sandboxID,
+ "ok": true,
})
}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index b18aae7b..b2ec896b 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -108,6 +108,9 @@ type Manager struct {
nextCID uint32
uploadWg sync.WaitGroup
+ // Checkpoint cache mutex: write-locked during cache creation, read-locked during fork
+ checkpointCacheMu sync.RWMutex
+
// Golden snapshot for fast VM creation
goldenDir string // path to golden snapshot dir (empty = not available)
goldenCID uint32 // CID used when the golden snapshot was created
@@ -193,6 +196,13 @@ func (m *Manager) PrepareGoldenSnapshot() error {
memFile := filepath.Join(goldenDir, "mem")
rootfsFile := filepath.Join(goldenDir, "rootfs.qcow2")
+ // If a previous PrepareGoldenSnapshot failed midway, clean up partial files
+ preparingMarker := filepath.Join(goldenDir, ".preparing")
+ if fileExists(preparingMarker) {
+ log.Printf("qemu: golden snapshot has .preparing marker — previous build failed, rebuilding")
+ os.RemoveAll(goldenDir)
+ }
+
// If golden snapshot already exists, just use it
if (fileExists(memFile) || fileExists(memFile+".zst")) && (fileExists(rootfsFile) || fileExists(filepath.Join(goldenDir, "rootfs.ext4"))) {
m.goldenDir = goldenDir
@@ -217,6 +227,11 @@ func (m *Manager) PrepareGoldenSnapshot() error {
return fmt.Errorf("mkdir golden dir: %w", err)
}
+ // Write marker so partial failures are detected on next startup
+ if err := os.WriteFile(preparingMarker, []byte("in-progress"), 0644); err != nil {
+ return fmt.Errorf("write preparing marker: %w", err)
+ }
+
// Prepare rootfs from default template
baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, "default")
if err != nil {
@@ -393,6 +408,9 @@ func (m *Manager) PrepareGoldenSnapshot() error {
log.Printf("qemu: golden mem compressed with zstd")
}
+ // Remove preparing marker — golden snapshot is complete
+ os.Remove(preparingMarker)
+
m.goldenDir = goldenDir
m.goldenCID = goldenCID
m.goldenGuestIP = netCfg.GuestIP
@@ -1166,15 +1184,22 @@ func (m *Manager) destroyVM(vm *VMInstance) error {
vm.agent.Close()
}
- // Try QMP quit first, fall back to process kill
+ // Try QMP quit first, then wait for QEMU to exit before cleaning up files
if vm.qmp != nil {
_ = vm.qmp.Quit()
vm.qmp.Close()
}
if vm.cmd != nil && vm.cmd.Process != nil {
- vm.cmd.Process.Kill()
- vm.cmd.Wait()
+ // Wait for QEMU to exit (with timeout) before removing files it may have open
+ waitDone := make(chan error, 1)
+ go func() { waitDone <- vm.cmd.Wait() }()
+ select {
+ case <-waitDone:
+ case <-time.After(5 * time.Second):
+ vm.cmd.Process.Kill()
+ <-waitDone
+ }
}
if vm.network != nil {
@@ -1456,7 +1481,10 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi
additionalMB = ((additionalMB + 127) / 128) * 128
if additionalMB != vm.virtioMemRequestedMB {
if err := vm.qmp.SetVirtioMemSize(additionalMB); err != nil {
- log.Printf("qemu: virtio-mem %s: set %dMB failed: %v", sandboxID, additionalMB, err)
+ log.Printf("qemu: virtio-mem %s: set %dMB failed: %v — capping cgroup to current VM memory", sandboxID, additionalMB, err)
+ // Cap cgroup memory limit to actual VM memory so we don't set
+ // cgroup higher than the physical RAM available to the guest.
+ maxMemoryBytes = int64(vm.MemoryMB) * 1024 * 1024
} else {
vm.virtioMemRequestedMB = additionalMB
vm.MemoryMB = vm.baseMemoryMB + additionalMB
@@ -1608,8 +1636,13 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
// Reconnect agent + remount workspace (VM resumed after savevm)
agentClient, reconnErr := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 10*time.Second)
if reconnErr != nil {
- log.Printf("qemu: CreateCheckpoint %s/%s: agent reconnect failed: %v", sandboxID, checkpointID, reconnErr)
- } else {
+ log.Printf("qemu: CreateCheckpoint %s/%s: agent reconnect failed (attempt 1): %v, retrying with longer timeout", sandboxID, checkpointID, reconnErr)
+ agentClient, reconnErr = m.waitForAgentSocket(context.Background(), vm.agentSockPath, 30*time.Second)
+ if reconnErr != nil {
+ log.Printf("qemu: CreateCheckpoint %s/%s: WARNING: agent reconnect failed after retry: %v (checkpoint is valid, agent connection lost temporarily)", sandboxID, checkpointID, reconnErr)
+ }
+ }
+ if reconnErr == nil {
vm.agent = agentClient
mountCtx, mountCancel := context.WithTimeout(context.Background(), 5*time.Second)
_, _ = agentClient.Exec(mountCtx, &pb.ExecRequest{
@@ -1622,6 +1655,8 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
// Cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process).
// Synchronous: reflink copy is instant (~1ms), and the image builder destroys the
// build sandbox immediately after checkpoint — async would race with destruction.
+ m.checkpointCacheMu.Lock()
+ defer m.checkpointCacheMu.Unlock()
cacheDir := m.checkpointCacheDir(checkpointID)
rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)
workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)
@@ -1729,6 +1764,9 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
// The new sandbox gets its own network, CID, and drives (reflinked from cache).
func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error) {
t0 := time.Now()
+
+ // Lock checkpoint cache for reading — prevents race with CreateCheckpoint writing cache
+ m.checkpointCacheMu.RLock()
cacheDir := m.checkpointCacheDir(checkpointID)
metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")
@@ -1736,6 +1774,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
cachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")
cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")
if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {
+ m.checkpointCacheMu.RUnlock()
return nil, fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)
}
@@ -1756,6 +1795,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
}
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", id)
if err := os.MkdirAll(sandboxDir, 0755); err != nil {
+ m.checkpointCacheMu.RUnlock()
return nil, fmt.Errorf("mkdir sandbox dir: %w", err)
}
@@ -1763,13 +1803,16 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")
workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")
if err := copyFileReflink(cachedRootfs, rootfsPath); err != nil {
+ m.checkpointCacheMu.RUnlock()
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("copy rootfs: %w", err)
}
if err := copyFileReflink(cachedWorkspace, workspacePath); err != nil {
+ m.checkpointCacheMu.RUnlock()
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("copy workspace: %w", err)
}
+ m.checkpointCacheMu.RUnlock()
// Allocate network
netCfg, err := m.subnets.Allocate()
diff --git a/internal/qemu/network.go b/internal/qemu/network.go
index d219ab8b..1855b3a6 100644
--- a/internal/qemu/network.go
+++ b/internal/qemu/network.go
@@ -164,10 +164,17 @@ func AddDNAT(cfg *NetworkConfig) error {
}
// Also add for locally-generated traffic
- _ = run("iptables", "-t", "nat", "-A", "OUTPUT",
+ if err := run("iptables", "-t", "nat", "-A", "OUTPUT",
"-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
"-j", "DNAT", "--to-destination",
- fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort)); err != nil {
+ // Roll back the PREROUTING rule we already added
+ _ = run("iptables", "-t", "nat", "-D", "PREROUTING",
+ "-p", "tcp", "--dport", fmt.Sprintf("%d", cfg.HostPort),
+ "-j", "DNAT", "--to-destination",
+ fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
+ return fmt.Errorf("add DNAT OUTPUT: %w", err)
+ }
cfg.DNATRuleAdded = true
return nil
@@ -272,6 +279,10 @@ func detectDefaultInterface() string {
}
// FindFreePort finds a free TCP port on the host.
+// Note: This has a TOCTOU race — two concurrent calls can get the same port.
+// In practice this is acceptable because the port is used for DNAT rules (not
+// a real listener), so collisions are extremely unlikely and would only occur
+// if two sandboxes are created in the same microsecond window.
func FindFreePort() (int, error) {
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 78188ffa..c0bcf391 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -57,18 +57,21 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
return nil, fmt.Errorf("mkdir snapshot dir: %w", err)
}
- // Step 1: Sync filesystems, unmount workspace, close agent.
- // Same as CreateCheckpoint — puts agent in Accept() mode so loadvm
- // on wake gets instant reconnection.
+ // Step 1: Sync filesystems, unmount workspace, quiesce agent.
+ // Send SIGUSR1 to PID 1 (agent) which calls PrepareHibernate() to reset
+ // the virtio-serial listener's active flag. This ensures savevm captures
+ // the agent in a clean "waiting for connection" state so loadvm on wake
+ // gets instant reconnection instead of waiting ~4s for gRPC timeout.
if vm.agent != nil {
shutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
_, _ = vm.agent.Exec(shutdownCtx, &pb.ExecRequest{
Command: "/bin/sh",
- Args: []string{"-c", "umount /workspace 2>/dev/null; sync"},
+ Args: []string{"-c", "umount /workspace 2>/dev/null; sync; kill -USR1 1"},
})
cancel()
vm.agent.Close()
vm.agent = nil
+ time.Sleep(500 * time.Millisecond) // let guest process SIGUSR1
}
log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())
@@ -80,6 +83,14 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
}
snapshotName := "hibernate"
if err := vm.qmp.SaveVM(snapshotName); err != nil {
+ // Try to resume VM so it's not left in a broken paused state
+ if contErr := vm.qmp.Cont(); contErr != nil {
+ log.Printf("qemu: hibernate %s: failed to resume after savevm failure: %v", vm.ID, contErr)
+ }
+ // Try to reconnect agent
+ if agent, reconnErr := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 5*time.Second); reconnErr == nil {
+ vm.agent = agent
+ }
return nil, fmt.Errorf("savevm failed: %w", err)
}
log.Printf("qemu: hibernate %s: savevm complete (%dms)", vm.ID, time.Since(t0).Milliseconds())
@@ -176,13 +187,13 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if _, err := checkpointStore.Upload(uploadCtx, checkpointKey, archivePath); err != nil {
- log.Printf("qemu: async S3 upload failed for %s: %v", sandboxID, err)
+ log.Printf("qemu: async S3 upload failed for %s: %v (keeping local archive for retry)", sandboxID, err)
return
}
log.Printf("qemu: hibernate %s: S3 upload complete (%dms, key=%s)",
sandboxID, time.Since(t2).Milliseconds(), checkpointKey)
- os.Remove(archivePath)
+ os.Remove(archivePath) // only delete after successful upload
}()
return &sandbox.HibernateResult{
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index e62237cf..c249f98b 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -189,6 +189,22 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
}
}
+ // Record initial scale event for billing
+ if s.store != nil {
+ memMB := cfg.MemoryMB
+ if memMB <= 0 {
+ memMB = 1024 // default
+ }
+ cpuPct := (memMB * 100) / 1024
+ if cpuPct < 100 {
+ cpuPct = 100
+ }
+ orgID := "00000000-0000-0000-0000-000000000001" // TODO: resolve from session
+ if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct); err != nil {
+ log.Printf("grpc: failed to record initial scale event for %s: %v", sb.ID, err)
+ }
+ }
+
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
@@ -196,6 +212,13 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
}
func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRequest) (*pb.DestroySandboxResponse, error) {
+ // End billing scale event before destroying
+ if s.store != nil {
+ if err := s.store.EndScaleEvent(ctx, req.SandboxId); err != nil {
+ log.Printf("grpc: failed to end scale event for %s: %v", req.SandboxId, err)
+ }
+ }
+
if err := s.manager.Kill(ctx, req.SandboxId); err != nil {
return nil, fmt.Errorf("failed to destroy sandbox: %w", err)
}
@@ -474,6 +497,13 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSand
return nil, fmt.Errorf("hibernation not configured on this worker")
}
+ // End billing scale event (sandbox going to sleep)
+ if s.store != nil {
+ if err := s.store.EndScaleEvent(ctx, req.SandboxId); err != nil {
+ log.Printf("grpc: failed to end scale event on hibernate for %s: %v", req.SandboxId, err)
+ }
+ }
+
result, err := s.manager.Hibernate(ctx, req.SandboxId, s.checkpointStore)
if err != nil {
return nil, fmt.Errorf("failed to hibernate sandbox: %w", err)
@@ -525,6 +555,16 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
}
}
+ // Resume billing scale event after wake
+ if s.store != nil {
+ memMB := 1024 // TODO: get actual memory from sandbox state
+ cpuPct := 100
+ orgID := "00000000-0000-0000-0000-000000000001"
+ if err := s.store.RecordScaleEvent(ctx, sb.ID, orgID, memMB, cpuPct); err != nil {
+ log.Printf("grpc: failed to record scale event on wake for %s: %v", sb.ID, err)
+ }
+ }
+
return &pb.WakeSandboxResponse{
SandboxId: sb.ID,
Status: string(sb.Status),
@@ -770,6 +810,17 @@ func (s *GRPCServer) SetSandboxLimits(ctx context.Context, req *pb.SetSandboxLim
if err := s.manager.SetResourceLimits(ctx, req.SandboxId, req.MaxPids, req.MaxMemoryBytes, req.CpuMaxUsec, req.CpuPeriodUsec); err != nil {
return nil, fmt.Errorf("set resource limits: %w", err)
}
+
+ // Record scale event for billing
+ if s.store != nil && req.MaxMemoryBytes > 0 {
+ memMB := int(req.MaxMemoryBytes / (1024 * 1024))
+ cpuPct := int(req.CpuMaxUsec / 1000) // 100000us → 100%
+ orgID := "00000000-0000-0000-0000-000000000001" // TODO: resolve from sandbox session
+ if err := s.store.RecordScaleEvent(ctx, req.SandboxId, orgID, memMB, cpuPct); err != nil {
+ log.Printf("grpc: failed to record scale event for %s: %v", req.SandboxId, err)
+ }
+ }
+
return &pb.SetSandboxLimitsResponse{}, nil
}
diff --git a/internal/worker/metadata.go b/internal/worker/metadata.go
index a9428793..113528b5 100644
--- a/internal/worker/metadata.go
+++ b/internal/worker/metadata.go
@@ -183,7 +183,7 @@ func (ms *MetadataServer) handleLimits(w http.ResponseWriter, r *http.Request) {
})
}
-// POST /v1/scale → accepts {"memoryMB", "cpuPercent", "maxPids"}, applies cgroup limits.
+// POST /v1/scale → accepts {"memoryMB", "cpuPercent", "pids"}, applies cgroup limits.
// Pricing model: 1 vCPU per 1GB RAM. memoryMB=2048 → cpuPercent=200 (2 vCPUs).
func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -200,44 +200,34 @@ func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {
var req struct {
MemoryMB int `json:"memoryMB"`
CPUPercent int `json:"cpuPercent"`
- MaxPids int `json:"maxPids"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
return
}
- // Apply pricing model: 1 vCPU per 1GB RAM
- // If memoryMB is set but cpuPercent is not, auto-calculate
+ // Auto-calculate CPU from memory: 1 vCPU per 1GB
if req.MemoryMB > 0 && req.CPUPercent == 0 {
- // 1 vCPU = 100% = 1024 MB
req.CPUPercent = (req.MemoryMB * 100) / 1024
if req.CPUPercent < 100 {
- req.CPUPercent = 100 // minimum 1 vCPU
+ req.CPUPercent = 100
}
}
// Convert to cgroup values
- var maxPids int32
var maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64
-
- if req.MaxPids > 0 {
- maxPids = int32(req.MaxPids)
- }
if req.MemoryMB > 0 {
maxMemoryBytes = int64(req.MemoryMB) * 1024 * 1024
}
if req.CPUPercent > 0 {
- // cpu.max format: $MAX $PERIOD
- // cpuPercent=200 means 2 vCPUs → cpuMaxUsec=200000, cpuPeriodUsec=100000
cpuPeriodUsec = 100000
- cpuMaxUsec = int64(req.CPUPercent) * 1000 // 100% = 100000us per 100000us period
+ cpuMaxUsec = int64(req.CPUPercent) * 1000
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
- if err := ms.manager.SetResourceLimits(ctx, entry.SandboxID, maxPids, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
+ if err := ms.manager.SetResourceLimits(ctx, entry.SandboxID, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
http.Error(w, fmt.Sprintf("failed to set limits: %v", err), http.StatusInternalServerError)
return
}
@@ -247,7 +237,6 @@ func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {
"ok": true,
"memoryMB": req.MemoryMB,
"cpuPercent": req.CPUPercent,
- "maxPids": req.MaxPids,
})
}
diff --git a/scripts/bench-qemu.sh b/scripts/bench-qemu.sh
index ccc9aa0a..d3833c05 100755
--- a/scripts/bench-qemu.sh
+++ b/scripts/bench-qemu.sh
@@ -34,6 +34,27 @@ bench() {
ALL_TIMES+=("${times[*]}")
}
+# bench_wait: like bench but waits for sandbox to be reachable between iterations
+bench_wait() {
+ local label="$1"; shift
+ local times=()
+ for i in $(seq 1 "$RUNS"); do
+ local t0=$(ms)
+ eval "$@" > /dev/null 2>&1
+ local t1=$(ms)
+ local dt=$((t1 - t0))
+ times+=($dt)
+ printf " #%d: %dms\n" "$i" "$dt"
+ # Wait for sandbox to be reachable before next iteration
+ for _r in $(seq 1 30); do
+ curl -s -X POST "$API/api/sandboxes/$SB/exec/run" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d '{"cmd":"true","args":[],"timeout":3}' > /dev/null 2>&1 && break
+ sleep 1
+ done
+ done
+ LABELS+=("$label")
+ ALL_TIMES+=("${times[*]}")
+}
+
stats() {
local nums=($1)
local sorted=($(printf '%s\n' "${nums[@]}" | sort -n))
@@ -60,21 +81,40 @@ for s in json.load(sys.stdin):
except: pass
" 2>/dev/null
+# ── Warm caches ──
+# Create+destroy a sandbox to warm QEMU binary/library page caches,
+# golden snapshot disk cache, and gRPC code paths.
+echo "Warming caches..."
+_WID=$(curl -s -X POST "$API/api/sandboxes" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d '{"timeout":60}' | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null)
+curl -s -X POST "$API/api/sandboxes/$_WID/exec/run" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d '{"cmd":"echo","args":["warm"],"timeout":5}' > /dev/null 2>&1
+curl -s -X POST "$API/api/sandboxes/$_WID/hibernate" -H "X-API-Key: $KEY" > /dev/null 2>&1
+sleep 3
+curl -s -X POST "$API/api/sandboxes/$_WID/wake" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d '{"timeout":60}' > /dev/null 2>&1
+sleep 1
+curl -s -X DELETE "$API/api/sandboxes/$_WID" -H "X-API-Key: $KEY" > /dev/null 2>&1
+sleep 1
+echo "Caches warm."
+
echo ""
echo "╔══════════════════════════════════════════════════════╗"
echo "║ QEMU Sandbox Benchmark ($RUNS runs each) ║"
echo "╚══════════════════════════════════════════════════════╝"
echo ""
-# ── Create sandbox ──
+# ── Create sandbox (each run creates then immediately deletes) ──
h "Create sandbox"
-SANDBOX_IDS=()
+BENCH_SIDS=()
bench "Create sandbox" '
R=$(curl -s -X POST "$API/api/sandboxes" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"timeout\":300}")
SID=$(echo "$R" | python3 -c "import sys,json; print(json.load(sys.stdin)[\"sandboxID\"])" 2>/dev/null)
- SANDBOX_IDS+=("$SID")
+ BENCH_SIDS+=("$SID")
'
+# Clean up create-bench sandboxes before creating the long-lived one
+for sid in "${BENCH_SIDS[@]}"; do
+ curl -s -X DELETE "$API/api/sandboxes/$sid" -H "X-API-Key: $KEY" > /dev/null 2>&1
+done
# Keep one sandbox for subsequent tests
+sleep 1
SB=$(curl -s -X POST "$API/api/sandboxes" -H 'Content-Type: application/json' -H "X-API-Key: $KEY" -d '{"timeout":600}' | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")
# ── Exec/run (simple command) ──
@@ -107,12 +147,6 @@ bench "List dir" '
curl -s "$API/api/sandboxes/$SB/files/list?path=/workspace" -H "X-API-Key: $KEY"
'
-# ── Scale up (memory hotplug) ──
-h "Scale up (1GB → 2GB)"
-bench "Scale up" '
- curl -s -X PUT "$API/api/sandboxes/$SB/limits" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"maxMemoryMB\":2048}"
-'
-
# ── Metadata API (from inside VM) ──
h "Metadata /v1/status (from inside VM)"
bench "Metadata status" '
@@ -121,17 +155,14 @@ bench "Metadata status" '
# ── Create checkpoint ──
h "Create checkpoint"
-CP_IDS=()
-bench "Create checkpoint" '
+LAST_CP=""
+bench_wait "Create checkpoint" '
R=$(curl -s -X POST "$API/api/sandboxes/$SB/checkpoints" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"name\":\"bench-$(date +%s)\"}")
- CPID=$(echo "$R" | python3 -c "import sys,json; print(json.load(sys.stdin)[\"id\"])" 2>/dev/null)
- CP_IDS+=("$CPID")
+ LAST_CP=$(echo "$R" | python3 -c "import sys,json; print(json.load(sys.stdin)[\"id\"])" 2>/dev/null)
'
-
-# Wait for last checkpoint to be ready
-LAST_CP="${CP_IDS[-1]:-}"
+# Wait for last checkpoint to be ready before restore tests
if [ -n "$LAST_CP" ]; then
- for i in $(seq 1 20); do
+ for i in $(seq 1 30); do
S=$(curl -s "$API/api/sandboxes/$SB/checkpoints/$LAST_CP" -H "X-API-Key: $KEY" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','?'))" 2>/dev/null)
[ "$S" = "ready" ] && break; sleep 1
done
@@ -140,15 +171,15 @@ fi
# ── Restore checkpoint (in-place) ──
h "Restore checkpoint (in-place)"
if [ -n "$LAST_CP" ]; then
- bench "Restore checkpoint" '
+ bench_wait "Restore checkpoint" '
curl -s -X POST "$API/api/sandboxes/$SB/checkpoints/$LAST_CP/restore" -H "Content-Type: application/json" -H "X-API-Key: $KEY"
'
fi
-# ── First command after restore ──
+# ── First command after restore (measures agent reconnect latency) ──
h "First exec after restore"
bench "First exec after restore" '
- curl -s -X POST "$API/api/sandboxes/$SB/exec/run" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"cmd\":\"echo\",\"args\":[\"restored\"],\"timeout\":5}"
+ curl -s -X POST "$API/api/sandboxes/$SB/exec/run" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"cmd\":\"echo\",\"args\":[\"restored\"],\"timeout\":10}"
'
# ── Fork from checkpoint ──
@@ -166,17 +197,34 @@ if [ -n "$LAST_CP" ]; then
'
fi
-# ── Hibernate ──
-h "Hibernate"
-bench "Hibernate" '
- curl -s -X POST "$API/api/sandboxes/$SB/hibernate" -H "X-API-Key: $KEY"
- sleep 2
-'
+# ── Hibernate + Wake (measured separately but run as pairs) ──
+h "Hibernate + Wake"
+HIB_TIMES=()
+WAKE_TIMES=()
+for i in $(seq 1 "$RUNS"); do
+ T0=$(ms)
+ curl -s -X POST "$API/api/sandboxes/$SB/hibernate" -H "X-API-Key: $KEY" > /dev/null 2>&1
+ T1=$(ms)
+ sleep 3 # let QEMU fully exit
+ T2=$(ms)
+ curl -s -X POST "$API/api/sandboxes/$SB/wake" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"timeout\":300}" > /dev/null 2>&1
+ T3=$(ms)
+ HIB_DT=$((T1-T0)); WAKE_DT=$((T3-T2))
+ HIB_TIMES+=($HIB_DT); WAKE_TIMES+=($WAKE_DT)
+ printf " #%d: hibernate=%dms wake=%dms\n" "$i" "$HIB_DT" "$WAKE_DT"
+ # Wait for sandbox to be reachable before next iteration
+ for _r in $(seq 1 30); do
+ curl -s -X POST "$API/api/sandboxes/$SB/exec/run" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d '{"cmd":"true","args":[],"timeout":3}' > /dev/null 2>&1 && break
+ sleep 1
+ done
+done
+LABELS+=("Hibernate"); ALL_TIMES+=("${HIB_TIMES[*]}")
+LABELS+=("Wake"); ALL_TIMES+=("${WAKE_TIMES[*]}")
-# ── Wake ──
-h "Wake"
-bench "Wake" '
- curl -s -X POST "$API/api/sandboxes/$SB/wake" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"timeout\":300}"
+# ── Scale up (memory hotplug) — after hibernate/wake to avoid inflating archives ──
+h "Scale up (1GB → 2GB)"
+bench "Scale up" '
+ curl -s -X PUT "$API/api/sandboxes/$SB/limits" -H "Content-Type: application/json" -H "X-API-Key: $KEY" -d "{\"memoryMB\":2048}"
'
# ── Get sandbox ──
@@ -202,9 +250,6 @@ bench "Delete sandbox" '
# ── Cleanup ──
h "Cleanup"
curl -s -X DELETE "$API/api/sandboxes/$SB" -H "X-API-Key: $KEY" > /dev/null
-for sid in "${SANDBOX_IDS[@]}"; do
- curl -s -X DELETE "$API/api/sandboxes/$sid" -H "X-API-Key: $KEY" > /dev/null 2>&1
-done
echo " Cleaned up"
# ── Results ──