Skip to content

An open-source, faster Devin alternative

TypeScript

workng wip

Brian Reardon9410e8b6686c
diff --git a/.github/workflows/build-worker-ami.yml b/.github/workflows/build-worker-ami.yml
new file mode 100644
index 00000000..48de139a
--- /dev/null
+++ b/.github/workflows/build-worker-ami.yml
@@ -0,0 +1,124 @@
+name: Build Worker Image
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'cmd/worker/**'
+ - 'cmd/agent/**'
+ - 'internal/**'
+ - 'proto/**'
+ - 'deploy/firecracker/rootfs/**'
+ - 'deploy/azure/**'
+ - 'deploy/ec2/build-rootfs-docker.sh'
+ - 'deploy/packer/**'
+ - 'scripts/claude-agent-wrapper/**'
+ - 'go.mod'
+ - 'go.sum'
+ - '.github/workflows/build-worker-ami.yml'
+ workflow_dispatch:
+
+env:
+ AZURE_RESOURCE_GROUP: ${{ secrets.AZURE_RESOURCE_GROUP }}
+ AZURE_LOCATION: westus2
+ AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
+
+jobs:
+ build-image:
+ name: Build Worker Image (Azure)
+ runs-on: ubuntu-latest
+ permissions:
+ id-token: write
+ contents: read
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.23'
+
+ - name: Build binaries (amd64)
+ run: |
+ VERSION=$(git rev-parse --short HEAD)
+ echo "VERSION=$VERSION" >> $GITHUB_ENV
+
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
+ -ldflags "-X main.WorkerVersion=$VERSION -X main.AgentVersion=$VERSION" \
+ -o bin/opensandbox-worker ./cmd/worker/
+
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
+ -ldflags "-X main.Version=$VERSION" \
+ -o bin/osb-agent ./cmd/agent/
+
+ - name: Azure Login
+ uses: azure/login@v2
+ with:
+ client-id: ${{ secrets.AZURE_CLIENT_ID }}
+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
+
+ - name: Setup Packer
+ uses: hashicorp/setup-packer@main
+
+ - name: Packer init
+ run: packer init deploy/packer/worker-ami.pkr.hcl
+
+ - name: Build image
+ run: |
+ packer build \
+ -var "worker_version=$VERSION" \
+ -var "agent_version=$VERSION" \
+ -var "subscription_id=$AZURE_SUBSCRIPTION_ID" \
+ -var "resource_group=$AZURE_RESOURCE_GROUP" \
+ -var "location=$AZURE_LOCATION" \
+ deploy/packer/worker-ami.pkr.hcl | tee /tmp/packer-output.txt
+
+ # Extract the managed image resource ID from Packer output
+ IMAGE_ID=$(grep -oP '/subscriptions/[^\s"]+' /tmp/packer-output.txt | tail -1)
+ if [ -z "$IMAGE_ID" ]; then
+ # Construct it from known values
+ IMAGE_NAME="opensandbox-worker-${VERSION}"
+ IMAGE_ID="/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP}/providers/Microsoft.Compute/images/${IMAGE_NAME}"
+ fi
+ echo "IMAGE_ID=$IMAGE_ID" >> $GITHUB_ENV
+ echo "Built image: $IMAGE_ID"
+
+ - name: Store image ID in Key Vault
+ run: |
+ az keyvault secret set \
+ --vault-name "${{ secrets.AZURE_KEY_VAULT_NAME }}" \
+ --name "worker-image-id" \
+ --value "$IMAGE_ID"
+
+ az keyvault secret set \
+ --vault-name "${{ secrets.AZURE_KEY_VAULT_NAME }}" \
+ --name "worker-image-version" \
+ --value "$VERSION"
+
+ echo "Published image ID to Key Vault"
+
+ - name: Cleanup old images
+ run: |
+ # List all worker images, keep the 5 most recent
+ IMAGES=$(az image list \
+ --resource-group "$AZURE_RESOURCE_GROUP" \
+ --query "[?tags.\"opensandbox-role\"=='worker'] | sort_by(@, &name) | reverse(@)" \
+ --output json)
+
+ STALE=$(echo "$IMAGES" | jq -r '.[5:] | .[].name')
+ if [ -z "$STALE" ]; then
+ echo "No old images to clean up"
+ exit 0
+ fi
+
+ for name in $STALE; do
+ echo "Deleting old image: $name"
+ az image delete --resource-group "$AZURE_RESOURCE_GROUP" --name "$name" || true
+ done
+
+ - name: Summary
+ run: |
+ echo "## Worker Image Build Complete" >> $GITHUB_STEP_SUMMARY
+ echo "- **Image:** $IMAGE_ID" >> $GITHUB_STEP_SUMMARY
+ echo "- **Version:** $VERSION" >> $GITHUB_STEP_SUMMARY
+ echo "- **Location:** $AZURE_LOCATION" >> $GITHUB_STEP_SUMMARY
diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml
index 4d569d87..063f5622 100644
--- a/.github/workflows/deploy-worker.yml
+++ b/.github/workflows/deploy-worker.yml
@@ -1,19 +1,8 @@
-name: Deploy Worker
+name: Deploy Worker (Hotfix)
+# Emergency hotfix: SSH-deploy binaries to running workers without waiting for AMI build.
+# For normal deploys, use build-worker-ami.yml which builds an immutable AMI.
on:
- push:
- branches: [main]
- paths:
- - 'cmd/worker/**'
- - 'cmd/agent/**'
- - 'internal/**'
- - 'proto/**'
- - 'deploy/firecracker/rootfs/**'
- - 'deploy/ec2/build-rootfs-docker.sh'
- - 'scripts/claude-agent-wrapper/**'
- - 'go.mod'
- - 'go.sum'
- - '.github/workflows/deploy-worker.yml'
workflow_dispatch:
env:
diff --git a/Makefile b/Makefile
index 316572bf..5fc7ea15 100644
--- a/Makefile
+++ b/Makefile
@@ -6,7 +6,9 @@ BINARY_WORKER = opensandbox-worker
BINARY_AGENT = osb-agent
BUILD_DIR = bin
VERSION ?= $(shell cat VERSION | tr -d '[:space:]').dev
+GIT_SHA ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "dev")
LDFLAGS_OC = -s -w -X github.com/opensandbox/opensandbox/cmd/oc/internal/commands.Version=$(VERSION)
+LDFLAGS_WORKER = -X main.WorkerVersion=$(GIT_SHA) -X main.AgentVersion=$(GIT_SHA)
## help: Show this help message
help:
@@ -21,11 +23,11 @@ build-server:
## build-worker: Build the sandbox worker
build-worker:
- CGO_ENABLED=1 go build -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker
+ CGO_ENABLED=1 go build -ldflags "$(LDFLAGS_WORKER)" -o $(BUILD_DIR)/$(BINARY_WORKER) ./cmd/worker
## build-worker-arm64: Cross-compile worker for Linux ARM64 (Graviton bare-metal)
build-worker-arm64:
- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o $(BUILD_DIR)/$(BINARY_WORKER)-arm64 ./cmd/worker
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS_WORKER)" -o $(BUILD_DIR)/$(BINARY_WORKER)-arm64 ./cmd/worker
## build-agent: Build the in-VM agent (static binary for Linux ARM64)
build-agent:
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index 77229c40..a6b2895b 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -80,6 +80,11 @@ func listenVirtioSerial(path string) (net.Listener, error) {
return nil, fmt.Errorf("open virtio-serial %s: %w", path, err)
}
+ // Mark CLOEXEC so the fd is closed on agent re-exec (upgrade).
+ // Without this, syscall.Exec inherits the fd, the host never sees the
+ // connection drop, and the new agent can't get a clean Accept.
+ unix.CloseOnExec(int(f.Fd()))
+
return &virtioSerialListener{
f: f,
closed: make(chan struct{}),
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 9767e62f..5fbf2aba 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -160,7 +160,7 @@ func main() {
var pool compute.Pool
var poolName string
- if cfg.AzureSubscriptionID != "" && cfg.AzureImageID != "" {
+ if cfg.AzureSubscriptionID != "" && (cfg.AzureImageID != "" || cfg.AzureKeyVaultName != "") {
// Build worker env template — new VMs get this via cloud-init.
// GRPC_ADVERTISE, HTTP_ADDR, and WORKER_ID are patched by cloud-init
// with the VM's actual private IP and hostname.
@@ -188,7 +188,7 @@ func main() {
"OPENSANDBOX_JWT_SECRET=%s\n"+
"OPENSANDBOX_WORKER_ID=PLACEHOLDER\n"+
"OPENSANDBOX_REGION=%s\n"+
- "OPENSANDBOX_MAX_CAPACITY=100\n"+
+ "OPENSANDBOX_MAX_CAPACITY=%d\n"+
"OPENSANDBOX_PORT=8081\n"+
"OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=%d\n"+
"OPENSANDBOX_DEFAULT_SANDBOX_CPUS=%d\n"+
@@ -201,6 +201,7 @@ func main() {
"OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n",
cfg.JWTSecret,
cfg.Region,
+ cfg.MaxCapacity,
cfg.DefaultSandboxMemoryMB,
cfg.DefaultSandboxCPUs,
workerDBURL,
@@ -221,15 +222,24 @@ func main() {
ImageID: cfg.AzureImageID,
SubnetID: cfg.AzureSubnetID,
SSHPublicKey: cfg.AzureSSHPublicKey,
+ KeyVaultName: cfg.AzureKeyVaultName,
WorkerEnvBase64: workerEnvB64,
})
if err != nil {
log.Fatalf("opensandbox: failed to create Azure pool: %v", err)
}
+ // If image not set statically but Key Vault is configured, fetch initial image
+ if cfg.AzureImageID == "" && cfg.AzureKeyVaultName != "" {
+ imgID, version, kvErr := azPool.RefreshAMI(context.Background())
+ if kvErr != nil {
+ log.Fatalf("opensandbox: Azure image not set and Key Vault fetch failed: %v", kvErr)
+ }
+ log.Printf("opensandbox: Azure image from Key Vault: %s (version=%s)", imgID, version)
+ }
pool = azPool
- poolName = fmt.Sprintf("Azure (size=%s, image=%s)", cfg.AzureVMSize, cfg.AzureImageID)
- } else if cfg.EC2AMI != "" {
- // AWS EC2 compute pool
+ poolName = fmt.Sprintf("Azure (size=%s, image=%s, keyvault=%s)", cfg.AzureVMSize, cfg.AzureImageID, cfg.AzureKeyVaultName)
+ } else if cfg.EC2AMI != "" || cfg.EC2SSMParameterName != "" {
+ // AWS EC2 compute pool (AMI from config or dynamically from SSM)
ec2Pool, err := compute.NewEC2Pool(compute.EC2PoolConfig{
Region: cfg.S3Region,
AccessKeyID: cfg.S3AccessKeyID,
@@ -241,12 +251,21 @@ func main() {
KeyName: cfg.EC2KeyName,
IAMInstanceProfile: cfg.EC2IAMInstanceProfile,
SecretsARN: cfg.SecretsARN,
+ SSMParameterName: cfg.EC2SSMParameterName,
})
if err != nil {
log.Fatalf("opensandbox: failed to create EC2 pool: %v", err)
}
+ // If AMI not set statically but SSM is configured, fetch initial AMI from SSM
+ if cfg.EC2AMI == "" && cfg.EC2SSMParameterName != "" {
+ amiID, version, ssmErr := ec2Pool.RefreshAMI(context.Background())
+ if ssmErr != nil {
+ log.Fatalf("opensandbox: EC2 AMI not set and SSM fetch failed: %v", ssmErr)
+ }
+ log.Printf("opensandbox: EC2 AMI from SSM: %s (version=%s)", amiID, version)
+ }
pool = ec2Pool
- poolName = fmt.Sprintf("EC2 (ami=%s, type=%s)", cfg.EC2AMI, cfg.EC2InstanceType)
+ poolName = fmt.Sprintf("EC2 (ami=%s, type=%s, ssm=%s)", cfg.EC2AMI, cfg.EC2InstanceType, cfg.EC2SSMParameterName)
}
if pool != nil {
@@ -258,6 +277,7 @@ func main() {
Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,
MinWorkers: cfg.MinWorkersPerRegion,
MaxWorkers: cfg.MaxWorkersPerRegion,
+ IdleReserve: cfg.IdleReserveWorkers,
})
scaler.Start()
defer scaler.Stop()
@@ -265,6 +285,22 @@ func main() {
}
}
+ // Stale migration recovery — reset sandboxes stuck in 'migrating' state
+ if opts.Store != nil {
+ go func() {
+ ticker := time.NewTicker(60 * time.Second)
+ defer ticker.Stop()
+ for range ticker.C {
+ recovered, err := opts.Store.RecoverStaleMigrations(context.Background(), 10*time.Minute)
+ if err != nil {
+ log.Printf("stale-migration-recovery: error: %v", err)
+ } else if recovered > 0 {
+ log.Printf("stale-migration-recovery: reverted %d stale migrations", recovered)
+ }
+ }
+ }()
+ }
+
// Initialize control plane subdomain proxy (server mode only).
// Routes *.workers.opensandbox.ai requests to the correct worker
// by looking up sandbox → worker mapping in PG + Redis registry.
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 9dc14b8c..507eaf01 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -29,6 +29,9 @@ import (
// AgentVersion is the expected agent version, set at build time via -ldflags.
var AgentVersion = "dev"
+// WorkerVersion is the worker binary version (git SHA), set at build time via -ldflags.
+var WorkerVersion = "dev"
+
func main() {
// Load secrets from Azure Key Vault if configured (before config.Load reads env vars).
if err := config.LoadSecretsFromKeyVault(); err != nil {
@@ -40,7 +43,7 @@ func main() {
log.Fatalf("failed to load config: %v", err)
}
- log.Printf("opensandbox-worker: starting (id=%s, region=%s, backend=qemu)...", cfg.WorkerID, cfg.Region)
+ log.Printf("opensandbox-worker: starting (id=%s, region=%s, version=%s, backend=qemu)...", cfg.WorkerID, cfg.Region, WorkerVersion)
ctx := context.Background()
@@ -327,6 +330,7 @@ func main() {
if err != nil {
log.Printf("opensandbox-worker: Redis heartbeat not available: %v", err)
} else {
+ hb.SetWorkerVersion(WorkerVersion)
if qemuMgr != nil {
hb.SetGoldenVersion(qemuMgr.GoldenVersion())
}
@@ -345,6 +349,31 @@ func main() {
cpuPct, memPct, diskPct := worker.SystemStats()
return cfg.MaxCapacity, count, cpuPct, memPct, diskPct
})
+ // On reconnect after outage, reconcile sandbox state with DB
+ if store != nil {
+ hb.OnReconnect(func() {
+ sandboxes, err := mgr.List(context.Background())
+ if err != nil {
+ log.Printf("opensandbox-worker: reconnect reconciliation failed (list): %v", err)
+ return
+ }
+ var runningIDs []string
+ for _, sb := range sandboxes {
+ if sb.Status == "running" {
+ runningIDs = append(runningIDs, sb.ID)
+ }
+ }
+ if len(runningIDs) == 0 {
+ return
+ }
+ fixed, err := store.ReconcileWorkerReconnect(context.Background(), cfg.WorkerID, runningIDs)
+ if err != nil {
+ log.Printf("opensandbox-worker: reconnect reconciliation failed: %v", err)
+ } else if fixed > 0 {
+ log.Printf("opensandbox-worker: reconnect reconciliation: %d sessions restored to running", fixed)
+ }
+ })
+ }
defer hb.Stop()
log.Println("opensandbox-worker: Redis heartbeat started")
}
diff --git a/deploy/azure/create-opencomputer-prod.sh b/deploy/azure/create-opencomputer-prod.sh
index 0366ca37..134ed573 100755
--- a/deploy/azure/create-opencomputer-prod.sh
+++ b/deploy/azure/create-opencomputer-prod.sh
@@ -388,7 +388,8 @@ cmd_deploy() {
GOOS=linux GOARCH=amd64 go build -o /tmp/oc-server ./cmd/server/
log "Building worker (amd64)..."
- GOOS=linux GOARCH=amd64 go build -ldflags="-X main.AgentVersion=$VERSION" -o /tmp/oc-worker ./cmd/worker/
+ GIT_SHA=$(git rev-parse --short HEAD 2>/dev/null || echo "dev")
+ GOOS=linux GOARCH=amd64 go build -ldflags="-X main.AgentVersion=$VERSION -X main.WorkerVersion=$GIT_SHA" -o /tmp/oc-worker ./cmd/worker/
log "Building agent (amd64)..."
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-X main.Version=$VERSION" -o /tmp/oc-agent ./cmd/agent/
diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.sh
index f32d6c60..4825eb01 100755
--- a/deploy/ec2/setup-instance.sh
+++ b/deploy/ec2/setup-instance.sh
@@ -1,83 +1,133 @@
#!/usr/bin/env bash
set -euo pipefail
-# Provision a fresh Ubuntu 24.04 EC2 instance as an OpenSandbox worker.
+# Provision a fresh Ubuntu 24.04 EC2 instance as an OpenSandbox worker (QEMU backend).
# Run this ON the instance (ssh in first), or pipe via ssh:
# ssh -i key.pem ubuntu@<IP> 'bash -s' < deploy/ec2/setup-instance.sh
#
# Supports both x86_64 (amd64) and aarch64 (arm64/Graviton) instances.
-# Optimized for Firecracker microVMs on bare-metal Graviton (r7gd.metal).
+# Optimized for bare-metal Graviton (r7gd.metal) or x86 (c7i.metal).
#
# Prerequisites:
# - Ubuntu 24.04 LTS AMI
-# - r7gd.metal (ARM64) or c7i.metal (x86_64) for production
-# - Security group: 8080 (HTTP), 9090 (gRPC), 9091 (metrics) open from VPC only (workers are internal)
+# - Bare-metal instance for KVM (r7gd.metal, c7i.metal)
+# - Security group: 8080 (HTTP), 9090 (gRPC), 9091 (metrics) open from VPC only
# - SSH access
# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
- x86_64) GOARCH="amd64"; FC_ARCH="x86_64" ;;
- aarch64) GOARCH="arm64"; FC_ARCH="aarch64" ;;
+ x86_64) GOARCH="amd64"; QEMU_PKG="qemu-system-x86" ;;
+ aarch64) GOARCH="arm64"; QEMU_PKG="qemu-system-arm" ;;
*) echo "ERROR: Unsupported architecture: $ARCH"; exit 1 ;;
esac
echo "==> Detected architecture: $ARCH ($GOARCH)"
+export DEBIAN_FRONTEND=noninteractive
+
echo "==> Updating packages..."
-sudo apt-get update && sudo apt-get upgrade -y
+sudo apt-get update -qq && sudo apt-get upgrade -y -qq
# -------------------------------------------------------------------
-# Firecracker microVM runtime
+# QEMU hypervisor
# -------------------------------------------------------------------
-echo "==> Installing Firecracker..."
-FC_VERSION="v1.9.1"
-FC_RELEASE="firecracker-${FC_VERSION}-${FC_ARCH}"
-FC_URL="https://github.com/firecracker-microvm/firecracker/releases/download/${FC_VERSION}/${FC_RELEASE}.tgz"
-
-cd /tmp
-curl -fSL -o firecracker.tgz "$FC_URL"
-tar xzf firecracker.tgz
-sudo cp "release-${FC_VERSION}-${FC_ARCH}/firecracker-${FC_VERSION}-${FC_ARCH}" /usr/local/bin/firecracker
-sudo chmod +x /usr/local/bin/firecracker
-rm -rf firecracker.tgz "release-${FC_VERSION}-${FC_ARCH}"
-cd /
-
-echo "==> Verifying Firecracker..."
-firecracker --version
-
-# Verify KVM access (required for Firecracker)
-if [ ! -e /dev/kvm ]; then
- echo "WARNING: /dev/kvm not found. Firecracker requires bare-metal or nested virt."
- echo " For bare-metal instances (r7gd.metal), /dev/kvm should exist."
- echo " For regular instances, enable nested virtualization in the AMI."
-fi
+echo "==> Installing QEMU..."
+sudo apt-get install -y -qq $QEMU_PKG qemu-utils
-# Ensure KVM permissions
-sudo chmod 666 /dev/kvm 2>/dev/null || true
+# -------------------------------------------------------------------
+# Guest kernel for QEMU VMs
+# -------------------------------------------------------------------
+echo "==> Setting up guest kernel..."
+KERNEL_DIR="/opt/opensandbox"
+sudo mkdir -p "$KERNEL_DIR"
+
+# Install generic kernel package (has VIRTIO_BLK, VIRTIO_NET, VIRTIO_PCI built-in)
+sudo apt-get install -y -qq linux-image-generic
+
+# Find the generic kernel and copy it
+GENERIC_VMLINUZ=$(ls -t /boot/vmlinuz-*-generic 2>/dev/null | head -1)
+if [ -n "$GENERIC_VMLINUZ" ]; then
+ sudo cp "$GENERIC_VMLINUZ" "$KERNEL_DIR/vmlinux"
+ sudo chmod 644 "$KERNEL_DIR/vmlinux"
+ GENERIC_KVER=$(basename "$GENERIC_VMLINUZ" | sed 's/vmlinuz-//')
+ echo " Guest kernel: $GENERIC_VMLINUZ ($GENERIC_KVER)"
+
+ # Extract vsock, overlay, and virtio_mem modules for the guest rootfs
+ MODDIR="/lib/modules/$GENERIC_KVER"
+ GUEST_MODDIR="$KERNEL_DIR/guest-modules"
+ sudo mkdir -p "$GUEST_MODDIR"
+ for mod in \
+ "$MODDIR/kernel/fs/overlayfs/overlay.ko"* \
+ "$MODDIR/kernel/net/vmw_vsock/vsock.ko"* \
+ "$MODDIR/kernel/net/vmw_vsock/vmw_vsock_virtio_transport_common.ko"* \
+ "$MODDIR/kernel/net/vmw_vsock/vmw_vsock_virtio_transport.ko"* \
+ "$MODDIR/kernel/drivers/virtio/virtio_mem.ko"*; do
+ [ -f "$mod" ] || continue
+ base=$(basename "$mod")
+ if [[ "$base" == *.zst ]]; then
+ sudo zstd -d "$mod" -o "$GUEST_MODDIR/${base%.zst}" 2>/dev/null
+ else
+ sudo cp "$mod" "$GUEST_MODDIR/"
+ fi
+ done
+ echo " Guest modules extracted to $GUEST_MODDIR:"
+ ls "$GUEST_MODDIR/"
+else
+ echo "WARNING: No generic kernel found. Guest VMs may not boot correctly."
+fi
# -------------------------------------------------------------------
-# Podman (kept as build tool for Dockerfile → ext4 conversion)
+# Podman (for Dockerfile -> ext4 rootfs conversion)
# -------------------------------------------------------------------
echo "==> Installing Podman (for template building)..."
-sudo apt-get install -y podman uidmap slirp4netns
+sudo apt-get install -y -qq podman uidmap slirp4netns
# -------------------------------------------------------------------
-# System tools for ext4 image creation
+# Docker (for rootfs building via build-rootfs-docker.sh)
# -------------------------------------------------------------------
-echo "==> Installing ext4 and rootfs tools..."
-sudo apt-get install -y e2fsprogs
+echo "==> Installing Docker..."
+if ! command -v docker &>/dev/null; then
+ curl -fsSL https://get.docker.com | sudo sh
+fi
+sudo systemctl enable --now docker
# -------------------------------------------------------------------
-# Redis
+# System tools for ext4 image creation and storage
# -------------------------------------------------------------------
-echo "==> Installing Redis..."
-sudo apt-get install -y redis-server
+echo "==> Installing system tools..."
+sudo apt-get install -y -qq e2fsprogs xfsprogs nvme-cli mdadm jq curl zstd
+
+# -------------------------------------------------------------------
+# KVM + vhost-vsock
+# -------------------------------------------------------------------
+echo "==> Loading kernel modules..."
+sudo modprobe kvm || true
+case "$ARCH" in
+ x86_64) sudo modprobe kvm_intel 2>/dev/null || sudo modprobe kvm_amd 2>/dev/null || true ;;
+ aarch64) ;; # KVM is built-in on ARM64
+esac
+sudo modprobe vhost_vsock || true
+
+# Persist modules across reboots
+sudo tee /etc/modules-load.d/kvm.conf > /dev/null << 'EOF'
+kvm
+vhost_vsock
+EOF
+
+# Ensure /dev/kvm and /dev/vhost-vsock are accessible
+sudo chmod 666 /dev/kvm 2>/dev/null || true
+sudo chmod 666 /dev/vhost-vsock 2>/dev/null || true
+
+# Udev rules for persistent permissions
+sudo tee /etc/udev/rules.d/99-opensandbox.rules > /dev/null << 'EOF'
+KERNEL=="kvm", GROUP="kvm", MODE="0666"
+KERNEL=="vhost-vsock", MODE="0666"
+EOF
# -------------------------------------------------------------------
# NVMe instance storage (XFS with reflink for instant rootfs copies)
# -------------------------------------------------------------------
echo "==> Installing NVMe boot service..."
-sudo apt-get install -y xfsprogs nvme-cli mdadm
sudo tee /usr/local/bin/opensandbox-nvme-setup.sh > /dev/null << 'NVME'
#!/usr/bin/env bash
@@ -103,7 +153,7 @@ done
if [ ${#NVME_DEVS[@]} -eq 0 ]; then
echo "opensandbox-nvme: no NVMe instance storage found, using root disk"
- mkdir -p "$MOUNT_POINT/sandboxes" "$MOUNT_POINT/firecracker/images" "$MOUNT_POINT/checkpoints"
+ mkdir -p "$MOUNT_POINT/sandboxes" "$MOUNT_POINT/images" "$MOUNT_POINT/checkpoints"
exit 0
fi
@@ -126,17 +176,21 @@ fi
# Create directory structure
mkdir -p "$MOUNT_POINT/sandboxes"
-mkdir -p "$MOUNT_POINT/firecracker/images"
+mkdir -p "$MOUNT_POINT/images"
mkdir -p "$MOUNT_POINT/checkpoints"
-# Copy Firecracker assets from EBS to NVMe if available
-SRC="/opt/opensandbox/firecracker"
-DST="$MOUNT_POINT/firecracker"
-if [ -d "$SRC" ] && [ ! -f "$DST/vmlinux-arm64" ]; then
- echo "opensandbox-nvme: copying Firecracker assets from $SRC to $DST"
- cp "$SRC/vmlinux-arm64" "$DST/"
- cp "$SRC/images/"* "$DST/images/"
- echo "opensandbox-nvme: assets copied ($(du -sh "$DST" | cut -f1))"
+# Copy QEMU assets from EBS to NVMe if available
+SRC="/opt/opensandbox"
+if [ -f "$SRC/vmlinux" ] && [ ! -f "$MOUNT_POINT/vmlinux" ]; then
+ echo "opensandbox-nvme: copying QEMU assets from $SRC to $MOUNT_POINT"
+ cp "$SRC/vmlinux" "$MOUNT_POINT/"
+ [ -d "$SRC/guest-modules" ] && cp -r "$SRC/guest-modules" "$MOUNT_POINT/"
+ # Copy base images if they exist (legacy path: /data/firecracker/images)
+ if [ -d "/data/firecracker/images" ] && ls /data/firecracker/images/*.ext4 &>/dev/null; then
+ mkdir -p "$MOUNT_POINT/images"
+ cp /data/firecracker/images/*.ext4 "$MOUNT_POINT/images/"
+ fi
+ echo "opensandbox-nvme: assets copied ($(du -sh "$MOUNT_POINT" | cut -f1))"
fi
echo "opensandbox-nvme: mounted at $MOUNT_POINT ($(df -h "$MOUNT_POINT" | tail -1 | awk '{print $2}') total)"
NVME
@@ -159,22 +213,13 @@ WantedBy=multi-user.target
SVC
# -------------------------------------------------------------------
-# Firecracker kernel + base rootfs images
+# IP forwarding + sysctl tuning for VM networking
# -------------------------------------------------------------------
-echo "==> Setting up Firecracker kernel and base images directory..."
-sudo mkdir -p /data/firecracker/images
-
-# Download kernel (will be populated by deploy script)
-echo " Kernel will be installed by deploy-worker.sh at /data/firecracker/vmlinux-arm64"
-echo " Base rootfs images will be installed at /data/firecracker/images/"
-
-# -------------------------------------------------------------------
-# IP forwarding + iptables for VM networking
-# -------------------------------------------------------------------
-echo "==> Configuring IP forwarding for Firecracker VMs..."
+echo "==> Configuring sysctl for QEMU VMs..."
sudo tee /etc/sysctl.d/99-opensandbox.conf > /dev/null << 'SYSCTL'
-# Enable IP forwarding for Firecracker VM networking
+# IP forwarding for VM networking
net.ipv4.ip_forward = 1
+net.ipv4.conf.all.route_localnet = 1
# Increase ARP cache for many TAP interfaces
net.ipv4.neigh.default.gc_thresh1 = 1024
net.ipv4.neigh.default.gc_thresh2 = 4096
@@ -185,7 +230,7 @@ fs.file-max = 1000000
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 524288
SYSCTL
-sudo sysctl --system
+sudo sysctl --system -q
# -------------------------------------------------------------------
# Dynamic worker identity (from EC2 IMDS at boot)
@@ -207,6 +252,7 @@ WORKER_ID="w-use2-${SHORT_ID}"
mkdir -p /etc/opensandbox
cat > /etc/opensandbox/worker-identity.env << EOF
OPENSANDBOX_WORKER_ID=${WORKER_ID}
+OPENSANDBOX_MACHINE_ID=${INSTANCE_ID}
OPENSANDBOX_HTTP_ADDR=http://${PRIVATE_IP}:8080
OPENSANDBOX_GRPC_ADVERTISE=${PRIVATE_IP}:9090
EOF
@@ -231,18 +277,19 @@ WantedBy=multi-user.target
SVC
# -------------------------------------------------------------------
-# Worker systemd unit (Firecracker)
+# Worker systemd unit (QEMU backend)
# -------------------------------------------------------------------
echo "==> Installing worker systemd unit..."
sudo tee /etc/systemd/system/opensandbox-worker.service > /dev/null << 'SVC'
[Unit]
-Description=OpenSandbox Worker (Firecracker)
+Description=OpenSandbox Worker (QEMU backend)
After=network-online.target opensandbox-nvme.service opensandbox-identity.service
Wants=network-online.target
Requires=opensandbox-nvme.service opensandbox-identity.service
[Service]
Type=simple
+ExecStartPre=/sbin/modprobe vhost_vsock
ExecStart=/usr/local/bin/opensandbox-worker
Restart=always
RestartSec=5
@@ -252,12 +299,12 @@ Environment=OPENSANDBOX_PORT=8080
Environment=OPENSANDBOX_REGION=use2
Environment=OPENSANDBOX_DATA_DIR=/data
Environment=OPENSANDBOX_SANDBOX_DOMAIN=workers.opensandbox.ai
-Environment=OPENSANDBOX_FIRECRACKER_BIN=/usr/local/bin/firecracker
-Environment=OPENSANDBOX_KERNEL_PATH=/data/firecracker/vmlinux-arm64
+Environment=OPENSANDBOX_QEMU_BIN=qemu-system-x86_64
+Environment=OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux
Environment=OPENSANDBOX_IMAGES_DIR=/data/firecracker/images
Environment=OPENSANDBOX_SECRETS_ARN=arn:aws:secretsmanager:us-east-2:739940681129:secret:opensandbox/worker-vtN2Ez
EnvironmentFile=/etc/opensandbox/worker-identity.env
-# Only signal the main process on stop (not Firecracker children)
+# Only signal the main process on stop (not QEMU children)
# so graceful shutdown can hibernate VMs before they are killed
KillMode=process
TimeoutStopSec=300
@@ -286,20 +333,25 @@ sudo systemctl enable opensandbox-worker
echo "==> Cleaning up..."
sudo apt-get clean
+# Determine QEMU binary name for display
+QEMU_BIN="qemu-system-x86_64"
+if [ "$ARCH" = "aarch64" ]; then
+ QEMU_BIN="qemu-system-aarch64"
+fi
+
echo ""
echo "============================================"
echo " Instance setup complete! ($ARCH)"
echo ""
echo " Installed:"
-echo " - Firecracker $(firecracker --version | head -1)"
-echo " - Podman $(podman --version)"
-echo " - Redis"
+echo " - QEMU: $($QEMU_BIN --version | head -1)"
+echo " - Podman: $(podman --version)"
+echo " - Docker: $(docker --version)"
+echo " - KVM: $(ls -la /dev/kvm 2>/dev/null || echo 'not available')"
+echo " - VSOCK: $(ls -la /dev/vhost-vsock 2>/dev/null || echo 'not available')"
echo ""
echo " Remaining steps:"
echo " 1. Deploy worker + agent binaries: ./deploy/ec2/deploy-worker.sh"
-echo " 2. Download kernel: scp bin/vmlinux-arm64 to /data/firecracker/"
-echo " 3. Build base rootfs images: sudo ./scripts/build-rootfs.sh all"
-echo " 4. Copy worker.env.example to /etc/opensandbox/worker.env and fill in secrets"
-echo " 5. Start services: sudo systemctl start opensandbox-worker"
-echo " 6. Set up wildcard DNS: *.workers.opencomputer.dev -> this instance IP"
+echo " 2. Build base rootfs images: sudo bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default"
+echo " 3. Start services: sudo systemctl start opensandbox-worker"
echo "============================================"
diff --git a/deploy/packer/worker-ami.pkr.hcl b/deploy/packer/worker-ami.pkr.hcl
new file mode 100644
index 00000000..fe5d3065
--- /dev/null
+++ b/deploy/packer/worker-ami.pkr.hcl
@@ -0,0 +1,193 @@
+# worker-image.pkr.hcl — Build an immutable Azure Managed Image for OpenSandbox workers (QEMU backend).
+#
+# The image includes everything a worker needs: QEMU, guest kernel, worker + agent
+# binaries, and pre-built rootfs images. At boot, only instance-specific config
+# (identity, secrets, worker env) is injected via cloud-init.
+#
+# Usage:
+# # Build binaries first (x86_64 for Azure):
+# CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-X main.WorkerVersion=$(git rev-parse --short HEAD)" \
+# -o bin/opensandbox-worker ./cmd/worker/
+# CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o bin/osb-agent ./cmd/agent/
+#
+# # Then build the image:
+# packer init deploy/packer/worker-image.pkr.hcl
+# packer build -var "worker_version=$(git rev-parse --short HEAD)" \
+# -var "subscription_id=YOUR_SUB" -var "resource_group=YOUR_RG" \
+# deploy/packer/worker-image.pkr.hcl
+
+packer {
+ required_plugins {
+ azure = {
+ version = ">= 2.1.0"
+ source = "github.com/hashicorp/azure"
+ }
+ }
+}
+
+# ---------------------------------------------------------------------
+# Variables
+# ---------------------------------------------------------------------
+
+variable "worker_version" {
+ type = string
+ description = "Worker version (git SHA). Baked into image name and tags."
+}
+
+variable "agent_version" {
+ type = string
+ default = ""
+ description = "Agent version (git SHA). Defaults to worker_version if empty."
+}
+
+variable "subscription_id" {
+ type = string
+ description = "Azure subscription ID."
+}
+
+variable "resource_group" {
+ type = string
+ description = "Resource group for the managed image."
+}
+
+variable "location" {
+ type = string
+ default = "westus2"
+}
+
+variable "vm_size" {
+ type = string
+ default = "Standard_D4s_v6"
+ description = "Builder VM size. Must be v6 family to match autoscaled worker disk controller."
+}
+
+variable "image_name_prefix" {
+ type = string
+ default = "opensandbox-worker"
+}
+
+variable "worker_binary" {
+ type = string
+ default = "bin/opensandbox-worker"
+ description = "Path to the pre-built worker binary (amd64 Linux)."
+}
+
+variable "agent_binary" {
+ type = string
+ default = "bin/osb-agent"
+ description = "Path to the pre-built agent binary (amd64 Linux)."
+}
+
+# ---------------------------------------------------------------------
+# Source: Ubuntu 24.04 x86_64 on Azure
+# ---------------------------------------------------------------------
+
+source "azure-arm" "worker" {
+ subscription_id = var.subscription_id
+ location = var.location
+
+ # Use managed identity or Azure CLI credentials
+ use_azure_cli_auth = true
+
+ # Base image: Ubuntu 24.04 LTS
+ image_publisher = "Canonical"
+ image_offer = "ubuntu-24_04-lts"
+ image_sku = "server"
+
+ os_type = "Linux"
+ vm_size = var.vm_size
+ ssh_username = "packer"
+
+ # Output: Managed Image in the specified resource group
+ managed_image_name = "${var.image_name_prefix}-${var.worker_version}"
+ managed_image_resource_group_name = var.resource_group
+
+ azure_tags = {
+ "opensandbox-role" = "worker"
+ "opensandbox-version" = var.worker_version
+ }
+}
+
+# ---------------------------------------------------------------------
+# Build
+# ---------------------------------------------------------------------
+
+build {
+ sources = ["source.azure-arm.worker"]
+
+ # 1. Upload pre-built binaries
+ provisioner "file" {
+ source = var.worker_binary
+ destination = "/tmp/opensandbox-worker"
+ }
+
+ provisioner "file" {
+ source = var.agent_binary
+ destination = "/tmp/osb-agent"
+ }
+
+ # 2. Upload rootfs build context as tarball
+ # Pre-create with: tar czf /tmp/packer-rootfs-ctx.tar.gz deploy/firecracker/rootfs/ deploy/ec2/build-rootfs-docker.sh scripts/claude-agent-wrapper/
+ provisioner "file" {
+ source = "/tmp/packer-rootfs-ctx.tar.gz"
+ destination = "/tmp/rootfs-ctx.tar.gz"
+ }
+
+ # 3. Run the Azure setup script (installs QEMU, kernel, system deps, systemd units)
+ provisioner "shell" {
+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ script = "deploy/azure/setup-azure-host.sh"
+ }
+
+ # 4. Install binaries and build rootfs
+ provisioner "shell" {
+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ inline = [
+ # Install worker and agent binaries
+ "mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker",
+ "chmod +x /usr/local/bin/opensandbox-worker",
+ "mv /tmp/osb-agent /usr/local/bin/osb-agent",
+ "chmod +x /usr/local/bin/osb-agent",
+
+ # Extract rootfs build context
+ "mkdir -p /tmp/rootfs-ctx",
+ "cd /tmp/rootfs-ctx && tar xzf /tmp/rootfs-ctx.tar.gz",
+
+ # Build rootfs images (Docker was installed by setup-azure-host.sh)
+ "mkdir -p /data/firecracker/images",
+ "cd /tmp/rootfs-ctx && bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent /data/firecracker/images default",
+
+ # Inject guest kernel modules into rootfs
+ "GUEST_MODDIR=/opt/opensandbox/guest-modules",
+ "if [ -d \"$GUEST_MODDIR\" ] && [ -f /data/firecracker/images/default.ext4 ]; then",
+ " MNTDIR=$(mktemp -d)",
+ " mount -o loop /data/firecracker/images/default.ext4 $MNTDIR",
+ " mkdir -p $MNTDIR/lib/modules/extra",
+ " cp $GUEST_MODDIR/*.ko* $MNTDIR/lib/modules/extra/ 2>/dev/null || true",
+ " umount $MNTDIR",
+ " rmdir $MNTDIR",
+ " echo 'Guest kernel modules injected into rootfs'",
+ "fi",
+
+ # Save rootfs to /opt (survives NVMe mount overlay on /data)
+ "mkdir -p /opt/opensandbox/images",
+ "cp /data/firecracker/images/*.ext4 /opt/opensandbox/images/",
+
+ # Cleanup build artifacts
+ "rm -rf /tmp/rootfs-ctx /tmp/rootfs-ctx.tar.gz",
+ "apt-get clean",
+ "rm -rf /var/lib/apt/lists/*",
+
+ # Remove any stale golden snapshot (must rebuild per-instance at first boot)
+ "rm -rf /data/sandboxes/golden-snapshot /data/sandboxes/golden 2>/dev/null || true",
+ ]
+ }
+
+ # 5. Deprovision for Azure image capture
+ provisioner "shell" {
+ execute_command = "chmod +x {{ .Path }}; {{ .Vars }} sudo -E bash '{{ .Path }}'"
+ inline = [
+ "/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync",
+ ]
+ }
+}
diff --git a/go.mod b/go.mod
index 4a09c5d3..9c4c06ad 100644
--- a/go.mod
+++ b/go.mod
@@ -8,7 +8,7 @@ require (
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0
- github.com/aws/aws-sdk-go-v2 v1.41.2
+ github.com/aws/aws-sdk-go-v2 v1.41.5
github.com/aws/aws-sdk-go-v2/config v1.32.10
github.com/aws/aws-sdk-go-v2/credentials v1.19.10
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1
@@ -36,12 +36,13 @@ require (
require (
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
+ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6 v6.4.0 // indirect
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5 // indirect
@@ -49,10 +50,11 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.6 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssm v1.68.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.11 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.41.7 // indirect
- github.com/aws/smithy-go v1.24.1 // indirect
+ github.com/aws/smithy-go v1.24.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
diff --git a/go.sum b/go.sum
index 8be9f3b7..13ab4625 100644
--- a/go.sum
+++ b/go.sum
@@ -8,12 +8,15 @@ github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDo
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0 h1:/Di3vB4sNeQ+7A8efjUVENvyB945Wruvstucqp7ZArg=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0/go.mod h1:gM3K25LQlsET3QR+4V74zxCsFAy0r6xMNN9n80SZn+4=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6 v6.4.0 h1:z7Mqz6l0EFH549GvHEqfjKvi+cRScxLWbaoeLm9wxVQ=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6 v6.4.0/go.mod h1:v6gbfH+7DG7xH2kUNs+ZJ9tF6O3iNnR85wMtmr+F54o=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.0.0 h1:lMW1lD/17LUA5z1XTURo7LcVG2ICBPlyMHjIUrcFZNQ=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.0.0/go.mod h1:ceIuwmxDWptoW3eCqSXlnPsZFKh4X+R38dWPv7GS9Vs=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0 h1:QM6sE5k2ZT/vI5BEe0r7mqjsUSnhVBFbOsVkEuaEfiA=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0/go.mod h1:243D9iHbcQXoFUtgHJwL7gl2zx1aDuDMjvBZVGr2uW0=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0 h1:ECsQtyERDVz3NP3kvDOTLvbQhqWp/x9EsGKtb4ogUr8=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0/go.mod h1:s1tW/At+xHqjNFvWU4G0c0Qv33KOhvbGNj0RCTQDV8s=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.2.0 h1:Dd+RhdJn0OTtVGaeDLZpcumkIVCtA/3/Fo42+eoYvVM=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0 h1:/g8S6wk65vfC6m3FIxJ+i5QDyN9JWwXI8Hb0Img10hU=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0/go.mod h1:gpl+q95AzZlKVI3xSoseF9QPrypk0hQqBiJYeB/cR/I=
github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4=
@@ -24,6 +27,8 @@ github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgv
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
github.com/aws/aws-sdk-go-v2 v1.41.2 h1:LuT2rzqNQsauaGkPK/7813XxcZ3o3yePY0Iy891T2ls=
github.com/aws/aws-sdk-go-v2 v1.41.2/go.mod h1:IvvlAZQXvTXznUPfRVfryiG1fbzE2NGK6m9u39YQ+S4=
+github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
+github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
github.com/aws/aws-sdk-go-v2/config v1.32.10 h1:9DMthfO6XWZYLfzZglAgW5Fyou2nRI5CuV44sTedKBI=
@@ -34,8 +39,12 @@ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 h1:Ii4s+Sq3yDfaMLpjrJsqD6
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18/go.mod h1:6x81qnY++ovptLE6nWQeWrpXxbnlIex+4H4eYYGcqfc=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 h1:F43zk1vemYIqPAwhjTjYIz0irU2EY7sOb/F5eJ3HuyM=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18/go.mod h1:w1jdlZXrGKaJcNoL+Nnrj+k5wlpGXqnNrKoP22HvAug=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 h1:xCeWVjj0ki0l3nruoyP2slHsGArMxeiiaoPN5QZH6YQ=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18/go.mod h1:r/eLGuGCBw6l36ZRWiw6PaZwPXb6YOj+i/7MizNl5/k=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
@@ -56,6 +65,8 @@ github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2 h1:hezAo5AQM0moD4qit
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2/go.mod h1:7+wvNfdX7NZtxNyVLbbS89gYldQ3H+1nlVRr7J9KQDA=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.6 h1:MzORe+J94I+hYu2a6XmV5yC9huoTv8NRcCrUNedDypQ=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.6/go.mod h1:hXzcHLARD7GeWnifd8j9RWqtfIgxj4/cAtIVIK7hg8g=
+github.com/aws/aws-sdk-go-v2/service/ssm v1.68.4 h1:5Wg8AAAnIWM2LE/0KFGqllZff96bm4dBs+uerYFfReE=
+github.com/aws/aws-sdk-go-v2/service/ssm v1.68.4/go.mod h1:nph0ypDLWm9D9iA9zOX39W/N+A4GqwzlxA13jzXVD4k=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.11 h1:7oGD8KPfBOJGXiCoRKrrrQkbvCp8N++u36hrLMPey6o=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.11/go.mod h1:0DO9B5EUJQlIDif+XJRWCljZRKsAFKh3gpFz7UnDtOo=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.15 h1:edCcNp9eGIUDUCrzoCu1jWAXLGFIizeqkdkKgRlJwWc=
@@ -64,6 +75,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.41.7 h1:NITQpgo9A5NrDZ57uOWj+abvXSb8
github.com/aws/aws-sdk-go-v2/service/sts v1.41.7/go.mod h1:sks5UWBhEuWYDPdwlnRFn1w7xWdH29Jcpe+/PJQefEs=
github.com/aws/smithy-go v1.24.1 h1:VbyeNfmYkWoxMVpGUAbQumkODcYmfMRfZ8yQiH30SK0=
github.com/aws/smithy-go v1.24.1/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
+github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
+github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 683142f8..3c834d2d 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -273,6 +273,11 @@ func (s *Server) execRunRemote(c echo.Context, sandboxID string, req types.Proce
if session.OrgID != orgID {
return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
}
+ if session.Status == "migrating" {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "sandbox is migrating, retry shortly",
+ })
+ }
client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index d794e57e..43176023 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -12,6 +12,7 @@ import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/pkg/types"
pb "github.com/opensandbox/opensandbox/proto/worker"
@@ -700,6 +701,20 @@ func (s *Server) migrateSandbox(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox must be running to migrate"})
}
+ // Mark as migrating — blocks exec/proxy routing until migration completes
+ migrationDone := false
+ if s.store != nil {
+ if err := s.store.SetMigrating(ctx, id, req.TargetWorker); err != nil {
+ log.Printf("migrate %s: failed to set migrating state: %v", id, err)
+ }
+ // Guarantee we revert on failure
+ defer func() {
+ if !migrationDone && s.store != nil {
+ s.store.FailMigration(ctx, id)
+ }
+ }()
+ }
+
// Get source and target worker gRPC clients
sourceClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
@@ -717,10 +732,23 @@ func (s *Server) migrateSandbox(c echo.Context) error {
// memory contents (including filesystem cache) migrate via QMP tcp.
prepCtx, prepCancel := context.WithTimeout(ctx, 2*time.Minute)
defer prepCancel()
+ // Parse sandbox config to get the actual memory/CPU (must match source for migration)
+ var sbCfg struct {
+ MemoryMB int `json:"memoryMB"`
+ CpuCount int `json:"cpuCount"`
+ }
+ _ = json.Unmarshal(session.Config, &sbCfg)
+ if sbCfg.MemoryMB <= 0 {
+ sbCfg.MemoryMB = 256 // default from golden snapshot
+ }
+ if sbCfg.CpuCount <= 0 {
+ sbCfg.CpuCount = 1
+ }
+
prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{
SandboxId: id,
- CpuCount: 1,
- MemoryMb: 1024,
+ CpuCount: int32(sbCfg.CpuCount),
+ MemoryMb: int32(sbCfg.MemoryMB),
GuestPort: 80,
Template: session.Template,
})
@@ -753,8 +781,16 @@ func (s *Server) migrateSandbox(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "complete migration: " + err.Error()})
}
- // Step 5: Update DB — sandbox now on target worker
- _, _ = s.store.Pool().Exec(ctx, "UPDATE sandbox_sessions SET worker_id = $1 WHERE sandbox_id = $2", req.TargetWorker, id)
+ // Step 5: Complete migration — update DB status and worker_id atomically
+ if s.store != nil {
+ s.store.CompleteMigration(ctx, id, req.TargetWorker)
+ }
+ migrationDone = true
+
+ // Invalidate proxy route cache so next request routes to the new worker
+ if s.sandboxAPIProxy != nil {
+ s.sandboxAPIProxy.InvalidateRouteCache(id)
+ }
elapsed := time.Since(t0).Milliseconds()
log.Printf("migrate %s: complete in %dms (source=%s target=%s)", id, elapsed, session.WorkerID, req.TargetWorker)
@@ -888,7 +924,9 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
})
}
- session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ ctx := c.Request().Context()
+
+ session, err := s.store.GetSandboxSession(ctx, sandboxID)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
}
@@ -896,14 +934,21 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not running"})
}
- client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ requestedMemMB := int(maxMemoryBytes / (1024 * 1024))
+ requestedCPUs := int(cpuMaxUsec / 1000 / 100) // cpuPercent / 100
+ if requestedCPUs < 1 {
+ requestedCPUs = 1
+ }
+
+ workerID := session.WorkerID
+
+ // Step 1: Try to apply limits on the current worker.
+ client, err := s.workerRegistry.GetWorkerClient(workerID)
if err != nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})
}
- grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 30*time.Second)
- defer cancel()
-
+ grpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
_, err = client.SetSandboxLimits(grpcCtx, &pb.SetSandboxLimitsRequest{
SandboxId: sandboxID,
MaxPids: maxPids,
@@ -911,18 +956,215 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
CpuMaxUsec: cpuMaxUsec,
CpuPeriodUsec: cpuPeriodUsec,
})
+ cancel()
+
+ // Step 2: If the worker can't fit the memory, migrate and retry.
+ migrated := false
if err != nil {
+ log.Printf("scale-limits %s: SetSandboxLimits error: %v", sandboxID, err)
+ }
+ if err != nil && strings.Contains(err.Error(), "insufficient_capacity") {
+ log.Printf("scale-migrate %s: worker %s can't fit %dMB, finding migration target", sandboxID, workerID, requestedMemMB)
+
+ target := s.findScaleMigrationTarget(workerID, requestedMemMB)
+ if target == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "insufficient capacity on current worker and no migration target available",
+ })
+ }
+
+ // Verify target is reachable before attempting expensive migration
+ targetClient, connErr := s.workerRegistry.GetWorkerClient(target.ID)
+ if connErr != nil {
+ log.Printf("scale-migrate %s: target %s unreachable, skipping", sandboxID, target.ID)
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "migration target unreachable, retry later",
+ })
+ }
+ // Quick health check — ping the target
+ pingCtx, pingCancel := context.WithTimeout(ctx, 5*time.Second)
+ _, pingErr := targetClient.ListSandboxes(pingCtx, &pb.ListSandboxesRequest{})
+ pingCancel()
+ if pingErr != nil {
+ log.Printf("scale-migrate %s: target %s failed health check: %v", sandboxID, target.ID, pingErr)
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "migration target failed health check, retry later",
+ })
+ }
+
+ // Mark as migrating before starting
+ if s.store != nil {
+ s.store.SetMigrating(ctx, sandboxID, target.ID)
+ }
+
+ if migrateErr := s.migrateForScale(ctx, sandboxID, session, target, requestedMemMB, requestedCPUs); migrateErr != nil {
+ if s.store != nil {
+ s.store.FailMigration(ctx, sandboxID)
+ }
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "scale migration failed: " + migrateErr.Error(),
+ })
+ }
+
+ // Migration succeeded — update state
+ if s.store != nil {
+ s.store.CompleteMigration(ctx, sandboxID, target.ID)
+ }
+ if s.sandboxAPIProxy != nil {
+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
+ }
+ workerID = target.ID
+ migrated = true
+
+ // Retry limits on the new worker
+ newClient, clientErr := s.workerRegistry.GetWorkerClient(workerID)
+ if clientErr != nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "new worker unreachable after migration"})
+ }
+
+ retryCtx, retryCancel := context.WithTimeout(ctx, 30*time.Second)
+ _, err = newClient.SetSandboxLimits(retryCtx, &pb.SetSandboxLimitsRequest{
+ SandboxId: sandboxID,
+ MaxPids: maxPids,
+ MaxMemoryBytes: maxMemoryBytes,
+ CpuMaxUsec: cpuMaxUsec,
+ CpuPeriodUsec: cpuPeriodUsec,
+ })
+ retryCancel()
+
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "set limits failed after migration: " + err.Error(),
+ })
+ }
+
+ log.Printf("scale-migrate %s: migrated to %s and scaled to %dMB", sandboxID, workerID, requestedMemMB)
+ } else if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": "set limits failed: " + err.Error(),
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
- "sandboxID": sandboxID,
- "ok": true,
+ "sandboxID": sandboxID,
+ "workerID": workerID,
+ "memoryMB": requestedMemMB,
+ "cpuPercent": int(cpuMaxUsec / 1000),
+ "migrated": migrated,
+ "ok": true,
})
}
+// findScaleMigrationTarget finds a worker with enough memory headroom for a scaled-up sandbox.
+// Prefers workers with more free capacity. Skips the source worker.
+func (s *Server) findScaleMigrationTarget(sourceWorkerID string, requestedMemMB int) *controlplane.WorkerEntry {
+ workers := s.workerRegistry.GetAllWorkers()
+ var best *controlplane.WorkerEntry
+ bestScore := -1.0
+
+ for _, w := range workers {
+ if w.ID == sourceWorkerID {
+ continue
+ }
+ if w.CPUPct > 80 || w.MemPct > 60 {
+ continue // need plenty of headroom for a big sandbox
+ }
+ remaining := w.Capacity - w.Current
+ if remaining <= 0 {
+ continue // worker is full, can't take a migrated sandbox
+ }
+ // Score: prefer emptier workers (more room for the big sandbox)
+ score := float64(remaining) * (100.0 - w.MemPct) / 100.0
+ if score > bestScore {
+ best = w
+ bestScore = score
+ }
+ }
+ return best
+}
+
+// migrateForScale performs a live migration to accommodate a resource scale-up.
+func (s *Server) migrateForScale(ctx context.Context, sandboxID string, session *db.SandboxSession, target *controlplane.WorkerEntry, memoryMB, cpuCount int) error {
+ sourceClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ if err != nil {
+ return fmt.Errorf("source worker unreachable: %w", err)
+ }
+ targetClient, err := s.workerRegistry.GetWorkerClient(target.ID)
+ if err != nil {
+ return fmt.Errorf("target worker unreachable: %w", err)
+ }
+
+ t0 := time.Now()
+ template := session.Template
+ if template == "" {
+ template = "default"
+ }
+
+ // The target QEMU must use the same base memory as the source for migration
+ // to work (QEMU requires matching RAM sizes). Use the session config to get
+ // the original base memory, not the new requested size. The virtio-mem pool
+ // handles scaling after migration completes.
+ var sbCfg struct {
+ MemoryMB int `json:"memoryMB"`
+ CpuCount int `json:"cpuCount"`
+ }
+ _ = json.Unmarshal(session.Config, &sbCfg)
+ baseMem := sbCfg.MemoryMB
+ if baseMem <= 0 {
+ baseMem = 256 // default from golden snapshot
+ }
+ baseCPU := sbCfg.CpuCount
+ if baseCPU <= 0 {
+ baseCPU = 1
+ }
+
+ log.Printf("scale-migrate %s: migrating to %s (template=%s, baseMem=%dMB, targetMem=%dMB, cpu=%d)", sandboxID, target.ID, template, baseMem, memoryMB, cpuCount)
+
+ // Step 1: Prepare target with the SOURCE's base memory (must match for migration)
+ prepCtx, prepCancel := context.WithTimeout(ctx, 2*time.Minute)
+ defer prepCancel()
+ prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{
+ SandboxId: sandboxID,
+ CpuCount: int32(baseCPU),
+ MemoryMb: int32(baseMem),
+ GuestPort: 80,
+ Template: template,
+ })
+ if err != nil {
+ log.Printf("scale-migrate %s: prepare target failed: %v", sandboxID, err)
+ return fmt.Errorf("prepare target: %w", err)
+ }
+
+ // Step 2: Live migrate
+ migrateCtx, migrateCancel := context.WithTimeout(ctx, 5*time.Minute)
+ defer migrateCancel()
+ _, err = sourceClient.LiveMigrate(migrateCtx, &pb.LiveMigrateRequest{
+ SandboxId: sandboxID,
+ IncomingAddr: prepResp.IncomingAddr,
+ })
+ if err != nil {
+ return fmt.Errorf("live migrate: %w", err)
+ }
+
+ // Step 3: Complete migration on target
+ completeCtx, completeCancel := context.WithTimeout(ctx, 30*time.Second)
+ defer completeCancel()
+ _, err = targetClient.CompleteMigrationIncoming(completeCtx, &pb.CompleteMigrationIncomingRequest{
+ SandboxId: sandboxID,
+ })
+ if err != nil {
+ return fmt.Errorf("complete migration: %w", err)
+ }
+
+ // Step 4: Update DB
+ // DB update is handled by CompleteMigration in the caller
+
+ log.Printf("scale-migrate %s: complete in %dms (source=%s target=%s, new=%dMB/%dvCPU)",
+ sandboxID, time.Since(t0).Milliseconds(), session.WorkerID, target.ID, memoryMB, cpuCount)
+
+ return nil
+}
+
func (s *Server) hibernateSandbox(c echo.Context) error {
id := c.Param("id")
ctx := c.Request().Context()
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index ee424721..d2639334 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -7,11 +7,13 @@ import (
"fmt"
"log"
"strings"
+ "sync"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
- "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute"
+ "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v6"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork"
+ "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"
)
const (
@@ -31,6 +33,7 @@ type AzurePoolConfig struct {
SSHPublicKey string // SSH public key content
DataDiskSizeGB int // data disk size (default: 256)
WorkerEnvBase64 string // base64-encoded worker.env content (injected via cloud-init)
+ KeyVaultName string // Azure Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")
}
// AzurePool implements compute.Pool using Azure VMs.
@@ -38,7 +41,9 @@ type AzurePool struct {
vmClient *armcompute.VirtualMachinesClient
diskClient *armcompute.DisksClient
nicClient *armnetwork.InterfacesClient
+ mu sync.RWMutex // protects cfg.ImageID
cfg AzurePoolConfig
+ kvClient *azsecrets.Client // Key Vault client for dynamic image refresh (nil if not configured)
}
// NewAzurePool creates an Azure compute pool using default credentials (managed identity, CLI, env vars).
@@ -70,12 +75,26 @@ func NewAzurePool(cfg AzurePoolConfig) (*AzurePool, error) {
cfg.DataDiskSizeGB = 256
}
- return &AzurePool{
+ pool := &AzurePool{
vmClient: vmClient,
diskClient: diskClient,
nicClient: nicClient,
cfg: cfg,
- }, nil
+ }
+
+ // Initialize Key Vault client for dynamic image refresh
+ if cfg.KeyVaultName != "" {
+ vaultURL := fmt.Sprintf("https://%s.vault.azure.net/", cfg.KeyVaultName)
+ kvClient, err := azsecrets.NewClient(vaultURL, cred, nil)
+ if err != nil {
+ log.Printf("azure: Key Vault client failed (image refresh disabled): %v", err)
+ } else {
+ pool.kvClient = kvClient
+ log.Printf("azure: Key Vault image refresh enabled (vault=%s)", cfg.KeyVaultName)
+ }
+ }
+
+ return pool, nil
}
func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine, error) {
@@ -119,8 +138,13 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machi
userData := p.buildUserData(opts)
userDataB64 := base64.StdEncoding.EncodeToString([]byte(userData))
+ // Read current image ID (may be updated by RefreshAMI)
+ p.mu.RLock()
+ imageID := p.cfg.ImageID
+ p.mu.RUnlock()
+
// Create VM
- log.Printf("azure: creating VM %s (size=%s, image=%s)", vmName, vmSize, p.cfg.ImageID)
+ log.Printf("azure: creating VM %s (size=%s, image=%s)", vmName, vmSize, imageID)
vmPoller, err := p.vmClient.BeginCreateOrUpdate(ctx, p.cfg.ResourceGroup, vmName, armcompute.VirtualMachine{
Location: to.Ptr(p.cfg.Region),
Tags: map[string]*string{
@@ -131,7 +155,7 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machi
HardwareProfile: &armcompute.HardwareProfile{
VMSize: to.Ptr(armcompute.VirtualMachineSizeTypes(vmSize)),
},
- StorageProfile: p.buildStorageProfile(),
+ StorageProfile: p.buildStorageProfile(imageID),
OSProfile: &armcompute.OSProfile{
ComputerName: to.Ptr(vmName),
AdminUsername: to.Ptr(p.cfg.AdminUsername),
@@ -300,13 +324,48 @@ func (p *AzurePool) DrainMachine(ctx context.Context, machineID string) error {
return err
}
+// RefreshAMI checks Azure Key Vault for a new worker image ID and version.
+// Satisfies the controlplane.AMIRefresher interface.
+// If Key Vault is not configured, returns the static image ID with no error.
+func (p *AzurePool) RefreshAMI(ctx context.Context) (imageID string, version string, err error) {
+ if p.kvClient == nil {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.cfg.ImageID, "", nil
+ }
+
+ // Fetch image ID from Key Vault
+ resp, err := p.kvClient.GetSecret(ctx, "worker-image-id", "", nil)
+ if err != nil {
+ return "", "", fmt.Errorf("azure: Key Vault get worker-image-id: %w", err)
+ }
+ if resp.Value == nil || *resp.Value == "" {
+ return "", "", fmt.Errorf("azure: Key Vault worker-image-id is empty")
+ }
+ newImageID := *resp.Value
+
+ // Fetch version
+ if vResp, vErr := p.kvClient.GetSecret(ctx, "worker-image-version", "", nil); vErr == nil && vResp.Value != nil {
+ version = *vResp.Value
+ }
+
+ p.mu.Lock()
+ if newImageID != p.cfg.ImageID {
+ log.Printf("azure: image updated via Key Vault: %s -> %s (version=%s)", p.cfg.ImageID, newImageID, version)
+ p.cfg.ImageID = newImageID
+ }
+ p.mu.Unlock()
+
+ return newImageID, version, nil
+}
+
// buildStorageProfile creates the storage profile, handling the difference between
// custom images (which already define OS disk) and marketplace images (which need explicit OS disk config).
-func (p *AzurePool) buildStorageProfile() *armcompute.StorageProfile {
- isCustomImage := strings.HasPrefix(p.cfg.ImageID, "/")
+func (p *AzurePool) buildStorageProfile(imageID string) *armcompute.StorageProfile {
+ isCustomImage := strings.HasPrefix(imageID, "/")
profile := &armcompute.StorageProfile{
- ImageReference: p.parseImageRef(),
+ ImageReference: p.parseImageRef(imageID),
}
// Custom images already define OS disk and may include data disks.
@@ -337,8 +396,7 @@ func (p *AzurePool) buildStorageProfile() *armcompute.StorageProfile {
// parseImageRef parses the image reference. Supports:
// - Full resource ID: /subscriptions/.../images/my-image
// - URN: Publisher:Offer:SKU:Version (e.g. Canonical:ubuntu-24_04-lts:server:latest)
-func (p *AzurePool) parseImageRef() *armcompute.ImageReference {
- img := p.cfg.ImageID
+func (p *AzurePool) parseImageRef(img string) *armcompute.ImageReference {
if strings.HasPrefix(img, "/") {
return &armcompute.ImageReference{ID: to.Ptr(img)}
}
@@ -399,21 +457,34 @@ func (p *AzurePool) buildUserData(opts MachineOpts) string {
var sb strings.Builder
sb.WriteString("#!/bin/bash\nset -euo pipefail\n\n")
- // Mount data disk — try already-formatted first, then format if new
- sb.WriteString("# Mount data disk\n")
+ // Mount data/temp disk as XFS with reflink (required for QEMU snapshot copies)
+ // v6 VMs use NVMe paths, v5 uses SCSI paths. Try both.
+ sb.WriteString("# Mount data disk (XFS with reflink)\n")
sb.WriteString("if ! mountpoint -q /data 2>/dev/null; then\n")
sb.WriteString(" mkdir -p /data\n")
- sb.WriteString(" # Find data disk (not sda=OS, not sdb=temp)\n")
- sb.WriteString(" for d in /dev/sdc /dev/sdd; do\n")
+ sb.WriteString(" DISK=\"\"\n")
+ sb.WriteString(" # Try NVMe temp disks (v6 VMs), then SCSI data disks (v5 VMs), then SCSI temp disk\n")
+ sb.WriteString(" for d in /dev/nvme1n1 /dev/nvme2n1 /dev/nvme0n1 /dev/sdc /dev/sdd /dev/sdb; do\n")
sb.WriteString(" [ -b \"$d\" ] || continue\n")
- sb.WriteString(" if blkid \"$d\" | grep -q xfs; then\n")
- sb.WriteString(" mount \"$d\" /data && break\n")
- sb.WriteString(" elif ! blkid \"$d\" &>/dev/null; then\n")
- sb.WriteString(" mkfs.xfs -m reflink=1 \"$d\" && mount \"$d\" /data && break\n")
- sb.WriteString(" fi\n")
+ sb.WriteString(" # Skip the OS disk\n")
+ sb.WriteString(" ROOT_DEV=$(lsblk -no PKNAME $(findmnt -n -o SOURCE /) 2>/dev/null | head -1)\n")
+ sb.WriteString(" [ \"$(basename $d)\" = \"$ROOT_DEV\" ] && continue\n")
+ sb.WriteString(" DISK=\"$d\"; break\n")
sb.WriteString(" done\n")
+ sb.WriteString(" if [ -n \"$DISK\" ]; then\n")
+ sb.WriteString(" if blkid \"$DISK\" 2>/dev/null | grep -q xfs; then\n")
+ sb.WriteString(" mount \"$DISK\" /data\n")
+ sb.WriteString(" else\n")
+ sb.WriteString(" mkfs.xfs -f -m reflink=1 \"$DISK\" && mount \"$DISK\" /data\n")
+ sb.WriteString(" fi\n")
+ sb.WriteString(" fi\n")
sb.WriteString("fi\n")
- sb.WriteString("mkdir -p /data/sandboxes /data/firecracker/images\n\n")
+ sb.WriteString("mkdir -p /data/sandboxes /data/firecracker/images\n")
+ sb.WriteString("# Copy rootfs images from OS disk to data disk (NVMe mount may overlay /data)\n")
+ sb.WriteString("if [ -d /opt/opensandbox/images ] && [ ! -f /data/firecracker/images/default.ext4 ]; then\n")
+ sb.WriteString(" cp /opt/opensandbox/images/*.ext4 /data/firecracker/images/ 2>/dev/null || true\n")
+ sb.WriteString(" echo 'Copied rootfs images from /opt/opensandbox/images to /data/firecracker/images'\n")
+ sb.WriteString("fi\n\n")
// Write worker env file from base64-encoded config
if p.cfg.WorkerEnvBase64 != "" {
diff --git a/internal/compute/ec2.go b/internal/compute/ec2.go
index 36714a9b..e3f11173 100644
--- a/internal/compute/ec2.go
+++ b/internal/compute/ec2.go
@@ -4,13 +4,16 @@ import (
"context"
"encoding/base64"
"fmt"
+ "log"
"strings"
+ "sync"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/aws-sdk-go-v2/service/ssm"
)
const (
@@ -31,11 +34,14 @@ type EC2PoolConfig struct {
KeyName string
IAMInstanceProfile string // IAM instance profile name (for Secrets Manager + S3 access)
SecretsARN string // Secrets Manager ARN passed to worker env
+ SSMParameterName string // SSM parameter for dynamic AMI ID (e.g. /opensandbox/prod/worker-ami-id)
}
// EC2Pool implements compute.Pool using AWS EC2 instances.
type EC2Pool struct {
client *ec2.Client
+ awsCfg aws.Config
+ mu sync.RWMutex // protects cfg.AMI
cfg EC2PoolConfig
}
@@ -44,9 +50,11 @@ type EC2Pool struct {
func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {
var client *ec2.Client
+ var awsCfgVal aws.Config
+
if cfg.AccessKeyID != "" {
// Static credentials
- awsCfg := aws.Config{
+ awsCfgVal = aws.Config{
Region: cfg.Region,
Credentials: credentials.NewStaticCredentialsProvider(
cfg.AccessKeyID,
@@ -54,20 +62,22 @@ func NewEC2Pool(cfg EC2PoolConfig) (*EC2Pool, error) {
"",
),
}
- client = ec2.NewFromConfig(awsCfg)
} else {
// IAM credential chain
- awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(),
+ var err error
+ awsCfgVal, err = awsconfig.LoadDefaultConfig(context.Background(),
awsconfig.WithRegion(cfg.Region),
)
if err != nil {
return nil, fmt.Errorf("ec2: failed to load AWS config: %w", err)
}
- client = ec2.NewFromConfig(awsCfg)
}
+ client = ec2.NewFromConfig(awsCfgVal)
+
return &EC2Pool{
client: client,
+ awsCfg: awsCfgVal,
cfg: cfg,
}, nil
}
@@ -78,10 +88,14 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine
instanceType = opts.Size
}
+ p.mu.RLock()
+ ami := p.cfg.AMI
+ p.mu.RUnlock()
+
userData := p.buildUserData(opts)
input := &ec2.RunInstancesInput{
- ImageId: aws.String(p.cfg.AMI),
+ ImageId: aws.String(ami),
InstanceType: ec2types.InstanceType(instanceType),
MinCount: aws.Int32(1),
MaxCount: aws.Int32(1),
@@ -260,6 +274,49 @@ func (p *EC2Pool) instanceToMachine(inst *ec2types.Instance) *Machine {
}
}
+// RefreshAMI checks SSM Parameter Store for a new AMI ID and updates the pool config.
+// Returns the current AMI ID and the version string (if a version parameter exists alongside).
+// If SSMParameterName is not configured, returns the static AMI with no error.
+func (p *EC2Pool) RefreshAMI(ctx context.Context) (amiID string, version string, err error) {
+ if p.cfg.SSMParameterName == "" {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ return p.cfg.AMI, "", nil
+ }
+
+ ssmClient := ssm.NewFromConfig(p.awsCfg)
+
+ // Fetch AMI ID
+ result, err := ssmClient.GetParameter(ctx, &ssm.GetParameterInput{
+ Name: aws.String(p.cfg.SSMParameterName),
+ })
+ if err != nil {
+ return "", "", fmt.Errorf("ec2: SSM GetParameter %s: %w", p.cfg.SSMParameterName, err)
+ }
+ newAMI := aws.ToString(result.Parameter.Value)
+ if newAMI == "" {
+ return "", "", fmt.Errorf("ec2: SSM parameter %s is empty", p.cfg.SSMParameterName)
+ }
+
+ // Fetch version (convention: sibling parameter with last segment replaced by "worker-ami-version")
+ // e.g. /opensandbox/prod/worker-ami-id -> /opensandbox/prod/worker-ami-version
+ versionParam := p.cfg.SSMParameterName[:strings.LastIndex(p.cfg.SSMParameterName, "/")+1] + "worker-ami-version"
+ if vResult, vErr := ssmClient.GetParameter(ctx, &ssm.GetParameterInput{
+ Name: aws.String(versionParam),
+ }); vErr == nil {
+ version = aws.ToString(vResult.Parameter.Value)
+ }
+
+ p.mu.Lock()
+ if newAMI != p.cfg.AMI {
+ log.Printf("ec2: AMI updated via SSM: %s -> %s (version=%s)", p.cfg.AMI, newAMI, version)
+ p.cfg.AMI = newAMI
+ }
+ p.mu.Unlock()
+
+ return newAMI, version, nil
+}
+
func (p *EC2Pool) buildUserData(opts MachineOpts) string {
var sb strings.Builder
sb.WriteString("#!/bin/bash\nset -euo pipefail\n\n")
diff --git a/internal/config/config.go b/internal/config/config.go
index 5d84cd33..f0912a86 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -79,6 +79,7 @@ type Config struct {
EC2KeyName string // SSH key pair name (for debugging)
EC2WorkerImage string // Docker image for containerized workers
EC2IAMInstanceProfile string // IAM instance profile for worker instances (Secrets Manager + S3)
+ EC2SSMParameterName string // SSM parameter name for dynamic AMI ID (e.g. /opensandbox/prod/worker-ami-id)
// Azure compute pool (server mode — for auto-scaling worker VMs)
AzureSubscriptionID string // Azure subscription ID
@@ -87,6 +88,7 @@ type Config struct {
AzureImageID string // Custom image ID or URN
AzureSubnetID string // Full resource ID of the VNet subnet
AzureSSHPublicKey string // SSH public key for worker VMs
+ AzureKeyVaultName string // Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")
// Cloudflare (custom hostname for org sandbox domains)
CFAPIToken string // Cloudflare API token with Custom Hostnames permission
@@ -94,8 +96,9 @@ type Config struct {
// Autoscaler
ScaleCooldownSec int // Cooldown between scale-up actions (seconds), default 300
- MinWorkersPerRegion int // Minimum workers per region (for pre-provisioned capacity), default 1
+ MinWorkersPerRegion int // Minimum total workers per region, default 1
MaxWorkersPerRegion int // Maximum workers per region (hard cap), default 10
+ IdleReserveWorkers int // Target idle workers for burst absorption, default 1
// Stripe billing
StripeSecretKey string
@@ -174,6 +177,7 @@ func Load() (*Config, error) {
EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),
EC2WorkerImage: envOrDefault("OPENSANDBOX_EC2_WORKER_IMAGE", "opensandbox-worker:latest"),
EC2IAMInstanceProfile: os.Getenv("OPENSANDBOX_EC2_IAM_INSTANCE_PROFILE"),
+ EC2SSMParameterName: os.Getenv("OPENSANDBOX_EC2_SSM_AMI_PARAM"),
AzureSubscriptionID: os.Getenv("OPENSANDBOX_AZURE_SUBSCRIPTION_ID"),
AzureResourceGroup: os.Getenv("OPENSANDBOX_AZURE_RESOURCE_GROUP"),
@@ -181,6 +185,7 @@ func Load() (*Config, error) {
AzureImageID: os.Getenv("OPENSANDBOX_AZURE_IMAGE_ID"),
AzureSubnetID: os.Getenv("OPENSANDBOX_AZURE_SUBNET_ID"),
AzureSSHPublicKey: os.Getenv("OPENSANDBOX_AZURE_SSH_PUBLIC_KEY"),
+ AzureKeyVaultName: os.Getenv("OPENSANDBOX_AZURE_KEY_VAULT_NAME"),
CFAPIToken: os.Getenv("OPENSANDBOX_CF_API_TOKEN"),
CFZoneID: os.Getenv("OPENSANDBOX_CF_ZONE_ID"),
@@ -188,6 +193,7 @@ func Load() (*Config, error) {
ScaleCooldownSec: envOrDefaultInt("OPENSANDBOX_SCALE_COOLDOWN_SEC", 300),
MinWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MIN_WORKERS", 1),
MaxWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MAX_WORKERS", 10),
+ IdleReserveWorkers: envOrDefaultInt("OPENSANDBOX_IDLE_RESERVE", 1),
StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index ce821cab..6c90a5cd 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -31,6 +31,7 @@ type WorkerEntry struct {
MemPct float64 `json:"mem_pct"`
DiskPct float64 `json:"disk_pct"`
GoldenVersion string `json:"golden_version,omitempty"`
+ WorkerVersion string `json:"worker_version,omitempty"`
}
// RedisWorkerRegistry maintains an in-memory cache of worker state
@@ -205,6 +206,9 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
if entry.GoldenVersion != "" {
existing.GoldenVersion = entry.GoldenVersion
}
+ if entry.WorkerVersion != "" {
+ existing.WorkerVersion = entry.WorkerVersion
+ }
if entry.GRPCAddr != "" {
existing.GRPCAddr = entry.GRPCAddr
}
@@ -221,26 +225,40 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
}
// Ensure gRPC connection exists and is healthy.
- // Re-dial if address changed OR connection is in a failed state.
+ // Re-dial if address changed, connection is failed/idle, or worker is newly registered.
if entry.GRPCAddr != "" {
+ needsDial := false
if conn, hasConn := r.conns[entry.ID]; hasConn {
addrChanged := existing != nil && existing.GRPCAddr != entry.GRPCAddr
state := conn.GetState()
connDead := state == connectivity.TransientFailure || state == connectivity.Shutdown
- if addrChanged || connDead {
+ // Also treat IDLE as potentially stale — the remote may have restarted.
+ // gRPC won't detect a dead peer until an RPC is attempted on an IDLE conn.
+ connIdle := state == connectivity.Idle
+ isNewWorker := existing == nil
+
+ if addrChanged || connDead || (connIdle && isNewWorker) {
if addrChanged {
log.Printf("redis_registry: worker %s gRPC address changed (%s → %s), re-dialing",
entry.ID, existing.GRPCAddr, entry.GRPCAddr)
} else {
- log.Printf("redis_registry: worker %s gRPC connection in %s state, re-dialing",
- entry.ID, conn.GetState().String())
+ log.Printf("redis_registry: worker %s gRPC connection in %s state (new=%v), re-dialing",
+ entry.ID, state.String(), isNewWorker)
}
conn.Close()
delete(r.conns, entry.ID)
delete(r.clients, entry.ID)
- r.dialWorkerLocked(entry.ID, entry.GRPCAddr)
+ needsDial = true
+ } else if connIdle {
+ // Existing worker with idle connection — force it to reconnect
+ // so stale connections are detected quickly.
+ conn.ResetConnectBackoff()
+ conn.Connect()
}
} else {
+ needsDial = true
+ }
+ if needsDial {
r.dialWorkerLocked(entry.ID, entry.GRPCAddr)
}
}
@@ -260,8 +278,8 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {
grpc.MaxCallSendMsgSize(256*1024*1024),
),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
- Time: 30 * time.Second,
- Timeout: 10 * time.Second,
+ Time: 10 * time.Second,
+ Timeout: 5 * time.Second,
PermitWithoutStream: true,
}),
)
@@ -283,28 +301,51 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {
// are skipped. If region is non-empty, only workers in that region are considered.
// If no workers match the region, falls back to all workers.
func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry, pb.SandboxWorkerClient, error) {
- r.mu.RLock()
- defer r.mu.RUnlock()
+ r.mu.Lock()
+ defer r.mu.Unlock()
var best *WorkerEntry
bestScore := -1.0
- // First pass: try workers in the requested region
- for _, w := range r.workers {
- if region != "" && w.Region != region {
- continue
+ // Bin-pack strategy: fill active workers before touching idle reserves.
+ // This keeps idle workers as headroom for burst absorption and avoids
+ // thrashing between scale-up (headroom) and scale-down (low utilization).
+ //
+ // Priority order:
+ // 1. Most-loaded worker that still has capacity (pack tightly)
+ // 2. Idle worker (dip into reserve only when active workers are full)
+ // 3. Over-capacity worker (absorb overflow while new workers boot)
+ scoreWorker := func(w *WorkerEntry) float64 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
+ return -1 // skip
}
remaining := w.Capacity - w.Current
+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
+
if remaining <= 0 {
+ // Over capacity: last resort
+ return 0.01 * resourceScore
+ }
+ if w.Current == 0 {
+ // Idle/reserve: prefer active workers over idle ones.
+ // Score between 0.1 and 1.0 so it ranks below any active worker.
+ return 0.1 * resourceScore
+ }
+ // Active with capacity: higher current = higher score (bin-pack).
+ // Add remaining as a tiebreaker so we don't overflow a nearly-full worker
+ // when another active worker has more room.
+ return float64(w.Current)*10.0 + float64(remaining)*resourceScore
+ }
+
+ // First pass: try workers in the requested region
+ for _, w := range r.workers {
+ if region != "" && w.Region != region {
continue
}
- // Skip workers under heavy resource pressure
- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
+ score := scoreWorker(w)
+ if score < 0 {
continue
}
- // Score: remaining capacity weighted by resource headroom
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
- score := float64(remaining) * resourceScore
if score > bestScore {
best = w
bestScore = score
@@ -314,15 +355,10 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
// Fallback: try any region
if best == nil && region != "" {
for _, w := range r.workers {
- remaining := w.Capacity - w.Current
- if remaining <= 0 {
+ score := scoreWorker(w)
+ if score < 0 {
continue
}
- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
- continue
- }
- resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
- score := float64(remaining) * resourceScore
if score > bestScore {
best = w
bestScore = score
@@ -339,6 +375,10 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
return nil, nil, fmt.Errorf("no gRPC connection to worker %s", best.ID)
}
+ // Optimistically increment Current so the next call spreads load.
+ // The heartbeat will correct this within 10s if the create fails.
+ best.Current++
+
return best, client, nil
}
@@ -427,6 +467,7 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
MemPct: w.MemPct,
DiskPct: w.DiskPct,
GoldenVersion: w.GoldenVersion,
+ WorkerVersion: w.WorkerVersion,
})
}
}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 59f62375..d073e069 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -15,23 +15,29 @@ import (
)
const (
- scaleUpThreshold = 0.70 // Scale up when utilization > 70%
- scaleDownThreshold = 0.30 // Scale down when utilization < 30%
+ scaleUpThreshold = 0.50 // Scale up when utilization > 50% (gives ~3 min runway for new worker to boot)
+ scaleDownThreshold = 0.20 // Scale down when utilization < 20%
maxWorkersPerRegion = 10 // Hard cap to prevent runaway launches
pendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register
// Resource-based scaling thresholds (applied per-worker, trigger on ANY worker exceeding)
- resourceCPUThreshold = 80.0 // Scale up if any worker CPU > 80%
- resourceMemThreshold = 85.0 // Scale up if any worker memory > 85%
- resourceDiskThreshold = 75.0 // Scale up if any worker disk > 75%
+ resourceCPUThreshold = 70.0 // Scale up if any worker CPU > 70%
+ resourceMemThreshold = 70.0 // Scale up if any worker memory > 70%
+ resourceDiskThreshold = 60.0 // Scale up if any worker disk > 60%
// Evacuation thresholds (per-worker, triggers live migration of sandboxes OFF the hot worker)
- evacuationCPUThreshold = 90.0
- evacuationMemThreshold = 90.0
- evacuationDiskThreshold = 80.0
+ evacuationCPUThreshold = 80.0
+ evacuationMemThreshold = 80.0
+ evacuationDiskThreshold = 70.0
+
+ // Emergency thresholds — above these, hibernate sandboxes to free resources immediately
+ // (no migration target needed, just dump to S3 and delete local files)
+ emergencyCPUThreshold = 95.0
+ emergencyMemThreshold = 95.0
+ emergencyDiskThreshold = 90.0
evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
- drainTimeout = 5 * time.Minute // max time to drain a worker before force-destroying
+ drainTimeout = 15 * time.Minute // max time to drain a worker via live migration
)
// ScalerRegistry is the interface the Scaler uses to query worker state.
@@ -44,6 +50,12 @@ type ScalerRegistry interface {
GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error)
}
+// AMIRefresher is an optional interface a Pool can implement to support dynamic AMI updates.
+// If the pool implements this, the scaler will periodically call RefreshAMI to check for new images.
+type AMIRefresher interface {
+ RefreshAMI(ctx context.Context) (amiID string, version string, err error)
+}
+
// ScalerConfig configures the autoscaler.
type ScalerConfig struct {
Pool compute.Pool
@@ -52,8 +64,9 @@ type ScalerConfig struct {
WorkerImage string
Cooldown time.Duration // minimum time between scale-up actions per region
Interval time.Duration // how often to evaluate scaling (0 = default 30s)
- MinWorkers int // minimum workers per region (0 = default 1). Set higher to pre-provision capacity.
- MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.
+ MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.
+ MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.
+ IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.
}
// pendingLaunch tracks an EC2 instance that was launched but hasn't registered yet.
@@ -78,17 +91,31 @@ type Scaler struct {
image string
cooldown time.Duration
interval time.Duration
- minWorkers int
- maxWorkers int
- lastScaleUp map[string]time.Time // region -> last scale-up time
- pending map[string][]pendingLaunch // region -> pending (unregistered) launches
+ minWorkers int
+ maxWorkers int
+ idleReserve int
+
+ // mu protects all mutable maps below (lastScaleUp, pending, draining, lastEvacuation)
+ mu sync.Mutex
+ lastScaleUp map[string]time.Time // region -> last scale-up time
+ pending map[string][]pendingLaunch // region -> pending (unregistered) launches
+ draining map[string]*drainState // machineID -> state (workers being drained for scale-down)
+ lastEvacuation map[string]time.Time // workerID -> last evacuation time
+
stop chan struct{}
wg sync.WaitGroup
+ migrating sync.Map // sandboxID -> struct{} (prevent double-migrate)
+
+ // In-flight migration tracking — prevents routing all migrations to the same target
+ inFlightMu sync.Mutex
+ inFlightTo map[string]int // workerID -> number of migrations currently targeting this worker
- // Drain & evacuation state
- draining map[string]*drainState // machineID -> state (workers being drained for scale-down)
- lastEvacuation map[string]time.Time // workerID -> last evacuation time
- migrating sync.Map // sandboxID -> struct{} (prevent double-migrate)
+ // Rolling replacement: version-aware AMI updates
+ targetWorkerVersion string // desired worker version (from SSM); workers not matching this get replaced
+ refreshCount int // tick counter for AMI refresh interval
+
+ // Rate-of-change scaling: track sandbox count per region to detect growth bursts
+ lastSandboxCount map[string]int // region -> sandbox count from previous eval tick
}
// NewScaler creates a new autoscaling controller.
@@ -109,6 +136,10 @@ func NewScaler(cfg ScalerConfig) *Scaler {
if maxWorkers <= 0 {
maxWorkers = maxWorkersPerRegion
}
+ idleReserve := cfg.IdleReserve
+ if idleReserve <= 0 {
+ idleReserve = 1
+ }
return &Scaler{
pool: cfg.Pool,
registry: cfg.Registry,
@@ -118,11 +149,14 @@ func NewScaler(cfg ScalerConfig) *Scaler {
interval: interval,
minWorkers: minWorkers,
maxWorkers: maxWorkers,
+ idleReserve: idleReserve,
lastScaleUp: make(map[string]time.Time),
pending: make(map[string][]pendingLaunch),
stop: make(chan struct{}),
- draining: make(map[string]*drainState),
- lastEvacuation: make(map[string]time.Time),
+ draining: make(map[string]*drainState),
+ lastEvacuation: make(map[string]time.Time),
+ inFlightTo: make(map[string]int),
+ lastSandboxCount: make(map[string]int),
}
}
@@ -156,6 +190,19 @@ func (s *Scaler) evaluate() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
+ // Refresh AMI from SSM every ~60s (every 2nd tick at 30s interval)
+ s.refreshCount++
+ if s.refreshCount%2 == 0 {
+ if refresher, ok := s.pool.(AMIRefresher); ok {
+ if _, version, err := refresher.RefreshAMI(ctx); err != nil {
+ log.Printf("scaler: AMI refresh failed: %v", err)
+ } else if version != "" && version != s.targetWorkerVersion {
+ log.Printf("scaler: target worker version updated: %q -> %q", s.targetWorkerVersion, version)
+ s.targetWorkerVersion = version
+ }
+ }
+ }
+
// Use discovered regions from workers, or fall back to the pool's region
regions := s.registry.Regions()
log.Printf("scaler: evaluate tick (regions=%v)", regions)
@@ -172,6 +219,9 @@ func (s *Scaler) evaluate() {
}
func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
workers := s.registry.GetWorkersByRegion(region)
utilization := s.registry.RegionUtilization(region)
maxCPU, maxMem, maxDisk := s.registry.RegionResourcePressure(region)
@@ -179,6 +229,9 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
// Expire stale pending launches
s.expirePending(region)
+ // Phase 0: Emergency hibernate — workers in critical state, no migration needed
+ s.emergencyHibernate(ctx, region, workers)
+
// Phase 1: Check progress on workers being drained
s.checkDrainingWorkers(ctx, region)
@@ -206,6 +259,34 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
reason = fmt.Sprintf("disk pressure %.1f%% > %.0f%%", maxDisk, resourceDiskThreshold)
}
+ // Rate-of-change scaling: if sandbox count is growing fast, scale up proactively.
+ // This triggers before utilization thresholds so new workers are booting while
+ // there's still headroom on existing workers.
+ currentSandboxes := 0
+ totalCapacity := 0
+ for _, w := range workers {
+ currentSandboxes += w.Current
+ totalCapacity += w.Capacity
+ }
+ prevSandboxes := s.lastSandboxCount[region]
+ s.lastSandboxCount[region] = currentSandboxes
+ growthRate := currentSandboxes - prevSandboxes // sandboxes added since last tick (30s)
+
+ if !needsScaleUp && growthRate > 0 && totalCapacity > 0 {
+ // Project: at this growth rate, how many ticks until we're full?
+ remaining := totalCapacity - currentSandboxes
+ if growthRate > 0 && remaining > 0 {
+ ticksUntilFull := remaining / growthRate
+ // If we'll be full within 6 ticks (~3 min, roughly how long a new worker takes to boot),
+ // scale up now so the new worker is ready in time.
+ if ticksUntilFull <= 6 {
+ needsScaleUp = true
+ reason = fmt.Sprintf("growth rate %d/tick, full in ~%d ticks (%d/%d used)",
+ growthRate, ticksUntilFull, currentSandboxes, totalCapacity)
+ }
+ }
+ }
+
// Ensure minimum workers are running (pre-provisioned capacity).
// Ignores cooldowns — if we're below minimum, launch immediately.
totalWorkers := len(workers) + len(s.pending[region])
@@ -219,6 +300,30 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
return
}
+ // Headroom: maintain a pool of idle workers for burst absorption.
+ // Uses minWorkers as the reserve target — this is separate from the
+ // minimum total workers check above. When bin-packing overflows into
+ // reserve workers, we launch replacements one at a time so there's
+ // always warm capacity without thrashing.
+ idleWorkers := 0
+ for _, w := range workers {
+ if _, isDraining := s.draining[w.MachineID]; isDraining {
+ continue
+ }
+ if w.Current == 0 {
+ idleWorkers++
+ }
+ }
+ pendingCount := len(s.pending[region])
+ reserveTarget := s.idleReserve
+ idleOrPending := idleWorkers + pendingCount
+ if idleOrPending < reserveTarget && totalWorkers+pendingCount < s.maxWorkers {
+ // Launch 1 at a time to avoid over-provisioning
+ log.Printf("scaler: region %s reserve low (%d idle + %d pending < %d target), launching 1",
+ region, idleWorkers, pendingCount, reserveTarget)
+ s.scaleUp(ctx, region)
+ }
+
if needsScaleUp {
// Check cooldown before scaling up
if last, ok := s.lastScaleUp[region]; ok && time.Since(last) < s.cooldown {
@@ -255,6 +360,9 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, initiating smart drain", region, utilization*100, scaleDownThreshold*100)
s.smartScaleDown(ctx, region, workers)
}
+
+ // Phase 5: Rolling replacement of workers running old versions
+ s.rollingReplace(ctx, region, workers)
}
func (s *Scaler) scaleUp(_ context.Context, region string) {
@@ -322,6 +430,71 @@ func (s *Scaler) expirePending(region string) {
s.pending[region] = remaining
}
+// --- Emergency Hibernate ---
+
+// emergencyHibernate hibernates sandboxes on workers that exceed critical thresholds.
+// Unlike evacuation (which live-migrates), this dumps sandboxes to S3 and frees
+// resources immediately. Used when a worker is about to run out of capacity and
+// there may not be a viable migration target.
+func (s *Scaler) emergencyHibernate(_ context.Context, region string, workers []*WorkerInfo) {
+ for _, w := range workers {
+ if w.CPUPct < emergencyCPUThreshold && w.MemPct < emergencyMemThreshold && w.DiskPct < emergencyDiskThreshold {
+ continue
+ }
+ // Cooldown — reuse evacuation cooldown to avoid hammering
+ if last, ok := s.lastEvacuation[w.ID]; ok && time.Since(last) < evacuationCooldown {
+ continue
+ }
+
+ log.Printf("scaler: EMERGENCY worker %s at critical levels (cpu=%.1f%% mem=%.1f%% disk=%.1f%%), hibernating sandboxes",
+ w.ID, w.CPUPct, w.MemPct, w.DiskPct)
+
+ s.lastEvacuation[w.ID] = time.Now()
+ go s.hibernateBatch(w.ID, evacuationBatchSize)
+ }
+}
+
+// hibernateBatch hibernates up to count idle sandboxes on a worker to free resources.
+// Picks sandboxes with the oldest last activity first.
+func (s *Scaler) hibernateBatch(workerID string, count int) {
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ client, err := s.registry.GetWorkerClient(workerID)
+ if err != nil {
+ log.Printf("scaler: emergency: no gRPC client for %s: %v", workerID, err)
+ return
+ }
+
+ listResp, err := client.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
+ if err != nil {
+ log.Printf("scaler: emergency: ListSandboxes failed for %s: %v", workerID, err)
+ return
+ }
+
+ hibernated := 0
+ for _, sb := range listResp.Sandboxes {
+ if hibernated >= count {
+ break
+ }
+ if sb.Status != "running" {
+ continue
+ }
+ _, err := client.HibernateSandbox(ctx, &pb.HibernateSandboxRequest{
+ SandboxId: sb.SandboxId,
+ })
+ if err != nil {
+ log.Printf("scaler: emergency: hibernate %s failed: %v", sb.SandboxId, err)
+ continue
+ }
+ hibernated++
+ log.Printf("scaler: emergency: hibernated %s on worker %s", sb.SandboxId, workerID)
+ }
+
+ log.Printf("scaler: emergency batch complete for %s: %d/%d hibernated",
+ workerID, hibernated, count)
+}
+
// --- Pressure Evacuation ---
// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical thresholds.
@@ -356,8 +529,17 @@ func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []
}
// findMigrationTarget returns the best worker to receive migrated sandboxes.
+// Accounts for in-flight migrations so we don't pile onto the same target.
func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfo {
workers := s.registry.GetWorkersByRegion(region)
+
+ s.inFlightMu.Lock()
+ inFlight := make(map[string]int, len(s.inFlightTo))
+ for k, v := range s.inFlightTo {
+ inFlight[k] = v
+ }
+ s.inFlightMu.Unlock()
+
var best *WorkerInfo
bestScore := -1.0
for _, w := range workers {
@@ -367,7 +549,9 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfo
if _, isDraining := s.draining[w.MachineID]; isDraining {
continue
}
- remaining := w.Capacity - w.Current
+ // Subtract in-flight migrations from remaining capacity
+ pending := inFlight[w.ID]
+ remaining := w.Capacity - w.Current - pending
if remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 || w.DiskPct > 85 {
continue
}
@@ -460,6 +644,69 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Wor
go s.drainWorker(target.ID, target.MachineID, region)
}
+// rollingReplace drains workers running an old version one at a time,
+// allowing the scaler to replace them with new-AMI workers.
+func (s *Scaler) rollingReplace(_ context.Context, region string, workers []*WorkerInfo) {
+ if s.targetWorkerVersion == "" {
+ return
+ }
+
+ var stale []*WorkerInfo
+ var current int
+ for _, w := range workers {
+ // Skip workers already being drained
+ if _, isDraining := s.draining[w.MachineID]; isDraining {
+ continue
+ }
+ // Skip manually provisioned workers (not autoscaler-managed)
+ if w.MachineID == "" {
+ continue
+ }
+ if !strings.HasPrefix(w.MachineID, "osb-worker-") {
+ continue
+ }
+ if w.MachineID == "osb-worker-1" {
+ continue // static worker, not autoscaled
+ }
+ if w.WorkerVersion == s.targetWorkerVersion {
+ current++
+ } else {
+ stale = append(stale, w)
+ }
+ }
+
+ if len(stale) == 0 {
+ return
+ }
+
+ // Don't drain if no current-version workers exist yet — scale up first
+ if current < 1 {
+ log.Printf("scaler: region %s has %d stale workers but 0 current-version, waiting for new workers to register",
+ region, len(stale))
+ return
+ }
+
+ // Only drain one stale worker at a time (conservative rolling update)
+ target := stale[0]
+ for _, w := range stale[1:] {
+ if w.Current < target.Current {
+ target = w
+ }
+ }
+
+ log.Printf("scaler: rolling replace: draining stale worker %s (version=%q, want=%q, sandboxes=%d)",
+ target.ID, target.WorkerVersion, s.targetWorkerVersion, target.Current)
+
+ s.draining[target.MachineID] = &drainState{
+ workerID: target.ID,
+ machineID: target.MachineID,
+ region: region,
+ startedAt: time.Now(),
+ }
+
+ go s.drainWorker(target.ID, target.MachineID, region)
+}
+
// drainWorker live-migrates all sandboxes off a worker, then signals completion
// via the draining map (checkDrainingWorkers will destroy the machine).
func (s *Scaler) drainWorker(workerID, machineID, region string) {
@@ -514,7 +761,8 @@ func (s *Scaler) drainWorker(workerID, machineID, region string) {
for _, sandboxID := range batch {
if err := s.liveMigrateSandbox(ctx, sandboxID, workerID, target.ID); err != nil {
- log.Printf("scaler: drain: migrate %s failed: %v", sandboxID, err)
+ log.Printf("scaler: drain: migrate %s to %s failed: %v, will retry next cycle", sandboxID, target.ID, err)
+ // Don't abort — try remaining sandboxes and retry failed ones next cycle
}
}
@@ -530,11 +778,12 @@ func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {
continue
}
- // Check if drain timed out
+ // Check if drain timed out — do NOT hibernate or destroy.
+ // Sandboxes must be preserved. Cancel the drain and let the worker
+ // keep running. The sandboxes will naturally expire or be manually cleaned up.
if time.Since(state.startedAt) > drainTimeout {
- log.Printf("scaler: drain timeout for worker %s (machine=%s), force-destroying",
- state.workerID, machineID)
- s.destroyDrainedMachine(machineID)
+ log.Printf("scaler: drain timeout for worker %s (machine=%s) after %s — cancelling drain, keeping worker alive with %d sandboxes",
+ state.workerID, machineID, drainTimeout, s.getDrainingWorkerSandboxCount(state.workerID))
delete(s.draining, machineID)
continue
}
@@ -553,6 +802,54 @@ func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {
}
}
+// getDrainingWorkerSandboxCount returns the current sandbox count for a draining worker.
+func (s *Scaler) getDrainingWorkerSandboxCount(workerID string) int {
+ for _, region := range s.registry.Regions() {
+ for _, w := range s.registry.GetWorkersByRegion(region) {
+ if w.ID == workerID {
+ return w.Current
+ }
+ }
+ }
+ return -1
+}
+
+// hibernateAllOnWorker attempts to hibernate all running sandboxes on a worker.
+// Best-effort — logs failures but doesn't block.
+func (s *Scaler) hibernateAllOnWorker(workerID string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+
+ client, err := s.registry.GetWorkerClient(workerID)
+ if err != nil {
+ log.Printf("scaler: hibernate-all: no gRPC client for %s: %v", workerID, err)
+ return
+ }
+
+ listResp, err := client.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
+ if err != nil {
+ log.Printf("scaler: hibernate-all: ListSandboxes failed for %s: %v", workerID, err)
+ return
+ }
+
+ hibernated := 0
+ for _, sb := range listResp.Sandboxes {
+ if sb.Status != "running" {
+ continue
+ }
+ _, err := client.HibernateSandbox(ctx, &pb.HibernateSandboxRequest{
+ SandboxId: sb.SandboxId,
+ })
+ if err != nil {
+ log.Printf("scaler: hibernate-all: hibernate %s failed: %v", sb.SandboxId, err)
+ continue
+ }
+ hibernated++
+ }
+
+ log.Printf("scaler: hibernate-all: %d sandboxes hibernated on worker %s", hibernated, workerID)
+}
+
// destroyDrainedMachine tags and terminates a machine after drain.
func (s *Scaler) destroyDrainedMachine(machineID string) {
go func() {
@@ -624,6 +921,32 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
}
defer s.migrating.Delete(sandboxID)
+ // Mark sandbox as migrating in DB — blocks exec routing during migration
+ migrationCompleted := false
+ if s.store != nil {
+ if err := s.store.SetMigrating(ctx, sandboxID, targetWorkerID); err != nil {
+ log.Printf("scaler: failed to set migrating state for %s: %v", sandboxID, err)
+ }
+ defer func() {
+ if !migrationCompleted && s.store != nil {
+ s.store.FailMigration(ctx, sandboxID)
+ }
+ }()
+ }
+
+ // Track in-flight migration to target so other evacuations don't pile on
+ s.inFlightMu.Lock()
+ s.inFlightTo[targetWorkerID]++
+ s.inFlightMu.Unlock()
+ defer func() {
+ s.inFlightMu.Lock()
+ s.inFlightTo[targetWorkerID]--
+ if s.inFlightTo[targetWorkerID] <= 0 {
+ delete(s.inFlightTo, targetWorkerID)
+ }
+ s.inFlightMu.Unlock()
+ }()
+
sourceClient, err := s.registry.GetWorkerClient(sourceWorkerID)
if err != nil {
return fmt.Errorf("source worker %s unreachable: %w", sourceWorkerID, err)
@@ -731,10 +1054,11 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
return fmt.Errorf("complete migration: %w", err)
}
- // Step 5: Update DB — sandbox now on target worker
+ // Step 5: Complete migration — update DB status and worker_id atomically
if s.store != nil {
- _, _ = s.store.Pool().Exec(ctx, "UPDATE sandbox_sessions SET worker_id = $1 WHERE sandbox_id = $2", targetWorkerID, sandboxID)
+ s.store.CompleteMigration(ctx, sandboxID, targetWorkerID)
}
+ migrationCompleted = true
elapsed := time.Since(t0).Milliseconds()
log.Printf("scaler: migrate %s: complete in %dms (source=%s target=%s)", sandboxID, elapsed, sourceWorkerID, targetWorkerID)
diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.go
new file mode 100644
index 00000000..a5c87c14
--- /dev/null
+++ b/internal/controlplane/scaler_test.go
@@ -0,0 +1,1272 @@
+package controlplane
+
+import (
+ "context"
+ "fmt"
+ "math/rand"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/compute"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// --- Mock ScalerRegistry ---
+
+type mockRegistry struct {
+ mu sync.RWMutex
+ workers map[string][]*WorkerInfo // region -> workers
+}
+
+func newMockRegistry() *mockRegistry {
+ return &mockRegistry{workers: make(map[string][]*WorkerInfo)}
+}
+
+func (r *mockRegistry) addWorker(w *WorkerInfo) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.workers[w.Region] = append(r.workers[w.Region], w)
+}
+
+func (r *mockRegistry) removeWorker(workerID string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for region, workers := range r.workers {
+ for i, w := range workers {
+ if w.ID == workerID {
+ r.workers[region] = append(workers[:i], workers[i+1:]...)
+ return
+ }
+ }
+ }
+}
+
+func (r *mockRegistry) getWorker(workerID string) *WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ for _, workers := range r.workers {
+ for _, w := range workers {
+ if w.ID == workerID {
+ return w
+ }
+ }
+ }
+ return nil
+}
+
+func (r *mockRegistry) updateWorker(workerID string, fn func(w *WorkerInfo)) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ for _, workers := range r.workers {
+ for _, w := range workers {
+ if w.ID == workerID {
+ fn(w)
+ return
+ }
+ }
+ }
+}
+
+func (r *mockRegistry) Regions() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ var regions []string
+ for region := range r.workers {
+ regions = append(regions, region)
+ }
+ return regions
+}
+
+func (r *mockRegistry) GetWorkersByRegion(region string) []*WorkerInfo {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ result := make([]*WorkerInfo, len(r.workers[region]))
+ copy(result, r.workers[region])
+ return result
+}
+
+func (r *mockRegistry) RegionUtilization(region string) float64 {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ var totalCap, totalCur int
+ for _, w := range r.workers[region] {
+ totalCap += w.Capacity
+ totalCur += w.Current
+ }
+ if totalCap == 0 {
+ return 0
+ }
+ return float64(totalCur) / float64(totalCap)
+}
+
+func (r *mockRegistry) RegionResourcePressure(region string) (maxCPU, maxMem, maxDisk float64) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ for _, w := range r.workers[region] {
+ if w.CPUPct > maxCPU {
+ maxCPU = w.CPUPct
+ }
+ if w.MemPct > maxMem {
+ maxMem = w.MemPct
+ }
+ if w.DiskPct > maxDisk {
+ maxDisk = w.DiskPct
+ }
+ }
+ return
+}
+
+func (r *mockRegistry) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {
+ return nil, fmt.Errorf("mock: no gRPC client for %s", workerID)
+}
+
+// --- Mock compute.Pool ---
+
+type mockPool struct {
+ mu sync.Mutex
+ machines map[string]string // machineID -> region
+ created int32
+ destroyed int32
+}
+
+func newMockPool() *mockPool {
+ return &mockPool{machines: make(map[string]string)}
+}
+
+func (p *mockPool) CreateMachine(_ context.Context, opts compute.MachineOpts) (*compute.Machine, error) {
+ id := fmt.Sprintf("osb-worker-%d", atomic.AddInt32(&p.created, 1))
+ p.mu.Lock()
+ p.machines[id] = opts.Region
+ p.mu.Unlock()
+ return &compute.Machine{ID: id, Addr: "10.0.0.1", Region: opts.Region}, nil
+}
+
+func (p *mockPool) DestroyMachine(_ context.Context, machineID string) error {
+ p.mu.Lock()
+ delete(p.machines, machineID)
+ p.mu.Unlock()
+ atomic.AddInt32(&p.destroyed, 1)
+ return nil
+}
+
+func (p *mockPool) DrainMachine(_ context.Context, _ string) error { return nil }
+func (p *mockPool) StartMachine(_ context.Context, _ string) error { return nil }
+func (p *mockPool) StopMachine(_ context.Context, _ string) error { return nil }
+func (p *mockPool) HealthCheck(_ context.Context, _ string) error { return nil }
+func (p *mockPool) ListMachines(_ context.Context) ([]*compute.Machine, error) { return nil, nil }
+func (p *mockPool) SupportedRegions(_ context.Context) ([]string, error) {
+ return []string{"us-east-1"}, nil
+}
+
+// --- Helpers ---
+
+func makeWorker(id, region string, capacity, current int) *WorkerInfo {
+ return &WorkerInfo{
+ ID: id,
+ MachineID: "osb-worker-" + id,
+ Region: region,
+ Capacity: capacity,
+ Current: current,
+ CPUPct: float64(current) / float64(capacity) * 60, // approximate
+ MemPct: float64(current) / float64(capacity) * 50,
+ DiskPct: 30.0,
+ }
+}
+
+func newTestScaler(registry *mockRegistry, pool *mockPool) *Scaler {
+ return NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: registry,
+ Cooldown: 1 * time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ })
+}
+
+// ============================================================
+// Test: Scale-up triggers
+// ============================================================
+
+func TestScaleUpOnHighUtilization(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // One worker at 80% capacity → utilization = 0.80 > 0.70 threshold
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 50, MemPct: 50, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+
+ // scaleUp runs async — wait briefly for the goroutine
+ time.Sleep(100 * time.Millisecond)
+ if atomic.LoadInt32(&pool.created) == 0 {
+ t.Error("expected scale-up due to high utilization, but no machine was created")
+ }
+}
+
+func TestNoScaleUpBelowThreshold(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // One worker at 50% capacity → utilization = 0.50 < 0.70 threshold
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 25, CPUPct: 40, MemPct: 40, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+
+ if atomic.LoadInt32(&pool.created) != 0 {
+ t.Error("expected no scale-up below threshold, but a machine was created")
+ }
+}
+
+func TestScaleUpOnCPUPressure(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Low utilization but high CPU → should still scale up
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 10, CPUPct: 75, MemPct: 40, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+ time.Sleep(100 * time.Millisecond)
+
+ if atomic.LoadInt32(&pool.created) == 0 {
+ t.Error("expected scale-up due to CPU pressure > 70%%, but no machine was created")
+ }
+}
+
+func TestScaleUpOnMemoryPressure(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 10, CPUPct: 40, MemPct: 75, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+ time.Sleep(100 * time.Millisecond)
+
+ if atomic.LoadInt32(&pool.created) == 0 {
+ t.Error("expected scale-up due to memory pressure > 70%%, but no machine was created")
+ }
+}
+
+func TestScaleUpOnDiskPressure(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 10, CPUPct: 40, MemPct: 40, DiskPct: 65,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+ time.Sleep(100 * time.Millisecond)
+
+ if atomic.LoadInt32(&pool.created) == 0 {
+ t.Error("expected scale-up due to disk pressure > 60%%, but no machine was created")
+ }
+}
+
+func TestScaleUpRespectsMaxWorkers(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // 20 workers all at high utilization — already at max
+ for i := 0; i < 20; i++ {
+ reg.addWorker(&WorkerInfo{
+ ID: fmt.Sprintf("w%d", i), MachineID: fmt.Sprintf("osb-worker-w%d", i), Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 50, MemPct: 50, DiskPct: 30,
+ })
+ }
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+
+ if atomic.LoadInt32(&pool.created) != 0 {
+ t.Error("expected no scale-up at max workers, but a machine was created")
+ }
+}
+
+func TestScaleUpRespectsCooldown(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 50, MemPct: 50, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+
+ // First evaluation: should scale up
+ s.evaluateRegion(ctx, "us-east-1")
+ time.Sleep(100 * time.Millisecond)
+ if atomic.LoadInt32(&pool.created) == 0 {
+ t.Fatal("expected first scale-up")
+ }
+
+ // Register the pending machine so it doesn't block
+ time.Sleep(10 * time.Millisecond)
+ s.pending["us-east-1"] = nil
+
+ // Second evaluation immediately: should be blocked by cooldown
+ created := atomic.LoadInt32(&pool.created)
+ s.evaluateRegion(ctx, "us-east-1")
+ if atomic.LoadInt32(&pool.created) != created {
+ t.Error("expected cooldown to prevent second scale-up")
+ }
+}
+
+func TestMinWorkersEnforced(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // No workers at all — should launch minWorkers
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: 1 * time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 3,
+ MaxWorkers: 10,
+ })
+
+ // Add the region so evaluateRegion runs
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 0, CPUPct: 0, MemPct: 0, DiskPct: 0,
+ })
+
+ ctx := context.Background()
+ s.evaluateRegion(ctx, "us-east-1")
+
+ // Should launch 2 more to meet minimum of 3
+ time.Sleep(50 * time.Millisecond) // async launches
+ if atomic.LoadInt32(&pool.created) < 2 {
+ t.Errorf("expected at least 2 machines launched to meet minWorkers=3, got %d", atomic.LoadInt32(&pool.created))
+ }
+}
+
+// ============================================================
+// Test: Scale-down triggers
+// ============================================================
+
+func TestSmartScaleDownTargetsLeastLoaded(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Three autoscaled workers, one with very low usage
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "w2", MachineID: "osb-worker-w2", Region: "us-east-1",
+ Capacity: 50, Current: 2, CPUPct: 10, MemPct: 10, DiskPct: 10,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "w3", MachineID: "osb-worker-w3", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+
+ // Utilization = 12/150 = 8% < 30% → scale down
+ s.smartScaleDown(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))
+
+ // w2 (lowest current=2) should be selected for draining
+ if _, ok := s.draining["osb-worker-w2"]; !ok {
+ t.Error("expected w2 to be selected for draining (least loaded)")
+ }
+}
+
+func TestScaleDownSkipsStaticWorker(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Only osb-worker-1 (static) is present
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-1", Region: "us-east-1",
+ Capacity: 50, Current: 2, CPUPct: 10, MemPct: 10, DiskPct: 10,
+ })
+
+ s := newTestScaler(reg, pool)
+ ctx := context.Background()
+
+ s.smartScaleDown(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))
+
+ if len(s.draining) != 0 {
+ t.Error("expected no draining — osb-worker-1 is static and should be skipped")
+ }
+}
+
+func TestScaleDownSkipsAlreadyDraining(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w2", MachineID: "osb-worker-w2", Region: "us-east-1",
+ Capacity: 50, Current: 2, CPUPct: 10, MemPct: 10, DiskPct: 10,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "w3", MachineID: "osb-worker-w3", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+ s.draining["osb-worker-w2"] = &drainState{workerID: "w2", machineID: "osb-worker-w2"}
+
+ ctx := context.Background()
+ s.smartScaleDown(ctx, "us-east-1", reg.GetWorkersByRegion("us-east-1"))
+
+ // w3 should be selected since w2 is already draining
+ if _, ok := s.draining["osb-worker-w3"]; !ok {
+ t.Error("expected w3 to be selected for draining (w2 already draining)")
+ }
+}
+
+// ============================================================
+// Test: Evacuation
+// ============================================================
+
+func TestEvacuationTriggersOnCPU(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Worker above evacuation CPU threshold (80%)
+ reg.addWorker(&WorkerInfo{
+ ID: "hot", MachineID: "osb-worker-hot", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ // Target worker
+ reg.addWorker(&WorkerInfo{
+ ID: "cold", MachineID: "osb-worker-cold", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+
+ // evacuateHotWorkers should trigger (can't actually migrate without gRPC, but it will try)
+ s.evacuateHotWorkers(context.Background(), "us-east-1", workers)
+
+ if _, ok := s.lastEvacuation["hot"]; !ok {
+ t.Error("expected evacuation to be triggered for hot worker")
+ }
+}
+
+func TestEvacuationSkipsBelowThreshold(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 30, CPUPct: 75, MemPct: 75, DiskPct: 65,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+
+ s.evacuateHotWorkers(context.Background(), "us-east-1", workers)
+
+ if _, ok := s.lastEvacuation["w1"]; ok {
+ t.Error("expected no evacuation below 80%% CPU / 80%% mem / 70%% disk thresholds")
+ }
+}
+
+func TestEvacuationRespectsColdown(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "hot", MachineID: "osb-worker-hot", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "cold", MachineID: "osb-worker-cold", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+
+ // Set recent evacuation
+ s.lastEvacuation["hot"] = time.Now()
+
+ workers := reg.GetWorkersByRegion("us-east-1")
+ s.evacuateHotWorkers(context.Background(), "us-east-1", workers)
+
+ // lastEvacuation should not be updated (cooldown active)
+ if s.lastEvacuation["hot"].After(time.Now().Add(-1 * time.Second)) {
+ // It was just set, which means it was re-triggered. Check more carefully.
+ // Actually, we set it above, so it will be recent regardless. The test is
+ // that evacuateBatch was NOT called (no goroutine launched).
+ // We can't easily check goroutine launch, so this test just validates
+ // the cooldown path doesn't panic.
+ }
+}
+
+func TestEvacuationOnDiskPressure(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "diskfull", MachineID: "osb-worker-diskfull", Region: "us-east-1",
+ Capacity: 50, Current: 20, CPUPct: 30, MemPct: 30, DiskPct: 75,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "target", MachineID: "osb-worker-target", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+ s.evacuateHotWorkers(context.Background(), "us-east-1", workers)
+
+ if _, ok := s.lastEvacuation["diskfull"]; !ok {
+ t.Error("expected evacuation triggered by disk pressure > 70%%")
+ }
+}
+
+// ============================================================
+// Test: Emergency hibernate
+// ============================================================
+
+func TestEmergencyHibernateTriggersAboveCritical(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Worker above emergency thresholds
+ reg.addWorker(&WorkerInfo{
+ ID: "critical", MachineID: "osb-worker-critical", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 96, MemPct: 96, DiskPct: 50,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+
+ s.emergencyHibernate(context.Background(), "us-east-1", workers)
+
+ // Should have triggered (sets lastEvacuation as cooldown marker)
+ if _, ok := s.lastEvacuation["critical"]; !ok {
+ t.Error("expected emergency hibernate triggered for critical worker (CPU > 95%%)")
+ }
+}
+
+func TestEmergencyHibernateOnDiskCritical(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "diskdead", MachineID: "osb-worker-diskdead", Region: "us-east-1",
+ Capacity: 50, Current: 30, CPUPct: 40, MemPct: 40, DiskPct: 92,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+ s.emergencyHibernate(context.Background(), "us-east-1", workers)
+
+ if _, ok := s.lastEvacuation["diskdead"]; !ok {
+ t.Error("expected emergency hibernate triggered for disk > 90%%")
+ }
+}
+
+func TestEmergencyHibernateSkipsBelowCritical(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 85, MemPct: 85, DiskPct: 80,
+ })
+
+ s := newTestScaler(reg, pool)
+ workers := reg.GetWorkersByRegion("us-east-1")
+ s.emergencyHibernate(context.Background(), "us-east-1", workers)
+
+ if _, ok := s.lastEvacuation["w1"]; ok {
+ t.Error("expected no emergency hibernate below critical thresholds")
+ }
+}
+
+// ============================================================
+// Test: Migration target selection
+// ============================================================
+
+func TestFindMigrationTargetSelectsLeastLoaded(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "hot", MachineID: "osb-worker-hot", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "medium", MachineID: "osb-worker-medium", Region: "us-east-1",
+ Capacity: 50, Current: 25, CPUPct: 40, MemPct: 40, DiskPct: 30,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "cold", MachineID: "osb-worker-cold", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 10, MemPct: 10, DiskPct: 10,
+ })
+
+ s := newTestScaler(reg, pool)
+ target := s.findMigrationTarget("us-east-1", "hot")
+
+ if target == nil {
+ t.Fatal("expected a migration target")
+ }
+ if target.ID != "cold" {
+ t.Errorf("expected cold worker as target, got %s", target.ID)
+ }
+}
+
+func TestFindMigrationTargetSkipsPressuredWorkers(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "hot", MachineID: "osb-worker-hot", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 90, MemPct: 50, DiskPct: 30,
+ })
+ // Only other worker is also under pressure
+ reg.addWorker(&WorkerInfo{
+ ID: "alsohot", MachineID: "osb-worker-alsohot", Region: "us-east-1",
+ Capacity: 50, Current: 40, CPUPct: 88, MemPct: 88, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+ target := s.findMigrationTarget("us-east-1", "hot")
+
+ if target != nil {
+ t.Errorf("expected no target (all workers under pressure), got %s", target.ID)
+ }
+}
+
+func TestFindMigrationTargetSkipsDraining(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "hot", MachineID: "osb-worker-hot", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "draining", MachineID: "osb-worker-draining", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 10, MemPct: 10, DiskPct: 10,
+ })
+
+ s := newTestScaler(reg, pool)
+ s.draining["osb-worker-draining"] = &drainState{workerID: "draining"}
+
+ target := s.findMigrationTarget("us-east-1", "hot")
+ if target != nil {
+ t.Errorf("expected no target (only candidate is draining), got %s", target.ID)
+ }
+}
+
+func TestFindMigrationTargetAccountsForInFlight(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "source", MachineID: "osb-worker-source", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ // Almost full when accounting for in-flight
+ reg.addWorker(&WorkerInfo{
+ ID: "target1", MachineID: "osb-worker-target1", Region: "us-east-1",
+ Capacity: 10, Current: 5, CPUPct: 40, MemPct: 40, DiskPct: 30,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "target2", MachineID: "osb-worker-target2", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+
+ // Simulate 5 in-flight migrations to target1 → effective remaining = 0
+ s.inFlightMu.Lock()
+ s.inFlightTo["target1"] = 5
+ s.inFlightMu.Unlock()
+
+ target := s.findMigrationTarget("us-east-1", "source")
+ if target == nil {
+ t.Fatal("expected a migration target")
+ }
+ if target.ID != "target2" {
+ t.Errorf("expected target2 (target1 full with in-flight), got %s", target.ID)
+ }
+}
+
+func TestFindMigrationTargetSkipsHighDisk(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "source", MachineID: "osb-worker-source", Region: "us-east-1",
+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,
+ })
+ // Good capacity but high disk
+ reg.addWorker(&WorkerInfo{
+ ID: "diskfull", MachineID: "osb-worker-diskfull", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 88,
+ })
+
+ s := newTestScaler(reg, pool)
+ target := s.findMigrationTarget("us-east-1", "source")
+
+ if target != nil {
+ t.Errorf("expected no target (only candidate has disk > 85%%), got %s", target.ID)
+ }
+}
+
+// ============================================================
+// Test: Drain timeout → hibernate
+// ============================================================
+
+func TestDrainTimeoutCancelsDrainKeepsWorker(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w2", MachineID: "osb-worker-w2", Region: "us-east-1",
+ Capacity: 50, Current: 5, CPUPct: 20, MemPct: 20, DiskPct: 20,
+ })
+
+ s := newTestScaler(reg, pool)
+
+ // Simulate a drain that started long ago (past timeout)
+ s.draining["osb-worker-w2"] = &drainState{
+ workerID: "w2",
+ machineID: "osb-worker-w2",
+ region: "us-east-1",
+ startedAt: time.Now().Add(-20 * time.Minute), // well past drainTimeout
+ }
+
+ ctx := context.Background()
+ s.checkDrainingWorkers(ctx, "us-east-1")
+
+ // Drain should be cancelled (removed from draining map) — worker stays alive
+ if _, ok := s.draining["osb-worker-w2"]; ok {
+ t.Error("expected timed-out drain to be cancelled")
+ }
+
+ // Machine should NOT be destroyed — sandboxes must be preserved
+ time.Sleep(50 * time.Millisecond)
+ if atomic.LoadInt32(&pool.destroyed) != 0 {
+ t.Error("machine should not be destroyed when drain times out with active sandboxes")
+ }
+}
+
+func TestDrainCompletesWhenEmpty(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Worker with 0 sandboxes
+ reg.addWorker(&WorkerInfo{
+ ID: "w2", MachineID: "osb-worker-w2", Region: "us-east-1",
+ Capacity: 50, Current: 0, CPUPct: 0, MemPct: 0, DiskPct: 0,
+ })
+
+ s := newTestScaler(reg, pool)
+ s.draining["osb-worker-w2"] = &drainState{
+ workerID: "w2",
+ machineID: "osb-worker-w2",
+ region: "us-east-1",
+ startedAt: time.Now(),
+ }
+
+ ctx := context.Background()
+ s.checkDrainingWorkers(ctx, "us-east-1")
+
+ if _, ok := s.draining["osb-worker-w2"]; ok {
+ t.Error("expected drain to complete (worker has 0 sandboxes)")
+ }
+
+ time.Sleep(50 * time.Millisecond)
+ if atomic.LoadInt32(&pool.destroyed) == 0 {
+ t.Error("expected machine to be destroyed after drain completes")
+ }
+}
+
+// ============================================================
+// Test: Golden version in migration target selection
+// ============================================================
+
+func TestGoldenVersionTrackedInWorkerInfo(t *testing.T) {
+ reg := newMockRegistry()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", Region: "us-east-1", GoldenVersion: "abc123",
+ Capacity: 50, Current: 10,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "w2", Region: "us-east-1", GoldenVersion: "abc123",
+ Capacity: 50, Current: 10,
+ })
+ reg.addWorker(&WorkerInfo{
+ ID: "w3", Region: "us-east-1", GoldenVersion: "def456",
+ Capacity: 50, Current: 10,
+ })
+
+ workers := reg.GetWorkersByRegion("us-east-1")
+ sameVersion := 0
+ for _, w := range workers {
+ if w.GoldenVersion == "abc123" {
+ sameVersion++
+ }
+ }
+ if sameVersion != 2 {
+ t.Errorf("expected 2 workers with same golden version, got %d", sameVersion)
+ }
+}
+
+// ============================================================
+// Test: 200 concurrent scale-up/down stress test
+// ============================================================
+
+func TestConcurrentScaleUpDown200(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping stress test in short mode")
+ }
+
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Start with 5 workers
+ for i := 0; i < 5; i++ {
+ reg.addWorker(&WorkerInfo{
+ ID: fmt.Sprintf("w%d", i),
+ MachineID: fmt.Sprintf("osb-worker-w%d", i),
+ Region: "us-east-1",
+ Capacity: 50,
+ Current: 25,
+ CPUPct: 50,
+ MemPct: 50,
+ DiskPct: 30,
+ })
+ }
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: 50 * time.Millisecond,
+ Interval: 10 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ })
+
+ // Run 200 concurrent goroutines that randomly change worker loads
+ // and trigger evaluations
+ var wg sync.WaitGroup
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ // Track panics
+ var panicked int32
+
+ for i := 0; i < 200; i++ {
+ wg.Add(1)
+ go func(id int) {
+ defer wg.Done()
+ defer func() {
+ if r := recover(); r != nil {
+ atomic.AddInt32(&panicked, 1)
+ t.Errorf("goroutine %d panicked: %v", id, r)
+ }
+ }()
+
+ rng := rand.New(rand.NewSource(int64(id)))
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ action := rng.Intn(10)
+ switch {
+ case action < 3:
+ // Simulate load increase on random worker
+ workers := reg.GetWorkersByRegion("us-east-1")
+ if len(workers) > 0 {
+ w := workers[rng.Intn(len(workers))]
+ reg.updateWorker(w.ID, func(w *WorkerInfo) {
+ w.Current = rng.Intn(w.Capacity + 1)
+ w.CPUPct = float64(rng.Intn(100))
+ w.MemPct = float64(rng.Intn(100))
+ w.DiskPct = float64(rng.Intn(100))
+ })
+ }
+
+ case action < 5:
+ // Evaluate (triggers scale decisions)
+ s.evaluateRegion(ctx, "us-east-1")
+
+ case action < 7:
+ // Add a new worker
+ newID := fmt.Sprintf("dyn-%d-%d", id, rng.Intn(1000))
+ reg.addWorker(&WorkerInfo{
+ ID: newID,
+ MachineID: "osb-worker-" + newID,
+ Region: "us-east-1",
+ Capacity: 50,
+ Current: rng.Intn(50),
+ CPUPct: float64(rng.Intn(80)),
+ MemPct: float64(rng.Intn(80)),
+ DiskPct: float64(rng.Intn(60)),
+ })
+
+ case action < 9:
+ // Remove a random worker
+ workers := reg.GetWorkersByRegion("us-east-1")
+ if len(workers) > 1 {
+ w := workers[rng.Intn(len(workers))]
+ reg.removeWorker(w.ID)
+ }
+
+ default:
+ // Query state (read contention)
+ _ = reg.RegionUtilization("us-east-1")
+ _, _, _ = reg.RegionResourcePressure("us-east-1")
+ _ = s.findMigrationTarget("us-east-1", "nonexistent")
+ }
+
+ time.Sleep(time.Duration(rng.Intn(5)) * time.Millisecond)
+ }
+ }(i)
+ }
+
+ wg.Wait()
+
+ if atomic.LoadInt32(&panicked) > 0 {
+ t.Fatalf("%d goroutines panicked during concurrent stress test", atomic.LoadInt32(&panicked))
+ }
+
+ t.Logf("stress test complete: created=%d, destroyed=%d, workers=%d",
+ atomic.LoadInt32(&pool.created),
+ atomic.LoadInt32(&pool.destroyed),
+ len(reg.GetWorkersByRegion("us-east-1")))
+}
+
+// ============================================================
+// Test: 200 sandbox disk pressure growth stress test
+// ============================================================
+
+func TestDiskPressureGrowth200Sandboxes(t *testing.T) {
+ if testing.Short() {
+ t.Skip("skipping stress test in short mode")
+ }
+
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // 5 workers, each with 40 sandboxes (200 total)
+ numWorkers := 5
+ sandboxesPerWorker := 40
+
+ for i := 0; i < numWorkers; i++ {
+ reg.addWorker(&WorkerInfo{
+ ID: fmt.Sprintf("w%d", i),
+ MachineID: fmt.Sprintf("osb-worker-w%d", i),
+ Region: "us-east-1",
+ Capacity: 50,
+ Current: sandboxesPerWorker,
+ CPUPct: 40,
+ MemPct: 40,
+ DiskPct: 30, // start at 30%
+ })
+ }
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: 50 * time.Millisecond,
+ Interval: 10 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ })
+
+ var panicked int32
+ var wg sync.WaitGroup
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ // Track events
+ var scaleUps, evacuations, emergencies int32
+
+ // Goroutine: randomly grow disk on workers (simulating sandbox disk growth)
+ for i := 0; i < 200; i++ {
+ wg.Add(1)
+ go func(sandboxNum int) {
+ defer wg.Done()
+ defer func() {
+ if r := recover(); r != nil {
+ atomic.AddInt32(&panicked, 1)
+ t.Errorf("sandbox %d panicked: %v", sandboxNum, r)
+ }
+ }()
+
+ rng := rand.New(rand.NewSource(int64(sandboxNum)))
+ workerIdx := sandboxNum % numWorkers
+ workerID := fmt.Sprintf("w%d", workerIdx)
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ }
+
+ // Randomly grow disk usage on the worker
+ growth := rng.Float64() * 2.0 // 0-2% per tick
+ reg.updateWorker(workerID, func(w *WorkerInfo) {
+ w.DiskPct += growth
+ if w.DiskPct > 99 {
+ w.DiskPct = 99
+ }
+ // Also slightly grow CPU/mem from the workload
+ w.CPUPct += rng.Float64() * 0.5
+ if w.CPUPct > 99 {
+ w.CPUPct = 99
+ }
+ w.MemPct += rng.Float64() * 0.3
+ if w.MemPct > 99 {
+ w.MemPct = 99
+ }
+ })
+
+ time.Sleep(time.Duration(10+rng.Intn(20)) * time.Millisecond)
+ }
+ }(i)
+ }
+
+ // Goroutine: scaler evaluation loop
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ // Snapshot state before evaluation
+ _, _, maxDiskBefore := reg.RegionResourcePressure("us-east-1")
+
+ s.evaluateRegion(ctx, "us-east-1")
+
+ // Track what happened
+ if atomic.LoadInt32(&pool.created) > 0 {
+ atomic.AddInt32(&scaleUps, 1)
+ }
+
+ // Check for evacuation and emergency triggers
+ workers := reg.GetWorkersByRegion("us-east-1")
+ for _, w := range workers {
+ if w.DiskPct > emergencyDiskThreshold {
+ atomic.AddInt32(&emergencies, 1)
+ } else if w.DiskPct > evacuationDiskThreshold {
+ atomic.AddInt32(&evacuations, 1)
+ }
+ }
+
+ // Simulate evacuation relief: if a worker had sandboxes migrated,
+ // its sandbox count and disk would decrease
+ for _, w := range workers {
+ if _, ok := s.lastEvacuation[w.ID]; ok {
+ reg.updateWorker(w.ID, func(w *WorkerInfo) {
+ if w.Current > 3 {
+ w.Current -= 3
+ }
+ w.DiskPct -= 5
+ if w.DiskPct < 20 {
+ w.DiskPct = 20
+ }
+ })
+ }
+ }
+
+ // If new workers were added, spread some load to them
+ if len(workers) > numWorkers {
+ for _, w := range workers {
+ if w.Current == 0 && w.DiskPct < 30 {
+ reg.updateWorker(w.ID, func(w *WorkerInfo) {
+ w.Current = 10
+ w.CPUPct = 30
+ w.MemPct = 30
+ w.DiskPct = 20
+ })
+ }
+ }
+ }
+
+ _ = maxDiskBefore
+ }
+ }
+ }()
+
+ wg.Wait()
+
+ if atomic.LoadInt32(&panicked) > 0 {
+ t.Fatalf("%d goroutines panicked during disk pressure stress test", atomic.LoadInt32(&panicked))
+ }
+
+ // Verify the system responded to pressure
+ finalWorkers := reg.GetWorkersByRegion("us-east-1")
+ _, _, maxDisk := reg.RegionResourcePressure("us-east-1")
+
+ t.Logf("disk stress test complete:")
+ t.Logf(" workers: %d (started with %d)", len(finalWorkers), numWorkers)
+ t.Logf(" machines created: %d", atomic.LoadInt32(&pool.created))
+ t.Logf(" max disk at end: %.1f%%", maxDisk)
+ t.Logf(" evacuation triggers: %d", atomic.LoadInt32(&evacuations))
+ t.Logf(" emergency triggers: %d", atomic.LoadInt32(&emergencies))
+
+ // The scaler should have responded — either scaled up or triggered evacuations
+ created := atomic.LoadInt32(&pool.created)
+ evacs := atomic.LoadInt32(&evacuations)
+ emers := atomic.LoadInt32(&emergencies)
+
+ if created == 0 && evacs == 0 && emers == 0 {
+ t.Error("scaler did not respond to disk pressure growth at all")
+ }
+}
+
+// ============================================================
+// Test: Pending launch tracking
+// ============================================================
+
+func TestPendingLaunchExpires(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "w1", MachineID: "osb-worker-w1", Region: "us-east-1",
+ Capacity: 50, Current: 10, CPUPct: 30, MemPct: 30, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+
+ // Simulate a pending launch from 15 minutes ago
+ s.pending["us-east-1"] = []pendingLaunch{
+ {machineID: "osb-worker-stale", launchedAt: time.Now().Add(-15 * time.Minute)},
+ }
+
+ s.expirePending("us-east-1")
+
+ if len(s.pending["us-east-1"]) != 0 {
+ t.Error("expected stale pending launch to be expired")
+ }
+}
+
+func TestPendingLaunchRegistered(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ // Worker that matches the pending machine ID
+ reg.addWorker(&WorkerInfo{
+ ID: "w-new", MachineID: "osb-worker-new", Region: "us-east-1",
+ Capacity: 50, Current: 0, CPUPct: 0, MemPct: 0, DiskPct: 0,
+ })
+
+ s := newTestScaler(reg, pool)
+ s.pending["us-east-1"] = []pendingLaunch{
+ {machineID: "osb-worker-new", launchedAt: time.Now()},
+ }
+
+ s.expirePending("us-east-1")
+
+ if len(s.pending["us-east-1"]) != 0 {
+ t.Error("expected registered pending launch to be cleared")
+ }
+}
+
+// ============================================================
+// Test: In-flight migration tracking
+// ============================================================
+
+func TestInFlightTrackingPreventsOverload(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ reg.addWorker(&WorkerInfo{
+ ID: "target", MachineID: "osb-worker-target", Region: "us-east-1",
+ Capacity: 5, Current: 2, CPUPct: 30, MemPct: 30, DiskPct: 30,
+ })
+
+ s := newTestScaler(reg, pool)
+
+ // 3 remaining capacity, but 3 in-flight → effective 0
+ s.inFlightMu.Lock()
+ s.inFlightTo["target"] = 3
+ s.inFlightMu.Unlock()
+
+ target := s.findMigrationTarget("us-east-1", "other")
+ if target != nil {
+ t.Error("expected no target — in-flight migrations fill remaining capacity")
+ }
+}
+
+func TestInFlightCleanup(t *testing.T) {
+ s := &Scaler{
+ inFlightTo: make(map[string]int),
+ }
+
+ // Simulate increment
+ s.inFlightMu.Lock()
+ s.inFlightTo["w1"]++
+ s.inFlightTo["w1"]++
+ s.inFlightMu.Unlock()
+
+ // Simulate one completion
+ s.inFlightMu.Lock()
+ s.inFlightTo["w1"]--
+ s.inFlightMu.Unlock()
+
+ s.inFlightMu.Lock()
+ if s.inFlightTo["w1"] != 1 {
+ t.Errorf("expected 1 in-flight after decrement, got %d", s.inFlightTo["w1"])
+ }
+ s.inFlightMu.Unlock()
+
+ // Simulate final completion
+ s.inFlightMu.Lock()
+ s.inFlightTo["w1"]--
+ if s.inFlightTo["w1"] <= 0 {
+ delete(s.inFlightTo, "w1")
+ }
+ s.inFlightMu.Unlock()
+
+ s.inFlightMu.Lock()
+ if _, exists := s.inFlightTo["w1"]; exists {
+ t.Error("expected w1 to be cleaned up from inFlightTo map")
+ }
+ s.inFlightMu.Unlock()
+}
diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.go
index ab216cfe..6bed9e81 100644
--- a/internal/controlplane/worker_registry.go
+++ b/internal/controlplane/worker_registry.go
@@ -24,6 +24,7 @@ type WorkerInfo struct {
MemPct float64 `json:"mem_pct"`
DiskPct float64 `json:"disk_pct"`
GoldenVersion string `json:"golden_version,omitempty"`
+ WorkerVersion string `json:"worker_version,omitempty"`
LastSeen time.Time `json:"-"`
MissedBeats int `json:"-"`
}
@@ -237,6 +238,9 @@ func (r *WorkerRegistry) handleHeartbeat(msg *nats.Msg) {
if hb.GoldenVersion != "" {
existing.GoldenVersion = hb.GoldenVersion
}
+ if hb.WorkerVersion != "" {
+ existing.WorkerVersion = hb.WorkerVersion
+ }
existing.LastSeen = time.Now()
existing.MissedBeats = 0
if hb.GRPCAddr != "" {
diff --git a/internal/db/migrations/019_migration_state.down.sql b/internal/db/migrations/019_migration_state.down.sql
new file mode 100644
index 00000000..bad0b1d1
--- /dev/null
+++ b/internal/db/migrations/019_migration_state.down.sql
@@ -0,0 +1 @@
+ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS migrating_to_worker;
diff --git a/internal/db/migrations/019_migration_state.up.sql b/internal/db/migrations/019_migration_state.up.sql
new file mode 100644
index 00000000..03dbbdeb
--- /dev/null
+++ b/internal/db/migrations/019_migration_state.up.sql
@@ -0,0 +1,2 @@
+-- Add migration state tracking to sandbox_sessions
+ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS migrating_to_worker TEXT NOT NULL DEFAULT '';
diff --git a/internal/db/store.go b/internal/db/store.go
index c86828ad..cd93f05e 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -453,6 +453,7 @@ type SandboxSession struct {
ErrorMsg *string `json:"errorMsg,omitempty"`
BasedOnCheckpointID *uuid.UUID `json:"basedOnCheckpointId,omitempty"`
LastPatchSequence int `json:"lastPatchSequence"`
+ MigratingToWorker string `json:"migratingToWorker,omitempty"`
}
func (s *Store) CreateSandboxSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, template, region, workerID string, config, metadata json.RawMessage) (*SandboxSession, error) {
@@ -492,6 +493,46 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
return nil
}
+// SetMigrating marks a sandbox as migrating to a target worker.
+// Only transitions from running → migrating.
+func (s *Store) SetMigrating(ctx context.Context, sandboxID, targetWorkerID string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'migrating', migrating_to_worker = $1
+ WHERE sandbox_id = $2 AND status = 'running'`,
+ targetWorkerID, sandboxID)
+ return err
+}
+
+// CompleteMigration marks a sandbox as running on the new worker after successful migration.
+func (s *Store) CompleteMigration(ctx context.Context, sandboxID, newWorkerID string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'running', worker_id = $1, migrating_to_worker = ''
+ WHERE sandbox_id = $2 AND status = 'migrating'`,
+ newWorkerID, sandboxID)
+ return err
+}
+
+// FailMigration reverts a sandbox to running on its original worker after a failed migration.
+func (s *Store) FailMigration(ctx context.Context, sandboxID string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'running', migrating_to_worker = ''
+ WHERE sandbox_id = $1 AND status = 'migrating'`,
+ sandboxID)
+ return err
+}
+
+// RecoverStaleMigrations resets any sandbox stuck in 'migrating' status for more than the given duration.
+func (s *Store) RecoverStaleMigrations(ctx context.Context, maxAge time.Duration) (int, error) {
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'running', migrating_to_worker = ''
+ WHERE status = 'migrating' AND started_at < now() - $1::interval`,
+ maxAge.String())
+ if err != nil {
+ return 0, err
+ }
+ return int(tag.RowsAffected()), nil
+}
+
func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
@@ -895,6 +936,23 @@ func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (h
return int(res1.RowsAffected()), int(res2.RowsAffected()), nil
}
+// ReconcileWorkerReconnect fixes sandbox sessions after a worker reconnects from
+// a network outage. Sandboxes that are actually running locally but marked as
+// "error" in the DB are reset to "running". Returns the number of sessions fixed.
+func (s *Store) ReconcileWorkerReconnect(ctx context.Context, workerID string, runningSandboxIDs []string) (fixed int, err error) {
+ if len(runningSandboxIDs) == 0 {
+ return 0, nil
+ }
+ res, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'running', error_msg = NULL
+ WHERE worker_id = $1 AND status = 'error'
+ AND sandbox_id = ANY($2)`, workerID, runningSandboxIDs)
+ if err != nil {
+ return 0, fmt.Errorf("reconcile worker reconnect: %w", err)
+ }
+ return int(res.RowsAffected()), nil
+}
+
// UpsertWorkspaceBackup creates or updates a workspace-only backup record for a sandbox.
// Uses hibernation_key prefix "workspace-backups/" to distinguish from full hibernation records.
// Only one workspace backup is kept per sandbox (previous is overwritten).
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
index d6f477ed..7797ff02 100644
--- a/internal/proxy/sandbox_api_proxy.go
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -155,6 +155,13 @@ func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {
})
}
+ // If migrating, reject requests until migration completes
+ if session.Status == "migrating" {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": fmt.Sprintf("sandbox %s is migrating, retry shortly", sandboxID),
+ })
+ }
+
// If hibernated, wake on demand
if session.Status == "hibernated" {
worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 706f566f..ea0a6d6a 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -9,7 +9,9 @@ import (
"fmt"
"io"
"log"
+ "net"
"os"
+ "strconv"
"os/exec"
"path/filepath"
"strings"
@@ -937,13 +939,21 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
if strings.HasSuffix(workspacePath, ".ext4") {
wsFmt = "raw"
}
+ // Memory layout: base memory + virtio-mem pool for hotplug scaling.
+ // The virtio-mem backend allocates lazily (only requested-size is committed),
+ // but maxmem must exceed base+pool for QEMU to accept the device.
+ // Pool size = 15GB covers scaling from 1GB base up to 16GB total.
+ // For migrations requesting >16GB, we use the full requested amount as base
+ // (no virtio-mem needed since the source already has the memory hotplugged).
+ virtioMemPoolMB := 15360 // 15GB — enough for 1GB->16GB scaling
+ maxMemMB := memMB + virtioMemPoolMB
+
return []string{
"-machine", "q35,accel=kvm",
"-cpu", "host",
- "-m", fmt.Sprintf("%dM,maxmem=16G", memMB),
+ "-m", fmt.Sprintf("%dM,slots=1,maxmem=%dM", memMB, maxMemMB),
// virtio-mem: pluggable memory pool. Scale via QMP qom-set requested-size.
- // 15GB max + base gives 16GB ceiling. Block size 128MB for granularity.
- "-object", "memory-backend-ram,id=vmem0,size=15360M",
+ "-object", fmt.Sprintf("memory-backend-ram,id=vmem0,size=%dM", virtioMemPoolMB),
"-device", "virtio-mem-pci,memdev=vmem0,id=vm0,block-size=128M,requested-size=0",
"-smp", fmt.Sprintf("%d", cpus),
"-kernel", m.cfg.KernelPath,
@@ -1653,12 +1663,28 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi
}
// Round up to 128MB block size
additionalMB = ((additionalMB + 127) / 128) * 128
+
+ // Check committed memory across all VMs before attempting hotplug.
+ // Reserve 20% of host RAM for OS, QEMU overhead, page cache, etc.
+ if additionalMB > vm.virtioMemRequestedMB {
+ deltaMB := additionalMB - vm.virtioMemRequestedMB
+ committedMB := m.totalCommittedMemoryMB()
+ hostTotalMB := m.hostMemoryMB()
+ reserveMB := hostTotalMB / 5 // 20% safety margin
+ availableMB := hostTotalMB - committedMB - reserveMB
+
+ if deltaMB > availableMB {
+ log.Printf("qemu: virtio-mem %s: need %dMB but only %dMB available (committed=%dMB, host=%dMB, reserve=%dMB)",
+ sandboxID, deltaMB, availableMB, committedMB, hostTotalMB, reserveMB)
+ return fmt.Errorf("insufficient_capacity: need %dMB additional but only %dMB available on this worker (committed=%dMB/%dMB)",
+ deltaMB, availableMB, committedMB, hostTotalMB)
+ }
+ }
+
if additionalMB != vm.virtioMemRequestedMB {
if err := vm.qmp.SetVirtioMemSize(additionalMB); err != nil {
- 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
+ log.Printf("qemu: virtio-mem %s: set %dMB failed: %v — returning insufficient capacity error", sandboxID, additionalMB, err)
+ return fmt.Errorf("insufficient_capacity: cannot hotplug %dMB on this worker: %w", additionalMB, err)
} else {
vm.virtioMemRequestedMB = additionalMB
vm.MemoryMB = vm.baseMemoryMB + additionalMB
@@ -1670,6 +1696,56 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi
return vm.agent.SetResourceLimits(ctx, maxPids, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)
}
+// totalCommittedMemoryMB returns the sum of MemoryMB (base + virtio-mem) across all running VMs.
+// This represents the maximum host memory that could be consumed if all VMs use their full allocation.
+func (m *Manager) totalCommittedMemoryMB() int {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ total := 0
+ for _, vm := range m.vms {
+ total += vm.MemoryMB
+ }
+ return total
+}
+
+// hostMemoryMB returns the host's total physical memory in MB.
+// getWorkerIP returns the worker's VNet-routable IP address for inter-worker communication.
+// Uses OPENSANDBOX_GRPC_ADVERTISE (host:port) if set, otherwise detects from the default route.
+func (m *Manager) getWorkerIP() string {
+ if addr := os.Getenv("OPENSANDBOX_GRPC_ADVERTISE"); addr != "" {
+ // Format: "10.100.1.5:9090" — extract just the IP
+ if host, _, err := net.SplitHostPort(addr); err == nil {
+ return host
+ }
+ return addr
+ }
+ // Fallback: detect from default route interface
+ if conn, err := net.Dial("udp", "8.8.8.8:80"); err == nil {
+ defer conn.Close()
+ if addr, ok := conn.LocalAddr().(*net.UDPAddr); ok {
+ return addr.IP.String()
+ }
+ }
+ return "127.0.0.1"
+}
+
+func (m *Manager) hostMemoryMB() int {
+ data, err := os.ReadFile("/proc/meminfo")
+ if err != nil {
+ return 64 * 1024 // fallback: assume 64GB
+ }
+ for _, line := range strings.Split(string(data), "\n") {
+ if strings.HasPrefix(line, "MemTotal:") {
+ fields := strings.Fields(line)
+ if len(fields) >= 2 {
+ kb, _ := strconv.Atoi(fields[1])
+ return kb / 1024
+ }
+ }
+ }
+ return 64 * 1024
+}
+
// Stats returns live resource usage from the VM.
func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {
vm, err := m.getReadyVM(ctx, sandboxID)
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index 04a5b29b..8e8233a5 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -265,12 +265,18 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco
// Start live migration
state.Phase = "migrating"
+ log.Printf("qemu: live migration %s: sending migrate tcp:%s", sandboxID, incomingAddr)
if err := vm.qmp.Migrate("tcp:" + incomingAddr); err != nil {
return fmt.Errorf("QMP migrate: %w", err)
}
// Wait for migration to complete
if err := vm.qmp.WaitMigration(5 * time.Minute); err != nil {
+ // Query detailed status for debugging
+ status, qErr := vm.qmp.QueryMigrate()
+ if qErr == nil {
+ log.Printf("qemu: live migration %s FAILED: status=%s error=%s", sandboxID, status.Status, status.ErrorDesc)
+ }
return fmt.Errorf("migration wait: %w", err)
}
@@ -322,6 +328,29 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf
return "", 0, fmt.Errorf("mkdir: %w", err)
}
+ // Resolve rootfs from template if not provided
+ if rootfsPath == "" {
+ if template == "" {
+ template = "default"
+ }
+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, template)
+ if err != nil {
+ return "", 0, fmt.Errorf("resolve base image for template %q: %w", template, err)
+ }
+ rootfsPath = filepath.Join(sandboxDir, "rootfs.qcow2")
+ if err := PrepareRootfs(baseImage, rootfsPath); err != nil {
+ return "", 0, fmt.Errorf("prepare rootfs: %w", err)
+ }
+ log.Printf("qemu: migration %s: prepared rootfs from template %q: %s", sandboxID, template, rootfsPath)
+ }
+ // Create workspace if not provided
+ if workspacePath == "" {
+ workspacePath = filepath.Join(sandboxDir, "workspace.ext4")
+ if err := CreateWorkspace(workspacePath, 4096); err != nil {
+ return "", 0, fmt.Errorf("create workspace: %w", err)
+ }
+ }
+
netCfg, err := m.subnets.Allocate()
if err != nil {
return "", 0, fmt.Errorf("allocate subnet: %w", err)
@@ -387,19 +416,38 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf
netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)
args = append(args, "-incoming", fmt.Sprintf("tcp:0:%d", migrationPort))
+ // Migration targets must have the exact same device configuration as the source.
+ // Keep -serial stdio but redirect stdout to /dev/null to avoid blocking.
+
+ log.Printf("qemu: migration-prepare %s: starting QEMU (mem=%dMB, cpu=%d, rootfs=%s, workspace=%s, qmp=%s)",
+ sandboxID, memMB, cpus, rootfsPath, workspacePath, qmpSockPath)
+
cmd := exec.Command(m.cfg.QEMUBin, args...)
- cmd.Stdout = logFile
+ // For migration targets: send stderr to log, but stdout to /dev/null.
+ // -serial stdio outputs kernel console to stdout which can block if piped to a file.
+ devNull, _ := os.Open(os.DevNull)
+ cmd.Stdout = devNull
cmd.Stderr = logFile
if err := cmd.Start(); err != nil {
logFile.Close()
+ if devNull != nil { devNull.Close() }
m.cleanupVM(netCfg, sandboxDir)
return "", 0, fmt.Errorf("start qemu: %w", err)
}
logFile.Close()
+ if devNull != nil { devNull.Close() }
+ log.Printf("qemu: migration-prepare %s: QEMU started (pid=%d), waiting for QMP", sandboxID, cmd.Process.Pid)
- // Connect QMP
- qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)
+ // Connect QMP — allow up to 60s for large-memory VMs (virtio-mem init takes time)
+ qmpClient, err := waitForQMP(qmpSockPath, 60*time.Second)
if err != nil {
+ // Check if QEMU exited
+ var exitErr string
+ if cmd.ProcessState != nil {
+ exitErr = cmd.ProcessState.String()
+ }
+ qemuLog, _ := os.ReadFile(filepath.Join(sandboxDir, "qemu.log"))
+ log.Printf("qemu: migration-prepare %s: QMP failed — exit=%s, log tail: %s", sandboxID, exitErr, string(qemuLog[max(0, len(qemuLog)-500):]))
cmd.Process.Kill()
cmd.Wait()
m.cleanupVM(netCfg, sandboxDir)
@@ -435,9 +483,12 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf
m.vms[sandboxID] = vm
m.mu.Unlock()
- // Return the private IP + port for the source to connect
- // The source will call: migrate tcp:PRIVATE_IP:PORT
- return fmt.Sprintf("%s:%d", netCfg.HostIP, migrationPort), hp, nil
+ // Return the worker's VNet IP + migration port for the source to connect.
+ // We use the advertise address (from OPENSANDBOX_GRPC_ADVERTISE) which is the
+ // worker's private IP on the VNet — reachable from other workers.
+ // netCfg.HostIP is the TAP host IP (172.16.x.x) which is NOT routable between workers.
+ workerIP := m.getWorkerIP()
+ return fmt.Sprintf("%s:%d", workerIP, migrationPort), hp, nil
}
// CompleteIncomingMigration is called after QMP migration finishes on the target.
@@ -448,6 +499,15 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin
return err
}
+ // Resume the VM — after live migration the target is paused
+ if vm.qmp != nil {
+ if err := vm.qmp.Cont(); err != nil {
+ log.Printf("qemu: migration %s: QMP continue failed: %v", sandboxID, err)
+ } else {
+ log.Printf("qemu: migration %s: VM resumed", sandboxID)
+ }
+ }
+
// Wait for agent via virtio-serial
agentClient, err := m.waitForAgentSocket(ctx, vm.agentSockPath, 10*time.Second)
if err != nil {
diff --git a/internal/qemu/qmp.go b/internal/qemu/qmp.go
index ab9760cf..d800f10a 100644
--- a/internal/qemu/qmp.go
+++ b/internal/qemu/qmp.go
@@ -47,7 +47,8 @@ type QMPStatus struct {
// QMPMigrateStatus represents the response from query-migrate.
type QMPMigrateStatus struct {
- Status string `json:"status"`
+ Status string `json:"status"`
+ ErrorDesc string `json:"error-desc,omitempty"`
}
// ConnectQMP connects to the QMP socket and completes the handshake:
diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.go
index c2f1bfed..0a560a37 100644
--- a/internal/worker/redis_heartbeat.go
+++ b/internal/worker/redis_heartbeat.go
@@ -23,6 +23,7 @@ type redisHeartbeatPayload struct {
MemPct float64 `json:"mem_pct"`
DiskPct float64 `json:"disk_pct"`
GoldenVersion string `json:"golden_version,omitempty"`
+ WorkerVersion string `json:"worker_version,omitempty"`
}
// RedisHeartbeat publishes periodic heartbeats to Redis for worker discovery.
@@ -37,7 +38,10 @@ type RedisHeartbeat struct {
grpcAddr string
httpAddr string
getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)
+ onReconnect func() // called when heartbeat succeeds after a previous failure
goldenVersion string
+ workerVersion string
+ wasDown bool // true if the last publish failed (used to detect reconnect)
stop chan struct{}
}
@@ -77,6 +81,17 @@ func (h *RedisHeartbeat) SetGoldenVersion(v string) {
h.goldenVersion = v
}
+// SetWorkerVersion sets the worker binary version (git SHA) for the heartbeat.
+func (h *RedisHeartbeat) SetWorkerVersion(v string) {
+ h.workerVersion = v
+}
+
+// OnReconnect sets a callback that fires when heartbeat succeeds after a failure.
+// Used to reconcile sandbox state after a network outage.
+func (h *RedisHeartbeat) OnReconnect(fn func()) {
+ h.onReconnect = fn
+}
+
// Start begins publishing heartbeats every 10 seconds.
func (h *RedisHeartbeat) Start(getStats func() (int, int, float64, float64, float64)) {
h.getStats = getStats
@@ -114,6 +129,7 @@ func (h *RedisHeartbeat) publish() {
MemPct: memPct,
DiskPct: diskPct,
GoldenVersion: h.goldenVersion,
+ WorkerVersion: h.workerVersion,
}
data, err := json.Marshal(payload)
@@ -127,8 +143,17 @@ func (h *RedisHeartbeat) publish() {
// SET with 30s TTL — key auto-expires if worker dies
key := "worker:" + h.workerID
- if err := h.rdb.Set(ctx, key, data, 30*time.Second).Err(); err != nil {
- log.Printf("redis_heartbeat: SET failed: %v", err)
+ setErr := h.rdb.Set(ctx, key, data, 30*time.Second).Err()
+ if setErr != nil {
+ log.Printf("redis_heartbeat: SET failed: %v", setErr)
+ h.wasDown = true
+ } else if h.wasDown {
+ // Heartbeat succeeded after previous failure — we reconnected
+ h.wasDown = false
+ log.Printf("redis_heartbeat: reconnected after outage, triggering reconciliation")
+ if h.onReconnect != nil {
+ go h.onReconnect()
+ }
}
// PUBLISH for real-time notification
diff --git a/scripts/qemu-tests/28-autoscaling-pressure.sh b/scripts/qemu-tests/28-autoscaling-pressure.sh
new file mode 100755
index 00000000..411348a8
--- /dev/null
+++ b/scripts/qemu-tests/28-autoscaling-pressure.sh
@@ -0,0 +1,392 @@
+#!/usr/bin/env bash
+# 28-autoscaling-pressure.sh — Autoscaling, disk pressure, and multi-worker stress tests
+#
+# Tests against real deployed infrastructure (westus2 / opensandbox prod).
+# Creates real sandboxes, grows real disk, verifies scaler responds.
+#
+# Required env:
+# OPENSANDBOX_API_URL — e.g. https://app.opencomputer.dev
+# OPENSANDBOX_API_KEY — API key for sandbox creation
+#
+# Optional env:
+# SANDBOX_COUNT — number of sandboxes to create (default: 120)
+# BATCH_SIZE — sandboxes per batch (default: 1)
+# BATCH_DELAY — seconds between batches (default: 5)
+# DISK_GROWTH_MB — MB to write per sandbox in disk test (default: 500)
+# SKIP_DISK_TEST — set to "true" to skip disk pressure test
+# SKIP_SCALE_TEST — set to "true" to skip sandbox scale test
+#
+source "$(dirname "$0")/common.sh"
+
+SANDBOX_COUNT="${SANDBOX_COUNT:-120}"
+DISK_GROWTH_MB="${DISK_GROWTH_MB:-500}"
+declare -a SANDBOXES=()
+
+cleanup() {
+ h "Cleanup: destroying ${#SANDBOXES[@]} sandboxes"
+ local pids=()
+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ destroy_sandbox "$sb" &
+ pids+=($!)
+ if [ ${#pids[@]} -ge 20 ]; then
+ for pid in "${pids[@]}"; do wait "$pid" 2>/dev/null || true; done
+ pids=()
+ fi
+ done
+ for pid in "${pids[@]+"${pids[@]}"}"; do wait "$pid" 2>/dev/null || true; done
+ echo "Cleanup complete"
+}
+trap cleanup EXIT
+
+get_workers() {
+ api "$API_URL/api/workers" 2>/dev/null || echo "[]"
+}
+
+worker_count() {
+ get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "0"
+}
+
+worker_summary() {
+ get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+for w in workers:
+ print(f' {w.get(\"worker_id\",\"?\"):30s} cpu={w.get(\"cpu_pct\",0):5.1f}% mem={w.get(\"mem_pct\",0):5.1f}% disk={w.get(\"disk_pct\",0):5.1f}% sandboxes={w.get(\"current\",0)}/{w.get(\"capacity\",0)} ver={w.get(\"worker_version\",\"?\")}')
+" 2>/dev/null || echo " (no worker data available)"
+}
+
+total_sandboxes() {
+ get_workers | python3 -c "
+import sys, json
+print(sum(w.get('current', 0) for w in json.load(sys.stdin)))
+" 2>/dev/null || echo "0"
+}
+
+# Create a sandbox with optional retry on transient failures
+create_sandbox_retry() {
+ local timeout="${1:-0}"
+ local max_retries=2
+ for attempt in $(seq 1 "$max_retries"); do
+ RESULT=$(api -X POST "$API_URL/api/sandboxes" -d "{\"timeout\":$timeout}" 2>/dev/null || echo '{}')
+ SB_ID=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null || echo "FAIL")
+ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then
+ echo "$SB_ID"
+ return 0
+ fi
+ [ "$attempt" -lt "$max_retries" ] && sleep 5
+ done
+ echo "FAIL"
+ return 1
+}
+
+# ============================================================
+# Phase 1: Baseline worker state
+# ============================================================
+h "Phase 1: Baseline"
+
+INITIAL_WORKERS=$(worker_count)
+echo "Initial workers: $INITIAL_WORKERS"
+worker_summary
+
+[ "$INITIAL_WORKERS" -ge 1 ] && pass "At least 1 worker online" || fail "No workers online"
+
+# ============================================================
+# Phase 2: Scale-up test — create sandboxes, test each immediately
+# ============================================================
+if [ "${SKIP_SCALE_TEST:-}" != "true" ]; then
+
+h "Phase 2: Scale-up ($SANDBOX_COUNT sandboxes)"
+
+BATCH_SIZE="${BATCH_SIZE:-1}"
+BATCH_DELAY="${BATCH_DELAY:-5}"
+CREATED=0
+FAILED=0
+RESPONSIVE=0
+UNRESPONSIVE=0
+
+for batch_start in $(seq 1 $BATCH_SIZE $SANDBOX_COUNT); do
+ batch_end=$((batch_start + BATCH_SIZE - 1))
+ [ "$batch_end" -gt "$SANDBOX_COUNT" ] && batch_end=$SANDBOX_COUNT
+
+ for i in $(seq "$batch_start" "$batch_end"); do
+ SB_ID=$(create_sandbox_retry 0)
+ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then
+ SANDBOXES+=("$SB_ID")
+ CREATED=$((CREATED+1))
+
+ # Test responsiveness immediately
+ OUT=$(exec_stdout "$SB_ID" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" = "alive" ]; then
+ RESPONSIVE=$((RESPONSIVE+1))
+ else
+ UNRESPONSIVE=$((UNRESPONSIVE+1))
+ fi
+ else
+ FAILED=$((FAILED+1))
+ fi
+ done
+
+ # Progress every 10
+ TOTAL_TRIED=$((CREATED + FAILED))
+ if [ "$TOTAL_TRIED" -ge 10 ] && [ $((TOTAL_TRIED % 10)) -eq 0 ]; then
+ echo " progress: created=$CREATED failed=$FAILED responsive=$RESPONSIVE unresponsive=$UNRESPONSIVE"
+ fi
+
+ sleep "$BATCH_DELAY"
+done
+
+echo ""
+echo "Creation results: $CREATED succeeded, $FAILED failed"
+echo "Immediate responsiveness: $RESPONSIVE/$CREATED"
+[ "$CREATED" -ge $((SANDBOX_COUNT * 80 / 100)) ] && pass "Created >= 80% of $SANDBOX_COUNT sandboxes ($CREATED)" || fail "Only $CREATED/$SANDBOX_COUNT created"
+[ "$RESPONSIVE" -ge $((CREATED * 90 / 100)) ] && pass "Immediate responsiveness >= 90% ($RESPONSIVE/$CREATED)" || fail "Immediate responsiveness: $RESPONSIVE/$CREATED"
+
+# Check if autoscaler added workers
+POST_SCALE_WORKERS=$(worker_count)
+echo ""
+echo "Workers after ramp: $POST_SCALE_WORKERS (was $INITIAL_WORKERS)"
+worker_summary
+
+if [ "$POST_SCALE_WORKERS" -gt "$INITIAL_WORKERS" ]; then
+ pass "Autoscaler added workers ($INITIAL_WORKERS → $POST_SCALE_WORKERS)"
+elif [ "$POST_SCALE_WORKERS" -eq "$INITIAL_WORKERS" ] && [ "$CREATED" -le $((INITIAL_WORKERS * 16)) ]; then
+ skip "No scale-up needed (capacity sufficient)"
+else
+ skip "Autoscaler did not add workers"
+fi
+
+# ============================================================
+# Phase 3: Worker distribution
+# ============================================================
+h "Phase 3: Worker distribution"
+worker_summary
+
+WORKERS_JSON=$(get_workers)
+DISTRIBUTION=$(echo "$WORKERS_JSON" | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+counts = [w.get('current', 0) for w in workers if w.get('current', 0) > 0]
+if len(counts) < 2:
+ print('SKIP')
+else:
+ ratio = max(counts) / max(min(counts), 1)
+ print(f'{ratio:.1f}')
+" 2>/dev/null || echo "SKIP")
+
+if [ "$DISTRIBUTION" = "SKIP" ]; then
+ skip "Not enough active workers to check distribution"
+elif [ "$(echo "$DISTRIBUTION > 5.0" | bc 2>/dev/null)" = "1" ]; then
+ fail "Load distribution ratio: ${DISTRIBUTION}x (> 5x is uneven)"
+else
+ pass "Load distribution ratio: ${DISTRIBUTION}x"
+fi
+
+# ============================================================
+# Phase 4: Scale-down — destroy sandboxes and watch scaler respond
+# ============================================================
+h "Phase 4: Scale-down"
+
+DESTROY_COUNT=$((${#SANDBOXES[@]} * 80 / 100))
+echo "Destroying $DESTROY_COUNT sandboxes to trigger scale-down..."
+
+declare -a REMAINING_SANDBOXES=()
+declare -a PIDS=()
+DESTROYED=0
+for i in "${!SANDBOXES[@]}"; do
+ if [ "$DESTROYED" -lt "$DESTROY_COUNT" ]; then
+ destroy_sandbox "${SANDBOXES[$i]}" &
+ PIDS+=($!)
+ DESTROYED=$((DESTROYED+1))
+
+ if [ ${#PIDS[@]} -ge 20 ]; then
+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
+ PIDS=()
+ fi
+ else
+ REMAINING_SANDBOXES+=("${SANDBOXES[$i]}")
+ fi
+done
+for pid in "${PIDS[@]+"${PIDS[@]}"}"; do wait "$pid" 2>/dev/null || true; done
+SANDBOXES=("${REMAINING_SANDBOXES[@]+"${REMAINING_SANDBOXES[@]}"}")
+
+echo "Destroyed $DESTROYED, remaining: ${#SANDBOXES[@]}"
+echo "Waiting 120s for autoscaler to react..."
+sleep 120
+
+POST_DOWN_WORKERS=$(worker_count)
+echo "Workers after scale-down: $POST_DOWN_WORKERS (was $POST_SCALE_WORKERS)"
+worker_summary
+
+if [ "$POST_DOWN_WORKERS" -lt "$POST_SCALE_WORKERS" ]; then
+ pass "Autoscaler removed workers ($POST_SCALE_WORKERS → $POST_DOWN_WORKERS)"
+else
+ skip "Autoscaler did not remove workers yet (drain may still be in progress)"
+fi
+
+else
+ skip "Scale test skipped (SKIP_SCALE_TEST=true)"
+fi # end SKIP_SCALE_TEST
+
+
+# ============================================================
+# Phase 5: Disk pressure test
+# ============================================================
+if [ "${SKIP_DISK_TEST:-}" != "true" ]; then
+
+h "Phase 5: Disk pressure (${DISK_GROWTH_MB}MB per sandbox)"
+
+declare -a DISK_SANDBOXES=()
+DISK_SANDBOX_COUNT="${DISK_SANDBOX_COUNT:-50}"
+
+echo "Creating $DISK_SANDBOX_COUNT sandboxes for disk pressure test..."
+DISK_CREATED=0
+for i in $(seq 1 "$DISK_SANDBOX_COUNT"); do
+ SB_ID=$(create_sandbox_retry 0)
+ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then
+ DISK_SANDBOXES+=("$SB_ID")
+ SANDBOXES+=("$SB_ID")
+ DISK_CREATED=$((DISK_CREATED+1))
+ fi
+done
+echo "Created $DISK_CREATED sandboxes for disk test"
+
+echo ""
+echo "Worker state before disk growth:"
+worker_summary
+
+# Grow disk in all sandboxes concurrently
+h "Growing disk: ${DISK_GROWTH_MB}MB per sandbox"
+
+declare -a PIDS=()
+for sb in "${DISK_SANDBOXES[@]+"${DISK_SANDBOXES[@]}"}"; do
+ (
+ set +e
+ CHUNK_MB=50
+ CHUNKS=$((DISK_GROWTH_MB / CHUNK_MB))
+ for c in $(seq 1 "$CHUNKS"); do
+ exec_run "$sb" "dd" "if=/dev/urandom" "of=/workspace/fill-${c}.dat" "bs=1M" "count=$CHUNK_MB" >/dev/null 2>&1
+ done
+ ) &
+ PIDS+=($!)
+
+ if [ ${#PIDS[@]} -ge 10 ]; then
+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
+ PIDS=()
+ fi
+done
+for pid in "${PIDS[@]+"${PIDS[@]}"}"; do wait "$pid" 2>/dev/null || true; done
+echo "Disk growth commands sent to all sandboxes"
+
+# Monitor disk pressure over time
+h "Monitoring disk pressure response (3 minutes)"
+for tick in $(seq 1 18); do
+ sleep 10
+ echo ""
+ echo "--- Tick $tick (${tick}0s) ---"
+ worker_summary
+done
+
+echo ""
+echo "Workers after disk test:"
+worker_summary
+
+# Verify sandboxes survived the pressure
+h "Verify sandboxes survived disk pressure"
+SURVIVED=0
+SAMPLE=10
+[ ${#DISK_SANDBOXES[@]} -lt "$SAMPLE" ] && SAMPLE=${#DISK_SANDBOXES[@]}
+
+if [ "$SAMPLE" -gt 0 ]; then
+ for i in $(seq 1 "$SAMPLE"); do
+ idx=$((RANDOM % ${#DISK_SANDBOXES[@]}))
+ sb="${DISK_SANDBOXES[$idx]}"
+ OUT=$(exec_stdout "$sb" "echo" "survived" 2>/dev/null)
+ [ "$OUT" = "survived" ] && SURVIVED=$((SURVIVED+1))
+ done
+ [ "$SURVIVED" -ge $((SAMPLE * 80 / 100)) ] && pass "Disk pressure survival: $SURVIVED/$SAMPLE responsive" || fail "Disk pressure survival: only $SURVIVED/$SAMPLE responsive"
+else
+ skip "No disk sandboxes to check"
+fi
+
+# Clean up disk fills
+declare -a PIDS=()
+for sb in "${DISK_SANDBOXES[@]+"${DISK_SANDBOXES[@]}"}"; do
+ exec_run "$sb" "rm" "-rf" "/workspace/fill-*.dat" >/dev/null 2>&1 &
+ PIDS+=($!)
+ if [ ${#PIDS[@]} -ge 20 ]; then
+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
+ PIDS=()
+ fi
+done
+for pid in "${PIDS[@]+"${PIDS[@]}"}"; do wait "$pid" 2>/dev/null || true; done
+pass "Disk fills cleaned"
+
+else
+ skip "Disk test skipped (SKIP_DISK_TEST=true)"
+fi # end SKIP_DISK_TEST
+
+
+# ============================================================
+# Phase 6: Resource pressure — CPU/memory stress
+# ============================================================
+h "Phase 6: Combined resource pressure"
+
+declare -a STRESS_SANDBOXES=()
+STRESS_COUNT=5
+for i in $(seq 1 "$STRESS_COUNT"); do
+ SB=$(create_sandbox_retry 300)
+ if [ -n "$SB" ] && [ "$SB" != "FAIL" ]; then
+ SANDBOXES+=("$SB")
+ STRESS_SANDBOXES+=("$SB")
+ fi
+done
+
+if [ ${#STRESS_SANDBOXES[@]} -ge 3 ]; then
+ for sb in "${STRESS_SANDBOXES[@]}"; do
+ api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":2048,"cpuPercent":200}' >/dev/null 2>&1
+ done
+ sleep 2
+
+ declare -a PIDS=()
+ for sb in "${STRESS_SANDBOXES[@]}"; do
+ ( set +e; exec_run "$sb" "sh" "-c" "for i in \$(seq 1 4); do while true; do :; done & done; sleep 30; kill %1 %2 %3 %4 2>/dev/null" >/dev/null 2>&1 ) &
+ PIDS+=($!)
+ ( set +e; exec_run "$sb" "python3" "-c" "x=bytearray(1500*1024*1024); import time; time.sleep(30)" >/dev/null 2>&1 ) &
+ PIDS+=($!)
+ ( set +e; exec_run "$sb" "dd" "if=/dev/urandom" "of=/workspace/stress.dat" "bs=1M" "count=200" >/dev/null 2>&1 ) &
+ PIDS+=($!)
+ done
+
+ echo "Combined stress running on ${#STRESS_SANDBOXES[@]} sandboxes..."
+ echo "Worker state during stress:"
+ sleep 15
+ worker_summary
+
+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done
+ pass "Combined resource pressure test completed"
+
+ # Verify sandboxes survived
+ ALIVE=0
+ for sb in "${STRESS_SANDBOXES[@]}"; do
+ OUT=$(exec_stdout "$sb" "echo" "ok" 2>/dev/null)
+ [ "$OUT" = "ok" ] && ALIVE=$((ALIVE+1))
+ done
+ [ "$ALIVE" -ge $((${#STRESS_SANDBOXES[@]} * 80 / 100)) ] && pass "Stress survival: $ALIVE/${#STRESS_SANDBOXES[@]} alive" || fail "Stress survival: $ALIVE/${#STRESS_SANDBOXES[@]} alive"
+else
+ skip "Combined stress test skipped (couldn't create enough sandboxes)"
+fi
+
+# ============================================================
+# Phase 7: Final state
+# ============================================================
+h "Phase 7: Final state"
+
+FINAL_WORKERS=$(worker_count)
+echo "Workers: $INITIAL_WORKERS (start) → $FINAL_WORKERS (end)"
+worker_summary
+
+TOTAL=$(total_sandboxes)
+echo "Total sandboxes across fleet: $TOTAL"
+echo "Test sandboxes to clean up: ${#SANDBOXES[@]}"
+
+summary
diff --git a/scripts/qemu-tests/29-chaos-scaling.sh b/scripts/qemu-tests/29-chaos-scaling.sh
new file mode 100755
index 00000000..f6c0f28f
--- /dev/null
+++ b/scripts/qemu-tests/29-chaos-scaling.sh
@@ -0,0 +1,275 @@
+#!/usr/bin/env bash
+# 29-chaos-scaling.sh — Chaos scaling stress test
+#
+# Ramps up sandboxes to a target count, then continuously scales random
+# sandboxes to different resource tiers, creates new ones, and destroys
+# others — all while the autoscaler is reacting.
+#
+# Required env:
+# OPENSANDBOX_API_URL — e.g. https://app.opencomputer.dev
+# OPENSANDBOX_API_KEY — API key for sandbox creation
+#
+# Optional env:
+# TARGET_COUNT — total sandboxes to ramp to (default: 200)
+# BATCH_SIZE — sandboxes to create per batch during ramp (default: 20)
+# CHAOS_ROUNDS — number of chaos rounds after ramp (default: 60)
+# CHAOS_INTERVAL — seconds between chaos rounds (default: 5)
+# SCALE_BATCH — sandboxes to scale per round (default: 10)
+# CHURN_COUNT — sandboxes to destroy+recreate per round (default: 5)
+
+source "$(dirname "$0")/common.sh"
+
+TARGET="${TARGET_COUNT:-200}"
+BATCH="${BATCH_SIZE:-20}"
+ROUNDS="${CHAOS_ROUNDS:-60}"
+INTERVAL="${CHAOS_INTERVAL:-5}"
+SCALE_BATCH="${SCALE_BATCH:-10}"
+CHURN="${CHURN_COUNT:-5}"
+
+# Valid memory tiers (from pkg/types/sandbox.go)
+TIERS=(4096 8192 16384 32768)
+# Corresponding CPU percents
+CPUS=(100 200 400 800)
+
+# Track all sandbox IDs
+declare -a SANDBOXES=()
+
+cleanup() {
+ echo ""
+ h "Cleanup: destroying ${#SANDBOXES[@]} sandboxes"
+ local pids=()
+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ destroy_sandbox "$sb" &
+ pids+=($!)
+ # Throttle: max 20 concurrent destroys
+ if [ ${#pids[@]} -ge 20 ]; then
+ wait "${pids[0]}" 2>/dev/null || true
+ pids=("${pids[@]:1}")
+ fi
+ done
+ wait 2>/dev/null || true
+ echo "Cleanup complete"
+}
+trap cleanup EXIT INT TERM
+
+# --- Helpers ---
+
+random_element() {
+ local arr=("$@")
+ echo "${arr[$((RANDOM % ${#arr[@]}))]}"
+}
+
+random_range() {
+ local min=$1 max=$2
+ echo $(( RANDOM % (max - min + 1) + min ))
+}
+
+get_workers() {
+ api "$API_URL/api/workers" 2>/dev/null | python3 -c "
+import sys, json
+try:
+ workers = json.load(sys.stdin)
+ for w in workers:
+ wid = w.get('worker_id','?')
+ cur = w.get('current',0)
+ cap = w.get('capacity',0)
+ cpu = w.get('cpu_pct',0)
+ mem = w.get('mem_pct',0)
+ ver = w.get('worker_version','?')
+ print(f' {wid}: {cur}/{cap} sandboxes, cpu={cpu:.0f}% mem={mem:.0f}% ver={ver}')
+except: pass
+" 2>/dev/null
+}
+
+# ============================================================
+# Phase 1: Ramp up
+# ============================================================
+h "Phase 1: Ramp up to $TARGET sandboxes (batches of $BATCH)"
+
+created=0
+while [ $created -lt "$TARGET" ]; do
+ batch_target=$((created + BATCH))
+ [ $batch_target -gt "$TARGET" ] && batch_target=$TARGET
+
+ # Create batch in parallel
+ pids=()
+ tmpdir=$(mktemp -d)
+ for i in $(seq $((created + 1)) "$batch_target"); do
+ (
+ sb=$(create_sandbox 7200)
+ echo "$sb" > "$tmpdir/$i"
+ ) &
+ pids+=($!)
+ done
+ wait "${pids[@]}" 2>/dev/null || true
+
+ # Collect IDs
+ for i in $(seq $((created + 1)) "$batch_target"); do
+ if [ -f "$tmpdir/$i" ]; then
+ sb=$(cat "$tmpdir/$i")
+ if [ -n "$sb" ] && [ "$sb" != "null" ]; then
+ SANDBOXES+=("$sb")
+ fi
+ fi
+ done
+ rm -rf "$tmpdir"
+
+ created=${#SANDBOXES[@]}
+ echo " Created: $created / $TARGET"
+done
+
+pass "Ramped to ${#SANDBOXES[@]} sandboxes"
+echo ""
+echo "Workers after ramp:"
+get_workers
+echo ""
+
+# ============================================================
+# Phase 2: Chaos rounds
+# ============================================================
+h "Phase 2: Chaos scaling ($ROUNDS rounds, every ${INTERVAL}s)"
+echo " Each round: scale $SCALE_BATCH random sandboxes + churn $CHURN"
+
+scales_ok=0
+scales_fail=0
+creates_ok=0
+destroys=0
+
+for round in $(seq 1 "$ROUNDS"); do
+ round_start=$(date +%s)
+
+ # --- Scale random sandboxes to random tiers ---
+ scale_pids=()
+ for _ in $(seq 1 "$SCALE_BATCH"); do
+ if [ ${#SANDBOXES[@]} -eq 0 ]; then break; fi
+ idx=$((RANDOM % ${#SANDBOXES[@]}))
+ sb="${SANDBOXES[$idx]}"
+ tier_idx=$((RANDOM % ${#TIERS[@]}))
+ mem="${TIERS[$tier_idx]}"
+ cpu="${CPUS[$tier_idx]}"
+
+ (
+ result=$(api -X PUT "$API_URL/api/sandboxes/$sb/limits" \
+ -d "{\"memoryMB\":$mem,\"cpuPercent\":$cpu}" 2>/dev/null)
+ if echo "$result" | grep -q "sandboxID"; then
+ echo "ok"
+ else
+ echo "fail"
+ fi
+ ) &
+ scale_pids+=($!)
+ done
+
+ # --- Churn: destroy some, create replacements ---
+ churn_pids=()
+ destroyed_indices=()
+ for _ in $(seq 1 "$CHURN"); do
+ if [ ${#SANDBOXES[@]} -le $((CHURN + 1)) ]; then break; fi
+ idx=$((RANDOM % ${#SANDBOXES[@]}))
+ sb="${SANDBOXES[$idx]}"
+ destroy_sandbox "$sb" &
+ churn_pids+=($!)
+ destroyed_indices+=("$idx")
+ destroys=$((destroys + 1))
+ done
+
+ # Wait for scales
+ for pid in "${scale_pids[@]}"; do
+ result=$(wait "$pid" 2>/dev/null && echo "ok" || echo "fail")
+ if [ "$result" = "ok" ]; then
+ scales_ok=$((scales_ok + 1))
+ else
+ scales_fail=$((scales_fail + 1))
+ fi
+ done
+
+ # Wait for destroys, then remove from array and create replacements
+ wait "${churn_pids[@]}" 2>/dev/null || true
+
+ # Remove destroyed sandboxes (in reverse order to preserve indices)
+ IFS=$'\n' sorted=($(printf '%s\n' "${destroyed_indices[@]}" | sort -rn)); unset IFS
+ for idx in "${sorted[@]}"; do
+ if [ "$idx" -lt ${#SANDBOXES[@]} ]; then
+ unset 'SANDBOXES[idx]'
+ fi
+ done
+ # Compact array
+ SANDBOXES=("${SANDBOXES[@]}")
+
+ # Create replacements
+ tmpdir=$(mktemp -d)
+ replace_pids=()
+ for i in $(seq 1 "$CHURN"); do
+ (
+ sb=$(create_sandbox 7200 2>/dev/null)
+ echo "$sb" > "$tmpdir/$i"
+ ) &
+ replace_pids+=($!)
+ done
+ wait "${replace_pids[@]}" 2>/dev/null || true
+ for i in $(seq 1 "$CHURN"); do
+ if [ -f "$tmpdir/$i" ]; then
+ sb=$(cat "$tmpdir/$i")
+ if [ -n "$sb" ] && [ "$sb" != "null" ]; then
+ SANDBOXES+=("$sb")
+ creates_ok=$((creates_ok + 1))
+ fi
+ fi
+ done
+ rm -rf "$tmpdir"
+
+ # Status every 10 rounds
+ if [ $((round % 10)) -eq 0 ]; then
+ elapsed=$(( $(date +%s) - round_start ))
+ echo " Round $round/$ROUNDS: ${#SANDBOXES[@]} sandboxes, scales=$scales_ok/$((scales_ok+scales_fail)), churn=$destroys destroyed / $creates_ok created (${elapsed}s)"
+ get_workers
+ fi
+
+ # Wait for interval
+ elapsed=$(( $(date +%s) - round_start ))
+ remaining=$((INTERVAL - elapsed))
+ [ $remaining -gt 0 ] && sleep "$remaining"
+done
+
+echo ""
+echo "Chaos results:"
+echo " Scales attempted: $((scales_ok + scales_fail))"
+echo " Scales succeeded: $scales_ok"
+echo " Scales failed: $scales_fail"
+echo " Sandboxes destroyed: $destroys"
+echo " Sandboxes created: $creates_ok"
+echo " Final count: ${#SANDBOXES[@]}"
+
+[ $scales_fail -lt $((scales_ok / 10)) ] && pass "Scale success rate > 90%" || fail "Too many scale failures: $scales_fail / $((scales_ok + scales_fail))"
+
+# ============================================================
+# Phase 3: Verify survivors
+# ============================================================
+h "Phase 3: Verify survivors (sample of 20)"
+
+sample_size=20
+[ ${#SANDBOXES[@]} -lt $sample_size ] && sample_size=${#SANDBOXES[@]}
+alive=0
+dead=0
+
+for _ in $(seq 1 "$sample_size"); do
+ idx=$((RANDOM % ${#SANDBOXES[@]}))
+ sb="${SANDBOXES[$idx]}"
+ result=$(exec_stdout "$sb" "echo" "alive" 2>/dev/null)
+ if [ "$result" = "alive" ]; then
+ alive=$((alive + 1))
+ else
+ dead=$((dead + 1))
+ fi
+done
+
+echo " Alive: $alive / $sample_size"
+[ $dead -le $((sample_size / 10)) ] && pass "Survival rate > 90%" || fail "Too many dead: $dead / $sample_size"
+
+# ============================================================
+# Phase 4: Final worker state
+# ============================================================
+h "Phase 4: Final worker state"
+get_workers
+
+summary
diff --git a/scripts/qemu-tests/30-responsiveness.sh b/scripts/qemu-tests/30-responsiveness.sh
new file mode 100755
index 00000000..7479edce
--- /dev/null
+++ b/scripts/qemu-tests/30-responsiveness.sh
@@ -0,0 +1,162 @@
+#!/usr/bin/env bash
+# 30-responsiveness.sh — Scale up sandboxes and test every single one responds
+#
+# Creates sandboxes one at a time, tests each immediately after creation,
+# then tests all of them again at the end before cleaning up.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+#
+# Optional env:
+# SANDBOX_COUNT — total sandboxes to create (default: 120)
+# BATCH_SIZE — sandboxes per batch (default: 1)
+# BATCH_DELAY — seconds between batches (default: 5)
+
+source "$(dirname "$0")/common.sh"
+
+SANDBOX_COUNT="${SANDBOX_COUNT:-120}"
+BATCH_SIZE="${BATCH_SIZE:-1}"
+BATCH_DELAY="${BATCH_DELAY:-5}"
+declare -a SANDBOXES=()
+declare -a WORKERS_SEEN=()
+
+cleanup() {
+ if [ ${#SANDBOXES[@]} -gt 0 ]; then
+ h "Cleanup: destroying ${#SANDBOXES[@]} sandboxes"
+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ destroy_sandbox "$sb" &
+ done
+ wait 2>/dev/null || true
+ echo "Cleanup complete"
+ fi
+}
+trap cleanup EXIT INT TERM
+
+get_workers() {
+ api "$API_URL/api/workers" 2>/dev/null || echo "[]"
+}
+
+worker_summary() {
+ get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+for w in workers:
+ print(f' {w.get(\"worker_id\",\"?\"):30s} {w.get(\"current\",0):>3}/{w.get(\"capacity\",0)} cpu={w.get(\"cpu_pct\",0):5.1f}% mem={w.get(\"mem_pct\",0):5.1f}% ver={w.get(\"worker_version\",\"?\")}')
+" 2>/dev/null || echo " (no worker data)"
+}
+
+# ============================================================
+# Phase 1: Baseline
+# ============================================================
+h "Phase 1: Baseline"
+worker_summary
+
+# ============================================================
+# Phase 2: Create sandboxes and test each one immediately
+# ============================================================
+h "Phase 2: Create $SANDBOX_COUNT sandboxes (batch=$BATCH_SIZE, delay=${BATCH_DELAY}s)"
+echo " Testing each sandbox immediately after creation"
+echo ""
+
+CREATE_OK=0
+CREATE_FAIL=0
+IMMEDIATE_OK=0
+IMMEDIATE_FAIL=0
+IMMEDIATE_FAILS=""
+
+for batch_start in $(seq 1 "$BATCH_SIZE" "$SANDBOX_COUNT"); do
+ batch_end=$((batch_start + BATCH_SIZE - 1))
+ [ "$batch_end" -gt "$SANDBOX_COUNT" ] && batch_end=$SANDBOX_COUNT
+
+ for i in $(seq "$batch_start" "$batch_end"); do
+ # Create
+ RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ SB_ID=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null || echo "FAIL")
+ WORKER=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null || echo "?")
+
+ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then
+ SANDBOXES+=("$SB_ID")
+ CREATE_OK=$((CREATE_OK + 1))
+
+ # Test immediately
+ OUT=$(exec_stdout "$SB_ID" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" = "alive" ]; then
+ IMMEDIATE_OK=$((IMMEDIATE_OK + 1))
+ else
+ IMMEDIATE_FAIL=$((IMMEDIATE_FAIL + 1))
+ IMMEDIATE_FAILS="$IMMEDIATE_FAILS $SB_ID($WORKER)"
+ fi
+ else
+ CREATE_FAIL=$((CREATE_FAIL + 1))
+ # Show the error
+ ERR=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','unknown'))" 2>/dev/null || echo "unknown")
+ echo " FAIL #$i: $ERR"
+ fi
+ done
+
+ # Progress every 10
+ if [ $((CREATE_OK + CREATE_FAIL)) -ge 10 ] && [ $(( (CREATE_OK + CREATE_FAIL) % 10 )) -eq 0 ]; then
+ echo " progress: created=$CREATE_OK failed=$CREATE_FAIL responsive=$IMMEDIATE_OK unresponsive=$IMMEDIATE_FAIL"
+ fi
+
+ sleep "$BATCH_DELAY"
+done
+
+echo ""
+echo "Creation: $CREATE_OK succeeded, $CREATE_FAIL failed"
+echo "Immediate responsiveness: $IMMEDIATE_OK/$CREATE_OK OK"
+if [ -n "$IMMEDIATE_FAILS" ]; then
+ echo " Failed sandboxes:$IMMEDIATE_FAILS"
+fi
+
+[ "$CREATE_OK" -ge $((SANDBOX_COUNT * 80 / 100)) ] && pass "Created >= 80% ($CREATE_OK/$SANDBOX_COUNT)" || fail "Only $CREATE_OK/$SANDBOX_COUNT created"
+[ "$IMMEDIATE_OK" -ge $((CREATE_OK * 90 / 100)) ] && pass "Immediate responsiveness >= 90% ($IMMEDIATE_OK/$CREATE_OK)" || fail "Immediate responsiveness: $IMMEDIATE_OK/$CREATE_OK"
+
+# ============================================================
+# Phase 3: Worker state
+# ============================================================
+h "Phase 3: Worker state after ramp"
+worker_summary
+
+# ============================================================
+# Phase 4: Test ALL sandboxes again
+# ============================================================
+h "Phase 4: Test all ${#SANDBOXES[@]} sandboxes"
+
+RECHECK_OK=0
+RECHECK_FAIL=0
+RECHECK_FAILS=""
+
+for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ OUT=$(exec_stdout "$sb" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" = "alive" ]; then
+ RECHECK_OK=$((RECHECK_OK + 1))
+ else
+ RECHECK_FAIL=$((RECHECK_FAIL + 1))
+ RECHECK_FAILS="$RECHECK_FAILS $sb"
+ fi
+done
+
+echo "Full recheck: $RECHECK_OK/${#SANDBOXES[@]} responsive"
+if [ -n "$RECHECK_FAILS" ]; then
+ echo " Failed:$RECHECK_FAILS"
+fi
+[ "$RECHECK_OK" -ge $(( ${#SANDBOXES[@]} * 90 / 100 )) ] && pass "Full recheck >= 90% ($RECHECK_OK/${#SANDBOXES[@]})" || fail "Full recheck: $RECHECK_OK/${#SANDBOXES[@]}"
+
+# ============================================================
+# Phase 5: Scale down
+# ============================================================
+h "Phase 5: Scale down"
+echo "Destroying all sandboxes..."
+for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ destroy_sandbox "$sb" &
+done
+wait 2>/dev/null || true
+SANDBOXES=()
+echo "All destroyed. Waiting 120s for autoscaler to drain..."
+sleep 120
+echo "Workers after drain:"
+worker_summary
+
+summary
diff --git a/scripts/qemu-tests/31-scale-migrate.sh b/scripts/qemu-tests/31-scale-migrate.sh
new file mode 100755
index 00000000..dd4ea3b7
--- /dev/null
+++ b/scripts/qemu-tests/31-scale-migrate.sh
@@ -0,0 +1,241 @@
+#!/usr/bin/env bash
+# 31-scale-migrate.sh — Test live migration triggered by resource scaling
+#
+# Scenario:
+# 1. Fill 2 workers to capacity with 4GB/1vCPU sandboxes (16 each = 32 total)
+# 2. Verify 1 idle reserve remains
+# 3. Scale one sandbox from 4GB/1vCPU to 16GB/4vCPU via the limits API
+# 4. The system should auto-migrate the sandbox to the reserve worker
+# 5. A new reserve should spin up to replace the one that was used
+# 6. Verify the sandbox survived migration and responds correctly
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+declare -a SANDBOXES=()
+
+cleanup() {
+ echo ""
+ echo "=== ${#SANDBOXES[@]} sandboxes left alive for inspection ==="
+ echo "To clean up manually: for sb in ${SANDBOXES[*]+"${SANDBOXES[*]}"}; do curl -s -X DELETE $API_URL/api/sandboxes/\$sb -H 'X-API-Key: $API_KEY'; done"
+}
+trap cleanup EXIT INT TERM
+
+get_workers() {
+ api "$API_URL/api/workers" 2>/dev/null || echo "[]"
+}
+
+worker_summary() {
+ get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+for w in workers:
+ print(f' {w.get(\"worker_id\",\"?\"):30s} {w.get(\"current\",0):>3}/{w.get(\"capacity\",0)} cpu={w.get(\"cpu_pct\",0):5.1f}% mem={w.get(\"mem_pct\",0):5.1f}% ver={w.get(\"worker_version\",\"?\")}')
+" 2>/dev/null || echo " (no worker data available)"
+}
+
+worker_count() {
+ get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "0"
+}
+
+# ============================================================
+# Phase 1: Fill 2 workers to capacity
+# ============================================================
+FILL_COUNT="${FILL_COUNT:-12}"
+h "Phase 1: Fill 1 worker ($FILL_COUNT sandboxes at 4GB/1vCPU)"
+
+echo "Starting state:"
+worker_summary
+
+CREATED=0
+TARGET="$FILL_COUNT"
+for i in $(seq 1 "$TARGET"); do
+ RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ SB_ID=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null || echo "FAIL")
+ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then
+ SANDBOXES+=("$SB_ID")
+ CREATED=$((CREATED+1))
+
+ # Scale to 4GB immediately so committed memory fills up.
+ # Base is 1GB, so this hotplugs 3GB per sandbox via virtio-mem.
+ # 12 sandboxes x 4GB = 48GB committed on a 64GB host.
+ api -X PUT "$API_URL/api/sandboxes/$SB_ID/limits" \
+ -d '{"memoryMB":4096,"cpuPercent":100}' >/dev/null 2>&1
+ fi
+ sleep 2
+ if [ $((CREATED % 10)) -eq 0 ]; then
+ echo " created: $CREATED/$TARGET"
+ worker_summary
+ fi
+done
+
+echo ""
+echo "Created $CREATED sandboxes"
+worker_summary
+
+[ "$CREATED" -ge $((TARGET * 80 / 100)) ] && pass "Filled workers ($CREATED sandboxes)" || fail "Only created $CREATED/$TARGET sandboxes"
+
+# ============================================================
+# Phase 2: Wait for reserves, verify layout
+# ============================================================
+h "Phase 2: Wait for idle reserves"
+
+echo "Waiting for at least 1 idle reserve..."
+for attempt in $(seq 1 24); do
+ IDLE=$(get_workers | python3 -c "import sys,json; print(sum(1 for w in json.load(sys.stdin) if w.get('current',0)==0))" 2>/dev/null || echo "0")
+ if [ "$IDLE" -ge 1 ]; then
+ echo " Reserve ready after $((attempt * 10))s ($IDLE idle)"
+ break
+ fi
+ echo " waiting... ($IDLE idle, attempt $attempt)"
+ sleep 10
+done
+
+WORKERS_JSON=$(get_workers)
+LAYOUT=$(echo "$WORKERS_JSON" | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+active = [w for w in workers if w.get('current', 0) > 0]
+idle = [w for w in workers if w.get('current', 0) == 0]
+print(f'{len(active)} active, {len(idle)} idle')
+for w in active:
+ print(f' ACTIVE {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]} mem={w[\"mem_pct\"]:.0f}%')
+for w in idle:
+ print(f' IDLE {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]}')
+" 2>/dev/null)
+echo "$LAYOUT"
+
+IDLE_COUNT=$(echo "$WORKERS_JSON" | python3 -c "
+import sys, json
+print(sum(1 for w in json.load(sys.stdin) if w.get('current',0)==0))
+" 2>/dev/null || echo "0")
+
+[ "$IDLE_COUNT" -ge 1 ] && pass "At least 1 idle reserve available" || fail "No idle reserves (need at least 1 for migration)"
+
+# ============================================================
+# Phase 3: Pick a sandbox and scale it up
+# ============================================================
+h "Phase 3: Scale sandbox from 4GB to 16GB"
+
+# Find a responsive sandbox on the most loaded worker
+BUSIEST_WORKER=$(get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+active = [w for w in workers if w.get('current', 0) > 0]
+if active:
+ busiest = max(active, key=lambda w: w['current'])
+ print(busiest['worker_id'])
+else:
+ print('')
+" 2>/dev/null)
+echo "Busiest worker: $BUSIEST_WORKER"
+
+TARGET_SB=""
+for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ # Check which worker this sandbox is on
+ SB_WORKER=$(api "$API_URL/api/sandboxes/$sb" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+ if [ "$SB_WORKER" = "$BUSIEST_WORKER" ]; then
+ OUT=$(exec_stdout "$sb" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" = "alive" ]; then
+ TARGET_SB="$sb"
+ break
+ fi
+ fi
+done
+# Fallback: any responsive sandbox
+if [ -z "$TARGET_SB" ]; then
+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do
+ OUT=$(exec_stdout "$sb" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" = "alive" ]; then
+ TARGET_SB="$sb"
+ break
+ fi
+ done
+fi
+
+if [ -z "$TARGET_SB" ]; then
+ fail "No responsive sandbox found to scale"
+ summary
+ exit 1
+fi
+
+echo "Target sandbox: $TARGET_SB"
+pass "Sandbox responsive before scale"
+
+# Get its current worker
+BEFORE_WORKER=$(api "$API_URL/api/sandboxes/$TARGET_SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null || echo "?")
+echo "Before: worker=$BEFORE_WORKER"
+
+# Scale to 16GB/4vCPU — this should trigger auto-migration
+echo "Scaling to 16GB / 4vCPU (may trigger migration, timeout 120s)..."
+SCALE_RESULT=$(TIMEOUT=120 api -X PUT "$API_URL/api/sandboxes/$TARGET_SB/limits" \
+ -d '{"memoryMB":16384,"cpuPercent":400}' 2>/dev/null)
+echo "Scale result: $SCALE_RESULT" | python3 -c "
+import sys, json
+try:
+ d = json.load(sys.stdin.read().split(': ', 1)[1] if ': ' in sys.stdin.read() else '{}')
+except:
+ pass
+" 2>/dev/null || echo " $SCALE_RESULT"
+
+MIGRATED=$(echo "$SCALE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('migrated', False))" 2>/dev/null || echo "false")
+AFTER_WORKER=$(echo "$SCALE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID', '?'))" 2>/dev/null || echo "?")
+
+echo "After: worker=$AFTER_WORKER, migrated=$MIGRATED"
+
+if [ "$MIGRATED" = "True" ] || [ "$MIGRATED" = "true" ]; then
+ pass "Sandbox was auto-migrated ($BEFORE_WORKER → $AFTER_WORKER)"
+elif [ "$AFTER_WORKER" != "$BEFORE_WORKER" ] && [ "$AFTER_WORKER" != "?" ]; then
+ pass "Sandbox moved to different worker ($BEFORE_WORKER → $AFTER_WORKER)"
+else
+ skip "Sandbox stayed on same worker (in-place scale may have worked)"
+fi
+
+# ============================================================
+# Phase 4: Verify sandbox survived
+# ============================================================
+h "Phase 4: Verify sandbox survived scaling/migration"
+
+sleep 3 # brief settle time
+
+OUT=$(exec_stdout "$TARGET_SB" "echo" "alive" 2>/dev/null)
+[ "$OUT" = "alive" ] && pass "Sandbox responsive after scale" || fail "Sandbox unresponsive after scale"
+
+# Check memory is actually scaled
+MEM=$(exec_stdout "$TARGET_SB" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+if [ -n "$MEM" ] && [ "$MEM" -gt 12000 ]; then
+ pass "Memory scaled: ${MEM}MB (expected ~16384MB)"
+elif [ -n "$MEM" ]; then
+ fail "Memory not scaled: ${MEM}MB (expected ~16384MB)"
+else
+ fail "Could not read memory"
+fi
+
+# ============================================================
+# Phase 5: Verify reserve replenishment
+# ============================================================
+h "Phase 5: Check reserve replenishment"
+
+echo "Waiting 60s for new reserve to boot..."
+sleep 60
+
+echo "Workers after scale + reserve replenishment:"
+worker_summary
+
+NEW_IDLE=$(echo "$(get_workers)" | python3 -c "
+import sys, json
+print(sum(1 for w in json.load(sys.stdin) if w.get('current',0)==0))
+" 2>/dev/null || echo "0")
+
+[ "$NEW_IDLE" -ge 1 ] && pass "Reserve replenished ($NEW_IDLE idle workers)" || skip "Reserve not yet replenished (may still be booting)"
+
+# ============================================================
+# Phase 6: Final state
+# ============================================================
+h "Phase 6: Final state"
+worker_summary
+
+summary
diff --git a/scripts/qemu-tests/migration-steps/00-env.sh b/scripts/qemu-tests/migration-steps/00-env.sh
new file mode 100755
index 00000000..819308b0
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/00-env.sh
@@ -0,0 +1,20 @@
+# Source this before running steps
+export API_URL="${OPENSANDBOX_API_URL:?Set OPENSANDBOX_API_URL}"
+export API_KEY="${OPENSANDBOX_API_KEY:?Set OPENSANDBOX_API_KEY}"
+
+api() {
+ curl -s --max-time "${TIMEOUT:-30}" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: $API_KEY" \
+ "$@"
+}
+
+workers() {
+ api "$API_URL/api/workers" | python3 -c "
+import sys, json
+ws=json.load(sys.stdin)
+for w in ws:
+ print(f' {w[\"worker_id\"]:30s} {w[\"current\"]:>3}/{w[\"capacity\"]} mem={w[\"mem_pct\"]:5.1f}%')
+print(f'{len(ws)} total')
+"
+}
diff --git a/scripts/qemu-tests/migration-steps/01-clean-slate.sh b/scripts/qemu-tests/migration-steps/01-clean-slate.sh
new file mode 100755
index 00000000..9601c286
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/01-clean-slate.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 1: Clean slate ==="
+echo "Destroying all sandboxes from API..."
+SANDBOXES=$(api "$API_URL/api/sandboxes?limit=100" | python3 -c "import sys,json; [print(s['sandboxID']) for s in json.load(sys.stdin)]" 2>/dev/null || echo "")
+for sb in $SANDBOXES; do
+ api -X DELETE "$API_URL/api/sandboxes/$sb" &
+done
+wait
+
+echo "Killing orphaned VMs on all workers..."
+for VM in $(az vm list --resource-group opensandbox-prod --query "[].name" -o tsv 2>/dev/null | grep osb-worker); do
+ az vm run-command invoke --resource-group opensandbox-prod --name "$VM" --command-id RunShellScript \
+ --scripts "systemctl stop opensandbox-worker; pkill -9 qemu-system 2>/dev/null; rm -rf /data/sandboxes/sandboxes/* /data/sandboxes/golden; systemctl start opensandbox-worker; sleep 5; systemctl is-active opensandbox-worker" 2>&1 | tail -1
+done
+
+sleep 10
+echo "Workers:"
+workers
+echo ""
+echo "DONE: Verify workers with 0 sandboxes above"
diff --git a/scripts/qemu-tests/migration-steps/02-create-12.sh b/scripts/qemu-tests/migration-steps/02-create-12.sh
new file mode 100755
index 00000000..869de67d
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/02-create-12.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 2: Create 12 sandboxes ==="
+CREATED=0
+for i in $(seq 1 12); do
+ RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}')
+ SB=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)
+ WK=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+ echo " $i: $SB -> $WK"
+ CREATED=$((CREATED+1))
+ sleep 1
+done
+echo ""
+echo "Created $CREATED sandboxes"
+workers
+echo ""
+echo "DONE: Verify all 12 on one worker"
diff --git a/scripts/qemu-tests/migration-steps/03-scale-all-4gb.sh b/scripts/qemu-tests/migration-steps/03-scale-all-4gb.sh
new file mode 100755
index 00000000..1bcbdd32
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/03-scale-all-4gb.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 3: Scale all sandboxes to 4GB ==="
+SANDBOXES=$(api "$API_URL/api/sandboxes?limit=100" | python3 -c "import sys,json; [print(s['sandboxID']) for s in json.load(sys.stdin)]" 2>/dev/null)
+COUNT=0
+for sb in $SANDBOXES; do
+ COUNT=$((COUNT+1))
+ RESULT=$(TIMEOUT=60 api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":4096,"cpuPercent":100}')
+ OK=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('ok','?'))" 2>/dev/null)
+ echo " $COUNT: $sb -> ok=$OK"
+ sleep 1
+done
+echo ""
+echo "Scaled $COUNT sandboxes"
+workers
+echo ""
+echo "DONE: Memory should be rising on the active worker"
diff --git a/scripts/qemu-tests/migration-steps/04-check-committed.sh b/scripts/qemu-tests/migration-steps/04-check-committed.sh
new file mode 100755
index 00000000..c5e7c339
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/04-check-committed.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 4: Check committed memory ==="
+workers
+echo ""
+
+# Check worker logs for committed memory
+echo "Checking worker logs for committed memory..."
+SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-digger.pem}"
+WORKER_IP=$(api "$API_URL/api/workers" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ if w['current'] > 0:
+ print(w['grpc_addr'].split(':')[0])
+ break
+" 2>/dev/null)
+
+if [ -n "$WORKER_IP" ]; then
+ echo "Active worker IP: $WORKER_IP"
+ echo ""
+ echo "DONE: 12 sandboxes at 4GB = 48GB committed. Check that mem% is elevated."
+else
+ echo "ERROR: No active worker found"
+fi
diff --git a/scripts/qemu-tests/migration-steps/05-scale-16gb.sh b/scripts/qemu-tests/migration-steps/05-scale-16gb.sh
new file mode 100755
index 00000000..e8ed9c29
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/05-scale-16gb.sh
@@ -0,0 +1,56 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 5: Scale one sandbox to 16GB ==="
+
+# Pick a sandbox from the busiest worker (most committed memory)
+BUSIEST=$(api "$API_URL/api/workers" | python3 -c "
+import sys,json
+ws=json.load(sys.stdin)
+best=max(ws, key=lambda w: w['current'])
+print(best['worker_id'])
+" 2>/dev/null)
+echo "Busiest worker: $BUSIEST"
+
+SB=$(api "$API_URL/api/sandboxes?limit=100" | python3 -c "
+import sys,json
+for s in json.load(sys.stdin):
+ if s.get('workerID','') == '$BUSIEST':
+ print(s['sandboxID'])
+ break
+" 2>/dev/null)
+WORKER=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+
+echo "Sandbox: $SB"
+echo "Current worker: $WORKER"
+echo ""
+
+# Test responsive first
+OUT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["alive"],"timeout":5}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)
+echo "Responsive: $OUT"
+echo ""
+
+echo "Scaling to 16GB / 4vCPU (timeout 180s)..."
+RESULT=$(TIMEOUT=180 api -X PUT "$API_URL/api/sandboxes/$SB/limits" -d '{"memoryMB":16384,"cpuPercent":400}')
+echo "Response: $RESULT"
+echo ""
+
+# Parse result
+MIGRATED=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('migrated','?'))" 2>/dev/null || echo "?")
+NEW_WORKER=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null || echo "?")
+ERROR=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','none'))" 2>/dev/null || echo "?")
+
+echo "Migrated: $MIGRATED"
+echo "New worker: $NEW_WORKER"
+echo "Error: $ERROR"
+echo ""
+
+# Check memory
+MEM=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"free","args":["-m"],"timeout":5}' | python3 -c "import sys,json; [print(l) for l in json.load(sys.stdin).get('stdout','').split('\n') if 'Mem' in l]" 2>/dev/null)
+echo "Memory: $MEM"
+echo ""
+
+workers
+echo ""
+echo "DONE: Check if migration happened or error above"
diff --git a/scripts/qemu-tests/migration-steps/06-check-logs.sh b/scripts/qemu-tests/migration-steps/06-check-logs.sh
new file mode 100755
index 00000000..3779e7d1
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/06-check-logs.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 6: Check server + worker logs ==="
+SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-digger.pem}"
+
+echo "--- Server logs ---"
+az vm run-command invoke --resource-group opensandbox-prod --name osb-controlplane --command-id RunShellScript \
+ --scripts "journalctl -u opensandbox-server --no-pager --since '5 min ago' | grep -E 'scale-limits|scale-migrate|migration-prepare|health check' | tail -15" 2>&1 | python3 -c "import sys,json; [print(v.get('message','')) for v in json.load(sys.stdin).get('value',[])]" 2>&1
+
+echo ""
+echo "--- Target worker logs ---"
+# Find the target worker from the server log
+TARGET=$(az vm run-command invoke --resource-group opensandbox-prod --name osb-controlplane --command-id RunShellScript \
+ --scripts "journalctl -u opensandbox-server --no-pager --since '5 min ago' | grep 'migrating to' | tail -1" 2>&1 | python3 -c "import sys,json; print([v.get('message','') for v in json.load(sys.stdin).get('value',[])][0])" 2>&1)
+echo " $TARGET"
+
+echo ""
+workers
+echo ""
+echo "DONE: Review logs above for the migration path"
diff --git a/scripts/qemu-tests/migration-steps/07-test-qemu-target.sh b/scripts/qemu-tests/migration-steps/07-test-qemu-target.sh
new file mode 100755
index 00000000..7aa1d7f8
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/07-test-qemu-target.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Step 7: Test QEMU startup on target worker ==="
+
+# Find the idle (target) worker
+TARGET_VM=$(az vm list --resource-group opensandbox-prod --query "[].name" -o tsv 2>&1 | grep "osb-worker-" | grep -v "osb-worker-1" | head -1)
+echo "Target VM: $TARGET_VM"
+
+if [ -z "$TARGET_VM" ]; then
+ echo "ERROR: No autoscaled worker found"
+ exit 1
+fi
+
+echo ""
+echo "Testing QEMU with 4GB base + 15GB virtio-mem pool..."
+az vm run-command invoke --resource-group opensandbox-prod --name "$TARGET_VM" --command-id RunShellScript \
+ --scripts "
+rm -rf /tmp/qemu-test; mkdir -p /tmp/qemu-test
+
+# Create qcow2 overlay
+qemu-img create -f qcow2 -b /data/firecracker/images/default.ext4 -F raw /tmp/qemu-test/rootfs.qcow2 2>&1
+
+# Start QEMU same as migration would
+qemu-system-x86_64 \
+ -machine q35,accel=kvm -cpu host \
+ -m 4096M,slots=1,maxmem=19456M \
+ -object memory-backend-ram,id=vmem0,size=15360M \
+ -device virtio-mem-pci,memdev=vmem0,id=vm0,block-size=128M,requested-size=0 \
+ -smp 1 \
+ -kernel /opt/opensandbox/vmlinux \
+ -append 'console=ttyS0 root=/dev/vda rw' \
+ -drive file=/tmp/qemu-test/rootfs.qcow2,format=qcow2,if=virtio \
+ -qmp unix:/tmp/qemu-test/qmp.sock,server,nowait \
+ -nographic -nodefaults \
+ -incoming tcp:0:44444 \
+ 2>/tmp/qemu-test/qemu.log &
+PID=\$!
+echo \"QEMU pid: \$PID\"
+
+for i in \$(seq 1 30); do
+ if python3 -c \"
+import socket
+s=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+s.settimeout(2)
+s.connect('/tmp/qemu-test/qmp.sock')
+data=s.recv(4096)
+print('QMP connected after \${i}s:', data.decode()[:100])
+s.close()
+\" 2>/dev/null; then
+ kill \$PID 2>/dev/null
+ rm -rf /tmp/qemu-test
+ exit 0
+ fi
+ sleep 1
+done
+
+echo 'QMP FAILED after 30s'
+echo 'QEMU log:'
+cat /tmp/qemu-test/qemu.log
+echo 'Process state:'
+ps -p \$PID -o stat= 2>/dev/null || echo 'dead'
+kill \$PID 2>/dev/null
+rm -rf /tmp/qemu-test
+" 2>&1 | python3 -c "import sys,json; [print(v.get('message','')) for v in json.load(sys.stdin).get('value',[])]" 2>&1
+
+echo ""
+echo "DONE: If QMP connected, the migration target QEMU works. If failed, check the log above."
diff --git a/scripts/qemu-tests/migration-steps/08-manual-migrate.sh b/scripts/qemu-tests/migration-steps/08-manual-migrate.sh
new file mode 100755
index 00000000..27f3dc5a
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/08-manual-migrate.sh
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Manual Migration Test ==="
+
+echo "Step 1: Create a sandbox"
+RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}')
+SB=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)
+SRC=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+echo " Sandbox: $SB on $SRC"
+
+echo ""
+echo "Step 2: Verify responsive"
+OUT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["hello"],"timeout":5}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','FAIL').strip())" 2>/dev/null)
+echo " Response: $OUT"
+
+echo ""
+echo "Step 3: Write a marker file"
+api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"sh","args":["-c","echo migration-test > /workspace/marker.txt"],"timeout":5}' >/dev/null
+MARKER=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"cat","args":["/workspace/marker.txt"],"timeout":5}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','FAIL').strip())" 2>/dev/null)
+echo " Marker: $MARKER"
+
+echo ""
+echo "Step 4: Find target worker"
+TARGET=$(api "$API_URL/api/workers" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ if w['worker_id'] != '$SRC':
+ print(w['worker_id'])
+ break
+" 2>/dev/null)
+echo " Source: $SRC"
+echo " Target: $TARGET"
+
+if [ -z "$TARGET" ] || [ "$TARGET" = "" ]; then
+ echo "ERROR: No target worker available"
+ exit 1
+fi
+
+echo ""
+echo "Step 5: Migrate (timeout 180s)"
+MIGRATE_RESULT=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB/migrate" -d "{\"targetWorker\":\"$TARGET\"}")
+echo " Result: $MIGRATE_RESULT"
+
+echo ""
+echo "Step 6: Verify sandbox survived (waiting 5s for agent)"
+sleep 5
+OUT2=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["alive"],"timeout":5}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','FAIL').strip())" 2>/dev/null)
+echo " Response: $OUT2"
+
+echo ""
+echo "Step 7: Verify marker file survived"
+MARKER2=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"cat","args":["/workspace/marker.txt"],"timeout":5}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','FAIL').strip())" 2>/dev/null)
+echo " Marker: $MARKER2"
+
+echo ""
+echo "Step 8: Check which worker it's on now"
+NEW_WORKER=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+echo " Before: $SRC"
+echo " After: $NEW_WORKER"
+
+echo ""
+if [ "$OUT2" = "alive" ] && [ "$MARKER2" = "migration-test" ] && [ "$NEW_WORKER" = "$TARGET" ]; then
+ echo "SUCCESS: Sandbox migrated and survived with data intact"
+else
+ echo "FAILED: something went wrong"
+ echo " alive=$OUT2 marker=$MARKER2 worker=$NEW_WORKER"
+fi
+
+echo ""
+echo "Step 9: Cleanup"
+api -X DELETE "$API_URL/api/sandboxes/$SB" >/dev/null 2>&1
+echo " Destroyed $SB"
diff --git a/scripts/qemu-tests/migration-steps/09-debug-migrate.sh b/scripts/qemu-tests/migration-steps/09-debug-migrate.sh
new file mode 100755
index 00000000..f3da3ec1
--- /dev/null
+++ b/scripts/qemu-tests/migration-steps/09-debug-migrate.sh
@@ -0,0 +1,90 @@
+#!/usr/bin/env bash
+set -euo pipefail
+source "$(dirname "$0")/00-env.sh"
+
+echo "=== Debug Migration Test ==="
+
+echo "Step 1: Create sandbox"
+RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}')
+SB=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)
+SRC=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+echo " $SB on $SRC"
+
+echo ""
+echo "Step 2: Exec before migration"
+EXEC_BEFORE=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["before-migrate"],"timeout":5}')
+echo " Raw response: $EXEC_BEFORE"
+
+echo ""
+echo "Step 3: Write marker"
+api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"sh","args":["-c","echo test123 > /workspace/marker.txt"],"timeout":5}' >/dev/null
+
+echo ""
+echo "Step 4: Find target"
+TARGET=$(api "$API_URL/api/workers" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ if w['worker_id'] != '$SRC':
+ print(w['worker_id'])
+ break
+" 2>/dev/null)
+echo " Source: $SRC"
+echo " Target: $TARGET"
+
+echo ""
+echo "Step 5: Check DB status BEFORE migrate"
+DB_BEFORE=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'status={d.get(\"status\",\"?\")} worker={d.get(\"workerID\",\"?\")}')" 2>/dev/null)
+echo " $DB_BEFORE"
+
+echo ""
+echo "Step 6: Migrate"
+MIGRATE_RESULT=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB/migrate" -d "{\"targetWorker\":\"$TARGET\"}")
+echo " Result: $MIGRATE_RESULT"
+
+echo ""
+echo "Step 7: Check DB status AFTER migrate"
+DB_AFTER=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'status={d.get(\"status\",\"?\")} worker={d.get(\"workerID\",\"?\")}')" 2>/dev/null)
+echo " $DB_AFTER"
+
+echo ""
+echo "Step 8: Exec IMMEDIATELY after migration (via control plane)"
+EXEC_AFTER=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["after-migrate"],"timeout":5}')
+echo " Raw response: $EXEC_AFTER"
+
+echo ""
+echo "Step 9: Wait 3s then exec again"
+sleep 3
+EXEC_WAIT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["after-wait"],"timeout":5}')
+echo " Raw response: $EXEC_WAIT"
+
+echo ""
+echo "Step 10: Try exec directly on TARGET worker HTTP (bypass CP)"
+TARGET_HTTP=$(api "$API_URL/api/workers" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ if w['worker_id'] == '$TARGET':
+ print(w['http_addr'])
+ break
+" 2>/dev/null)
+echo " Target HTTP: $TARGET_HTTP"
+if [ -n "$TARGET_HTTP" ]; then
+ # Get a token for the sandbox
+ TOKEN=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null)
+ DIRECT_EXEC=$(curl -s --max-time 10 -X POST "$TARGET_HTTP/sandboxes/$SB/exec/run" \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer $TOKEN" \
+ -d '{"cmd":"echo","args":["direct-exec"],"timeout":5}')
+ echo " Direct response: $DIRECT_EXEC"
+fi
+
+echo ""
+echo "Step 11: Check marker file"
+MARKER=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"cat","args":["/workspace/marker.txt"],"timeout":5}')
+echo " Marker response: $MARKER"
+
+echo ""
+echo "Step 12: Workers state"
+workers
+
+echo ""
+echo "=== NOT cleaning up — sandbox $SB left alive for inspection ==="