Skip to content

An open-source, faster Devin alternative

TypeScript

Test suite (#233)

Brian Reardonab2affbbe760
diff --git a/.github/workflows/ci-gc.yml b/.github/workflows/ci-gc.yml
new file mode 100644
index 00000000..aea2d4cd
--- /dev/null
+++ b/.github/workflows/ci-gc.yml
@@ -0,0 +1,39 @@
+name: CI GC (stale PR stacks)
+
+on:
+ schedule:
+ - cron: '0 6 * * *' # daily 06:00 UTC
+ workflow_dispatch:
+ inputs:
+ max_age_hours:
+ description: 'Tear down PR stacks older than this many hours'
+ type: number
+ default: 24
+
+permissions:
+ id-token: write
+ contents: read
+
+jobs:
+ gc:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install SSH key
+ run: |
+ mkdir -p ~/.ssh
+ echo "${{ secrets.OPENCOMPUTER_CI_SSH_KEY }}" > ~/.ssh/opencomputer-ci
+ chmod 600 ~/.ssh/opencomputer-ci
+
+ - uses: azure/login@v2
+ with:
+ client-id: ${{ secrets.AZURE_CLIENT_ID }}
+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
+
+ - name: GC stale PR stacks
+ env:
+ MAX_AGE_HOURS: ${{ inputs.max_age_hours || 24 }}
+ run: ./ci/persistent/gc.sh
diff --git a/.github/workflows/pr-integration.yml b/.github/workflows/pr-integration.yml
new file mode 100644
index 00000000..3d514d7e
--- /dev/null
+++ b/.github/workflows/pr-integration.yml
@@ -0,0 +1,82 @@
+name: PR Integration Test
+
+# Runs in the PR's context (not pull_request_target), so fork PRs run WITHOUT
+# secrets — eliminating the standard pull_request_target exfiltration vector.
+# For PRs from branches in this repo (org-member flow), the workflow does have
+# secrets, so we additionally gate behind an explicit `osb-ci-approve` label
+# applied by a maintainer. A companion workflow (pr-strip-approval.yml) auto-
+# removes the label on each push, forcing a fresh per-SHA approval.
+on:
+ pull_request:
+ types: [labeled]
+
+concurrency:
+ group: pr-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+permissions:
+ id-token: write
+ contents: read
+ pull-requests: write
+
+jobs:
+ gate:
+ # Only the osb-ci-approve label triggers CI; other labels do nothing.
+ if: github.event.label.name == 'osb-ci-approve'
+ runs-on: ubuntu-latest
+ outputs:
+ approved: ${{ steps.check.outputs.approved }}
+ steps:
+ - id: check
+ run: echo "approved=true" >> "$GITHUB_OUTPUT"
+
+ ci:
+ needs: gate
+ if: needs.gate.outputs.approved == 'true'
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - name: Checkout PR head
+ uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: go.mod
+
+ - name: Pre-flight tests (no infra)
+ run: go test -count=1 ./ci/tests/migration/...
+
+ - name: Install SSH key
+ run: |
+ mkdir -p ~/.ssh
+ echo "${{ secrets.OPENCOMPUTER_CI_SSH_KEY }}" > ~/.ssh/opencomputer-ci
+ chmod 600 ~/.ssh/opencomputer-ci
+ # Public half is derived once from the private key.
+ ssh-keygen -y -f ~/.ssh/opencomputer-ci > ~/.ssh/opencomputer-ci.pub
+
+ - uses: azure/login@v2
+ with:
+ client-id: ${{ secrets.AZURE_CLIENT_ID }}
+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
+
+ - name: Bring up PR stack (2 workers, cross-version baseline)
+ id: up
+ env:
+ BASELINE_FROM_GALLERY: "1"
+ run: |
+ ./ci/pr/up.sh ${{ github.event.pull_request.number }} 2
+
+ - name: API test suite
+ env:
+ OSB_TEST_SERVER_URL: ${{ steps.up.outputs.server_url }}
+ OSB_TEST_API_KEY: ${{ steps.up.outputs.api_key }}
+ OSB_TEST_WORKERS: ${{ steps.up.outputs.workers }}
+ run: go test -count=1 -v ./ci/tests/api/...
+
+ - name: Tear down PR stack
+ if: always()
+ run: |
+ ./ci/pr/down.sh ${{ github.event.pull_request.number }} || true
diff --git a/.github/workflows/pr-strip-approval.yml b/.github/workflows/pr-strip-approval.yml
new file mode 100644
index 00000000..7e31ab4b
--- /dev/null
+++ b/.github/workflows/pr-strip-approval.yml
@@ -0,0 +1,23 @@
+name: Strip CI Approval On Push
+
+# Removes the osb-ci-approve label whenever a PR receives new commits, forcing
+# a maintainer to re-review the new SHA before integration tests can run again.
+# Pairs with pr-integration.yml, which only fires on the `labeled` event.
+on:
+ pull_request:
+ types: [synchronize]
+
+permissions:
+ pull-requests: write
+
+jobs:
+ strip:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Remove osb-ci-approve label
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: |
+ gh pr edit ${{ github.event.pull_request.number }} \
+ --remove-label osb-ci-approve \
+ -R ${{ github.repository }} 2>/dev/null || true
diff --git a/ci/persistent/down.sh b/ci/persistent/down.sh
new file mode 100755
index 00000000..b327fc01
--- /dev/null
+++ b/ci/persistent/down.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# Tear down the entire opencomputer-ci RG. Big red button — only for full reset.
+# Storage account contents (compat-corpus + checkpoints) and KV secrets are
+# unrecoverable after this runs (KV soft-delete retains for 90 days; storage
+# is gone). Confirm before invoking.
+
+set -euo pipefail
+
+RG="${RG:-opencomputer-ci}"
+
+if ! az group exists --name "$RG" 2>/dev/null | grep -q true; then
+ echo "RG $RG doesn't exist; nothing to do."
+ exit 0
+fi
+
+echo ">>> About to delete EVERYTHING in resource group: $RG"
+echo " (KV: opencomputer-ci-kv goes into 90-day soft-delete)"
+echo " (Storage: data is permanently lost)"
+read -r -p "Type 'yes' to proceed: " confirm
+[[ "$confirm" == "yes" ]] || { echo "aborted."; exit 1; }
+
+az group delete -n "$RG" --yes --no-wait
+echo "delete initiated (running in background, takes ~5 min to complete)."
diff --git a/ci/persistent/gc.sh b/ci/persistent/gc.sh
new file mode 100755
index 00000000..e253a853
--- /dev/null
+++ b/ci/persistent/gc.sh
@@ -0,0 +1,62 @@
+#!/usr/bin/env bash
+# Garbage-collect stale PR stacks (older than MAX_AGE_HOURS, default 24).
+#
+# Lists pr-*-server VMs, checks their creation time, and tears down any older
+# than the threshold. Designed to run from a GitHub Actions scheduled workflow
+# (daily). Safe to re-run; idempotent.
+#
+# Usage: ./gc.sh # default: stacks >24h old
+# MAX_AGE_HOURS=4 ./gc.sh # tighter window
+
+set -euo pipefail
+
+RG="${RG:-opencomputer-ci}"
+MAX_AGE_HOURS="${MAX_AGE_HOURS:-24}"
+DOWN_SCRIPT="${DOWN_SCRIPT:-$(dirname "$0")/../pr/down.sh}"
+
+[[ -x "$DOWN_SCRIPT" ]] || { echo "FATAL: $DOWN_SCRIPT not executable"; exit 1; }
+
+echo ">>> scanning pr-*-server VMs in $RG (cutoff: ${MAX_AGE_HOURS}h)"
+
+cutoff_epoch=$(($(date -u +%s) - MAX_AGE_HOURS * 3600))
+
+# VM names don't contain whitespace, so simple word-splitting works (and is
+# portable to macOS bash 3.2, which lacks mapfile).
+VMS=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server')].name" -o tsv)
+if [[ -z "$VMS" ]]; then
+ echo "no PR stacks found."
+ exit 0
+fi
+
+KILLED=0
+for vm in $VMS; do
+ created=$(az vm show -g "$RG" -n "$vm" --query "timeCreated" -o tsv 2>/dev/null || echo "")
+ if [[ -z "$created" ]]; then
+ echo " $vm: no timeCreated metadata, skipping"
+ continue
+ fi
+
+ # Strip fractional seconds + parse to epoch (BSD/macOS and Linux tolerant).
+ ts=$(echo "$created" | sed -E 's/\.[0-9]+//; s/\+.*//')
+ if date --version >/dev/null 2>&1; then
+ created_epoch=$(date -u -d "$ts" +%s)
+ else
+ created_epoch=$(date -u -j -f "%Y-%m-%dT%H:%M:%S" "$ts" +%s)
+ fi
+
+ age_h=$(( ($(date -u +%s) - created_epoch) / 3600 ))
+ pr_num=$(echo "$vm" | sed -E 's/^pr-([0-9]+)-server$/\1/')
+
+ if [[ "$created_epoch" -lt "$cutoff_epoch" ]]; then
+ echo " $vm (PR $pr_num, age=${age_h}h) — TEARING DOWN"
+ if "$DOWN_SCRIPT" "$pr_num"; then
+ KILLED=$((KILLED + 1))
+ else
+ echo " down.sh failed for PR $pr_num — continuing"
+ fi
+ else
+ echo " $vm (PR $pr_num, age=${age_h}h) — keeping"
+ fi
+done
+
+echo "DONE. tore down $KILLED stale stack(s)."
diff --git a/ci/persistent/up.sh b/ci/persistent/up.sh
new file mode 100755
index 00000000..300bca50
--- /dev/null
+++ b/ci/persistent/up.sh
@@ -0,0 +1,205 @@
+#!/usr/bin/env bash
+# Bring up the persistent layer for the opencomputer-ci test stack.
+# Idempotent: safe to re-run. Existing resources are skipped or updated in place.
+#
+# Creates: VNet+subnets+NSGs, two managed identities, Key Vault, storage account
+# (with checkpoints/ and compat-corpus/ containers), and a single B4ms VM running
+# Postgres 16 + Redis 7 via systemd. Generates secrets and stores them in KV.
+#
+# Run once. To tear down: ./down.sh.
+
+set -euo pipefail
+
+RG="${RG:-opencomputer-ci}"
+LOCATION="${LOCATION:-centralus}"
+VNET="oc-ci-vnet"
+KV="${KV:-opencomputer-ci-kv}"
+STORAGE="${STORAGE:-occiblob$(openssl rand -hex 2)}" # globally unique
+DATA_VM="oc-ci-data"
+DATA_IDENTITY="osb-ci-data-identity"
+WORKER_IDENTITY="osb-ci-worker-identity"
+SSH_KEY="${SSH_KEY:-$HOME/.ssh/opencomputer-ci.pub}"
+
+[[ -f "$SSH_KEY" ]] || { echo "FATAL: SSH key $SSH_KEY not found"; exit 1; }
+
+ME=$(az ad signed-in-user show --query id -o tsv)
+SUB=$(az account show --query id -o tsv)
+echo ">>> subscription=$SUB me=$ME rg=$RG region=$LOCATION"
+
+echo ">>> [1/9] resource group"
+az group create -n "$RG" -l "$LOCATION" --tags purpose=ci -o none
+
+echo ">>> [2/9] vnet + subnets + nsgs"
+az network vnet create -g "$RG" -n "$VNET" \
+ --address-prefix 10.210.0.0/16 \
+ --subnet-name data --subnet-prefix 10.210.1.0/24 \
+ -o none
+az network vnet subnet show -g "$RG" --vnet-name "$VNET" -n compute -o none 2>/dev/null \
+ || az network vnet subnet create -g "$RG" --vnet-name "$VNET" \
+ -n compute --address-prefix 10.210.2.0/24 -o none
+
+az network nsg create -g "$RG" -n oc-ci-nsg-data -o none
+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-pg-compute \
+ --priority 100 --source-address-prefixes 10.210.2.0/24 --destination-port-ranges 5432 \
+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true
+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-redis-compute \
+ --priority 110 --source-address-prefixes 10.210.2.0/24 --destination-port-ranges 6379 \
+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true
+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-data -n allow-ssh \
+ --priority 200 --destination-port-ranges 22 \
+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true
+az network vnet subnet update -g "$RG" --vnet-name "$VNET" -n data \
+ --network-security-group oc-ci-nsg-data -o none
+
+az network nsg create -g "$RG" -n oc-ci-nsg-compute -o none
+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-compute -n allow-ssh \
+ --priority 100 --destination-port-ranges 22 \
+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true
+az network nsg rule create -g "$RG" --nsg-name oc-ci-nsg-compute -n allow-http \
+ --priority 110 --destination-port-ranges 8080 8081 9090 \
+ --protocol Tcp --access Allow --direction Inbound -o none 2>/dev/null || true
+az network vnet subnet update -g "$RG" --vnet-name "$VNET" -n compute \
+ --network-security-group oc-ci-nsg-compute -o none
+
+echo ">>> [3/9] managed identities"
+az identity create -g "$RG" -n "$DATA_IDENTITY" -o none
+az identity create -g "$RG" -n "$WORKER_IDENTITY" -o none
+DATA_PRINCIPAL=$(az identity show -g "$RG" -n "$DATA_IDENTITY" --query principalId -o tsv)
+WORKER_PRINCIPAL=$(az identity show -g "$RG" -n "$WORKER_IDENTITY" --query principalId -o tsv)
+DATA_IDENTITY_ID=$(az identity show -g "$RG" -n "$DATA_IDENTITY" --query id -o tsv)
+WORKER_IDENTITY_ID=$(az identity show -g "$RG" -n "$WORKER_IDENTITY" --query id -o tsv)
+
+echo ">>> [4/9] key vault (RBAC mode)"
+az keyvault show -n "$KV" -o none 2>/dev/null \
+ || az keyvault create -g "$RG" -n "$KV" --enable-rbac-authorization true -o none
+KV_SCOPE="/subscriptions/$SUB/resourceGroups/$RG/providers/Microsoft.KeyVault/vaults/$KV"
+
+az role assignment create --assignee-object-id "$ME" --assignee-principal-type User \
+ --role "Key Vault Administrator" --scope "$KV_SCOPE" -o none 2>/dev/null || true
+az role assignment create --assignee-object-id "$DATA_PRINCIPAL" --assignee-principal-type ServicePrincipal \
+ --role "Key Vault Secrets User" --scope "$KV_SCOPE" -o none 2>/dev/null || true
+az role assignment create --assignee-object-id "$WORKER_PRINCIPAL" --assignee-principal-type ServicePrincipal \
+ --role "Key Vault Secrets User" --scope "$KV_SCOPE" -o none 2>/dev/null || true
+
+echo ">>> waiting 45s for RBAC propagation..."
+sleep 45
+
+echo ">>> [5/9] generating + storing secrets"
+gen_or_keep() {
+ local name="$1" gen_cmd="$2"
+ if az keyvault secret show --vault-name "$KV" --name "$name" -o none 2>/dev/null; then
+ echo " $name (kept)"
+ else
+ local val
+ val=$(eval "$gen_cmd")
+ az keyvault secret set --vault-name "$KV" --name "$name" --value "$val" -o none
+ echo " $name (generated)"
+ fi
+}
+gen_or_keep "pg-password" "openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 32"
+gen_or_keep "redis-password" "openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 32"
+gen_or_keep "server-api-key" "echo osb_ci_\$(openssl rand -hex 32)"
+gen_or_keep "server-jwt-secret" "openssl rand -hex 32"
+gen_or_keep "worker-jwt-secret" "az keyvault secret show --vault-name $KV --name server-jwt-secret --query value -o tsv"
+gen_or_keep "server-secret-encryption-key" "openssl rand -hex 32"
+
+PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv)
+REDIS_PASS=$(az keyvault secret show --vault-name "$KV" --name redis-password --query value -o tsv)
+
+echo ">>> [6/9] storage account + containers"
+if ! az storage account show -g "$RG" -n "$STORAGE" -o none 2>/dev/null; then
+ EXISTING=$(az keyvault secret show --vault-name "$KV" --name storage-account-name --query value -o tsv 2>/dev/null || echo "")
+ if [[ -n "$EXISTING" ]]; then STORAGE="$EXISTING"; fi
+fi
+if ! az storage account show -g "$RG" -n "$STORAGE" -o none 2>/dev/null; then
+ az storage account create -g "$RG" -n "$STORAGE" -l "$LOCATION" \
+ --sku Standard_LRS --kind StorageV2 -o none
+ az keyvault secret set --vault-name "$KV" --name storage-account-name --value "$STORAGE" -o none
+fi
+STORAGE_KEY=$(az storage account keys list -g "$RG" -n "$STORAGE" --query "[0].value" -o tsv)
+az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n checkpoints -o none 2>/dev/null || true
+az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n compat-corpus -o none 2>/dev/null || true
+az keyvault secret set --vault-name "$KV" --name worker-s3-access-key --value "$STORAGE" -o none
+az keyvault secret set --vault-name "$KV" --name worker-s3-secret-key --value "$STORAGE_KEY" -o none
+
+echo ">>> [7/9] data VM cloud-init"
+CLOUD_INIT=$(mktemp)
+trap "rm -f $CLOUD_INIT" EXIT
+cat > "$CLOUD_INIT" <<EOF
+#cloud-config
+package_update: true
+packages:
+ - postgresql-16
+ - postgresql-contrib-16
+ - redis-server
+runcmd:
+ - bash -c "echo \"listen_addresses = '*'\" >> /etc/postgresql/16/main/postgresql.conf"
+ - bash -c "echo 'host all all 10.210.0.0/16 md5' >> /etc/postgresql/16/main/pg_hba.conf"
+ - sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '${PG_PASS}';"
+ - sudo -u postgres psql -c "CREATE USER osbciuser WITH PASSWORD '${PG_PASS}' CREATEDB;"
+ - sudo -u postgres psql -c "GRANT pg_read_all_data, pg_write_all_data TO osbciuser;"
+ - sed -i 's/^bind 127.0.0.1.*/bind 0.0.0.0/' /etc/redis/redis.conf
+ - sed -i 's|^# requirepass.*|requirepass ${REDIS_PASS}|' /etc/redis/redis.conf
+ - sed -i 's/^protected-mode yes/protected-mode no/' /etc/redis/redis.conf
+ - systemctl restart postgresql
+ - systemctl restart redis-server
+ - systemctl enable postgresql redis-server
+EOF
+
+echo ">>> [8/9] data VM"
+if ! az vm show -g "$RG" -n "$DATA_VM" -o none 2>/dev/null; then
+ az vm create -g "$RG" -n "$DATA_VM" \
+ --image Ubuntu2404 \
+ --size Standard_B4ms \
+ --vnet-name "$VNET" --subnet data \
+ --public-ip-address "${DATA_VM}-pip" \
+ --public-ip-sku Standard \
+ --admin-username azureuser \
+ --ssh-key-values "$SSH_KEY" \
+ --assign-identity "$DATA_IDENTITY_ID" \
+ --custom-data "$CLOUD_INIT" \
+ --os-disk-size-gb 64 \
+ --nsg oc-ci-nsg-data \
+ -o none
+else
+ echo " $DATA_VM already exists (cloud-init not re-run; rebuild with down.sh + up.sh)"
+fi
+
+DATA_VM_PIP=$(az vm show -d -g "$RG" -n "$DATA_VM" --query publicIps -o tsv)
+DATA_VM_PRIVATE=$(az vm show -d -g "$RG" -n "$DATA_VM" --query privateIps -o tsv)
+
+echo ">>> [9/9] connection strings into KV"
+az keyvault secret set --vault-name "$KV" --name data-vm-private-ip --value "$DATA_VM_PRIVATE" -o none
+az keyvault secret set --vault-name "$KV" --name server-database-url \
+ --value "postgres://osbciuser:${PG_PASS}@${DATA_VM_PRIVATE}:5432/postgres?sslmode=disable" -o none
+az keyvault secret set --vault-name "$KV" --name worker-database-url \
+ --value "postgres://osbciuser:${PG_PASS}@${DATA_VM_PRIVATE}:5432/postgres?sslmode=disable" -o none
+az keyvault secret set --vault-name "$KV" --name server-redis-url \
+ --value "redis://default:${REDIS_PASS}@${DATA_VM_PRIVATE}:6379/0" -o none
+az keyvault secret set --vault-name "$KV" --name worker-redis-url \
+ --value "redis://default:${REDIS_PASS}@${DATA_VM_PRIVATE}:6379/0" -o none
+
+cat <<DONE
+
+================================================================
+DONE. opencomputer-ci persistent layer is up.
+
+ resource group: $RG
+ region: $LOCATION
+ data VM: $DATA_VM public=$DATA_VM_PIP private=$DATA_VM_PRIVATE
+ key vault: $KV
+ storage: $STORAGE
+ data identity: $DATA_IDENTITY_ID
+ worker identity: $WORKER_IDENTITY_ID
+
+ postgres: postgres://osbciuser:***@${DATA_VM_PRIVATE}:5432/postgres
+ redis: redis://default:***@${DATA_VM_PRIVATE}:6379/0
+
+ smoke test: ./verify.sh
+ ssh: ssh azureuser@${DATA_VM_PIP}
+ cloud-init log: /var/log/cloud-init-output.log on the VM
+
+ IMPORTANT: cloud-init takes ~3-4 min after VM create to finish installing
+ Postgres + Redis. Run ./verify.sh after a few minutes.
+================================================================
+DONE
diff --git a/ci/persistent/verify.sh b/ci/persistent/verify.sh
new file mode 100755
index 00000000..0bca4329
--- /dev/null
+++ b/ci/persistent/verify.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# Smoke-test the persistent layer: SSH to data VM, prove Postgres + Redis are up
+# and listening on the data subnet, prove KV is reachable from the worker identity.
+
+set -euo pipefail
+
+RG="${RG:-opencomputer-ci}"
+KV="${KV:-opencomputer-ci-kv}"
+DATA_VM="oc-ci-data"
+
+DATA_VM_PIP=$(az vm show -d -g "$RG" -n "$DATA_VM" --query publicIps -o tsv)
+DATA_VM_PRIVATE=$(az vm show -d -g "$RG" -n "$DATA_VM" --query privateIps -o tsv)
+
+echo ">>> data VM: public=$DATA_VM_PIP private=$DATA_VM_PRIVATE"
+
+PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv)
+REDIS_PASS=$(az keyvault secret show --vault-name "$KV" --name redis-password --query value -o tsv)
+
+echo ">>> SSH check"
+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 azureuser@"$DATA_VM_PIP" "uptime" || {
+ echo "SSH failed — VM may still be cloud-init'ing. Wait 1-2 min and re-run."
+ exit 1
+}
+
+echo ">>> postgres check (psql via SSH tunnel)"
+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "PGPASSWORD='$PG_PASS' psql -h localhost -U osbciuser -d postgres -c 'SELECT version();'"
+
+echo ">>> redis check"
+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "redis-cli -a '$REDIS_PASS' ping"
+
+echo ">>> postgres listening on 0.0.0.0:5432?"
+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "ss -tln | grep ':5432' || echo 'NOT LISTENING'"
+
+echo ">>> redis listening on 0.0.0.0:6379?"
+ssh -i ~/.ssh/opencomputer-ci -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null azureuser@"$DATA_VM_PIP" "ss -tln | grep ':6379' || echo 'NOT LISTENING'"
+
+echo
+echo "all checks passed."
diff --git a/ci/pr/down.sh b/ci/pr/down.sh
new file mode 100755
index 00000000..832c5c58
--- /dev/null
+++ b/ci/pr/down.sh
@@ -0,0 +1,67 @@
+#!/usr/bin/env bash
+# Tear down a PR's ephemeral test stack.
+#
+# Usage: ./down.sh <PR_NUM>
+#
+# Deletes: pr-<num>-* VMs (and their NICs/disks/IPs), pr-<num>-checkpoints
+# storage container, and the pr_<num> Postgres database. Leaves persistent
+# resources (data VM, KV, storage account) untouched.
+
+set -euo pipefail
+
+PR_NUM="${1:-}"
+[[ -n "$PR_NUM" ]] || { echo "usage: $0 <PR_NUM>"; exit 1; }
+[[ "$PR_NUM" =~ ^[0-9]+$ ]] || { echo "PR_NUM must be numeric"; exit 1; }
+
+RG="opencomputer-ci"
+KV="opencomputer-ci-kv"
+SSH_KEY_PRIV="$HOME/.ssh/opencomputer-ci"
+SSH_OPTS="-i $SSH_KEY_PRIV -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
+
+DATA_VM_PIP=$(az vm show -d -g "$RG" -n oc-ci-data --query publicIps -o tsv 2>/dev/null || echo "")
+PG_PASS=$(az keyvault secret show --vault-name "$KV" --name pg-password --query value -o tsv 2>/dev/null || echo "")
+STORAGE=$(az keyvault secret show --vault-name "$KV" --name storage-account-name --query value -o tsv 2>/dev/null || echo "")
+STORAGE_KEY=$(az keyvault secret show --vault-name "$KV" --name worker-s3-secret-key --query value -o tsv 2>/dev/null || echo "")
+
+DB_NAME="pr_$PR_NUM"
+CONTAINER="pr-${PR_NUM}-checkpoints"
+
+echo ">>> [1/3] delete VMs (and their NICs/disks/IPs)"
+VMS=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-${PR_NUM}-')].name" -o tsv 2>/dev/null || echo "")
+if [[ -z "$VMS" ]]; then
+ echo " no pr-${PR_NUM}-* VMs found"
+else
+ for vm in $VMS; do
+ echo " $vm"
+ osdisk=$(az vm show -g "$RG" -n "$vm" --query "storageProfile.osDisk.name" -o tsv 2>/dev/null || echo "")
+ nic_ids=$(az vm show -g "$RG" -n "$vm" --query "networkProfile.networkInterfaces[].id" -o tsv 2>/dev/null || echo "")
+ pip_name="${vm}-pip"
+ az vm delete -g "$RG" -n "$vm" --yes -o none
+ for nic_id in $nic_ids; do
+ az network nic delete --ids "$nic_id" -o none 2>/dev/null || true
+ done
+ # Disk deletion can race with VM deletion (Azure detach lag); retry.
+ if [[ -n "$osdisk" ]]; then
+ for _ in 1 2 3 4 5; do
+ if az disk delete -g "$RG" -n "$osdisk" --yes -o none 2>/dev/null; then
+ break
+ fi
+ sleep 5
+ done
+ fi
+ az network public-ip delete -g "$RG" -n "$pip_name" -o none 2>/dev/null || true
+ done
+fi
+
+echo ">>> [2/3] DROP DATABASE $DB_NAME"
+if [[ -n "$DATA_VM_PIP" && -n "$PG_PASS" ]]; then
+ ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" \
+ "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -c \"DROP DATABASE IF EXISTS $DB_NAME WITH (FORCE);\""
+fi
+
+echo ">>> [3/3] delete container $CONTAINER"
+if [[ -n "$STORAGE" && -n "$STORAGE_KEY" ]]; then
+ az storage container delete --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null || true
+fi
+
+echo "DONE. PR-$PR_NUM stack torn down."
diff --git a/ci/pr/up.sh b/ci/pr/up.sh
new file mode 100755
index 00000000..18e42ac3
--- /dev/null
+++ b/ci/pr/up.sh
@@ -0,0 +1,456 @@
+#!/usr/bin/env bash
+# Bring up an ephemeral test stack for a PR.
+#
+# Usage: ./up.sh <PR_NUM> [WORKERS=0]
+#
+# Creates: pr_<num> Postgres database, pr-<num>-checkpoints storage container,
+# pr-<num>-server VM, and N pr-<num>-worker-X VMs. Deploys server + worker
+# binaries (built from the current tree) and replaces the gallery-baked agent
+# inside default.ext4 with the PR's agent. Waits for /healthz green and worker
+# registration. Echoes connection info.
+
+set -euo pipefail
+
+PR_NUM="${1:-}"
+WORKERS="${2:-0}"
+
+[[ -n "$PR_NUM" ]] || { echo "usage: $0 <PR_NUM> [WORKERS=0]"; exit 1; }
+[[ "$PR_NUM" =~ ^[0-9]+$ ]] || { echo "PR_NUM must be numeric"; exit 1; }
+[[ "$WORKERS" =~ ^[0-9]+$ ]] || { echo "WORKERS must be numeric"; exit 1; }
+
+RG="opencomputer-ci"
+LOCATION="${CI_LOCATION:-eastus2}"
+KV="opencomputer-ci-kv"
+VNET="oc-ci-vnet"
+SUBNET="compute"
+SSH_KEY_PRIV="$HOME/.ssh/opencomputer-ci"
+SSH_KEY_PUB="$HOME/.ssh/opencomputer-ci.pub"
+SSH_OPTS="-i $SSH_KEY_PRIV -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
+MAX_CONCURRENT_PRS="${MAX_CONCURRENT_PRS:-8}"
+WORKER_SIZE="${WORKER_SIZE:-Standard_D16ads_v7}"
+
+# Prod gallery image — CI grants opensandbox-test-gh-action SP Reader on this.
+WORKER_IMAGE_VERSION="${WORKER_IMAGE_VERSION:-1.0.66}"
+WORKER_IMAGE_ID="/subscriptions/070cd7a5-4e38-4ad2-9f40-bf261000a040/resourceGroups/opencomputer-prod/providers/Microsoft.Compute/galleries/oc_prod_gallery/images/osb-worker-v7/versions/${WORKER_IMAGE_VERSION}"
+
+REPO_ROOT=$(git -C "$(dirname "$0")" rev-parse --show-toplevel)
+
+ACTIVE=$(az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server') && name != 'pr-${PR_NUM}-server'] | length(@)" -o tsv)
+if [[ "$ACTIVE" -ge "$MAX_CONCURRENT_PRS" ]]; then
+ echo "FATAL: $ACTIVE PR stacks already active (cap=$MAX_CONCURRENT_PRS). Wait or tear one down."
+ az vm list -g "$RG" --query "[?starts_with(name,'pr-') && ends_with(name,'-server')].{name:name,created:timeCreated}" -o table
+ exit 1
+fi
+
+echo ">>> [0/9] read persistent state from KV"
+kv() { az keyvault secret show --vault-name "$KV" --name "$1" --query value -o tsv; }
+DATA_VM_PRIV=$(kv data-vm-private-ip)
+DATA_VM_PIP=$(az vm show -d -g "$RG" -n oc-ci-data --query publicIps -o tsv)
+PG_PASS=$(kv pg-password)
+REDIS_PASS=$(kv redis-password)
+API_KEY=$(kv server-api-key)
+JWT=$(kv server-jwt-secret)
+ENC_KEY=$(kv server-secret-encryption-key)
+STORAGE=$(kv storage-account-name)
+STORAGE_KEY=$(kv worker-s3-secret-key)
+
+DB_NAME="pr_$PR_NUM"
+CONTAINER="pr-${PR_NUM}-checkpoints"
+SERVER_VM="pr-${PR_NUM}-server"
+
+SCRATCH=$(mktemp -d)
+trap "rm -rf $SCRATCH" EXIT
+
+echo ">>> [1/9] build linux/amd64 binaries (server + worker + agent)"
+SERVER_BIN="$SCRATCH/opensandbox-server"
+WORKER_BIN="$SCRATCH/opensandbox-worker"
+AGENT_BIN="$SCRATCH/osb-agent"
+(cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$SERVER_BIN" ./cmd/server/) >/dev/null
+if [[ "$WORKERS" -gt 0 ]]; then
+ (cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$WORKER_BIN" ./cmd/worker/) >/dev/null
+ (cd "$REPO_ROOT" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o "$AGENT_BIN" ./cmd/agent/) >/dev/null
+ echo " current: server=$(du -h "$SERVER_BIN" | cut -f1) worker=$(du -h "$WORKER_BIN" | cut -f1) agent=$(du -h "$AGENT_BIN" | cut -f1)"
+else
+ echo " server=$(du -h "$SERVER_BIN" | cut -f1) (workers=0, skipping worker+agent build)"
+fi
+
+# Optional cross-version setup: if BASELINE_FROM_GALLERY=1 and WORKERS>=2,
+# worker 1 keeps the gallery image's pre-baked agent + worker binaries (= the
+# current prod golden), while workers 2..N get the PR's overrides. Lets the
+# migrate test exercise real old-golden → new-golden upgrade on every PR.
+BASELINE_FROM_GALLERY="${BASELINE_FROM_GALLERY:-0}"
+if [[ "$BASELINE_FROM_GALLERY" == "1" && "$WORKERS" -lt 2 ]]; then
+ echo " BASELINE_FROM_GALLERY=1 requires WORKERS>=2, ignoring"
+ BASELINE_FROM_GALLERY=0
+fi
+if [[ "$BASELINE_FROM_GALLERY" == "1" ]]; then
+ echo " cross-version mode: worker 1 uses gallery-baked binaries (current prod golden)"
+fi
+
+echo ">>> [2/9] CREATE DATABASE $DB_NAME"
+ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" \
+ "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -tc \"SELECT 1 FROM pg_database WHERE datname='$DB_NAME'\" | grep -q 1 \
+ || PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d postgres -c \"CREATE DATABASE $DB_NAME OWNER osbciuser;\""
+
+echo ">>> [3/9] storage container $CONTAINER"
+# Azure soft-deletes containers and refuses recreation for ~30s after delete.
+# If down.sh just ran for this PR, the first `container create` will silently
+# fail and workers boot without a container to upload bases to. Poll until
+# the container actually exists.
+for i in $(seq 1 24); do
+ if az storage container show --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null; then
+ break
+ fi
+ out=$(az storage container create --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" 2>&1 || true)
+ if echo "$out" | grep -q '"created": true'; then
+ break
+ fi
+ echo " container not ready yet (attempt $i, retrying in 5s)"
+ sleep 5
+done
+if ! az storage container show --account-name "$STORAGE" --account-key "$STORAGE_KEY" -n "$CONTAINER" -o none 2>/dev/null; then
+ echo "FATAL: container $CONTAINER did not become available"
+ exit 1
+fi
+
+echo ">>> [4/9] provision $SERVER_VM"
+if ! az vm show -g "$RG" -n "$SERVER_VM" -o none 2>/dev/null; then
+ az vm create -g "$RG" -n "$SERVER_VM" \
+ --image Ubuntu2404 \
+ --size Standard_B2s \
+ --vnet-name "$VNET" --subnet "$SUBNET" \
+ --public-ip-address "${SERVER_VM}-pip" \
+ --public-ip-sku Standard \
+ --admin-username azureuser \
+ --ssh-key-values "$SSH_KEY_PUB" \
+ --os-disk-size-gb 32 \
+ --nsg oc-ci-nsg-compute \
+ --tags purpose=ci pr="$PR_NUM" role=server \
+ -o none
+fi
+SERVER_PIP=$(az vm show -d -g "$RG" -n "$SERVER_VM" --query publicIps -o tsv)
+SERVER_PRIV=$(az vm show -d -g "$RG" -n "$SERVER_VM" --query privateIps -o tsv)
+
+echo ">>> [5/9] wait for SSH on $SERVER_PIP"
+for _ in $(seq 1 40); do
+ ssh $SSH_OPTS -o ConnectTimeout=5 azureuser@"$SERVER_PIP" "echo ok" 2>/dev/null | grep -q ok && break
+ sleep 5
+done
+
+echo ">>> [6/9] deploy server (env + binary + systemd)"
+cat > "$SCRATCH/server.env" <<EOF
+OPENSANDBOX_MODE=server
+OPENSANDBOX_PORT=8080
+OPENSANDBOX_HTTP_ADDR=http://$SERVER_PIP:8080
+OPENSANDBOX_DATABASE_URL=postgres://osbciuser:$PG_PASS@$DATA_VM_PRIV:5432/$DB_NAME?sslmode=disable
+OPENSANDBOX_REDIS_URL=redis://default:$REDIS_PASS@$DATA_VM_PRIV:6379/0
+OPENSANDBOX_API_KEY=$API_KEY
+OPENSANDBOX_JWT_SECRET=$JWT
+OPENSANDBOX_SECRET_ENCRYPTION_KEY=$ENC_KEY
+OPENSANDBOX_REGION=$LOCATION
+OPENSANDBOX_S3_BUCKET=$CONTAINER
+OPENSANDBOX_S3_ENDPOINT=https://$STORAGE.blob.core.windows.net
+OPENSANDBOX_S3_REGION=$LOCATION
+OPENSANDBOX_S3_ACCESS_KEY_ID=$STORAGE
+OPENSANDBOX_S3_SECRET_ACCESS_KEY=$STORAGE_KEY
+OPENSANDBOX_S3_FORCE_PATH_STYLE=false
+OPENSANDBOX_MIN_WORKERS=0
+OPENSANDBOX_MAX_WORKERS=$WORKERS
+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024
+OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=20480
+OPENSANDBOX_SANDBOX_DOMAIN=ci.local
+OPENSANDBOX_IDLE_RESERVE=0
+EOF
+
+cat > "$SCRATCH/server.service" <<EOF
+[Unit]
+Description=opensandbox server (PR $PR_NUM)
+After=network.target
+
+[Service]
+Type=simple
+ExecStart=/opt/opensandbox/server
+EnvironmentFile=/etc/opensandbox/server.env
+WorkingDirectory=/opt/opensandbox
+Restart=on-failure
+RestartSec=5
+KillMode=process
+TimeoutStopSec=60
+
+[Install]
+WantedBy=multi-user.target
+EOF
+
+scp $SSH_OPTS "$SERVER_BIN" "$SCRATCH/server.env" "$SCRATCH/server.service" azureuser@"$SERVER_PIP":/tmp/ >/dev/null
+ssh $SSH_OPTS azureuser@"$SERVER_PIP" "sudo bash -se" <<'REMOTE'
+set -e
+mkdir -p /opt/opensandbox /etc/opensandbox
+mv /tmp/opensandbox-server /opt/opensandbox/server
+chmod +x /opt/opensandbox/server
+mv /tmp/server.env /etc/opensandbox/server.env
+chmod 600 /etc/opensandbox/server.env
+mv /tmp/server.service /etc/systemd/system/opensandbox-server.service
+systemctl daemon-reload
+systemctl enable opensandbox-server >/dev/null 2>&1
+systemctl restart opensandbox-server
+REMOTE
+
+echo ">>> [7/9] wait for /healthz"
+HEALTHY=0
+for i in $(seq 1 40); do
+ resp=$(curl -s -m 3 "http://$SERVER_PIP:8080/healthz" 2>/dev/null || true)
+ if [[ -n "$resp" ]] && echo "$resp" | grep -qiE "ok|status"; then
+ HEALTHY=1
+ echo " healthy after ${i}x3s"
+ break
+ fi
+ sleep 3
+done
+if [[ "$HEALTHY" == "0" ]]; then
+ echo " /healthz did not respond. server logs:"
+ ssh $SSH_OPTS azureuser@"$SERVER_PIP" "sudo journalctl -u opensandbox-server --no-pager -n 50 || true"
+ exit 1
+fi
+
+# Seed the static API key into pr_<num>.api_keys so PG-backed auth accepts it.
+# Server-mode validates X-API-Key against the api_keys table, not the env var.
+KEY_HASH=$(printf '%s' "$API_KEY" | { sha256sum 2>/dev/null || shasum -a 256; } | cut -d' ' -f1)
+KEY_PREFIX=$(printf '%s' "$API_KEY" | cut -c1-8)
+ssh $SSH_OPTS azureuser@"$DATA_VM_PIP" "PGPASSWORD='$PG_PASS' psql -h localhost -U postgres -d $DB_NAME" <<SQL >/dev/null
+INSERT INTO orgs (id, name, slug) VALUES ('00000000-0000-0000-0000-000000000001', 'CI Org', 'ci')
+ON CONFLICT DO NOTHING;
+INSERT INTO api_keys (id, org_id, key_hash, key_prefix, name)
+VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', '$KEY_HASH', '$KEY_PREFIX', 'ci-key')
+ON CONFLICT DO NOTHING;
+SQL
+
+# ─── Worker provisioning ────────────────────────────────────────────────────
+if [[ "$WORKERS" -gt 0 ]]; then
+ # Disk setup happens over SSH after VM boot. The gallery image's cloud-init
+ # config skips runcmd, so embedding it as custom-data is unreliable.
+
+ provision_worker() {
+ local idx=$1
+ local vm_name="pr-${PR_NUM}-worker-${idx}"
+ local stage="[worker $idx]"
+
+ if ! az vm show -g "$RG" -n "$vm_name" -o none 2>/dev/null; then
+ echo " $stage az vm create (cross-region first boot is ~3-4 min slower)"
+ az vm create -g "$RG" -n "$vm_name" \
+ --image "$WORKER_IMAGE_ID" \
+ --size "$WORKER_SIZE" \
+ --vnet-name "$VNET" --subnet "$SUBNET" \
+ --public-ip-address "${vm_name}-pip" \
+ --public-ip-sku Standard \
+ --admin-username azureuser \
+ --ssh-key-values "$SSH_KEY_PUB" \
+ --os-disk-size-gb 64 \
+ --nsg oc-ci-nsg-compute \
+ --tags purpose=ci pr="$PR_NUM" role=worker \
+ -o none
+ fi
+ local pip=$(az vm show -d -g "$RG" -n "$vm_name" --query publicIps -o tsv)
+ local priv=$(az vm show -d -g "$RG" -n "$vm_name" --query privateIps -o tsv)
+
+ echo " $stage waiting for SSH on $pip"
+ for _ in $(seq 1 60); do
+ ssh $SSH_OPTS -o ConnectTimeout=5 azureuser@"$pip" "echo ok" 2>/dev/null | grep -q ok && break
+ sleep 5
+ done
+
+ cat > "$SCRATCH/worker-${idx}.env" <<EOF
+OPENSANDBOX_MODE=worker
+OPENSANDBOX_VM_BACKEND=qemu
+OPENSANDBOX_QEMU_BIN=qemu-system-x86_64
+OPENSANDBOX_DATA_DIR=/data2/sandboxes
+OPENSANDBOX_KERNEL_PATH=/opt/opensandbox/vmlinux
+OPENSANDBOX_IMAGES_DIR=/data/firecracker/images
+OPENSANDBOX_GRPC_ADVERTISE=$priv:9090
+OPENSANDBOX_HTTP_ADDR=http://$priv:8081
+OPENSANDBOX_PORT=8081
+OPENSANDBOX_JWT_SECRET=$JWT
+OPENSANDBOX_WORKER_ID=w-pr${PR_NUM}-${idx}
+OPENSANDBOX_REGION=$LOCATION
+OPENSANDBOX_SANDBOX_DOMAIN=ci.local
+OPENSANDBOX_MAX_CAPACITY=20
+OPENSANDBOX_DEFAULT_SANDBOX_CPUS=2
+OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB=1024
+OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB=20480
+OPENSANDBOX_DATABASE_URL=postgres://osbciuser:$PG_PASS@$DATA_VM_PRIV:5432/$DB_NAME?sslmode=disable
+OPENSANDBOX_REDIS_URL=redis://default:$REDIS_PASS@$DATA_VM_PRIV:6379/0
+OPENSANDBOX_S3_BUCKET=$CONTAINER
+OPENSANDBOX_S3_ENDPOINT=https://$STORAGE.blob.core.windows.net
+OPENSANDBOX_S3_REGION=$LOCATION
+OPENSANDBOX_S3_ACCESS_KEY_ID=$STORAGE
+OPENSANDBOX_S3_SECRET_ACCESS_KEY=$STORAGE_KEY
+OPENSANDBOX_S3_FORCE_PATH_STYLE=false
+EOF
+
+ # Worker 1 uses the gallery image's pre-baked binaries when in cross-version
+ # mode — that represents the current prod golden. Other workers get the
+ # PR's freshly-built binaries.
+ local use_gallery_baseline=0
+ if [[ "$idx" == "1" && "$BASELINE_FROM_GALLERY" == "1" ]]; then
+ use_gallery_baseline=1
+ echo " $stage cross-version mode: keeping gallery-baked binaries"
+ fi
+ echo " $stage scp env"
+ scp $SSH_OPTS "$SCRATCH/worker-${idx}.env" azureuser@"$pip":/tmp/worker.env >/dev/null
+ if [[ "$use_gallery_baseline" == "0" ]]; then
+ echo " $stage scp PR-built worker + agent"
+ scp $SSH_OPTS "$WORKER_BIN" azureuser@"$pip":/tmp/opensandbox-worker >/dev/null
+ scp $SSH_OPTS "$AGENT_BIN" azureuser@"$pip":/tmp/osb-agent >/dev/null
+ fi
+ ssh $SSH_OPTS azureuser@"$pip" "sudo bash -se" <<REMOTE
+set -e
+USE_GALLERY_BASELINE=$use_gallery_baseline
+systemctl stop opensandbox-worker 2>/dev/null || true
+
+# Mount the local NVMe at /data2 with XFS+reflink (required by the worker's
+# QEMU manager). On D-d-series_v7 the local disk is an unformatted nvme device
+# that isn't the OS disk.
+if ! mountpoint -q /data2; then
+ ROOT_DEV=\$(findmnt -no SOURCE / | sed "s|p\\?[0-9]*\$||")
+ DEV=""
+ for d in /dev/nvme*n1; do
+ [ -b "\$d" ] || continue
+ [ "\$d" = "\$ROOT_DEV" ] && continue
+ if ! blkid "\$d" >/dev/null 2>&1; then DEV="\$d"; break; fi
+ done
+ if [ -z "\$DEV" ]; then echo "FATAL: no unformatted local NVMe found" >&2; exit 1; fi
+ echo "formatting \$DEV"
+ mkfs.xfs -m reflink=1 -f "\$DEV"
+ mkdir -p /data2
+ mount "\$DEV" /data2
+fi
+mkdir -p /data2/sandboxes /data2/checkpoints
+chmod 0777 /data2 /data2/sandboxes /data2/checkpoints
+
+mkdir -p /etc/opensandbox
+mv /tmp/worker.env /etc/opensandbox/worker.env
+chmod 600 /etc/opensandbox/worker.env
+
+if [[ "\$USE_GALLERY_BASELINE" == "1" ]]; then
+ echo "cross-version mode: keeping gallery-baked /usr/local/bin/opensandbox-worker and ext4-baked agent"
+else
+ # Override worker binary + swap PR's agent into default.ext4 via loop-mount.
+ mv /tmp/opensandbox-worker /usr/local/bin/opensandbox-worker
+ chmod +x /usr/local/bin/opensandbox-worker
+ mkdir -p /mnt/rootfs-${idx}
+ mount -o loop /data/firecracker/images/default.ext4 /mnt/rootfs-${idx}
+ cp /tmp/osb-agent /mnt/rootfs-${idx}/usr/local/bin/osb-agent
+ chmod +x /mnt/rootfs-${idx}/usr/local/bin/osb-agent
+ sync
+ umount /mnt/rootfs-${idx}
+ rm /tmp/osb-agent
+ # Drop any cached golden snapshot — agent change invalidates it.
+ rm -rf /data/sandboxes/golden /data2/sandboxes/golden 2>/dev/null || true
+fi
+
+systemctl daemon-reload
+systemctl enable opensandbox-worker >/dev/null 2>&1 || true
+systemctl restart opensandbox-worker
+REMOTE
+ echo " $stage ready (priv=$priv)"
+ }
+
+ echo ">>> [8/9] provision $WORKERS worker(s) in parallel"
+ pids=()
+ for i in $(seq 1 "$WORKERS"); do
+ provision_worker "$i" &
+ pids+=($!)
+ done
+ fail=0
+ for pid in "${pids[@]}"; do
+ if ! wait "$pid"; then fail=1; fi
+ done
+ if [[ "$fail" -ne 0 ]]; then
+ echo " one or more workers failed to provision"
+ exit 1
+ fi
+
+ echo ">>> wait for worker readiness via /api/workers (golden_version populated)"
+ REGISTERED=0
+ for i in $(seq 1 60); do
+ # A worker is "ready" when it shows up in /api/workers AND has golden_version
+ # set — that field is only populated after the golden snapshot finishes
+ # building (~25s post-startup), which is when the worker can actually
+ # accept sandbox creation requests.
+ ready=$(curl -s -m 5 -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/workers" 2>/dev/null \
+ | jq '[.[] // empty | select(.golden_version != null and .golden_version != "")] | length' 2>/dev/null || echo 0)
+ if [[ "$ready" =~ ^[0-9]+$ ]] && [[ "$ready" -ge "$WORKERS" ]]; then
+ REGISTERED=1
+ echo " $ready worker(s) ready (golden built) after ${i}x5s"
+ break
+ fi
+ sleep 5
+ done
+ if [[ "$REGISTERED" == "0" ]]; then
+ echo " workers did not register. Last /api/workers response:"
+ curl -s -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/workers" 2>&1 | head -20
+ echo " --- worker 1 logs:"
+ pip=$(az vm show -d -g "$RG" -n "pr-${PR_NUM}-worker-1" --query publicIps -o tsv 2>/dev/null || true)
+ [[ -n "$pip" ]] && ssh $SSH_OPTS azureuser@"$pip" "sudo journalctl -u opensandbox-worker --no-pager -n 50 || true"
+ exit 1
+ fi
+
+ # Warmup probe: golden_version populated means the snapshot is built, but
+ # the first exec round-trip (API → gRPC → vsock → agent → process spawn)
+ # often takes longer than tests' 30s HTTP timeout on a cold worker. Spin
+ # a throwaway sandbox + echo to confirm the full exec path is hot before
+ # declaring the stack ready.
+ echo ">>> warmup probe: spawn sandbox + echo + delete"
+ WARM=0
+ for i in $(seq 1 18); do
+ sbox=$(curl -s -m 30 -X POST -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"cpuCount":1,"memoryMB":1024,"diskMB":20480,"timeout":60}' \
+ "http://$SERVER_PIP:8080/api/sandboxes" 2>/dev/null | jq -r '.sandboxID // empty')
+ if [[ -n "$sbox" ]]; then
+ out=$(curl -s -m 30 -X POST -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"cmd":"echo","args":["warmup"],"timeout":10}' \
+ "http://$SERVER_PIP:8080/api/sandboxes/$sbox/exec/run" 2>/dev/null)
+ curl -s -X DELETE -H "X-API-Key: $API_KEY" "http://$SERVER_PIP:8080/api/sandboxes/$sbox" >/dev/null 2>&1
+ if echo "$out" | grep -q '"exitCode":0'; then
+ WARM=1
+ echo " warmup OK after ${i} attempt(s)"
+ break
+ fi
+ fi
+ sleep 5
+ done
+ if [[ "$WARM" == "0" ]]; then
+ echo " FATAL: warmup probe never succeeded (worker exec path not ready)"
+ exit 1
+ fi
+fi
+
+echo ">>> [9/9] DONE"
+
+# Emit step outputs for the GitHub Actions workflow.
+if [[ -n "${GITHUB_OUTPUT:-}" ]]; then
+ {
+ echo "server_url=http://$SERVER_PIP:8080"
+ echo "api_key=$API_KEY"
+ echo "workers=$WORKERS"
+ } >> "$GITHUB_OUTPUT"
+fi
+
+cat <<DONE
+
+================================================================
+PR-$PR_NUM stack is up.
+
+ server URL: http://$SERVER_PIP:8080
+ api key: $API_KEY
+ database: $DB_NAME (on data VM $DATA_VM_PRIV)
+ storage: $CONTAINER (account: $STORAGE)
+ workers: $WORKERS (image: osb-worker-v7:${WORKER_IMAGE_VERSION})
+
+ smoke: curl -H "X-API-Key: $API_KEY" http://$SERVER_PIP:8080/api/orgs
+ ssh server: ssh -i ~/.ssh/opencomputer-ci azureuser@$SERVER_PIP
+ ssh worker 1: ssh -i ~/.ssh/opencomputer-ci azureuser@\$(az vm show -d -g $RG -n pr-${PR_NUM}-worker-1 --query publicIps -o tsv 2>/dev/null)
+ logs: ssh ... 'sudo journalctl -u opensandbox-{server,worker} -f'
+ teardown: ./down.sh $PR_NUM
+================================================================
+DONE
diff --git a/ci/tests/api/auth_test.go b/ci/tests/api/auth_test.go
new file mode 100644
index 00000000..804afea3
--- /dev/null
+++ b/ci/tests/api/auth_test.go
@@ -0,0 +1,41 @@
+package api_test
+
+import (
+ "net/http"
+ "testing"
+)
+
+// TestAuth_RejectsBadKeys covers the three negative auth paths against an
+// authenticated endpoint (/api/workers, which requires a valid API key in PG).
+func TestAuth_RejectsBadKeys(t *testing.T) {
+ c := newClient(t)
+ cases := []struct {
+ name string
+ headers map[string]string
+ wantMin int // accept >= this
+ wantMax int // accept <= this (so 401 or 403 both pass)
+ }{
+ {"no key", map[string]string{}, 401, 403},
+ {"empty key", map[string]string{"X-API-Key": ""}, 401, 403},
+ {"wrong key", map[string]string{"X-API-Key": "osb_ci_definitely_not_a_real_key"}, 401, 403},
+ {"bearer of api key", map[string]string{"Authorization": "Bearer " + c.apiKey}, 401, 403},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ code, body := c.raw(t, http.MethodGet, "/api/workers", tc.headers)
+ if code < tc.wantMin || code > tc.wantMax {
+ t.Fatalf("want %d-%d, got %d (body=%q)", tc.wantMin, tc.wantMax, code, body)
+ }
+ })
+ }
+}
+
+func TestAuth_AcceptsValidKey(t *testing.T) {
+ c := newClient(t)
+ code, body := c.raw(t, http.MethodGet, "/api/workers", map[string]string{
+ "X-API-Key": c.apiKey,
+ })
+ if code != http.StatusOK {
+ t.Fatalf("/api/workers with valid key: want 200, got %d (body=%q)", code, body)
+ }
+}
diff --git a/ci/tests/api/checkpoints_test.go b/ci/tests/api/checkpoints_test.go
new file mode 100644
index 00000000..4db3f3cb
--- /dev/null
+++ b/ci/tests/api/checkpoints_test.go
@@ -0,0 +1,244 @@
+package api_test
+
+import (
+ "fmt"
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+)
+
+// TestCheckpoints_CreateAndFork covers the warm-cache checkpoint path:
+// create sandbox → checkpoint → wait status=ready → fork → verify keys.
+//
+// Key assertion: when status=ready, both rootfsS3Key and workspaceS3Key
+// must be non-empty. This catches the regression class where the worker's
+// async upload silently failed but the DB row was still marked ready
+// (leading to forks of empty workspaces). The /api/sandboxes/from-checkpoint
+// path then has real keys to download, exercising the upload-and-fetch flow.
+func TestCheckpoints_CreateAndFork(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping checkpoint test", envWorkers)
+ }
+ c := newClient(t)
+ sourceID, _ := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,
+ })
+ t.Logf("source sandbox: %s", sourceID)
+
+ // Write a marker into the workspace so we can verify the fork inherited it.
+ const marker = "ci-checkpoint-marker"
+ writeMarker(t, c, sourceID, marker)
+
+ // Step 2: create checkpoint
+ cpName := fmt.Sprintf("ci-cp-%d", time.Now().UnixNano())
+ var cp struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ Name string `json:"name"`
+ RootfsS3Key *string `json:"rootfsS3Key"`
+ WorkspaceS3Key *string `json:"workspaceS3Key"`
+ }
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sourceID+"/checkpoints",
+ map[string]any{"name": cpName}, &cp)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)
+ }
+ if cp.ID == "" || cp.Status != "processing" {
+ t.Fatalf("create checkpoint response: %+v", cp)
+ }
+ t.Logf("checkpoint created: id=%s status=processing", cp.ID)
+
+ // Step 3: poll until status=ready (or timeout). Empty sandboxes take ~20-40s.
+ deadline := time.Now().Add(5 * time.Minute)
+ var ready struct {
+ Status string
+ RootfsS3Key *string
+ WorkspaceS3Key *string
+ SizeBytes int64
+ }
+ for time.Now().Before(deadline) {
+ var cps []struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ RootfsS3Key *string `json:"rootfsS3Key"`
+ WorkspaceS3Key *string `json:"workspaceS3Key"`
+ SizeBytes int64 `json:"sizeBytes"`
+ }
+ code, err := c.do(t, http.MethodGet,
+ "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)
+ if err == nil && code == http.StatusOK {
+ for _, x := range cps {
+ if x.ID == cp.ID {
+ ready.Status = x.Status
+ ready.RootfsS3Key = x.RootfsS3Key
+ ready.WorkspaceS3Key = x.WorkspaceS3Key
+ ready.SizeBytes = x.SizeBytes
+ break
+ }
+ }
+ }
+ if ready.Status == "ready" || ready.Status == "failed" {
+ break
+ }
+ time.Sleep(3 * time.Second)
+ }
+ if ready.Status != "ready" {
+ t.Fatalf("checkpoint never reached ready (final status=%q)", ready.Status)
+ }
+ t.Logf("checkpoint ready: size=%d bytes", ready.SizeBytes)
+
+ // Step 4: critical regression check — keys must be populated.
+ if ready.RootfsS3Key == nil || *ready.RootfsS3Key == "" {
+ t.Errorf("checkpoint status=ready but rootfsS3Key is empty (regression: empty-key checkpoint)")
+ }
+ if ready.WorkspaceS3Key == nil || *ready.WorkspaceS3Key == "" {
+ t.Errorf("checkpoint status=ready but workspaceS3Key is empty (regression: empty-key checkpoint)")
+ }
+ if ready.SizeBytes <= 0 {
+ t.Errorf("checkpoint sizeBytes=%d (regression: size not persisted)", ready.SizeBytes)
+ }
+ if t.Failed() {
+ t.FailNow() // don't try forking against a broken checkpoint
+ }
+
+ // Step 5: fork — POST /api/sandboxes/from-checkpoint/:checkpointId
+ var fork struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err = c.do(t, http.MethodPost,
+ "/api/sandboxes/from-checkpoint/"+cp.ID,
+ map[string]any{
+ "cpuCount": 1,
+ "memoryMB": 1024,
+ "diskMB": 20480,
+ "timeout": 120,
+ }, &fork)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("fork: code=%d err=%v", code, err)
+ }
+ if fork.SandboxID == "" || fork.Status != "running" {
+ t.Fatalf("fork response: %+v", fork)
+ }
+ t.Logf("forked sandbox: %s on %s", fork.SandboxID, fork.WorkerID)
+ t.Cleanup(func() {
+ c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil)
+ c.do(t, http.MethodDelete,
+ "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)
+ })
+
+ // Step 6: confirm fork shows up in list
+ var sandboxes []struct {
+ SandboxID string `json:"sandboxID"`
+ }
+ code, err = c.do(t, http.MethodGet, "/api/sandboxes", nil, &sandboxes)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("list: %v code=%d", err, code)
+ }
+ var found bool
+ for _, s := range sandboxes {
+ if s.SandboxID == fork.SandboxID {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("fork %s not in /api/sandboxes list", fork.SandboxID)
+ }
+
+ // Step 7: verify the workspace state survived. This catches the
+ // "fork succeeded but workspace is empty" regression class (e.g. the
+ // empty-key bug where SetCheckpointReady got "" keys and forks landed
+ // on an empty rootfs).
+ time.Sleep(5 * time.Second) // post-fork agent readiness
+ if got := readMarker(t, c, fork.SandboxID); got != marker {
+ t.Errorf("fork workspace state: want marker=%q, got %q", marker, got)
+ }
+}
+
+// TestCheckpoints_MultipleForks creates a checkpoint, then forks it twice
+// back-to-back. With WORKERS>=2 the scheduler typically lands the second fork
+// on the worker that didn't create the checkpoint — that fork has to download
+// the rootfs/workspace from blob (cold path), which is the case where the
+// empty-key regression manifested (no local cache to fall back to, must use
+// real S3 keys). Without the keys, the worker errors loudly.
+func TestCheckpoints_MultipleForks(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping multi-fork test", envWorkers)
+ }
+ c := newClient(t)
+ sourceID, _ := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,
+ })
+ const marker = "ci-multi-fork-marker"
+ writeMarker(t, c, sourceID, marker)
+
+ cpName := fmt.Sprintf("ci-multi-cp-%d", time.Now().UnixNano())
+ var cp struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ }
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sourceID+"/checkpoints",
+ map[string]any{"name": cpName}, &cp)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)
+ }
+
+ // Wait for status=ready
+ deadline := time.Now().Add(5 * time.Minute)
+ for time.Now().Before(deadline) {
+ var cps []struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ }
+ c.do(t, http.MethodGet, "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)
+ var s string
+ for _, x := range cps {
+ if x.ID == cp.ID {
+ s = x.Status
+ break
+ }
+ }
+ if s == "ready" {
+ break
+ }
+ if s == "failed" {
+ t.Fatalf("checkpoint failed during multi-fork setup")
+ }
+ time.Sleep(3 * time.Second)
+ }
+ t.Cleanup(func() {
+ c.do(t, http.MethodDelete, "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)
+ })
+
+ // Two forks back-to-back. With 2+ workers the scheduler distributes,
+ // so at least one is on a worker that doesn't have the cache locally.
+ for i := 1; i <= 2; i++ {
+ var fork struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/from-checkpoint/"+cp.ID,
+ map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,
+ }, &fork)
+ if err != nil || code/100 != 2 || fork.SandboxID == "" {
+ t.Fatalf("fork %d: code=%d err=%v resp=%+v", i, code, err, fork)
+ }
+ t.Logf("fork %d: %s on %s (status=%s)", i, fork.SandboxID, fork.WorkerID, fork.Status)
+ t.Cleanup(func() {
+ c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil)
+ })
+ time.Sleep(5 * time.Second) // post-fork agent readiness
+ if got := readMarker(t, c, fork.SandboxID); got != marker {
+ t.Errorf("fork %d workspace: want marker=%q, got %q", i, marker, got)
+ }
+ }
+}
diff --git a/ci/tests/api/cli_test.go b/ci/tests/api/cli_test.go
new file mode 100644
index 00000000..8c1e0bfe
--- /dev/null
+++ b/ci/tests/api/cli_test.go
@@ -0,0 +1,65 @@
+package api_test
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// TestCLI_Smoke builds the oc CLI binary and exercises a few subcommands.
+// Catches argparse / output regressions invisible to direct-API tests.
+//
+// Builds via `go build` so the binary is consistent with the rest of the PR.
+// Skips if go isn't on PATH (shouldn't happen in CI).
+func TestCLI_Smoke(t *testing.T) {
+ if _, err := exec.LookPath("go"); err != nil {
+ t.Skip("go not on PATH")
+ }
+ root := repoRoot(t)
+ cliBin := filepath.Join(t.TempDir(), "oc")
+ build := exec.Command("go", "build", "-o", cliBin, "./cmd/oc")
+ build.Dir = root
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build oc: %v\n%s", err, out)
+ }
+
+ // --help: every CLI must expose usage. Catches malformed cobra trees.
+ out, err := exec.Command(cliBin, "--help").CombinedOutput()
+ if err != nil {
+ t.Fatalf("oc --help: %v\n%s", err, out)
+ }
+ if !strings.Contains(string(out), "Usage:") {
+ t.Errorf("oc --help: missing 'Usage:' in output: %q", out)
+ }
+
+ // version: smoke check that the version subcommand exists and exits 0
+ out, err = exec.Command(cliBin, "version").CombinedOutput()
+ if err != nil {
+ // version is optional in some CLIs — log but don't fail
+ t.Logf("oc version: %v (output=%q) — skipping version assertion", err, out)
+ } else if len(strings.TrimSpace(string(out))) == 0 {
+ t.Errorf("oc version: empty output")
+ }
+
+ // If we have a running stack, exercise an API-authenticated command.
+ server := os.Getenv(envServerURL)
+ apiKey := os.Getenv(envAPIKey)
+ if server == "" || apiKey == "" {
+ t.Logf("no live stack — skipping live CLI command test")
+ return
+ }
+ cmd := exec.Command(cliBin, "agent", "list")
+ cmd.Env = append(os.Environ(),
+ "OPENCOMPUTER_API_URL="+server,
+ "OPENCOMPUTER_API_KEY="+apiKey,
+ )
+ out, err = cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("oc agent list: %v\n%s", err, out)
+ }
+ // Just confirm it returned without error — the org may have zero agents.
+ t.Logf("oc agent list returned %d bytes", len(out))
+}
+
diff --git a/ci/tests/api/cross_golden_test.go b/ci/tests/api/cross_golden_test.go
new file mode 100644
index 00000000..266c6f86
--- /dev/null
+++ b/ci/tests/api/cross_golden_test.go
@@ -0,0 +1,138 @@
+package api_test
+
+import (
+ "fmt"
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+)
+
+// TestCheckpoint_ForkCrossGolden creates a checkpoint on a worker running the
+// OLD golden (gallery-baked binaries), drains that worker, then forks. The
+// fork lands on a worker running the NEW golden (PR binaries) and must
+// successfully resume the checkpoint's workspace.
+//
+// This is the canonical regression class: a customer's checkpoint was taken
+// against last week's golden, and now they fork after a rolling-replace
+// upgraded all workers. If the new code can't load the old checkpoint's
+// rootfs/workspace formats, every customer using that checkpoint breaks.
+//
+// Requires BASELINE_FROM_GALLERY=1 + WORKERS>=2 (i.e. distinct goldens on the
+// two workers). Skips if goldens are the same.
+func TestCheckpoint_ForkCrossGolden(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {
+ t.Skipf("%s<2, skipping cross-golden test", envWorkers)
+ }
+ c := newClient(t)
+
+ // Verify workers have distinct goldens; otherwise this test isn't testing
+ // the cross-golden path.
+ var workers []struct {
+ WorkerID string `json:"worker_id"`
+ GoldenVersion string `json:"golden_version"`
+ Draining bool `json:"draining"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("list workers: code=%d err=%v", code, err)
+ }
+ if len(workers) < 2 {
+ t.Skipf("need 2 workers, got %d", len(workers))
+ }
+ goldens := map[string]bool{}
+ for _, w := range workers {
+ if !w.Draining {
+ goldens[w.GoldenVersion] = true
+ }
+ }
+ if len(goldens) < 2 {
+ t.Skipf("workers share the same golden_version (%v); set BASELINE_FROM_GALLERY=1 in up.sh to get distinct goldens", goldens)
+ }
+
+ // Create sandbox, write marker
+ sourceID, sourceWorker := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,
+ })
+ sourceGolden := goldenVersionOf(t, c, sourceWorker)
+ t.Logf("source sandbox: %s on %s (golden=%s)", sourceID, sourceWorker, sourceGolden)
+
+ const marker = "ci-cross-golden-marker"
+ writeMarker(t, c, sourceID, marker)
+
+ // Create checkpoint against the source golden
+ cpName := fmt.Sprintf("ci-xgolden-%d", time.Now().UnixNano())
+ var cp struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ }
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sourceID+"/checkpoints",
+ map[string]any{"name": cpName}, &cp)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("create checkpoint: code=%d err=%v", code, err)
+ }
+ t.Cleanup(func() {
+ c.do(t, http.MethodDelete, "/api/sandboxes/"+sourceID+"/checkpoints/"+cp.ID, nil, nil)
+ })
+
+ // Wait for status=ready
+ deadline := time.Now().Add(5 * time.Minute)
+ for time.Now().Before(deadline) {
+ var cps []struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ }
+ c.do(t, http.MethodGet, "/api/sandboxes/"+sourceID+"/checkpoints", nil, &cps)
+ var s string
+ for _, x := range cps {
+ if x.ID == cp.ID {
+ s = x.Status
+ break
+ }
+ }
+ if s == "ready" {
+ break
+ }
+ if s == "failed" {
+ t.Fatalf("checkpoint failed during setup")
+ }
+ time.Sleep(3 * time.Second)
+ }
+ t.Logf("checkpoint ready (captured against golden %s)", sourceGolden)
+
+ // Drain the source worker so the fork lands on a different-golden worker.
+ drainWorker(t, c, sourceWorker)
+
+ // Fork
+ var fork struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/from-checkpoint/"+cp.ID,
+ map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,
+ }, &fork)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("fork: code=%d err=%v resp=%+v", code, err, fork)
+ }
+ if fork.SandboxID == "" || fork.Status != "running" {
+ t.Fatalf("fork response: %+v", fork)
+ }
+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+fork.SandboxID, nil, nil) })
+
+ // Verify fork landed on a DIFFERENT golden than the source
+ forkGolden := goldenVersionOf(t, c, fork.WorkerID)
+ t.Logf("fork: %s on %s (golden=%s)", fork.SandboxID, fork.WorkerID, forkGolden)
+ if forkGolden == sourceGolden {
+ t.Fatalf("fork landed on same-golden worker (%s); drain didn't redirect — expected cross-golden", forkGolden)
+ }
+
+ // Verify marker survived the cross-golden fork.
+ time.Sleep(5 * time.Second)
+ if got := readMarker(t, c, fork.SandboxID); got != marker {
+ t.Errorf("marker corrupted across golden boundary (%s → %s): want %q, got %q",
+ sourceGolden, forkGolden, marker, got)
+ }
+}
diff --git a/ci/tests/api/cross_worker_test.go b/ci/tests/api/cross_worker_test.go
new file mode 100644
index 00000000..3cd8582d
--- /dev/null
+++ b/ci/tests/api/cross_worker_test.go
@@ -0,0 +1,77 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+)
+
+// TestHibernate_WakeCrossWorker hibernates a sandbox on worker A, drains A so
+// the scheduler can't pick it again, then wakes — should land on worker B.
+// Verifies the workspace state survives the S3 round-trip + handoff.
+//
+// This is distinct from TestMigrate_CrossWorker: that one uses live migration
+// (direct TCP between workers). This one goes through blob storage, which is
+// the path customers feel during worker retirements / rolling-replace.
+func TestHibernate_WakeCrossWorker(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {
+ t.Skipf("%s<2, skipping cross-worker hibernate test", envWorkers)
+ }
+ c := newClient(t)
+
+ sandboxID, sourceWorker := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,
+ })
+ t.Logf("source sandbox: %s on %s", sandboxID, sourceWorker)
+
+ const marker = "ci-hib-cross-marker"
+ writeMarker(t, c, sandboxID, marker)
+
+ // Hibernate
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/hibernate", nil, nil)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("hibernate: code=%d err=%v", code, err)
+ }
+ if !waitForStatus(t, c, sandboxID, "hibernated", 3*time.Minute) {
+ t.Fatalf("sandbox never reached hibernated")
+ }
+ t.Logf("hibernated on %s", sourceWorker)
+
+ // Hibernation upload to S3 is async — `status=hibernated` is set before
+ // uploaded_at. If we drain the source before upload completes, wake on
+ // the other worker correctly refuses with 503 ("source unavailable and
+ // upload not complete"). Wait long enough for the upload to finish.
+ // For a 1GB empty sandbox this is ~5-15s; 30s gives margin.
+ t.Logf("waiting 30s for hibernation S3 upload to complete...")
+ time.Sleep(30 * time.Second)
+
+ // Drain the source worker so the scheduler will pick the other one for wake.
+ drainWorker(t, c, sourceWorker)
+
+ // Wake
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/wake", nil, nil)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("wake: code=%d err=%v", code, err)
+ }
+ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {
+ t.Fatalf("sandbox never returned to running")
+ }
+
+ // Verify the wake landed on the OTHER worker.
+ var sb struct {
+ WorkerID string `json:"workerID"`
+ }
+ c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)
+ if sb.WorkerID == sourceWorker {
+ t.Fatalf("wake landed on same worker %s despite drain; expected cross-worker", sourceWorker)
+ }
+ t.Logf("woke on %s (different worker)", sb.WorkerID)
+
+ // Verify marker survived.
+ time.Sleep(5 * time.Second)
+ if got := readMarker(t, c, sandboxID); got != marker {
+ t.Errorf("marker corrupted across hibernate→wake→cross-worker: want %q, got %q", marker, got)
+ }
+}
diff --git a/ci/tests/api/exec_test.go b/ci/tests/api/exec_test.go
new file mode 100644
index 00000000..07254efd
--- /dev/null
+++ b/ci/tests/api/exec_test.go
@@ -0,0 +1,64 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// TestExec_Run runs a one-shot command inside a fresh sandbox and verifies the
+// output. This exercises the full path: API → worker gRPC → agent inside the
+// guest VM → process spawn → output round-trip.
+func TestExec_Run(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping exec test", envWorkers)
+ }
+ c := newClient(t)
+ sandboxID, _ := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,
+ })
+
+ // Run commands and verify stdout/exit codes
+ cases := []struct {
+ name string
+ cmd string
+ args []string
+ wantExit int
+ wantStdoutPart string
+ }{
+ {"echo prints to stdout", "echo", []string{"hello-ci"}, 0, "hello-ci"},
+ {"true exits 0", "true", nil, 0, ""},
+ {"false exits 1", "false", nil, 1, ""},
+ {"uname returns linux", "uname", []string{"-s"}, 0, "Linux"},
+ {"hostname matches sandbox", "hostname", nil, 0, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var result struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ body := map[string]any{"cmd": tc.cmd, "timeout": 30}
+ if len(tc.args) > 0 {
+ body["args"] = tc.args
+ }
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sandboxID+"/exec/run", body, &result)
+ if err != nil {
+ t.Fatalf("exec: %v", err)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("exec: code=%d", code)
+ }
+ if result.ExitCode != tc.wantExit {
+ t.Errorf("exit: want %d, got %d (stderr=%q)", tc.wantExit, result.ExitCode, result.Stderr)
+ }
+ if tc.wantStdoutPart != "" && !strings.Contains(result.Stdout, tc.wantStdoutPart) {
+ t.Errorf("stdout: want substring %q, got %q", tc.wantStdoutPart, result.Stdout)
+ }
+ })
+ }
+}
diff --git a/ci/tests/api/exec_variants_test.go b/ci/tests/api/exec_variants_test.go
new file mode 100644
index 00000000..4bb40715
--- /dev/null
+++ b/ci/tests/api/exec_variants_test.go
@@ -0,0 +1,161 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+)
+
+// These variants help characterize the worker→agent exec flake we observed:
+// the current TestExec_Run (5 commands ~50ms apart on a fresh sandbox) shows
+// ~30-40% flake. Customers don't usually fire commands that fast, but agents
+// running setup-style sequences (`cat /etc/...`, `which X`, `pwd`) can.
+//
+// Each variant isolates one dimension. Compare flake rates across variants:
+// - Burst (baseline) : matches TestExec_Run; expected ~30% flake
+// - Paced : same 5 cmds with 1s sleeps — customer-like cadence
+// - Stress : 50 fast cmds on one sandbox — bursty leak detector
+// - Warm : burst cmds on a sandbox after 10s warmup — separates "cold sandbox" from "fast burst"
+
+func runExecCmd(t *testing.T, c *client, sandboxID, cmd string, args []string) (exitCode int, stdout string, latency time.Duration) {
+ t.Helper()
+ body := map[string]any{"cmd": cmd, "timeout": 10}
+ if len(args) > 0 {
+ body["args"] = args
+ }
+ var result struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ start := time.Now()
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sandboxID+"/exec/run", body, &result)
+ latency = time.Since(start)
+ if err != nil {
+ t.Errorf("exec %q: %v (latency=%s)", cmd, err, latency)
+ return -1, "", latency
+ }
+ if code != http.StatusOK {
+ t.Errorf("exec %q: HTTP %d (latency=%s, stderr=%q)", cmd, code, latency, result.Stderr)
+ return -1, "", latency
+ }
+ return result.ExitCode, result.Stdout, latency
+}
+
+func createSandboxForExec(t *testing.T, c *client, timeout int) string {
+ t.Helper()
+ var sb struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes", map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": timeout,
+ }, &sb)
+ if err != nil || code/100 != 2 || sb.Status != "running" {
+ t.Fatalf("create sandbox: code=%d err=%v resp=%+v", code, err, sb)
+ }
+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+sb.SandboxID, nil, nil) })
+ return sb.SandboxID
+}
+
+// Variant A: Burst — current pattern. 5 trivial commands back-to-back on a
+// fresh sandbox.
+func TestExecVariant_Burst(t *testing.T) {
+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {
+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")
+ }
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping", envWorkers)
+ }
+ c := newClient(t)
+ sbox := createSandboxForExec(t, c, 120)
+
+ cmds := []string{"echo", "true", "false", "uname", "hostname"}
+ for i, cmd := range cmds {
+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)
+ t.Logf("burst[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)
+ }
+}
+
+// Variant B: Paced — same 5 commands but with 1s sleeps between.
+// If this is much less flaky than Burst, the issue is timing-specific
+// (fast back-to-back exec) and customers at normal pace are fine.
+func TestExecVariant_Paced(t *testing.T) {
+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {
+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")
+ }
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping", envWorkers)
+ }
+ c := newClient(t)
+ sbox := createSandboxForExec(t, c, 120)
+
+ cmds := []string{"echo", "true", "false", "uname", "hostname"}
+ for i, cmd := range cmds {
+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)
+ t.Logf("paced[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)
+ if i < len(cmds)-1 {
+ time.Sleep(1 * time.Second)
+ }
+ }
+}
+
+// Variant C: Stress — 50 fast commands on one sandbox. Hammers the worker→agent
+// path. If the flake is a leak (e.g. accumulating stuck channels), the failure
+// rate should rise across the 50 calls. If it's a fixed-probability transient,
+// it should hit early and then either recover or stay flaky.
+func TestExecVariant_Stress(t *testing.T) {
+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {
+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")
+ }
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping", envWorkers)
+ }
+ c := newClient(t)
+ sbox := createSandboxForExec(t, c, 300)
+
+ const n = 50
+ var slow, failed int
+ for i := range n {
+ exit, _, lat := runExecCmd(t, c, sbox, "true", nil)
+ if lat > 2*time.Second {
+ slow++
+ t.Logf("stress[%d] SLOW: latency=%s exit=%d", i, lat, exit)
+ }
+ if exit < 0 || exit > 1 {
+ failed++
+ }
+ }
+ t.Logf("stress summary: n=%d slow(>2s)=%d failed=%d", n, slow, failed)
+ if failed > 0 {
+ t.Errorf("stress: %d/%d calls failed", failed, n)
+ }
+}
+
+// Variant D: Warm — burst the same 5 commands but only after a 10-second pause
+// post-create. If this is much less flaky than Burst, the issue is specific
+// to "cold sandbox + immediate exec" (something inside the agent or worker's
+// per-sandbox bookkeeping isn't ready yet right after boot).
+func TestExecVariant_Warm(t *testing.T) {
+ if os.Getenv("OSB_TEST_VARIANTS") != "1" {
+ t.Skip("variant diagnostics gated by OSB_TEST_VARIANTS=1")
+ }
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping", envWorkers)
+ }
+ c := newClient(t)
+ sbox := createSandboxForExec(t, c, 120)
+
+ t.Logf("warm: sleeping 10s before first exec")
+ time.Sleep(10 * time.Second)
+
+ cmds := []string{"echo", "true", "false", "uname", "hostname"}
+ for i, cmd := range cmds {
+ exit, _, lat := runExecCmd(t, c, sbox, cmd, nil)
+ t.Logf("warm[%d] %s: exit=%d latency=%s", i, cmd, exit, lat)
+ }
+}
+
diff --git a/ci/tests/api/files_test.go b/ci/tests/api/files_test.go
new file mode 100644
index 00000000..20a361c9
--- /dev/null
+++ b/ci/tests/api/files_test.go
@@ -0,0 +1,107 @@
+package api_test
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// TestFiles_UploadDownload exercises the signed-URL file path: get an upload
+// URL, PUT content to it, get a download URL, GET it back, verify byte match.
+// Also confirms exec sees the same content (proves the upload landed in the
+// sandbox's workspace, not just a server-side cache).
+func TestFiles_UploadDownload(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping file ops test", envWorkers)
+ }
+ c := newClient(t)
+ sandboxID, _ := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 300,
+ })
+
+ const path = "/home/sandbox/upload-test.txt"
+ payload := []byte("hello-ci-upload " + strconv.FormatInt(int64(len(path)), 10))
+
+ // Get upload URL
+ var uploadResp struct {
+ URL string `json:"url"`
+ }
+ code, err := c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sandboxID+"/files/upload-url",
+ map[string]any{"path": path, "expiresIn": 60}, &uploadResp)
+ if err != nil || code/100 != 2 || uploadResp.URL == "" {
+ t.Fatalf("upload-url: code=%d err=%v resp=%+v", code, err, uploadResp)
+ }
+
+ // PUT content to the upload URL. Signed URLs are HMAC-authenticated so
+ // they don't need our X-API-Key header.
+ uploadURL := uploadResp.URL
+ if strings.HasPrefix(uploadURL, "/") {
+ uploadURL = c.baseURL + uploadURL
+ }
+ req, err := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader(payload))
+ if err != nil {
+ t.Fatalf("build PUT: %v", err)
+ }
+ req.Header.Set("Content-Type", "application/octet-stream")
+ resp, err := c.http.Do(req)
+ if err != nil {
+ t.Fatalf("PUT: %v", err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode/100 != 2 {
+ t.Fatalf("PUT upload: status=%d body=%q", resp.StatusCode, body)
+ }
+
+ // Get download URL
+ var downloadResp struct {
+ URL string `json:"url"`
+ }
+ code, err = c.do(t, http.MethodPost,
+ "/api/sandboxes/"+sandboxID+"/files/download-url",
+ map[string]any{"path": path, "expiresIn": 60}, &downloadResp)
+ if err != nil || code/100 != 2 || downloadResp.URL == "" {
+ t.Fatalf("download-url: code=%d err=%v resp=%+v", code, err, downloadResp)
+ }
+
+ downloadURL := downloadResp.URL
+ if strings.HasPrefix(downloadURL, "/") {
+ downloadURL = c.baseURL + downloadURL
+ }
+ req, err = http.NewRequest(http.MethodGet, downloadURL, nil)
+ if err != nil {
+ t.Fatalf("build GET: %v", err)
+ }
+ resp, err = c.http.Do(req)
+ if err != nil {
+ t.Fatalf("GET: %v", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode/100 != 2 {
+ raw, _ := io.ReadAll(resp.Body)
+ t.Fatalf("GET download: status=%d body=%q", resp.StatusCode, raw)
+ }
+ got, _ := io.ReadAll(resp.Body)
+ if !bytes.Equal(got, payload) {
+ t.Errorf("download bytes mismatch: want %q, got %q", payload, got)
+ }
+
+ // Cross-check via exec — the file should be in the workspace.
+ body2 := map[string]any{"cmd": "cat", "args": []string{path}, "timeout": 10}
+ var r struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ }
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body2, &r)
+ if err != nil || code != http.StatusOK || r.ExitCode != 0 {
+ t.Fatalf("exec cat: code=%d err=%v exit=%d", code, err, r.ExitCode)
+ }
+ if !strings.Contains(r.Stdout, string(payload)) {
+ t.Errorf("exec sees different content: want %q, got %q", payload, r.Stdout)
+ }
+}
diff --git a/ci/tests/api/health_test.go b/ci/tests/api/health_test.go
new file mode 100644
index 00000000..b30e4c66
--- /dev/null
+++ b/ci/tests/api/health_test.go
@@ -0,0 +1,23 @@
+package api_test
+
+import (
+ "net/http"
+ "testing"
+)
+
+func TestHealthz(t *testing.T) {
+ c := newClient(t)
+ var resp struct {
+ Status string `json:"status"`
+ }
+ code, err := c.do(t, http.MethodGet, "/healthz", nil, &resp)
+ if err != nil {
+ t.Fatalf("/healthz: %v", err)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("/healthz: want 200, got %d", code)
+ }
+ if resp.Status != "alive" {
+ t.Fatalf("/healthz: want status=alive, got %q", resp.Status)
+ }
+}
diff --git a/ci/tests/api/helpers_test.go b/ci/tests/api/helpers_test.go
new file mode 100644
index 00000000..1bec52fb
--- /dev/null
+++ b/ci/tests/api/helpers_test.go
@@ -0,0 +1,219 @@
+// Package api contains integration tests against a running opensandbox stack.
+// Tests connect to OSB_TEST_SERVER_URL with OSB_TEST_API_KEY (set by ci/pr/up.sh).
+// If those env vars are missing, every test in the package skips so `go test ./...`
+// stays green for unit-test runs that don't have a stack provisioned.
+package api_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ envServerURL = "OSB_TEST_SERVER_URL"
+ envAPIKey = "OSB_TEST_API_KEY"
+ envWorkers = "OSB_TEST_WORKERS"
+)
+
+type client struct {
+ baseURL string
+ apiKey string
+ http *http.Client
+}
+
+func newClient(t *testing.T) *client {
+ t.Helper()
+ url := os.Getenv(envServerURL)
+ key := os.Getenv(envAPIKey)
+ if url == "" || key == "" {
+ t.Skipf("%s and %s must be set to run integration tests", envServerURL, envAPIKey)
+ }
+ return &client{
+ baseURL: strings.TrimRight(url, "/"),
+ apiKey: key,
+ http: &http.Client{Timeout: 60 * time.Second},
+ }
+}
+
+// do issues a request and decodes JSON into out (if non-nil). Returns the
+// response status code and any error. The body is fully consumed.
+//
+// No retries on 5xx — we want failures visible. The product surface is what
+// customers see; if the worker→agent transport is flaky, tests should mirror
+// that, not paper over it.
+func (c *client) do(t *testing.T, method, path string, body, out any) (int, error) {
+ t.Helper()
+ var rdr io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return 0, fmt.Errorf("marshal body: %w", err)
+ }
+ rdr = bytes.NewReader(b)
+ }
+ req, err := http.NewRequest(method, c.baseURL+path, rdr)
+ if err != nil {
+ return 0, err
+ }
+ req.Header.Set("X-API-Key", c.apiKey)
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return 0, err
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(resp.Body)
+ if out != nil && len(raw) > 0 {
+ if err := json.Unmarshal(raw, out); err != nil {
+ return resp.StatusCode, fmt.Errorf("decode %s %s (status=%d, body=%q): %w",
+ method, path, resp.StatusCode, truncate(raw, 200), err)
+ }
+ }
+ return resp.StatusCode, nil
+}
+
+// raw issues a request without auth headers (for testing missing/wrong keys).
+func (c *client) raw(t *testing.T, method, path string, headers map[string]string) (int, []byte) {
+ t.Helper()
+ req, err := http.NewRequest(method, c.baseURL+path, nil)
+ if err != nil {
+ t.Fatalf("new request: %v", err)
+ }
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ t.Fatalf("do: %v", err)
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, raw
+}
+
+func truncate(b []byte, n int) []byte {
+ if len(b) <= n {
+ return b
+ }
+ return append(b[:n:n], []byte("…")...)
+}
+
+// createReadySandbox creates a sandbox and waits 5s before returning.
+//
+// The API returns status:"running" once the VM has booted and the worker
+// Pinged the agent, but the agent has a known post-boot window where Exec
+// calls can hang. Tests that hit Exec immediately see ~40% flake. A short
+// pause sidesteps the worst of it. Tracked separately as a product bug;
+// the real fix is the worker doing an Exec round-trip readiness probe
+// before declaring the sandbox running.
+//
+// Use for any test that will Exec right after creating a sandbox. Tests
+// that only verify list/get/delete don't need it.
+func createReadySandbox(t *testing.T, c *client, cfg map[string]any) (string, string) {
+ t.Helper()
+ var sb struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes", cfg, &sb)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("create sandbox: code=%d err=%v resp=%+v", code, err, sb)
+ }
+ if sb.SandboxID == "" || sb.Status != "running" {
+ t.Fatalf("create sandbox: unexpected response %+v", sb)
+ }
+ t.Cleanup(func() { c.do(t, http.MethodDelete, "/api/sandboxes/"+sb.SandboxID, nil, nil) })
+ time.Sleep(5 * time.Second)
+ return sb.SandboxID, sb.WorkerID
+}
+
+// writeMarker writes content to /home/sandbox/marker via exec. Asserts the
+// echo-back. Used by tests that need to verify workspace state survives a
+// round-trip (checkpoint, hibernate, migrate, etc.).
+func writeMarker(t *testing.T, c *client, sandboxID, content string) {
+ t.Helper()
+ body := map[string]any{
+ "cmd": "sh",
+ "args": []string{"-c", "echo " + content + " > /home/sandbox/marker && cat /home/sandbox/marker"},
+ "timeout": 10,
+ }
+ var r struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &r)
+ if err != nil || code != http.StatusOK || r.ExitCode != 0 {
+ t.Fatalf("writeMarker(%q): code=%d err=%v exit=%d stderr=%q", content, code, err, r.ExitCode, r.Stderr)
+ }
+ if !strings.Contains(r.Stdout, content) {
+ t.Fatalf("writeMarker(%q): echo didn't return content, stdout=%q", content, r.Stdout)
+ }
+}
+
+// drainWorker marks a worker as draining (POST /admin/workers/:id/drain) so
+// the scheduler won't place new sandboxes / wakes on it. Tests use this to
+// force a wake or fork onto a specific other worker. Returns a cleanup func
+// that un-drains the worker (call via t.Cleanup).
+func drainWorker(t *testing.T, c *client, workerID string) {
+ t.Helper()
+ code, _ := c.raw(t, http.MethodPost, "/admin/workers/"+workerID+"/drain",
+ map[string]string{"X-API-Key": c.apiKey})
+ if code/100 != 2 {
+ t.Fatalf("drain %s: code=%d", workerID, code)
+ }
+ t.Cleanup(func() {
+ c.raw(t, http.MethodPost, "/admin/workers/"+workerID+"/drain?drain=false",
+ map[string]string{"X-API-Key": c.apiKey})
+ })
+}
+
+// goldenVersionOf returns the golden_version of the named worker, or "" if
+// unknown. Used by cross-golden tests to assert old/new pairs differ.
+func goldenVersionOf(t *testing.T, c *client, workerID string) string {
+ t.Helper()
+ var workers []struct {
+ WorkerID string `json:"worker_id"`
+ GoldenVersion string `json:"golden_version"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("list workers: code=%d err=%v", code, err)
+ }
+ for _, w := range workers {
+ if w.WorkerID == workerID {
+ return w.GoldenVersion
+ }
+ }
+ return ""
+}
+
+// readMarker returns the contents of /home/sandbox/marker as read by `cat`.
+// Fails the test if the file can't be read.
+func readMarker(t *testing.T, c *client, sandboxID string) string {
+ t.Helper()
+ body := map[string]any{"cmd": "cat", "args": []string{"/home/sandbox/marker"}, "timeout": 10}
+ var r struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &r)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("readMarker: code=%d err=%v stderr=%q", code, err, r.Stderr)
+ }
+ if r.ExitCode != 0 {
+ t.Fatalf("readMarker: exit=%d stderr=%q (file missing?)", r.ExitCode, r.Stderr)
+ }
+ return strings.TrimSpace(r.Stdout)
+}
diff --git a/ci/tests/api/hibernate_test.go b/ci/tests/api/hibernate_test.go
new file mode 100644
index 00000000..a3c13d22
--- /dev/null
+++ b/ci/tests/api/hibernate_test.go
@@ -0,0 +1,122 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestHibernate_Wake exercises the hibernate→S3→wake round-trip and verifies
+// workspace state survives. Writes a marker file in the workspace, hibernates,
+// waits for status=hibernated, wakes, waits for running, reads the marker back.
+//
+// This catches a class of regressions: hibernate upload silently failing,
+// wake fetching an empty workspace, status transitions stuck mid-flight, or
+// the marker file being lost across the round-trip.
+func TestHibernate_Wake(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping hibernate test", envWorkers)
+ }
+ c := newClient(t)
+ sandboxID, _ := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,
+ })
+ t.Logf("source sandbox: %s", sandboxID)
+
+ // Step 1: write a marker file in the workspace.
+ const marker = "ci-hibernate-marker-v1"
+ body := map[string]any{
+ "cmd": "sh",
+ "args": []string{"-c", "echo " + marker + " > /home/sandbox/marker && cat /home/sandbox/marker"},
+ "timeout": 10,
+ }
+ var execResult struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("write marker: code=%d err=%v stderr=%q", code, err, execResult.Stderr)
+ }
+ if !strings.Contains(execResult.Stdout, marker) {
+ t.Fatalf("marker write didn't echo back: stdout=%q", execResult.Stdout)
+ }
+
+ // Step 2: hibernate
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/hibernate", nil, nil)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("hibernate: code=%d err=%v", code, err)
+ }
+ t.Logf("hibernate request sent")
+
+ // Step 3: poll until status=hibernated. Upload of mem+workspace can take
+ // 10-30s on a small sandbox; allow generous budget.
+ if !waitForStatus(t, c, sandboxID, "hibernated", 3*time.Minute) {
+ t.Fatalf("sandbox never reached hibernated status")
+ }
+ t.Logf("hibernate complete")
+
+ // Step 4: wake
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/wake", nil, nil)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("wake: code=%d err=%v", code, err)
+ }
+ t.Logf("wake request sent")
+
+ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {
+ t.Fatalf("sandbox never returned to running status")
+ }
+ t.Logf("wake complete")
+
+ // Step 5: wait for exec readiness post-wake, then verify marker survived.
+ time.Sleep(2 * time.Second)
+ body = map[string]any{
+ "cmd": "cat",
+ "args": []string{"/home/sandbox/marker"},
+ "timeout": 10,
+ }
+ execResult = struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }{}
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("read marker post-wake: code=%d err=%v stderr=%q", code, err, execResult.Stderr)
+ }
+ if execResult.ExitCode != 0 {
+ t.Fatalf("read marker post-wake: exit=%d stderr=%q (file lost?)", execResult.ExitCode, execResult.Stderr)
+ }
+ if !strings.Contains(execResult.Stdout, marker) {
+ t.Errorf("marker survived hibernate→wake but content corrupted: want %q, got %q", marker, execResult.Stdout)
+ }
+}
+
+// waitForStatus polls /api/sandboxes/:id and returns true when status matches
+// `want` within `timeout`, false otherwise.
+func waitForStatus(t *testing.T, c *client, sandboxID, want string, timeout time.Duration) bool {
+ t.Helper()
+ deadline := time.Now().Add(timeout)
+ last := ""
+ for time.Now().Before(deadline) {
+ var sb struct {
+ Status string `json:"status"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)
+ if err == nil && code == http.StatusOK {
+ if sb.Status == want {
+ return true
+ }
+ if sb.Status != last {
+ t.Logf(" status: %s", sb.Status)
+ last = sb.Status
+ }
+ }
+ time.Sleep(3 * time.Second)
+ }
+ return false
+}
diff --git a/ci/tests/api/migrate_test.go b/ci/tests/api/migrate_test.go
new file mode 100644
index 00000000..6f699599
--- /dev/null
+++ b/ci/tests/api/migrate_test.go
@@ -0,0 +1,136 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestMigrate_CrossWorker exercises live migration: create sandbox on worker A,
+// write a marker, migrate to worker B, verify the marker survives AND that the
+// sandbox is actually now on worker B.
+//
+// Catches: migration upload/download bugs, vmstate replay races, sandbox session
+// row not updated post-migration, workspace state lost across handoff.
+//
+// Requires WORKERS>=2. Skipped on single-worker stacks.
+func TestMigrate_CrossWorker(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 2 {
+ t.Skipf("%s<2 (need at least 2 workers), skipping cross-worker test", envWorkers)
+ }
+ c := newClient(t)
+
+ // Discover available workers. Cross-golden migration is supported as long
+ // as each worker has uploaded its golden base to blob (uploadBaseImageIfNew
+ // runs in background after golden snapshot creation).
+ var workers []struct {
+ WorkerID string `json:"worker_id"`
+ Draining bool `json:"draining"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &workers)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("list workers: code=%d err=%v", code, err)
+ }
+ var liveIDs []string
+ for _, w := range workers {
+ if !w.Draining {
+ liveIDs = append(liveIDs, w.WorkerID)
+ }
+ }
+ if len(liveIDs) < 2 {
+ t.Fatalf("need 2 live workers, got %d: %+v", len(liveIDs), liveIDs)
+ }
+
+ // Create sandbox.
+ sandboxID, sourceWorker := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 600,
+ })
+ t.Logf("source sandbox: %s on %s", sandboxID, sourceWorker)
+
+ // Pick a destination worker that's NOT the current one.
+ var target string
+ for _, w := range liveIDs {
+ if w != sourceWorker {
+ target = w
+ break
+ }
+ }
+ if target == "" {
+ t.Fatalf("no candidate target worker (all %d workers match source %q)", len(liveIDs), sourceWorker)
+ }
+ t.Logf("migrating: %s → %s", sourceWorker, target)
+
+ // Write marker.
+ const marker = "ci-migrate-marker-v1"
+ body := map[string]any{
+ "cmd": "sh",
+ "args": []string{"-c", "echo " + marker + " > /home/sandbox/marker && cat /home/sandbox/marker"},
+ "timeout": 10,
+ }
+ var execResult struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("write marker: code=%d err=%v stderr=%q", code, err, execResult.Stderr)
+ }
+ if !strings.Contains(execResult.Stdout, marker) {
+ t.Fatalf("marker write didn't echo back: stdout=%q", execResult.Stdout)
+ }
+
+ // Migrate.
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/migrate",
+ map[string]any{"targetWorker": target}, nil)
+ if err != nil || code/100 != 2 {
+ t.Fatalf("migrate: code=%d err=%v", code, err)
+ }
+ t.Logf("migrate request accepted")
+
+ // Wait for status to return to "running" (it goes via "migrating").
+ if !waitForStatus(t, c, sandboxID, "running", 3*time.Minute) {
+ t.Fatalf("sandbox didn't return to running after migrate")
+ }
+
+ // Verify the sandbox's workerID changed.
+ var sb struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err = c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("get post-migrate: code=%d err=%v", code, err)
+ }
+ if sb.WorkerID != target {
+ t.Errorf("workerID after migrate: want %q, got %q", target, sb.WorkerID)
+ }
+ t.Logf("sandbox now on: %s", sb.WorkerID)
+
+ // Verify the marker survived.
+ time.Sleep(2 * time.Second)
+ body = map[string]any{
+ "cmd": "cat",
+ "args": []string{"/home/sandbox/marker"},
+ "timeout": 10,
+ }
+ execResult = struct {
+ ExitCode int `json:"exitCode"`
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ }{}
+ code, err = c.do(t, http.MethodPost, "/api/sandboxes/"+sandboxID+"/exec/run", body, &execResult)
+ if err != nil || code != http.StatusOK {
+ t.Fatalf("read marker post-migrate: code=%d err=%v stderr=%q", code, err, execResult.Stderr)
+ }
+ if execResult.ExitCode != 0 {
+ t.Fatalf("read marker post-migrate: exit=%d stderr=%q (file lost?)", execResult.ExitCode, execResult.Stderr)
+ }
+ if !strings.Contains(execResult.Stdout, marker) {
+ t.Errorf("marker corrupted across migrate: want %q, got %q", marker, execResult.Stdout)
+ }
+}
diff --git a/ci/tests/api/sandboxes_test.go b/ci/tests/api/sandboxes_test.go
new file mode 100644
index 00000000..60786a7c
--- /dev/null
+++ b/ci/tests/api/sandboxes_test.go
@@ -0,0 +1,76 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+)
+
+// TestSandboxes_Lifecycle creates a sandbox, confirms it shows up in list/get,
+// then deletes it. Skipped when WORKERS=0 since sandbox creation requires an
+// actual worker to spawn the VM. Sandbox returns already-running on create.
+func TestSandboxes_Lifecycle(t *testing.T) {
+ if v, _ := strconv.Atoi(os.Getenv(envWorkers)); v < 1 {
+ t.Skipf("%s<1, skipping sandbox lifecycle test", envWorkers)
+ }
+ c := newClient(t)
+ sandboxID, workerID := createReadySandbox(t, c, map[string]any{
+ "cpuCount": 1, "memoryMB": 1024, "diskMB": 20480, "timeout": 120,
+ })
+ t.Logf("created %s on %s", sandboxID, workerID)
+
+ t.Run("get returns same sandbox", func(t *testing.T) {
+ var sb struct {
+ SandboxID string `json:"sandboxID"`
+ Status string `json:"status"`
+ WorkerID string `json:"workerID"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/sandboxes/"+sandboxID, nil, &sb)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("get: want 200, got %d", code)
+ }
+ if sb.SandboxID != sandboxID {
+ t.Fatalf("get: sandboxID mismatch (want %q, got %q)", sandboxID, sb.SandboxID)
+ }
+ if sb.Status != "running" {
+ t.Fatalf("get: status=%q", sb.Status)
+ }
+ })
+
+ t.Run("list includes new sandbox", func(t *testing.T) {
+ var sandboxes []struct {
+ SandboxID string `json:"sandboxID"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/sandboxes", nil, &sandboxes)
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("list: want 200, got %d", code)
+ }
+ var found bool
+ for _, s := range sandboxes {
+ if s.SandboxID == sandboxID {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("created %s not in list (got %d sandboxes)", sandboxID, len(sandboxes))
+ }
+ })
+
+ t.Run("delete returns 2xx", func(t *testing.T) {
+ code, err := c.do(t, http.MethodDelete, "/api/sandboxes/"+sandboxID, nil, nil)
+ if err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if code/100 != 2 {
+ t.Fatalf("delete: want 2xx, got %d", code)
+ }
+ })
+}
diff --git a/ci/tests/api/sdk_test.go b/ci/tests/api/sdk_test.go
new file mode 100644
index 00000000..5cb8e804
--- /dev/null
+++ b/ci/tests/api/sdk_test.go
@@ -0,0 +1,97 @@
+package api_test
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// TestSDK_PythonImport installs the Python SDK + its runtime deps (httpx,
+// websockets) into a temp venv and imports it. Catches missing-dep / syntax /
+// package-config regressions. Skipped only if python3 has no venv module —
+// in which case the runner setup is broken, not the SDK.
+func TestSDK_PythonImport(t *testing.T) {
+ py, err := exec.LookPath("python3")
+ if err != nil {
+ t.Skip("python3 not on PATH")
+ }
+ sdk := filepath.Join(repoRoot(t), "sdks", "python")
+ if _, err := os.Stat(filepath.Join(sdk, "pyproject.toml")); err != nil {
+ t.Skipf("python SDK dir missing: %v", err)
+ }
+
+ venv := filepath.Join(t.TempDir(), "venv")
+ if out, err := exec.Command(py, "-m", "venv", venv).CombinedOutput(); err != nil {
+ t.Skipf("python3 -m venv failed (no venv module?): %v\n%s", err, out)
+ }
+ venvPy := filepath.Join(venv, "bin", "python")
+ venvPip := filepath.Join(venv, "bin", "pip")
+
+ // Editable install pulls in httpx + websockets per pyproject.toml deps.
+ install := exec.Command(venvPip, "install", "-q", "--disable-pip-version-check", "-e", sdk)
+ if out, err := install.CombinedOutput(); err != nil {
+ t.Fatalf("pip install -e %s: %v\n%s", sdk, err, out)
+ }
+
+ out, err := exec.Command(venvPy, "-c",
+ "import opencomputer; from opencomputer import Sandbox; print(opencomputer.__name__)").
+ CombinedOutput()
+ if err != nil {
+ t.Fatalf("python import: %v\n%s", err, out)
+ }
+ if !strings.Contains(string(out), "opencomputer") {
+ t.Errorf("python import: unexpected output: %q", out)
+ }
+}
+
+// TestSDK_TypeScriptBuild verifies the TS SDK compiles. Catches type / package
+// drift between the Go API and the published types.
+func TestSDK_TypeScriptBuild(t *testing.T) {
+ npm, err := exec.LookPath("npm")
+ if err != nil {
+ t.Skip("npm not on PATH")
+ }
+ sdk := filepath.Join(repoRoot(t), "sdks", "typescript")
+ if _, err := os.Stat(filepath.Join(sdk, "package.json")); err != nil {
+ t.Skipf("ts SDK dir missing: %v", err)
+ }
+ // Install (idempotent if node_modules cached)
+ install := exec.Command(npm, "ci", "--prefer-offline", "--no-audit", "--no-fund")
+ install.Dir = sdk
+ if out, err := install.CombinedOutput(); err != nil {
+ // `npm ci` requires package-lock.json; if missing, fall back to install
+ install = exec.Command(npm, "install", "--prefer-offline", "--no-audit", "--no-fund")
+ install.Dir = sdk
+ if out2, err2 := install.CombinedOutput(); err2 != nil {
+ t.Logf("npm install: %v\n%s\n(after ci failure: %v\n%s)", err2, out2, err, out)
+ t.Skip("npm install failed — SDK runtime deps unavailable in this env")
+ }
+ }
+ build := exec.Command(npm, "run", "build")
+ build.Dir = sdk
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("npm run build: %v\n%s", err, out)
+ }
+}
+
+func repoRoot(t *testing.T) string {
+ t.Helper()
+ _, file, _, ok := runtime.Caller(0)
+ if !ok {
+ t.Fatal("runtime.Caller failed")
+ }
+ dir := filepath.Dir(file)
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
+ return dir
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ t.Fatal("no go.mod found")
+ }
+ dir = parent
+ }
+}
diff --git a/ci/tests/api/secret_stores_test.go b/ci/tests/api/secret_stores_test.go
new file mode 100644
index 00000000..2fc64eba
--- /dev/null
+++ b/ci/tests/api/secret_stores_test.go
@@ -0,0 +1,140 @@
+package api_test
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+)
+
+// TestSecretStores_CRUD covers the full lifecycle of a secret store and the
+// secret entries inside it. The store is created with a unique name per test
+// run so concurrent runs don't collide.
+func TestSecretStores_CRUD(t *testing.T) {
+ c := newClient(t)
+ storeName := fmt.Sprintf("ci-test-store-%d", time.Now().UnixNano())
+
+ // Create store
+ var created struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ code, err := c.do(t, http.MethodPost, "/api/secret-stores",
+ map[string]any{"name": storeName}, &created)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if code/100 != 2 {
+ t.Fatalf("create: want 2xx, got %d", code)
+ }
+ if created.ID == "" || created.Name != storeName {
+ t.Fatalf("create response: %+v", created)
+ }
+ storeID := created.ID
+ t.Cleanup(func() { cleanupStore(t, c, storeID) })
+
+ t.Run("list includes new store", func(t *testing.T) {
+ var stores []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/secret-stores", nil, &stores)
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("list: want 200, got %d", code)
+ }
+ var found bool
+ for _, s := range stores {
+ if s.ID == storeID {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("created store %s not in list (got %d stores)", storeID, len(stores))
+ }
+ })
+
+ t.Run("get", func(t *testing.T) {
+ var s struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ code, err := c.do(t, http.MethodGet, "/api/secret-stores/"+storeID, nil, &s)
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if code != http.StatusOK || s.ID != storeID {
+ t.Fatalf("get: code=%d resp=%+v", code, s)
+ }
+ })
+
+ t.Run("set + list + delete entry", func(t *testing.T) {
+ // Set
+ code, err := c.do(t, http.MethodPut,
+ "/api/secret-stores/"+storeID+"/secrets/MY_KEY",
+ map[string]any{"value": "super-secret-value"}, nil)
+ if err != nil {
+ t.Fatalf("set entry: %v", err)
+ }
+ if code/100 != 2 {
+ t.Fatalf("set entry: want 2xx, got %d", code)
+ }
+
+ // List (try both shapes)
+ var entries []struct {
+ Name string `json:"name"`
+ }
+ code, err = c.do(t, http.MethodGet,
+ "/api/secret-stores/"+storeID+"/secrets", nil, &entries)
+ if err != nil {
+ var wrapped struct {
+ Entries []struct {
+ Name string `json:"name"`
+ } `json:"entries"`
+ }
+ code2, err2 := c.do(t, http.MethodGet,
+ "/api/secret-stores/"+storeID+"/secrets", nil, &wrapped)
+ if err2 != nil {
+ t.Fatalf("list entries: %v / %v", err, err2)
+ }
+ code = code2
+ entries = wrapped.Entries
+ }
+ if code != http.StatusOK {
+ t.Fatalf("list entries: want 200, got %d", code)
+ }
+ var found bool
+ for _, e := range entries {
+ if e.Name == "MY_KEY" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("MY_KEY not in entries: %+v", entries)
+ }
+
+ // Delete
+ code, err = c.do(t, http.MethodDelete,
+ "/api/secret-stores/"+storeID+"/secrets/MY_KEY", nil, nil)
+ if err != nil {
+ t.Fatalf("delete entry: %v", err)
+ }
+ if code/100 != 2 {
+ t.Fatalf("delete entry: want 2xx, got %d", code)
+ }
+ })
+}
+
+func cleanupStore(t *testing.T, c *client, storeID string) {
+ if storeID == "" {
+ return
+ }
+ code, _ := c.do(t, http.MethodDelete, "/api/secret-stores/"+storeID, nil, nil)
+ if code/100 != 2 && code != http.StatusNotFound {
+ t.Logf("cleanup: failed to delete store %s (code=%d)", storeID, code)
+ }
+}
diff --git a/ci/tests/api/workers_test.go b/ci/tests/api/workers_test.go
new file mode 100644
index 00000000..b7287078
--- /dev/null
+++ b/ci/tests/api/workers_test.go
@@ -0,0 +1,49 @@
+package api_test
+
+import (
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+)
+
+// TestWorkers_List queries /api/workers and asserts the count matches what
+// up.sh provisioned (OSB_TEST_WORKERS env var). If WORKERS is 0 the test
+// just confirms the endpoint returns successfully.
+func TestWorkers_List(t *testing.T) {
+ c := newClient(t)
+ want := 0
+ if v := os.Getenv(envWorkers); v != "" {
+ n, err := strconv.Atoi(v)
+ if err != nil {
+ t.Fatalf("parse %s: %v", envWorkers, err)
+ }
+ want = n
+ }
+
+ // /api/workers returns either an array or {"workers":[...]} — accept both.
+ var arr []map[string]any
+ var wrapped struct {
+ Workers []map[string]any `json:"workers"`
+ }
+
+ // Try array first.
+ code, err := c.do(t, http.MethodGet, "/api/workers", nil, &arr)
+ got := len(arr)
+ if err != nil {
+ // Try the wrapped form.
+ code2, err2 := c.do(t, http.MethodGet, "/api/workers", nil, &wrapped)
+ if err2 != nil {
+ t.Fatalf("/api/workers: %v / %v", err, err2)
+ }
+ code = code2
+ got = len(wrapped.Workers)
+ }
+ if code != http.StatusOK {
+ t.Fatalf("/api/workers: want 200, got %d", code)
+ }
+ if got < want {
+ t.Fatalf("/api/workers: want at least %d worker(s), got %d", want, got)
+ }
+ t.Logf("workers registered: %d (expected at least %d)", got, want)
+}
diff --git a/ci/tests/migration/registered_test.go b/ci/tests/migration/registered_test.go
new file mode 100644
index 00000000..b3aff509
--- /dev/null
+++ b/ci/tests/migration/registered_test.go
@@ -0,0 +1,120 @@
+// Package migration validates that every *.up.sql file in
+// internal/db/migrations/ is registered in store.go's hand-maintained
+// migration slice. The slice is the source of truth at runtime: a SQL file
+// that's only on disk but not in the slice will silently never run.
+//
+// This test is the cheapest defense against the listed migrations.md pitfall.
+// It needs no infrastructure — runs as a plain unit test.
+package migration_test
+
+import (
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// repoRoot walks up from the test source file to find go.mod.
+func repoRoot(t *testing.T) string {
+ t.Helper()
+ _, file, _, ok := runtime.Caller(0)
+ if !ok {
+ t.Fatal("runtime.Caller failed")
+ }
+ dir := filepath.Dir(file)
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
+ return dir
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ t.Fatal("walked to filesystem root without finding go.mod")
+ }
+ dir = parent
+ }
+}
+
+func TestMigrations_AllSQLFilesRegistered(t *testing.T) {
+ root := repoRoot(t)
+ migrationsDir := filepath.Join(root, "internal", "db", "migrations")
+
+ // Collect on-disk *.up.sql files.
+ entries, err := os.ReadDir(migrationsDir)
+ if err != nil {
+ t.Fatalf("read migrations dir: %v", err)
+ }
+ onDisk := map[string]bool{}
+ for _, e := range entries {
+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {
+ onDisk[e.Name()] = true
+ }
+ }
+ if len(onDisk) == 0 {
+ t.Fatal("found zero *.up.sql files — migrations dir layout changed?")
+ }
+
+ // Extract registered entries from store.go's migration slice.
+ storeGo, err := os.ReadFile(filepath.Join(root, "internal", "db", "store.go"))
+ if err != nil {
+ t.Fatalf("read store.go: %v", err)
+ }
+ re := regexp.MustCompile(`\{\s*(\d+)\s*,\s*"migrations/([^"]+)"\s*\}`)
+ matches := re.FindAllStringSubmatch(string(storeGo), -1)
+ if len(matches) == 0 {
+ t.Fatal("no migration entries found in store.go — slice format changed?")
+ }
+ registered := map[string]int{} // filename → version
+ versions := map[int]string{} // version → filename
+ for _, m := range matches {
+ ver := m[1]
+ fn := m[2]
+ registered[fn] = atoi(t, ver)
+ if existing, dup := versions[atoi(t, ver)]; dup {
+ t.Errorf("duplicate migration version %s: %q and %q", ver, existing, fn)
+ }
+ versions[atoi(t, ver)] = fn
+ }
+
+ // Every on-disk file must be registered.
+ var unregistered []string
+ for fn := range onDisk {
+ if _, ok := registered[fn]; !ok {
+ unregistered = append(unregistered, fn)
+ }
+ }
+ if len(unregistered) > 0 {
+ sort.Strings(unregistered)
+ t.Errorf("unregistered migrations (in dir but not in store.go's slice — they will never run!):\n %s",
+ strings.Join(unregistered, "\n "))
+ }
+
+ // Every registered entry must have a real file.
+ var dangling []string
+ for fn := range registered {
+ if !onDisk[fn] {
+ dangling = append(dangling, fn)
+ }
+ }
+ if len(dangling) > 0 {
+ sort.Strings(dangling)
+ t.Errorf("dangling references in store.go (in slice but no .up.sql file):\n %s",
+ strings.Join(dangling, "\n "))
+ }
+
+ t.Logf("validated %d migrations: dir=%d registered=%d", len(onDisk), len(onDisk), len(registered))
+}
+
+func atoi(t *testing.T, s string) int {
+ t.Helper()
+ var n int
+ for _, c := range s {
+ if c < '0' || c > '9' {
+ t.Fatalf("non-digit in version %q", s)
+ }
+ n = n*10 + int(c-'0')
+ }
+ return n
+}
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index 349cb859..3bc322bc 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -538,6 +538,21 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin
return err
}
+ // Wait for QEMU to finish loading the migrated state before resuming.
+ // The source's `migrate` command completes when it has SENT all data;
+ // the dest's QEMU may still be in `inmigrate` parsing/applying it when
+ // the server calls CompleteIncomingMigration. On a contended or smaller
+ // dest, that load can take >10s, in which case Cont blocks waiting for
+ // QEMU to transition and our 10s response read fires before QEMU answers.
+ // Polling query-status until `paused`/`postmigrate` makes Cont a no-op
+ // from QEMU's perspective and turns this from "Cont times out, agent
+ // reconnect times out, migration fails" into a clean wait.
+ if vm.qmp != nil {
+ if err := m.waitForMigrationReady(vm.qmp, 60*time.Second); err != nil {
+ log.Printf("qemu: migration %s: waitForMigrationReady failed: %v (attempting cont anyway)", sandboxID, err)
+ }
+ }
+
// Resume the VM — after live migration the target is paused
if vm.qmp != nil {
if err := vm.qmp.Cont(); err != nil {