An open-source, faster Devin alternative
TypeScript
rebuild microvm images when the guest changes
Brian Reardon5a9e513903eb
diff --git a/.github/workflows/publish-microvm-images.yml b/.github/workflows/publish-microvm-images.ymlnew file mode 100644index 00000000..3877b8c8--- /dev/null+++ b/.github/workflows/publish-microvm-images.yml@@ -0,0 +1,95 @@+name: MicroVM images++# Republish the guest images when merged code changes them, and let prod follow+# dev only once dev has proved the image actually works.+#+# They drifted once for three weeks: the guest gained /oc/secrets, /oc/envs and+# /oc/stats on 2026-09-01, nothing rebuilt the images, and the control plane+# called routes its own guests did not serve. That surfaces as 415 with an empty+# body — invisible until the first customer whose create carried a secret.+#+# Two decisions this encodes:+#+# 1. "Affects the images" is decided by asking the compiler, not by a paths:+# filter. manifest.py hashes the `go list -deps` closure of cmd/agent and+# cmd/microvm-hooks plus the Dockerfile and build.sh. A filter would have+# missed the original bug — the guest imports ten packages under internal/.+#+# 2. prod publishes on merge like dev. Manual prod publishing is what let the+# drift last three weeks — "someone will remember" is the failure, not the+# safeguard. Three things stand in for a human here, and none needs a+# credential: this drift check, AWS's own /ready and /validate image build+# hooks (an image that cannot boot or exec never goes active, and publish.sh+# exits non-zero), and TestOCRoutesBeatTheAgentCatchAll, which fails if the+# guest stops serving a route the control plane calls.++on:+ push:+ branches: [main]+ workflow_dispatch:+ inputs:+ allow_resize:+ description: 'Permit a memory-tier change (normally refused)'+ required: false+ default: false+ type: boolean++concurrency:+ group: microvm-images+ cancel-in-progress: false++jobs:+ publish:+ runs-on: ubuntu-latest+ permissions:+ id-token: write+ contents: read+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ cache: true++ # opencomputer-gha: already trusts repo:diggerhq/opencomputer:* and can+ # create/update microvm images, pass the build role, and write the+ # artifact bucket.+ - uses: aws-actions/[email protected]+ with:+ role-to-assume: ${{ secrets.AWS_ROLE_ARN }}+ aws-region: us-east-1++ - id: dev_drift+ run: |+ if ./deploy/microvm/manifest.py check-drift dev; then+ echo "stale=false" >> "$GITHUB_OUTPUT"+ else+ echo "stale=true" >> "$GITHUB_OUTPUT"+ fi++ - name: Publish every dev tier from one artifact+ if: steps.dev_drift.outputs.stale == 'true'+ run: ./deploy/microvm/release.sh dev+ env:+ MICROVM_ALLOW_RESIZE: ${{ github.event.inputs.allow_resize && '1' || '0' }}++ - id: prod_drift+ run: |+ if ./deploy/microvm/manifest.py check-drift prod; then+ echo "stale=false" >> "$GITHUB_OUTPUT"+ echo "prod already matches this commit." >> "$GITHUB_STEP_SUMMARY"+ else+ echo "stale=true" >> "$GITHUB_OUTPUT"+ fi++ - name: Publish every prod tier from one artifact+ if: steps.prod_drift.outputs.stale == 'true'+ run: ./deploy/microvm/release.sh prod+ env:+ MICROVM_ALLOW_RESIZE: ${{ github.event.inputs.allow_resize && '1' || '0' }}++ - name: Confirm nothing is behind+ run: |+ ./deploy/microvm/manifest.py check-drift dev+ ./deploy/microvm/manifest.py check-drift prod+ echo "dev and prod images match this commit." >> "$GITHUB_STEP_SUMMARY"diff --git a/cmd/microvm-hooks/oc_test.go b/cmd/microvm-hooks/oc_test.goindex fe84a4fa..fbf1476c 100644--- a/cmd/microvm-hooks/oc_test.go+++ b/cmd/microvm-hooks/oc_test.go@@ -148,6 +148,11 @@ func TestOCRoutesBeatTheAgentCatchAll(t *testing.T) {ocFSPrefix + "stat", ocFSPrefix + "download", ocFSPrefix + "upload",ocStatsPath, ocRebootPath, ocPortPrefix + "3000/",ocRunPath, ocClaimPath, ocClaimRunPath,+ // Absent from this list until 2026-09-14, and the omission was not+ // theoretical: a published image that did not serve /oc/secrets failed+ // every create carrying a secret or an egress allowlist, with the+ // unexplained 415 this test exists to catch.+ ocSecretsPath, ocSecretsUpdatePath, ocEnvsPath,} {_, pattern := mux.Handler(httptest.NewRequest(http.MethodPost, path, nil))if pattern == "/" {diff --git a/deploy/microvm/images.json b/deploy/microvm/images.jsonnew file mode 100644index 00000000..38d733e5--- /dev/null+++ b/deploy/microvm/images.json@@ -0,0 +1,76 @@+{+ "_comment": [+ "The MicroVM guest images this repo owns, and the memory tier each carries.",+ "",+ "SCOPE. This AWS account is shared. It also holds managed-agents-runtime-*",+ "and managed-agents-production-runtime (the serverless-agent runtime, built",+ "from the blue repo), blue-* experiments, nslabs-benchmark-runtime, and",+ "osb-tpl-* images built per customer template at run time by",+ "internal/api/template_microvm_build.go. None of those are ours. Every name",+ "here must start with ownedPrefix and release.sh refuses otherwise, so a",+ "typo cannot reach another product's runtime.",+ "",+ "TIERS. Memory is a property of the IMAGE, not of a launch: RunMicrovmInput",+ "carries no memory field. A size tier IS an image, so N sizes means N images",+ "built from ONE artifact. A tier built but not configured is refused at",+ "create; a tier configured but not built fails at launch \u2014 so release.sh",+ "prints the control-plane configuration that matches what it just published.",+ "",+ "FRESHNESS. The published image drifted three weeks behind the guest code",+ "once: /oc/secrets, /oc/envs and /oc/stats landed 2026-09-01 and nothing",+ "rebuilt prod, so the control plane called routes its own guests did not",+ "serve. An unregistered path falls through to the agent's gRPC listener,",+ "which answers 415 with an empty body \u2014 invisible until the first customer",+ "whose create carried a secret. One artifact, every tier, on every change.",+ "DEFAULT TIER. The default image's memoryMB must equal awsvm's deliveredMicrovmMemoryMB (currently 4096). That constant is what metering prices on, so an image below it bills every default create for memory it did not get \u2014 which is exactly what happened: the lite images were published at 2048 while the constant was raised to 4096 on 2026-08-24, so prod metered 4096 on a 2048 box. manifest.py asserts the two agree on every run."+ ],+ "region": "us-east-1",+ "artifactBucket": "opensandbox-microvm-artifacts-739940681129",+ "ownedPrefix": "opensandbox-agent-lite-",+ "environments": {+ "prod": {+ "artifactKey": "microvm/agent-image-lite-prod.zip",+ "images": [+ {+ "name": "opensandbox-agent-lite-prod",+ "memoryMB": 4096,+ "default": true+ },+ {+ "name": "opensandbox-agent-lite-prod-1024",+ "memoryMB": 1024+ },+ {+ "name": "opensandbox-agent-lite-prod-2048",+ "memoryMB": 2048+ },+ {+ "name": "opensandbox-agent-lite-prod-8192",+ "memoryMB": 8192+ }+ ]+ },+ "dev": {+ "artifactKey": "microvm/agent-image-lite.zip",+ "images": [+ {+ "name": "opensandbox-agent-lite-dev",+ "memoryMB": 4096,+ "default": true+ },+ {+ "name": "opensandbox-agent-lite-dev-1024",+ "memoryMB": 1024+ },+ {+ "name": "opensandbox-agent-lite-dev-2048",+ "memoryMB": 2048+ },+ {+ "name": "opensandbox-agent-lite-dev-8192",+ "memoryMB": 8192+ }+ ]+ }+ }+}diff --git a/deploy/microvm/manifest.py b/deploy/microvm/manifest.pynew file mode 100755index 00000000..1cfd8ef3--- /dev/null+++ b/deploy/microvm/manifest.py@@ -0,0 +1,211 @@+#!/usr/bin/env python3+"""Read deploy/microvm/images.json for release.sh.++A separate file rather than heredocs inside the shell script: the first version+embedded these as heredocs inside process substitution, which `bash -n` accepts+and bash then refuses at run time with "bad substitution". The failure came+after the ownership guard had already been written and reviewed, which is the+worst place to discover a quoting bug.++Subcommands print plain lines for the shell to read.+"""+import json+import re+import subprocess+import sys++HERE = __file__.rsplit("/", 1)[0]+MANIFEST = f"{HERE}/images.json"+CLIENT_GO = f"{HERE}/../../internal/awsvm/client.go"+++def delivered_default_mb():+ """awsvm's deliveredMicrovmMemoryMB — what metering prices the default on.++ Read from the source rather than duplicated here. The two drifting is the+ bug this guards: the constant was raised 2048 -> 4096 on 2026-08-24 and the+ lite images stayed at 2048, so every default create was metered for memory+ it did not get.+ """+ m = re.search(r"deliveredMicrovmMemoryMB\s*=\s*(\d+)", open(CLIENT_GO).read())+ if not m:+ sys.exit("could not read deliveredMicrovmMemoryMB from internal/awsvm/client.go")+ return int(m.group(1))+++def load(env):+ m = json.load(open(MANIFEST))+ e = m["environments"].get(env)+ if not e:+ sys.exit(f"unknown environment {env!r}; have: {', '.join(m['environments'])}")+ # Ownership guard. This account also serves the blue serverless-agent+ # runtime (managed-agents-*), blue-* experiments, and osb-tpl-* images built+ # per customer template at run time. A name outside our prefix means the+ # manifest points at another product's runtime, and publishing would replace+ # the image its boxes boot from. Refuse before anything is built.+ prefix = m.get("ownedPrefix", "")+ stray = [i["name"] for i in e["images"] if not i["name"].startswith(prefix)]+ if stray:+ sys.exit(f"refusing: not ours (must start with {prefix!r}): {', '.join(stray)}")+ return m, e+++def guest_hash():+ """A hash of everything that ends up in the guest image.++ Not a hash of the artifact zip: zip stores mtimes, so two builds of+ identical code differ. Not a path filter either — that was the first+ attempt, and it was already wrong: the guest binaries import ten packages+ under internal/ (agent, secretsproxy, sandbox, crypto, storage, blobstore,+ db, diskpolicy, logship, wsconn), so a change to any of them rebuilds the+ guest while touching nothing the filter watched.++ So ask the compiler. `go list -deps` yields the real closure for both+ binaries; hash every .go file in the packages belonging to this module,+ plus the Dockerfile and build.sh that shape the image. Deterministic,+ machine-independent, and it extends itself when a new dependency appears.+ """+ import hashlib+ import os+ root = os.path.abspath(f"{HERE}/../..")+ mod = subprocess.run(["go", "list", "-m"], cwd=root, capture_output=True,+ text=True, check=True).stdout.strip()+ pkgs = subprocess.run(+ ["go", "list", "-deps", "-f", "{{.Dir}}|{{.ImportPath}}",+ "./cmd/agent", "./cmd/microvm-hooks"],+ cwd=root, capture_output=True, text=True, check=True).stdout.splitlines()+ files = []+ for line in pkgs:+ d, _, ip = line.partition("|")+ if not ip.startswith(mod) or not d:+ continue # stdlib and third-party are pinned by go.sum, not by us+ for f in sorted(os.listdir(d)):+ if f.endswith(".go") and not f.endswith("_test.go"):+ files.append(os.path.join(d, f))+ files += [f"{HERE}/Dockerfile", f"{HERE}/build.sh"]+ h = hashlib.sha256()+ for f in sorted(set(files)):+ rel = os.path.relpath(f, root)+ h.update(rel.encode())+ h.update(open(f, "rb").read())+ return h.hexdigest()[:16]+++def published_hash(region, acct, name):+ """The guest hash stamped on an image, or None. The image API has no tags,+ so the stamp rides in --description."""+ out = subprocess.run(+ ["aws", "lambda-microvms", "get-microvm-image",+ "--image-identifier", arn(region, acct, name), "--region", region,+ "--query", "description", "--output", "text"],+ capture_output=True, text=True)+ desc = out.stdout.strip()+ m = re.search(r"guest=([0-9a-f]{16})", desc or "")+ return m.group(1) if m else None+++def account():+ return subprocess.run(+ ["aws", "sts", "get-caller-identity", "--query", "Account", "--output", "text"],+ capture_output=True, text=True, check=True).stdout.strip()+++def arn(region, acct, name):+ return f"arn:aws:lambda:{region}:{acct}:microvm-image:{name}"+++def main():+ cmd, env = sys.argv[1], sys.argv[2]+ m, e = load(env)+ region = m["region"]++ if cmd == "config":+ print(region, m["artifactBucket"], e["artifactKey"])++ elif cmd == "images":+ for i in e["images"]:+ print(i["name"], i["memoryMB"])++ elif cmd == "check-memory":+ # Two different checks, and the first one is the one that was missing.+ #+ # 1. The DEFAULT image must deliver what metering prices it at. This is+ # an invariant against the code, not against the live image — asking+ # only "does the manifest match what is published" happily confirms a+ # value that was wrong when it was published, which is how 2048+ # survived a review.+ expected = delivered_default_mb()+ default = next((i for i in e["images"] if i.get("default")), None)+ if default and int(default["memoryMB"]) != expected:+ sys.exit(+ f"refusing: default tier {default['name']} is {default['memoryMB']}MiB "+ f"but awsvm meters the default at {expected}MiB — every default "+ f"create would be billed for memory it does not get")+ print(f" default tier matches awsvm deliveredMicrovmMemoryMB ({expected}MiB)")++ # 2. No tier silently changes size. A deliberate resize needs+ # MICROVM_ALLOW_RESIZE=1, so it cannot ride along with a code rebuild.+ import os+ allow_resize = os.environ.get("MICROVM_ALLOW_RESIZE") == "1"+ acct, bad = account(), []+ for i in e["images"]:+ out = subprocess.run(+ ["aws", "lambda-microvms", "list-microvm-image-versions",+ "--image-identifier", arn(region, acct, i["name"]),+ "--region", region,+ "--query", "items[0].resources[0].minimumMemoryInMiB",+ "--output", "text"], capture_output=True, text=True)+ live = out.stdout.strip()+ if live in ("", "None", "null"):+ print(f" {i['name']}: new image, will be created at {i['memoryMB']}MiB")+ elif int(live) != int(i["memoryMB"]):+ bad.append(f" {i['name']}: live={live}MiB manifest={i['memoryMB']}MiB")+ else:+ print(f" {i['name']}: {live}MiB (matches)")+ if bad and not allow_resize:+ print("\nREFUSING — manifest memory does not match the live image:")+ print("\n".join(bad))+ print("\nIf this resize is intended, re-run with MICROVM_ALLOW_RESIZE=1.")+ sys.exit(1)+ if bad:+ print("\nMICROVM_ALLOW_RESIZE=1 — resizing:")+ print("\n".join(bad))++ elif cmd == "cp-config":+ acct = account()+ imgs = e["images"]+ default = next((i for i in imgs if i.get("default")), imgs[0])+ print(f"OPENSANDBOX_MICROVM_IMAGE_ARN={arn(region, acct, default['name'])}")+ tiers = [i for i in imgs if not i.get("default")]+ if tiers:+ print("OPENSANDBOX_MICROVM_SIZE_IMAGES=" + ",".join(+ f"{i['memoryMB']}={arn(region, acct, i['name'])}" for i in tiers))+ else:+ print("# no size tiers — leave OPENSANDBOX_MICROVM_SIZE_IMAGES unset")+ elif cmd == "guest-hash":+ print(guest_hash())++ elif cmd == "check-drift":+ # Exact: what this checkout would build vs what each image was built+ # from. Catches a bypassed CI run and a dependency nobody thought to+ # watch, both of which a path filter misses.+ want, acct, stale = guest_hash(), account(), []+ print(f" guest source hash: {want}")+ for i in e["images"]:+ got = published_hash(region, acct, i["name"])+ if got == want:+ print(f" {i['name']}: current")+ else:+ stale.append(i["name"])+ print(f" {i['name']}: STALE (published from {got or 'unstamped'})")+ if stale:+ print(f"\n{len(stale)} image(s) behind this checkout: {', '.join(stale)}")+ print("Run: ./deploy/microvm/release.sh " + env)+ sys.exit(1)++ else:+ sys.exit(f"unknown subcommand {cmd!r}")+++if __name__ == "__main__":+ main()diff --git a/deploy/microvm/publish.sh b/deploy/microvm/publish.shindex 949fe0e9..d6e39f18 100755--- a/deploy/microvm/publish.sh+++ b/deploy/microvm/publish.sh@@ -92,6 +92,30 @@ RESOURCES="[{\"minimumMemoryInMiB\":${MEMORY_MB}}]"# instead of wherever the service would otherwise default.LOGGING="{\"cloudWatch\":{\"logGroup\":\"/aws/lambda/microvms/${NAME}\"}}"+# Egress connectors are carried explicitly on every update.+#+# They were not, and omitting them on an update is not "leave as it was" — the+# same way base-image-arn and build-role-arn are required on every update. A+# routine rebuild would have detached INTERNET_EGRESS from the image and every+# new sandbox would have booted with no route off the box, which looks like the+# customer's code hanging rather than like a deploy. Read what the image already+# has and pass it back; fall back to AWS's internet connector for a new image.+EXISTING_EGRESS="$(aws lambda-microvms list-microvm-image-versions \+ --image-identifier "$IMAGE_ARN" --region "$REGION" \+ --query 'items[0].egressNetworkConnectors' --output json 2>/dev/null || echo 'null')"+if [[ -z "$EXISTING_EGRESS" || "$EXISTING_EGRESS" == "null" || "$EXISTING_EGRESS" == "[]" ]]; then+ EGRESS="${MICROVM_EGRESS_CONNECTORS:-arn:aws:lambda:${REGION}:aws:network-connector:aws-network-connector:INTERNET_EGRESS}"+else+ EGRESS="$(printf '%s' "$EXISTING_EGRESS" | python3 -c 'import json,sys; print(",".join(json.load(sys.stdin)))')"+fi+echo "egress connectors: ${EGRESS}"++# The stamp that makes drift detectable. The image API has no tags, so the guest+# source hash rides in the description and manifest.py check-drift compares it+# against what the checkout would build. Without it, "is this image current?"+# has no answer short of rebuilding and diffing binaries.+DESCRIPTION="${MICROVM_IMAGE_DESCRIPTION:-guest=unstamped}"+common=(--code-artifact "uri=${DEST}"--base-image-arn "$BASE_IMAGE_ARN"@@ -100,6 +124,8 @@ common=(--cpu-configurations "$CPU"--resources "$RESOURCES"--logging "$LOGGING"+ --description "$DESCRIPTION"+ --egress-network-connectors "$EGRESS"--region "$REGION")diff --git a/deploy/microvm/release.sh b/deploy/microvm/release.shnew file mode 100755index 00000000..cda259fb--- /dev/null+++ b/deploy/microvm/release.sh@@ -0,0 +1,60 @@+#!/usr/bin/env bash+# Build the guest artifact once and publish EVERY image tier from it.+#+# The drift this prevents, in the shape it took: the guest gained /oc/secrets,+# /oc/envs and /oc/stats on 2026-09-01. Nothing rebuilt the published images, so+# the control plane called routes its own guests did not serve. A JSON POST to+# an unregistered path falls through to the agent's gRPC listener, which answers+# 415 with an empty body — so it surfaced as an unexplained "failed to start the+# sandbox" weeks later, to the first customer whose create carried a secret.+#+# The tier half is the same defect one level down: memory is a property of the+# image, so N sizes means N images, and republishing only the default leaves the+# rest behind.+#+# So: one build, every image in images.json, or nothing.+#+# ./deploy/microvm/release.sh dev+# ./deploy/microvm/release.sh prod+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+MANIFEST="$HERE/manifest.py"+ENVIRONMENT="${1:-}"+if [[ -z "$ENVIRONMENT" ]]; then+ echo "usage: $0 <environment>" >&2+ exit 2+fi++# The ownership guard lives in manifest.py and runs on every read, so an+# environment naming another product's runtime fails here, before any build.+read -r REGION BUCKET KEY <<<"$("$MANIFEST" config "$ENVIRONMENT")"+DEST="s3://${BUCKET}/${KEY}"+export AWS_REGION="$REGION"++echo "environment : $ENVIRONMENT"+echo "artifact : $DEST"+echo+echo "=== memory tiers (publishing may change code, never size) ==="+"$MANIFEST" check-memory "$ENVIRONMENT"++# Stamped onto every image so drift is an exact comparison later, not a guess.+GUEST_HASH="$("$MANIFEST" guest-hash "$ENVIRONMENT")"+GIT_SHA="$(git -C "$HERE/../.." rev-parse --short HEAD 2>/dev/null || echo unknown)"+export MICROVM_IMAGE_DESCRIPTION="guest=${GUEST_HASH} git=${GIT_SHA}"+echo "stamp : $MICROVM_IMAGE_DESCRIPTION"++echo+"$HERE/build.sh" "$DEST"++# Every image, from the one artifact just uploaded. set -e makes a failure here+# fatal: a half-published set is the drift this exists to prevent.+while read -r NAME MEM; do+ echo+ echo "=== publishing $NAME (${MEM}MiB) ==="+ MICROVM_IMAGE_NAME="$NAME" MICROVM_IMAGE_MEMORY_MB="$MEM" "$HERE/publish.sh" "$DEST"+done < <("$MANIFEST" images "$ENVIRONMENT")++echo+echo "=== published. Control-plane configuration for $ENVIRONMENT ==="+"$MANIFEST" cp-config "$ENVIRONMENT"diff --git a/deploy/microvm/smoke.sh b/deploy/microvm/smoke.shnew file mode 100755index 00000000..dcb24732--- /dev/null+++ b/deploy/microvm/smoke.sh@@ -0,0 +1,52 @@+#!/usr/bin/env bash+# Prove a freshly published guest image actually serves a real create.+#+# Publishing only proves the image BUILT. This proves it boots and answers the+# control plane — which is the gap that let a guest missing /oc/secrets sit in+# production for three weeks: it built fine, and nothing ever asked it to serve+# the route the control plane was calling.+#+# The create deliberately carries an egressAllowlist. That trips HasSecrets(),+# which is what sends the control plane to /oc/secrets — the exact path whose+# absence returned 415 with an empty body and failed every create carrying a+# secret. A plain create would pass against a broken image.+#+# ./deploy/microvm/smoke.sh https://app2.opensandbox.ai "$API_KEY"+set -euo pipefail++BASE="${1:-}"+KEY="${2:-}"+if [[ -z "$BASE" || -z "$KEY" ]]; then+ echo "usage: $0 <base-url> <api-key>" >&2+ exit 2+fi++echo "smoke: creating a sandbox with an egress allowlist on $BASE"+BODY="$(mktemp)"; trap 'rm -f "$BODY"' EXIT+CODE="$(curl -sS -o "$BODY" -w '%{http_code}' -X POST "$BASE/api/sandboxes" \+ -H "X-API-Key: $KEY" -H 'content-type: application/json' \+ -H 'x-oc-sdk-version: 1.0.0' \+ -d '{"egressAllowlist":["api.github.com"]}')"++if [[ "$CODE" != "201" ]]; then+ echo "smoke FAILED: create returned $CODE" >&2+ head -c 600 "$BODY" >&2; echo >&2+ echo >&2+ echo "A 415 on /oc/secrets here means the published guest does not serve it —" >&2+ echo "the image is older than the control plane calling it." >&2+ exit 1+fi++SB="$(python3 -c "import json;print(json.load(open('$BODY'))['sandboxID'])")"+WORKER="$(python3 -c "import json;print(json.load(open('$BODY')).get('workerID',''))")"+echo "smoke: created $SB on $WORKER"++# It must be a MicroVM box, or we proved nothing about the image we just built.+case "$WORKER" in+ vmhost:*|microvm:*) ;;+ *) echo "smoke FAILED: $SB landed on $WORKER, not a MicroVM worker" >&2; exit 1 ;;+esac++# Best effort: a leaked smoke box costs money until the service cap.+curl -sS -X DELETE "$BASE/api/sandboxes/$SB" -H "X-API-Key: $KEY" -o /dev/null || true+echo "smoke: OK (deleted $SB)"