An open-source, faster Devin alternative
TypeScript
tests and fixes
Brian Reardon5ae620d48c8a
diff --git a/examples/typescript/27-ts-sdk-ops.ts b/examples/typescript/27-ts-sdk-ops.tsnew file mode 100644index 00000000..47230805--- /dev/null+++ b/examples/typescript/27-ts-sdk-ops.ts@@ -0,0 +1,278 @@+/**+ * 80 operations through the TypeScript SDK + CLI — tests every API surface.+ * Run: cd examples/typescript && npx tsx ../../scripts/qemu-tests/27-ts-sdk-ops.ts+ */++import { Sandbox } from "../../sdks/typescript/src/index.js";+import { execSync } from "child_process";+import * as crypto from "crypto";++const API_KEY = process.env.OPENSANDBOX_API_KEY || "";+const API_URL = process.env.OPENSANDBOX_API_URL || "http://20.114.60.29:8080";+const OC = "/tmp/oc";++let PASS = 0;+let FAIL = 0;++function ok(msg: string) { PASS++; console.log(` \x1b[32m✓ ${msg}\x1b[0m`); }+function bad(msg: string) { FAIL++; console.log(` \x1b[31m✗ ${msg}\x1b[0m`); }+function check(name: string, cond: boolean, detail = "") {+ cond ? ok(name) : bad(`${name}: ${detail}`);+}+function h(msg: string) { console.log(`\n\x1b[1;34m=== ${msg} ===\x1b[0m`); }++function cli(...args: string[]): string {+ try {+ return execSync(`${OC} ${args.join(" ")}`, {+ env: { ...process.env, OPENCOMPUTER_API_KEY: API_KEY, OPENCOMPUTER_API_URL: API_URL },+ timeout: 30000,+ }).toString().trim();+ } catch (e: any) {+ return e.stdout?.toString().trim() || e.message;+ }+}++function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }++async function main() {+ const t0 = Date.now();++ // ── Create via CLI ─────────────────────────────────────────────+ h("Create (CLI)");+ const createJson = cli("create", "--json");+ const sbId = JSON.parse(createJson).sandboxID;+ check("CLI create", sbId.startsWith("sb-"), sbId);++ const sb = await Sandbox.connect(sbId, { apiKey: API_KEY, apiUrl: API_URL });+ check("SDK connect", sb.sandboxId === sbId);++ // ── Exec via SDK (15 ops) ──────────────────────────────────────+ h("Exec — SDK (15 operations)");++ let r = await sb.exec.run("echo hello");+ check("exec echo", r.stdout.trim() === "hello", r.stdout.trim());++ r = await sb.exec.run("python3 -c 'print(2+2)'");+ check("exec python", r.stdout.trim() === "4", r.stdout.trim());++ r = await sb.exec.run("node -e 'console.log(3*3)'");+ check("exec node", r.stdout.trim() === "9", r.stdout.trim());++ r = await sb.exec.run("whoami");+ check("exec whoami", r.stdout.trim() === "sandbox", r.stdout.trim());++ r = await sb.exec.run("bash -c 'exit 42'");+ check("non-zero exit", r.exitCode === 42, `exit=${r.exitCode}`);++ r = await sb.exec.run("python3 -c 'print(\"x\"*50000)'");+ check("large stdout", r.stdout.length >= 50000, `len=${r.stdout.length}`);++ r = await sb.exec.run("echo $MY_VAR", { env: { MY_VAR: "ts-env" } });+ check("env vars", r.stdout.trim() === "ts-env", r.stdout.trim());++ r = await sb.exec.run("pwd", { cwd: "/tmp" });+ check("cwd", r.stdout.trim() === "/tmp", r.stdout.trim());++ r = await sb.exec.run("sleep 30", { timeout: 2 });+ check("exec timeout", r.exitCode !== 0, `exit=${r.exitCode}`);++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get");+ check("network HTTPS", r.stdout.trim() === "200", r.stdout.trim());++ for (let i = 0; i < 5; i++) {+ r = await sb.exec.run(`echo rapid-${i}`);+ check(`rapid exec ${i}`, r.stdout.trim() === `rapid-${i}`, r.stdout.trim());+ }++ // ── Exec via CLI (5 ops) ───────────────────────────────────────+ h("Exec — CLI (5 operations)");++ let out = cli("exec", sbId, "--wait", "--", "echo", "cli-hello");+ check("CLI exec echo", out === "cli-hello", out);++ out = cli("exec", sbId, "--wait", "--", "python3", "-c", "'print(\"cli-py\")'");+ check("CLI exec python", out === "cli-py", out);++ out = cli("exec", sbId, "--wait", "--", "git", "--version");+ check("CLI exec git", out.includes("git version"), out);++ out = cli("exec", sbId, "--wait", "--", "uname", "-s");+ check("CLI exec uname", out === "Linux", out);++ out = cli("exec", sbId, "--wait", "--", "free", "-m");+ check("CLI exec free", out.includes("Mem:"), out.substring(0, 40));++ // ── Files via SDK (10 ops) ─────────────────────────────────────+ h("Files — SDK (10 operations)");++ for (let i = 0; i < 5; i++) {+ await sb.files.write(`/workspace/ts-file-${i}.txt`, `ts-content-${i}`);+ }+ check("write 5 files", true);++ let allMatch = true;+ for (let i = 0; i < 5; i++) {+ const c = await sb.files.read(`/workspace/ts-file-${i}.txt`);+ if (c !== `ts-content-${i}`) allMatch = false;+ }+ check("read 5 files", allMatch);++ const binData = crypto.randomBytes(100 * 1024);+ const binHash = crypto.createHash("sha256").update(binData).digest("hex");+ await sb.files.write("/workspace/ts-binary.bin", binData);+ r = await sb.exec.run("sha256sum /workspace/ts-binary.bin | cut -d' ' -f1");+ check("100KB binary hash", r.stdout.trim() === binHash, r.stdout.trim().substring(0, 16));++ const entries = await sb.files.list("/workspace");+ check("list dir", entries.length > 5, `entries=${entries.length}`);++ await sb.files.makeDir("/workspace/ts-nested/deep");+ r = await sb.exec.run("test -d /workspace/ts-nested/deep && echo yes || echo no");+ check("mkdir", r.stdout.trim() === "yes", r.stdout.trim());++ await sb.files.write("/workspace/ts-del.txt", "bye");+ await sb.files.remove("/workspace/ts-del.txt");+ const gone = await sb.files.exists("/workspace/ts-del.txt");+ check("remove file", !gone);++ const dlUrl = await sb.downloadUrl("/workspace/ts-file-0.txt");+ check("download URL", dlUrl.includes("signature"));++ const ulUrl = await sb.uploadUrl("/workspace/ts-upload.txt");+ check("upload URL", ulUrl.includes("signature"));++ // ── Scale (5 ops) ──────────────────────────────────────────────+ h("Scale (5 operations)");++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'");+ check("baseline memory", parseInt(r.stdout.trim()) > 800, `${r.stdout.trim()}MB`);++ for (const mem of [2048, 4096, 2048]) {+ r = await sb.exec.run(`curl -s -X POST http://169.254.169.254/v1/scale -d '{"memoryMB":${mem}}'`);+ await sleep(500);+ }+ check("3 scale operations", true);++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'");+ check("memory after scale", parseInt(r.stdout.trim()) > 1800, `${r.stdout.trim()}MB`);++ r = await sb.exec.run("curl -s -X POST http://169.254.169.254/v1/scale -d '{\"memoryMB\":1024}'");+ check("scale back to 1GB", true);++ // ── Preview URLs (4 ops) ───────────────────────────────────────+ h("Preview URLs (4 operations)");++ await sb.exec.run("bash -c 'setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &'");+ await sleep(1000);++ const preview = await sb.createPreviewURL({ port: 3000 });+ check("create preview", !!preview.hostname, preview.hostname);++ const previews = await sb.listPreviewURLs();+ check("list previews", previews.length >= 1, `count=${previews.length}`);++ await sb.deletePreviewURL(3000);+ check("delete preview", true);++ await sb.exec.run("pkill -9 -f 'http.server 3000' 2>/dev/null; true");+ check("cleanup server", true);++ // ── Checkpoint + Fork via SDK (10 ops) ─────────────────────────+ h("Checkpoint + Fork — SDK (10 operations)");++ await sb.exec.run("bash -c 'echo ts-checkpoint > /workspace/ts-cp.txt && sync && sync'");+ await sleep(1000);++ const cp = await sb.createCheckpoint(`ts-cp-${Date.now()}`);+ check("create checkpoint", !!cp.id, cp.id.substring(0, 12));++ const cps = await sb.listCheckpoints();+ check("list checkpoints", cps.length >= 1, `count=${cps.length}`);++ await sleep(5000);+ const fork = await Sandbox.createFromCheckpoint(cp.id, { apiKey: API_KEY, apiUrl: API_URL, timeout: 120 });+ check("fork", fork.sandboxId.startsWith("sb-"), fork.sandboxId);++ await sleep(5000);+ r = await fork.exec.run("cat /workspace/ts-cp.txt");+ check("fork data", r.stdout.trim() === "ts-checkpoint", r.stdout.trim());++ await fork.exec.run("echo fork-only > /workspace/fork-only.txt");+ r = await sb.exec.run("cat /workspace/fork-only.txt 2>/dev/null || echo not-found");+ check("fork isolated", r.stdout.trim() === "not-found");++ await fork.kill();+ check("kill fork", true);++ // Restore+ await sb.exec.run("echo post-cp > /workspace/ts-cp.txt");+ await sb.restoreCheckpoint(cp.id);+ await sleep(15000);+ r = await sb.exec.run("cat /workspace/ts-cp.txt");+ check("restore reverted", r.stdout.trim() === "ts-checkpoint", r.stdout.trim());++ await sb.deleteCheckpoint(cp.id);+ check("delete checkpoint", true);++ // ── Hibernate + Wake via SDK (6 ops) ───────────────────────────+ h("Hibernate + Wake — SDK (6 operations)");++ await sb.exec.run("echo pre-hib > /workspace/hib.txt");+ await sb.hibernate();+ check("hibernate", true);++ await sb.wake({ timeout: 3600 });+ check("wake", true);++ r = await sb.exec.run("cat /workspace/hib.txt");+ check("data survived", r.stdout.trim() === "pre-hib", r.stdout.trim());++ r = await sb.exec.run("echo post-wake");+ check("exec after wake", r.stdout.trim() === "post-wake");++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get");+ check("network after wake", r.stdout.trim() === "200", r.stdout.trim());++ r = await sb.exec.run("python3 -c 'print(1+1)'");+ check("python after wake", r.stdout.trim() === "2");++ // ── CLI: hibernate + wake (3 ops) ──────────────────────────────+ h("Hibernate + Wake — CLI (3 operations)");++ cli("sandbox", "hibernate", sbId);+ check("CLI hibernate", true);++ cli("sandbox", "wake", sbId);+ check("CLI wake", true);++ out = cli("exec", sbId, "--wait", "--", "echo", "cli-post-wake");+ check("CLI exec after wake", out === "cli-post-wake", out);++ // ── Timeout via SDK (2 ops) ────────────────────────────────────+ h("Timeout (2 operations)");++ await sb.setTimeout(600);+ check("set timeout 600s", true);++ await sb.setTimeout(0);+ check("set timeout 0 (unlimited)", true);++ // ── Final checks (3 ops) ───────────────────────────────────────+ h("Final Checks (3 operations)");++ r = await sb.exec.run("echo final-ts-health");+ check("final exec", r.stdout.trim() === "final-ts-health");++ const running = await sb.isRunning();+ check("sandbox running", running);++ await sb.kill();+ check("kill sandbox", true);++ const elapsed = ((Date.now() - t0) / 1000).toFixed(0);+ const total = PASS + FAIL;+ console.log(`\n\x1b[1m${PASS} passed, ${FAIL} failed (${total} total, ${elapsed}s)\x1b[0m`);+ process.exit(FAIL > 0 ? 1 : 0);+}++main().catch(e => { console.error(e); process.exit(1); });diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex a7a23672..35748e7d 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1355,10 +1355,17 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {}// Dispatch restore in background — return immediately.- // Commands will block until restore completes.+ // Commands will block until restore completes (via pendingCreates + waitForReady).pending := &pendingCreate{ready: make(chan struct{})}s.pendingCreates.Store(sandboxID, pending)+ // Invalidate the proxy route cache so subsequent requests go through+ // the full ProxyHandler path and hit waitForReady. Without this, cached+ // routes bypass the readiness check and hit the mid-restore VM.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)+ }+if s.workerRegistry != nil {grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {diff --git a/internal/db/store.go b/internal/db/store.goindex 2c0d1ef9..1deb814e 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -32,7 +32,15 @@ func (s *Store) SetEncryptor(enc *crypto.Encryptor) {// NewStore creates a new Store with a connection pool.func NewStore(ctx context.Context, databaseURL string) (*Store, error) {- pool, err := pgxpool.New(ctx, databaseURL)+ poolCfg, err := pgxpool.ParseConfig(databaseURL)+ if err != nil {+ return nil, fmt.Errorf("failed to parse database URL: %w", err)+ }+ // Default pool is 4 connections — far too low for proxy-per-request pattern.+ // Each proxied exec/file/pty call does a DB lookup before forwarding.+ poolCfg.MaxConns = 50+ poolCfg.MinConns = 5+ pool, err := pgxpool.NewWithConfig(ctx, poolCfg)if err != nil {return nil, fmt.Errorf("failed to connect to database: %w", err)}diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.goindex 3e4eb32a..01f4ecc1 100644--- a/internal/proxy/controlplane_proxy.go+++ b/internal/proxy/controlplane_proxy.go@@ -26,6 +26,7 @@ type ControlPlaneProxy struct {baseDomain stringstore *db.Storeregistry *controlplane.RedisWorkerRegistry+ transport *http.Transport}// NewControlPlaneProxy creates a proxy for control plane subdomain routing.@@ -34,6 +35,17 @@ func NewControlPlaneProxy(baseDomain string, store *db.Store, registry *controlpbaseDomain: baseDomain,store: store,registry: registry,+ transport: &http.Transport{+ DialContext: (&net.Dialer{+ Timeout: 5 * time.Second,+ KeepAlive: 30 * time.Second,+ }).DialContext,+ ResponseHeaderTimeout: 30 * time.Second,+ MaxIdleConns: 200,+ MaxIdleConnsPerHost: 50,+ MaxConnsPerHost: 100,+ IdleConnTimeout: 120 * time.Second,+ },}}@@ -213,13 +225,7 @@ func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string,}proxy := httputil.NewSingleHostReverseProxy(target)- proxy.Transport = &http.Transport{- DialContext: (&net.Dialer{- Timeout: 5 * time.Second,- }).DialContext,- ResponseHeaderTimeout: 30 * time.Second,- MaxIdleConnsPerHost: 10,- }+ proxy.Transport = p.transportvar proxyErr errorproxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.goindex 8e8688cd..d6f477ed 100644--- a/internal/proxy/sandbox_api_proxy.go+++ b/internal/proxy/sandbox_api_proxy.go@@ -25,19 +25,84 @@ import (// termination: clients talk to the control plane through the ALB, and the// control plane forwards exec/files/pty/agent requests to workers over the// internal VPC network.+// proxyRouteCache caches the sandbox→worker mapping + JWT to avoid DB/Redis+// lookups and JWT minting on every proxied request. TTL-based eviction.+type proxyRouteCache struct {+ mu sync.RWMutex+ entries map[string]*routeCacheEntry+}++type routeCacheEntry struct {+ workerURL string+ workerID string+ token string+ expiresAt time.Time+}++const routeCacheTTL = 10 * time.Second++func newProxyRouteCache() *proxyRouteCache {+ return &proxyRouteCache{entries: make(map[string]*routeCacheEntry)}+}++func (c *proxyRouteCache) get(sandboxID string) (workerURL, workerID, token string, ok bool) {+ c.mu.RLock()+ defer c.mu.RUnlock()+ e, exists := c.entries[sandboxID]+ if !exists || time.Now().After(e.expiresAt) {+ return "", "", "", false+ }+ return e.workerURL, e.workerID, e.token, true+}++func (c *proxyRouteCache) set(sandboxID, workerURL, workerID, token string) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.entries[sandboxID] = &routeCacheEntry{+ workerURL: workerURL,+ workerID: workerID,+ token: token,+ expiresAt: time.Now().Add(routeCacheTTL),+ }+}++func (c *proxyRouteCache) invalidate(sandboxID string) {+ c.mu.Lock()+ defer c.mu.Unlock()+ delete(c.entries, sandboxID)+}++// SandboxAPIProxy proxies data-plane HTTP/WebSocket requests from the control+// plane to the worker that owns the sandbox.type SandboxAPIProxy struct {store *db.Storeregistry *controlplane.RedisWorkerRegistryjwtIssuer *auth.JWTIssuer+ transport *http.Transport // shared connection pool for all proxy requests+ routeCache *proxyRouteCache // sandbox→worker cache to avoid DB lookup per requestwaitForReady func(ctx context.Context, sandboxID string) error // blocks until async sandbox creation completes; nil = no-op}// NewSandboxAPIProxy creates a new sandbox API proxy.func NewSandboxAPIProxy(store *db.Store, registry *controlplane.RedisWorkerRegistry, jwtIssuer *auth.JWTIssuer) *SandboxAPIProxy {return &SandboxAPIProxy{- store: store,- registry: registry,- jwtIssuer: jwtIssuer,+ store: store,+ registry: registry,+ jwtIssuer: jwtIssuer,+ routeCache: newProxyRouteCache(),+ // Shared transport with connection pooling — creating a new Transport per request+ // exhausts ephemeral ports under load and causes 502s.+ transport: &http.Transport{+ DialContext: (&net.Dialer{+ Timeout: 5 * time.Second,+ KeepAlive: 30 * time.Second,+ }).DialContext,+ ResponseHeaderTimeout: 600 * time.Second,+ MaxIdleConns: 200,+ MaxIdleConnsPerHost: 50,+ MaxConnsPerHost: 100,+ IdleConnTimeout: 120 * time.Second,+ },}}@@ -48,9 +113,16 @@ func (p *SandboxAPIProxy) SetWaitForReady(fn func(ctx context.Context, sandboxIDp.waitForReady = fn}+// InvalidateRouteCache removes a sandbox from the proxy route cache.+// Call this on hibernate, kill, or any event that changes the sandbox→worker mapping.+func (p *SandboxAPIProxy) InvalidateRouteCache(sandboxID string) {+ if p.routeCache != nil {+ p.routeCache.invalidate(sandboxID)+ }+}+// ProxyHandler forwards requests for a sandbox to the worker that owns it.-// It extracts the sandbox ID from the path param ":id", looks up the worker,-// mints a short-lived JWT, and proxies the request.+// Uses a short-TTL cache to avoid DB + Redis lookups on every request.func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {sandboxID := c.Param("id")if sandboxID == "" {@@ -61,6 +133,11 @@ func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {ctx := c.Request().Context()+ // Fast path: check route cache (avoids DB + Redis + JWT mint)+ if workerURL, workerID, token, ok := p.routeCache.get(sandboxID); ok {+ return p.forwardWithToken(c, sandboxID, workerURL, workerID, token)+ }+// If this sandbox is still being created asynchronously, wait for it.if p.waitForReady != nil {if err := p.waitForReady(ctx, sandboxID); err != nil {@@ -113,9 +190,8 @@ func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {return p.forward(c, sandboxID, worker.HTTPAddr, session.WorkerID)}-// forward proxies the request to the worker, adding a sandbox JWT for auth.+// forward proxies the request to the worker, mints a JWT, caches the route.func (p *SandboxAPIProxy) forward(c echo.Context, sandboxID, workerURL, workerID string) error {- // Mint a short-lived JWT for the workertoken := ""if p.jwtIssuer != nil {orgID, _ := auth.GetOrgID(c)@@ -125,6 +201,14 @@ func (p *SandboxAPIProxy) forward(c echo.Context, sandboxID, workerURL, workerID}}+ // Cache the route for subsequent requests to the same sandbox+ p.routeCache.set(sandboxID, workerURL, workerID, token)++ return p.forwardWithToken(c, sandboxID, workerURL, workerID, token)+}++// forwardWithToken proxies the request using a pre-resolved worker URL and JWT.+func (p *SandboxAPIProxy) forwardWithToken(c echo.Context, sandboxID, workerURL, workerID, token string) error {if isWebSocketUpgrade(c.Request()) {return p.doWebSocket(c, sandboxID, workerURL, token)}@@ -143,19 +227,13 @@ func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token str}proxy := httputil.NewSingleHostReverseProxy(target)- proxy.FlushInterval = -1 // flush chunks immediately- proxy.Transport = &http.Transport{- DialContext: (&net.Dialer{- Timeout: 5 * time.Second,- }).DialContext,- ResponseHeaderTimeout: 600 * time.Second, // exec/run can take minutes (npm build, etc.)- MaxIdleConnsPerHost: 10,- IdleConnTimeout: 120 * time.Second,- }+ proxy.FlushInterval = -1 // flush chunks immediately+ proxy.Transport = p.transport // shared connection pool — avoids ephemeral port exhaustionproxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {log.Printf("sandbox-api-proxy: error proxying sandbox %s to %s: %v", sandboxID, workerURL, err)- // Write error JSON directly — headers may not have been sent yet+ // Invalidate cache — worker may have moved or restarted+ p.routeCache.invalidate(sandboxID)w.Header().Set("Content-Type", "application/json")w.WriteHeader(http.StatusBadGateway)fmt.Fprintf(w, `{"error":"sandbox %s: upstream unavailable"}`, sandboxID)diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex bc7c77a6..33b64ef3 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -409,26 +409,38 @@ func (c *AgentClient) WriteFileStream(ctx context.Context, path string, mode uinreturn 0, err}+ // Always send the first message with path + mode, even for empty files.+ // Without this, an empty body sends no gRPC messages and the agent gets EOF.buf := make([]byte, streamChunkSize)- first := true- for {- n, err := r.Read(buf)- if n > 0 {- msg := &pb.WriteFileStreamRequest{Data: buf[:n]}- if first {- msg.Path = path- msg.Mode = mode- first = false+ n, readErr := r.Read(buf)+ firstMsg := &pb.WriteFileStreamRequest{+ Path: path,+ Mode: mode,+ Data: buf[:n],+ }+ if sendErr := stream.Send(firstMsg); sendErr != nil {+ return 0, fmt.Errorf("send first chunk: %w", sendErr)+ }++ if readErr != nil && readErr != io.EOF {+ return 0, fmt.Errorf("read source: %w", readErr)+ }++ // Send remaining chunks+ if readErr != io.EOF {+ for {+ n, err := r.Read(buf)+ if n > 0 {+ if sendErr := stream.Send(&pb.WriteFileStreamRequest{Data: buf[:n]}); sendErr != nil {+ return 0, fmt.Errorf("send chunk: %w", sendErr)+ }}- if sendErr := stream.Send(msg); sendErr != nil {- return 0, fmt.Errorf("send chunk: %w", sendErr)+ if err == io.EOF {+ break+ }+ if err != nil {+ return 0, fmt.Errorf("read source: %w", err)}- }- if err == io.EOF {- break- }- if err != nil {- return 0, fmt.Errorf("read source: %w", err)}}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 0ee1e6c2..1a5caee8 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1641,9 +1641,7 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStoreturn nil, err}- if !vm.opMu.TryLock() {- return nil, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)- }+ vm.opMu.Lock()defer vm.opMu.Unlock()// Check if agent needs upgrading before we hibernate.@@ -1760,7 +1758,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDsyncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", "sync; kill -USR1 1"},+ Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},RunAsRoot: true,})cancel()@@ -1863,9 +1861,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoireturn err}- if !vm.opMu.TryLock() {- return fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)- }+ vm.opMu.Lock()defer vm.opMu.Unlock()t0 := time.Now()@@ -1914,6 +1910,15 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoisnapshotName = strings.TrimSpace(string(data))}+ // Read checkpoint metadata for base topology. loadvm requires the same CPU/memory+ // topology as when the snapshot was taken. If the sandbox was scaled after checkpoint,+ // vm.MemoryMB reflects the scaled value — but we must boot with the base value+ // and re-scale after loadvm.+ var cpMeta SnapshotMeta+ if metaData, err := os.ReadFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")); err == nil {+ json.Unmarshal(metaData, &cpMeta)+ }+sandboxDir := vm.sandboxDirrootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")@@ -1969,8 +1974,24 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoios.Remove(qmpSockPath)os.Remove(agentSockPath)+ // Boot with checkpoint's base topology so loadvm succeeds.+ // After loadvm, re-scale to the user's desired size if different.+ bootCpus := cpMeta.CpuCount+ if bootCpus <= 0 {+ bootCpus = vm.CpuCount+ }+ bootMemMB := cpMeta.BaseMemoryMB+ if bootMemMB <= 0 {+ bootMemMB = vm.baseMemoryMB+ }+ if bootMemMB <= 0 {+ bootMemMB = m.cfg.DefaultMemoryMB+ }+ // Remember what the user had so we can re-scale after loadvm+ desiredMemMB := vm.MemoryMB+logFile, _ := os.Create(filepath.Join(sandboxDir, "qemu.log"))- args := m.buildQEMUArgs(vm.CpuCount, vm.MemoryMB, rootfsPath, workspacePath,+ args := m.buildQEMUArgs(bootCpus, bootMemMB, rootfsPath, workspacePath,netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)args = append(args, "-S")@@ -1989,7 +2010,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi}// Step 6: QMP connect + loadvm + cont- qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)+ qmpClient, err := waitForQMP(qmpSockPath, 30*time.Second)if err != nil {cmd.Process.Kill()cmd.Wait()@@ -2005,6 +2026,21 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoireturn fmt.Errorf("loadvm: %w", err)}+ // Re-scale virtio-mem BEFORE cont — the VM is paused, so the kernel sees full+ // memory immediately on resume. Without this, restored processes that were using+ // >baseMemMB would OOM before the post-resume re-scale completes.+ if desiredMemMB > bootMemMB {+ additionalMB := desiredMemMB - bootMemMB+ additionalMB = ((additionalMB + 127) / 128) * 128 // align to 128MB block size+ if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {+ log.Printf("qemu: RestoreFromCheckpoint %s: pre-resume scale to %dMB failed: %v (continuing with base %dMB)",+ sandboxID, desiredMemMB, err, bootMemMB)+ } else {+ log.Printf("qemu: RestoreFromCheckpoint %s: pre-resume scale to %dMB (base=%d + virtio-mem=%d)",+ sandboxID, bootMemMB+additionalMB, bootMemMB, additionalMB)+ }+ }+if err := qmpClient.Cont(); err != nil {qmpClient.Close()cmd.Process.Kill()@@ -2014,7 +2050,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi}// Step 7: Reconnect agent + patch network- agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)+ agentClient, err := m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)if err != nil {qmpClient.Close()cmd.Process.Kill()@@ -2041,8 +2077,20 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoivm.guestMAC = guestMACvm.bootArgs = bootArgsvm.pid = cmd.Process.Pid+ vm.CpuCount = bootCpus+ vm.baseMemoryMB = bootMemMB+ if desiredMemMB > bootMemMB {+ additionalMB := ((desiredMemMB - bootMemMB + 127) / 128) * 128+ vm.MemoryMB = bootMemMB + additionalMB+ vm.virtioMemRequestedMB = additionalMB+ } else {+ vm.MemoryMB = bootMemMB+ vm.virtioMemRequestedMB = 0+ }- m.upgradeAgentIfNeeded(context.Background(), vm)+ // Don't upgrade agent during restore — the checkpoint was created from the+ // same rootfs, and the upgrade's syscall.Exec + reconnect cycle is fragile.+ // Agent upgrades happen on golden snapshot creation and wake instead.log.Printf("qemu: RestoreFromCheckpoint %s/%s: complete (%dms, port=%d, tap=%s)",sandboxID, checkpointID, time.Since(t0).Milliseconds(), hostPort, netCfg.TAPName)@@ -2613,11 +2661,16 @@ func (m *Manager) upgradeAgentIfNeeded(ctx context.Context, vm *VMInstance) {vm.agent.Close()newAgent, err := m.waitForAgentSocket(ctx, vm.agentSockPath, 30*time.Second)if err != nil {- log.Printf("qemu: agent %s: reconnect failed: %v", vm.ID, err)+ log.Printf("qemu: agent %s: reconnect after upgrade failed: %v, retrying...", vm.ID, err)fallback, fbErr := m.waitForAgentSocket(ctx, vm.agentSockPath, 15*time.Second)if fbErr == nil {vm.agent = fallbacklog.Printf("qemu: agent %s: fallback reconnect succeeded", vm.ID)+ } else {+ // Both reconnect attempts failed — agent is dead.+ // Set to nil so callers get "agent not available" instead of using a closed connection.+ vm.agent = nil+ log.Printf("qemu: agent %s: CRITICAL: all reconnect attempts failed after upgrade, agent unavailable", vm.ID)}return}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex cbfbbe77..42b91a8f 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -66,7 +66,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoshutdownCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, _ = vm.agent.Exec(shutdownCtx, &pb.ExecRequest{Command: "/bin/sh",- Args: []string{"-c", "sync; kill -USR1 1"},+ Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},RunAsRoot: true,})cancel()diff --git a/internal/worker/handlers.go b/internal/worker/handlers.goindex 7de7767d..ae349508 100644--- a/internal/worker/handlers.go+++ b/internal/worker/handlers.go@@ -36,9 +36,9 @@ func (s *HTTPServer) setTimeout(c echo.Context) error {})}- if req.Timeout <= 0 {+ if req.Timeout < 0 {return c.JSON(http.StatusBadRequest, map[string]string{- "error": "timeout must be positive",+ "error": "timeout must be non-negative (0 = no timeout)",})}diff --git a/scripts/qemu-tests/21-latency-stress.sh b/scripts/qemu-tests/21-latency-stress.shnew file mode 100755index 00000000..c8236aa9--- /dev/null+++ b/scripts/qemu-tests/21-latency-stress.sh@@ -0,0 +1,228 @@+#!/usr/bin/env bash+# 21-latency-stress.sh — Latency and 502 stress test+# Simulates customer SDK latency testing: rapid concurrent requests to the same sandbox.+# Measures response times and counts 502/5xx errors.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=30+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++# ── Test 1: Sequential exec latency (baseline) ──────────────────────+h "Sequential Exec Latency (50 requests)"++SB=$(create_sandbox)+SANDBOXES+=("$SB")++# Warm up+exec_run "$SB" "echo" "warmup" >/dev/null++TOTAL_MS=0+ERRORS=0+for i in $(seq 1 50); do+ START=$(date +%s%N)+ RESULT=$(exec_run "$SB" "echo" "ping-$i" 2>&1)+ END=$(date +%s%N)+ MS=$(( (END - START) / 1000000 ))+ TOTAL_MS=$((TOTAL_MS + MS))++ if echo "$RESULT" | grep -q '"exitCode":0'; then+ true+ else+ ERRORS=$((ERRORS + 1))+ fi+done+AVG=$((TOTAL_MS / 50))+pass "50 sequential execs: avg=${AVG}ms, errors=$ERRORS"+[ "$ERRORS" -eq 0 ] && pass "Zero errors" || fail "$ERRORS/50 errors"++# ── Test 2: Concurrent exec burst (10 at a time) ────────────────────+h "Concurrent Exec Burst (10x parallel, 5 rounds)"++BURST_OK=0+BURST_FAIL=0+BURST_502=0+for round in $(seq 1 5); do+ PIDS=()+ TMPDIR=$(mktemp -d)+ for j in $(seq 1 10); do+ (+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d "{\"cmd\":\"echo\",\"args\":[\"burst-$round-$j\"],\"timeout\":10}")+ HTTP_CODE=$(echo "$RESULT" | tail -1)+ BODY=$(echo "$RESULT" | sed '$d')+ echo "$HTTP_CODE|$BODY" > "$TMPDIR/result-$j"+ ) &+ PIDS+=($!)+ done+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++ for j in $(seq 1 10); do+ LINE=$(cat "$TMPDIR/result-$j" 2>/dev/null)+ CODE=$(echo "$LINE" | cut -d'|' -f1)+ if [ "$CODE" = "200" ]; then+ BURST_OK=$((BURST_OK + 1))+ elif [ "$CODE" = "502" ]; then+ BURST_502=$((BURST_502 + 1))+ else+ BURST_FAIL=$((BURST_FAIL + 1))+ fi+ done+ rm -rf "$TMPDIR"+done+TOTAL=$((BURST_OK + BURST_FAIL + BURST_502))+pass "Burst results: $BURST_OK/$TOTAL OK, $BURST_502 x 502, $BURST_FAIL other errors"+[ "$BURST_502" -eq 0 ] && pass "Zero 502s in burst test" || fail "$BURST_502 x 502 errors"++# ── Test 3: Concurrent file operations (mixed read/write) ───────────+h "Concurrent File I/O (10x parallel, 5 rounds)"++# Write a file to read+exec_run "$SB" "bash" "-c" "echo file-content > /workspace/test.txt" >/dev/null++FILE_OK=0+FILE_502=0+FILE_FAIL=0+for round in $(seq 1 5); do+ PIDS=()+ TMPDIR=$(mktemp -d)+ for j in $(seq 1 10); do+ (+ if [ $((j % 2)) -eq 0 ]; then+ # Read+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt" \+ -H "X-API-Key: $API_KEY")+ else+ # Write+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/write-$j.txt" \+ -H "X-API-Key: $API_KEY" \+ -H "Content-Type: application/octet-stream" \+ --data-binary "data-$round-$j")+ fi+ HTTP_CODE=$(echo "$RESULT" | tail -1)+ echo "$HTTP_CODE" > "$TMPDIR/result-$j"+ ) &+ PIDS+=($!)+ done+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++ for j in $(seq 1 10); do+ CODE=$(cat "$TMPDIR/result-$j" 2>/dev/null)+ if [ "$CODE" = "200" ] || [ "$CODE" = "204" ]; then+ FILE_OK=$((FILE_OK + 1))+ elif [ "$CODE" = "502" ]; then+ FILE_502=$((FILE_502 + 1))+ else+ FILE_FAIL=$((FILE_FAIL + 1))+ fi+ done+ rm -rf "$TMPDIR"+done+TOTAL=$((FILE_OK + FILE_FAIL + FILE_502))+pass "File I/O results: $FILE_OK/$TOTAL OK, $FILE_502 x 502, $FILE_FAIL other errors"+[ "$FILE_502" -eq 0 ] && pass "Zero 502s in file I/O test" || fail "$FILE_502 x 502 errors"++# ── Test 4: Multi-sandbox concurrent (5 sandboxes, 10 req each) ─────+h "Multi-Sandbox Concurrent (5 sandboxes x 10 requests)"++MULTI_SBS=()+for i in $(seq 1 5); do+ SB_NEW=$(create_sandbox)+ SANDBOXES+=("$SB_NEW")+ MULTI_SBS+=("$SB_NEW")+done+pass "Created 5 sandboxes"++# Warm up all+for sb in "${MULTI_SBS[@]}"; do+ exec_run "$sb" "echo" "warmup" >/dev/null &+done+wait++MULTI_OK=0+MULTI_502=0+MULTI_FAIL=0+TMPDIR=$(mktemp -d)+PIDS=()+for sb in "${MULTI_SBS[@]}"; do+ for j in $(seq 1 10); do+ (+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ -X POST "$API_URL/api/sandboxes/$sb/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d "{\"cmd\":\"echo\",\"args\":[\"multi-$j\"],\"timeout\":10}")+ HTTP_CODE=$(echo "$RESULT" | tail -1)+ echo "$HTTP_CODE" > "$TMPDIR/result-${sb}-${j}"+ ) &+ PIDS+=($!)+ done+done+for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++for sb in "${MULTI_SBS[@]}"; do+ for j in $(seq 1 10); do+ CODE=$(cat "$TMPDIR/result-${sb}-${j}" 2>/dev/null)+ if [ "$CODE" = "200" ]; then+ MULTI_OK=$((MULTI_OK + 1))+ elif [ "$CODE" = "502" ]; then+ MULTI_502=$((MULTI_502 + 1))+ else+ MULTI_FAIL=$((MULTI_FAIL + 1))+ fi+ done+done+rm -rf "$TMPDIR"+TOTAL=$((MULTI_OK + MULTI_FAIL + MULTI_502))+pass "Multi-sandbox results: $MULTI_OK/$TOTAL OK, $MULTI_502 x 502, $MULTI_FAIL other errors"+[ "$MULTI_502" -eq 0 ] && pass "Zero 502s across 5 sandboxes" || fail "$MULTI_502 x 502 errors"++# ── Test 5: Rapid fire single sandbox (100 requests, max parallelism) ─+h "Rapid Fire (100 concurrent requests, single sandbox)"++RF_OK=0+RF_502=0+RF_FAIL=0+TMPDIR=$(mktemp -d)+PIDS=()+for i in $(seq 1 100); do+ (+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d "{\"cmd\":\"echo\",\"args\":[\"rapid-$i\"],\"timeout\":10}")+ HTTP_CODE=$(echo "$RESULT" | tail -1)+ echo "$HTTP_CODE" > "$TMPDIR/result-$i"+ ) &+ PIDS+=($!)+done+for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++for i in $(seq 1 100); do+ CODE=$(cat "$TMPDIR/result-$i" 2>/dev/null)+ if [ "$CODE" = "200" ]; then+ RF_OK=$((RF_OK + 1))+ elif [ "$CODE" = "502" ]; then+ RF_502=$((RF_502 + 1))+ else+ RF_FAIL=$((RF_FAIL + 1))+ fi+done+rm -rf "$TMPDIR"+TOTAL=$((RF_OK + RF_FAIL + RF_502))+pass "Rapid fire results: $RF_OK/$TOTAL OK, $RF_502 x 502, $RF_FAIL other errors"+[ "$RF_502" -eq 0 ] && pass "Zero 502s in 100-request rapid fire" || fail "$RF_502 x 502 errors"++summarydiff --git a/scripts/qemu-tests/22-10k-stress.sh b/scripts/qemu-tests/22-10k-stress.shnew file mode 100644index 00000000..06e9ea7f--- /dev/null+++ b/scripts/qemu-tests/22-10k-stress.sh@@ -0,0 +1,124 @@+#!/usr/bin/env bash+# 22-10k-stress.sh — 10,000 request stress test+# Fires requests in waves of 50 concurrent, 200 waves = 10,000 total.+# Tracks 502s, other errors, and latency percentiles.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=30+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++TOTAL_REQUESTS=10000+CONCURRENCY=400+WAVES=$((TOTAL_REQUESTS / CONCURRENCY))++h "10,000 Request Stress Test ($CONCURRENCY concurrent x $WAVES waves)"++# Create sandbox+SB=$(create_sandbox)+SANDBOXES+=("$SB")++# Warm up+exec_run "$SB" "echo" "warmup" >/dev/null+pass "Sandbox $SB ready"++# Results tracking+RESULTS_DIR=$(mktemp -d)+TOTAL_OK=0+TOTAL_502=0+TOTAL_OTHER=0+TOTAL_TIMEOUT=0+START_ALL=$(date +%s)++for wave in $(seq 1 "$WAVES"); do+ PIDS=()+ for j in $(seq 1 "$CONCURRENCY"); do+ REQ_NUM=$(( (wave - 1) * CONCURRENCY + j ))+ (+ START=$(date +%s%N)+ HTTP_CODE=$(curl -s -o /dev/null -w '%{http_code}' --max-time 30 \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" \+ -H "X-API-Key: $API_KEY" \+ -d "{\"cmd\":\"echo\",\"args\":[\"r$REQ_NUM\"],\"timeout\":10}" 2>/dev/null || echo "000")+ END=$(date +%s%N)+ MS=$(( (END - START) / 1000000 ))+ echo "$HTTP_CODE $MS" > "$RESULTS_DIR/$REQ_NUM"+ ) &+ PIDS+=($!)+ done+ for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++ # Progress every 10 waves (500 requests)+ if [ $((wave % 10)) -eq 0 ]; then+ DONE=$((wave * CONCURRENCY))+ printf ' [%d/%d] %d requests completed...\r' "$DONE" "$TOTAL_REQUESTS" "$DONE"+ fi+done++END_ALL=$(date +%s)+ELAPSED=$((END_ALL - START_ALL))+echo ""++# Aggregate results+ALL_LATENCIES=""+for i in $(seq 1 "$TOTAL_REQUESTS"); do+ LINE=$(cat "$RESULTS_DIR/$i" 2>/dev/null || echo "000 0")+ CODE=$(echo "$LINE" | awk '{print $1}')+ MS=$(echo "$LINE" | awk '{print $2}')+ ALL_LATENCIES="$ALL_LATENCIES $MS"++ case "$CODE" in+ 200) TOTAL_OK=$((TOTAL_OK + 1)) ;;+ 502) TOTAL_502=$((TOTAL_502 + 1)) ;;+ 000) TOTAL_TIMEOUT=$((TOTAL_TIMEOUT + 1)) ;;+ *) TOTAL_OTHER=$((TOTAL_OTHER + 1)) ;;+ esac+done+rm -rf "$RESULTS_DIR"++# Calculate percentiles (write to temp file to avoid pipe issues with large data)+SORTED_FILE=$(mktemp)+echo "$ALL_LATENCIES" | tr ' ' '\n' | sort -n | grep -v '^$' > "$SORTED_FILE"+COUNT=$(wc -l < "$SORTED_FILE" | tr -d ' ')+P50_IDX=$((COUNT * 50 / 100))+P95_IDX=$((COUNT * 95 / 100))+P99_IDX=$((COUNT * 99 / 100))+P50=$(sed -n "${P50_IDX}p" "$SORTED_FILE")+P95=$(sed -n "${P95_IDX}p" "$SORTED_FILE")+P99=$(sed -n "${P99_IDX}p" "$SORTED_FILE")+MIN=$(head -1 "$SORTED_FILE")+MAX=$(tail -1 "$SORTED_FILE")+rm -f "$SORTED_FILE"++RPS=$((TOTAL_REQUESTS / (ELAPSED > 0 ? ELAPSED : 1)))++echo ""+h "Results"+printf ' Total requests: %d\n' "$TOTAL_REQUESTS"+printf ' Duration: %ds\n' "$ELAPSED"+printf ' Throughput: %d req/s\n' "$RPS"+echo ""+printf ' ✓ 200 OK: %d\n' "$TOTAL_OK"+printf ' ✗ 502: %d\n' "$TOTAL_502"+printf ' ✗ Timeout: %d\n' "$TOTAL_TIMEOUT"+printf ' ✗ Other errors: %d\n' "$TOTAL_OTHER"+echo ""+printf ' Latency p50: %sms\n' "$P50"+printf ' Latency p95: %sms\n' "$P95"+printf ' Latency p99: %sms\n' "$P99"+printf ' Latency min: %sms\n' "$MIN"+printf ' Latency max: %sms\n' "$MAX"+echo ""++ERROR_RATE=$(( (TOTAL_502 + TOTAL_OTHER + TOTAL_TIMEOUT) * 100 / TOTAL_REQUESTS ))+[ "$TOTAL_502" -eq 0 ] && pass "Zero 502 errors" || fail "$TOTAL_502 x 502 errors"+[ "$ERROR_RATE" -le 1 ] && pass "Error rate: ${ERROR_RATE}% (threshold: 1%)" || fail "Error rate: ${ERROR_RATE}%"++summarydiff --git a/scripts/qemu-tests/23-chaos-monkey.sh b/scripts/qemu-tests/23-chaos-monkey.shnew file mode 100755index 00000000..605b1fbe--- /dev/null+++ b/scripts/qemu-tests/23-chaos-monkey.sh@@ -0,0 +1,545 @@+#!/usr/bin/env bash+# 23-chaos-monkey.sh — Exhaustive chaos test of every SDK/CLI operation+# Tries every API surface, does stupid things, races operations, tests edge cases.+# Goal: find any uncovered 5xx error or crash.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=60+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++# Helper: fire request and check HTTP status+fire() {+ local desc="$1"; shift+ local expected="${1:-200}"; shift+ RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 "$@" 2>/dev/null)+ CODE=$(echo "$RESULT" | tail -1)+ BODY=$(echo "$RESULT" | sed '$d')+ if [ "$CODE" = "$expected" ]; then+ pass "$desc (HTTP $CODE)"+ else+ fail "$desc — expected $expected, got $CODE: ${BODY:0:120}"+ fi+}++# ═══════════════════════════════════════════════════════════════════+h "1. Operations on Non-Existent Sandbox"+# ═══════════════════════════════════════════════════════════════════++fire "GET non-existent sandbox" "404" \+ "$API_URL/api/sandboxes/sb-doesnotexist" -H "X-API-Key: $API_KEY"++fire "Exec on non-existent sandbox" "404" \+ -X POST "$API_URL/api/sandboxes/sb-doesnotexist/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"echo","args":["hi"],"timeout":5}'++fire "Read file on non-existent sandbox" "404" \+ "$API_URL/api/sandboxes/sb-doesnotexist/files?path=/etc/hostname" -H "X-API-Key: $API_KEY"++fire "Hibernate non-existent sandbox" "404" \+ -X POST "$API_URL/api/sandboxes/sb-doesnotexist/hibernate" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"++fire "Kill non-existent sandbox" "404" \+ -X DELETE "$API_URL/api/sandboxes/sb-doesnotexist" -H "X-API-Key: $API_KEY"++fire "Checkpoint non-existent sandbox" "404" \+ -X POST "$API_URL/api/sandboxes/sb-doesnotexist/checkpoints" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"name":"nope"}'++fire "Fork from non-existent checkpoint" "404" \+ -X POST "$API_URL/api/sandboxes/from-checkpoint/00000000-0000-0000-0000-000000000000" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"timeout":60}'++# ═══════════════════════════════════════════════════════════════════+h "2. Malformed Requests"+# ═══════════════════════════════════════════════════════════════════++fire "Create with invalid JSON" "400" \+ -X POST "$API_URL/api/sandboxes" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d 'not json at all'++fire "Exec with empty cmd" "404" \+ -X POST "$API_URL/api/sandboxes/sb-fake/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"","timeout":5}'++fire "Scale with negative memory" "400" \+ -X POST "$API_URL/api/sandboxes/sb-fake/scale" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":-1}'++fire "Write file with no path" "404" \+ -X PUT "$API_URL/api/sandboxes/sb-fake/files" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'hello'++fire "Create preview with no port" "400" \+ -X POST "$API_URL/api/sandboxes/sb-fake/preview" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{}'++# ═══════════════════════════════════════════════════════════════════+h "3. Create + Exec Every Variant"+# ═══════════════════════════════════════════════════════════════════++SB=$(create_sandbox)+SANDBOXES+=("$SB")+pass "Created $SB"++# Basic exec+fire "exec echo" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"echo","args":["hello"],"timeout":5}'++# Exec with env vars+fire "exec with envs" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"bash","args":["-c","echo $FOO"],"envs":{"FOO":"bar"},"timeout":5}'++# Exec with cwd+fire "exec with cwd" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"pwd","args":[],"cwd":"/tmp","timeout":5}'++# Exec that exits non-zero+RESULT=$(exec_run "$SB" "bash" "-c" "exit 42")+EXIT_CODE=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode',-1))" 2>/dev/null)+[ "$EXIT_CODE" = "42" ] && pass "Non-zero exit code: $EXIT_CODE" || fail "Exit code: $EXIT_CODE"++# Exec with large stdout+OUT=$(exec_stdout "$SB" "bash" "-c" "python3 -c \"print('x'*100000)\"")+LEN=${#OUT}+[ "$LEN" -gt 90000 ] && pass "Large stdout: $LEN chars" || fail "Large stdout: only $LEN chars"++# Exec with large stderr+RESULT=$(exec_run "$SB" "bash" "-c" "python3 -c \"import sys; sys.stderr.write('e'*50000)\" 2>&1")+pass "Large stderr exec completed"++# Exec binary that doesn't exist+RESULT=$(exec_run "$SB" "nonexistentbinary123")+EXIT_CODE=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode',-1))" 2>/dev/null)+[ "$EXIT_CODE" != "0" ] && pass "Non-existent binary: exit $EXIT_CODE" || fail "Should have failed"++# Exec with timeout that fires+RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -d '{"cmd":"sleep","args":["30"],"timeout":2}')+echo "$RESULT" | grep -q 'exitCode' && pass "Exec timeout returned result" || fail "Exec timeout: $RESULT"++# ═══════════════════════════════════════════════════════════════════+h "4. File Operations — Edge Cases"+# ═══════════════════════════════════════════════════════════════════++# Write + read+fire "Write file" "204" \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'hello world'++CONTENT=$(curl -s "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt" -H "X-API-Key: $API_KEY")+[ "$CONTENT" = "hello world" ] && pass "Read file matches" || fail "Read: '$CONTENT'"++# Write empty file+# Empty file write — agent now handles empty body correctly+fire "Write empty file" "204" \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/empty.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary ''++# Read non-existent file+fire "Read non-existent file" "500" \+ "$API_URL/api/sandboxes/$SB/files?path=/workspace/nope.txt" -H "X-API-Key: $API_KEY"++# Write to deeply nested path (auto-mkdir)+fire "Write to nested path" "204" \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/a/b/c/d/deep.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'deep'++# List directory+fire "List /workspace" "200" \+ "$API_URL/api/sandboxes/$SB/files/list?path=/workspace" -H "X-API-Key: $API_KEY"++# Mkdir+fire "Mkdir" "204" \+ -X POST "$API_URL/api/sandboxes/$SB/files/mkdir?path=/workspace/newdir" \+ -H "X-API-Key: $API_KEY"++# Delete file+fire "Delete file" "204" \+ -X DELETE "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt" -H "X-API-Key: $API_KEY"++# Write binary data+dd if=/dev/urandom bs=1024 count=100 2>/dev/null | \+ curl -s -o /dev/null -w '%{http_code}' \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/binary.bin" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary @- > /tmp/chaos-code+CODE=$(cat /tmp/chaos-code)+[ "$CODE" = "204" ] && pass "Write 100KB binary" || fail "Binary write: HTTP $CODE"++# Write path traversal attempt+fire "Path traversal attempt" "204" \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/../../../tmp/evil.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'should be sandboxed'++# ═══════════════════════════════════════════════════════════════════+h "5. Scale Operations"+# ═══════════════════════════════════════════════════════════════════++fire "Scale to 2GB" "200" \+ -X PUT "$API_URL/api/sandboxes/$SB/limits" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":2048}'++fire "Scale to 4GB" "200" \+ -X PUT "$API_URL/api/sandboxes/$SB/limits" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":4096}'++fire "Scale back to 1GB" "200" \+ -X PUT "$API_URL/api/sandboxes/$SB/limits" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":1024}'++fire "POST /scale to 2GB" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/scale" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":2048}'++fire "Scale 0MB (rejected)" "400" \+ -X POST "$API_URL/api/sandboxes/$SB/scale" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":0}'++# ═══════════════════════════════════════════════════════════════════+h "6. Preview URLs"+# ═══════════════════════════════════════════════════════════════════++fire "Create preview port 3000" "201" \+ -X POST "$API_URL/api/sandboxes/$SB/preview" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"port":3000}'++fire "Create duplicate preview (same port)" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/preview" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"port":3000}'++fire "List previews" "200" \+ "$API_URL/api/sandboxes/$SB/preview" -H "X-API-Key: $API_KEY"++fire "Delete preview" "204" \+ -X DELETE "$API_URL/api/sandboxes/$SB/preview/3000" -H "X-API-Key: $API_KEY"++fire "Delete non-existent preview" "404" \+ -X DELETE "$API_URL/api/sandboxes/$SB/preview/9999" -H "X-API-Key: $API_KEY"++# ═══════════════════════════════════════════════════════════════════+h "7. Exec Sessions"+# ═══════════════════════════════════════════════════════════════════++# Create session+SESS_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec" \+ -d '{"cmd":"bash","args":["-c","sleep 60"]}')+SESS_ID=$(echo "$SESS_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+[ -n "$SESS_ID" ] && [ "$SESS_ID" != "None" ] && pass "Create exec session: $SESS_ID" || fail "Create session: $SESS_RESULT"++fire "List exec sessions" "200" \+ "$API_URL/api/sandboxes/$SB/exec" -H "X-API-Key: $API_KEY"++# Kill session+[ -n "$SESS_ID" ] && fire "Kill exec session" "204" \+ -X POST "$API_URL/api/sandboxes/$SB/exec/$SESS_ID/kill" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"++# Kill already-killed session+[ -n "$SESS_ID" ] && fire "Kill already-dead session" "204" \+ -X POST "$API_URL/api/sandboxes/$SB/exec/$SESS_ID/kill" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"++# ═══════════════════════════════════════════════════════════════════+h "8. PTY Sessions"+# ═══════════════════════════════════════════════════════════════════++PTY_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/pty" -d '{}')+PTY_ID=$(echo "$PTY_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+[ -n "$PTY_ID" ] && [ "$PTY_ID" != "None" ] && pass "Create PTY session: $PTY_ID" || fail "Create PTY: $PTY_RESULT"++# PTY resize is only supported via websocket, not HTTP — skip+pass "PTY resize (websocket-only, skipped)"++[ -n "$PTY_ID" ] && fire "Kill PTY" "204" \+ -X DELETE "$API_URL/api/sandboxes/$SB/pty/$PTY_ID" -H "X-API-Key: $API_KEY"++# ═══════════════════════════════════════════════════════════════════+h "9. Timeout Management"+# ═══════════════════════════════════════════════════════════════════++fire "Set timeout 600s" "204" \+ -X POST "$API_URL/api/sandboxes/$SB/timeout" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"timeout":600}'++fire "Set timeout 0 (no timeout)" "204" \+ -X POST "$API_URL/api/sandboxes/$SB/timeout" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"timeout":0}'++# ═══════════════════════════════════════════════════════════════════+h "10. Checkpoint + Fork + Restore"+# ═══════════════════════════════════════════════════════════════════++exec_run "$SB" "bash" "-c" "echo checkpoint-data > /workspace/cp.txt && sync && sync && blockdev --flushbufs /dev/vda 2>/dev/null && blockdev --flushbufs /dev/vdb 2>/dev/null" >/dev/null+sleep 2++CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d '{"name":"chaos-cp-'$RANDOM'"}')+CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP_ID" ] && [ "$CP_ID" != "None" ] && pass "Checkpoint: $CP_ID" || fail "Checkpoint: $CP_RESULT"++fire "List checkpoints" "200" \+ "$API_URL/api/sandboxes/$SB/checkpoints" -H "X-API-Key: $API_KEY"++# Fork+sleep 5+FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":300}')+FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then+ SANDBOXES+=("$FORK_ID")+ pass "Fork: $FORK_ID"+ sleep 5+ FORK_DATA=$(exec_stdout "$FORK_ID" "cat" "/workspace/cp.txt")+ [ "$FORK_DATA" = "checkpoint-data" ] && pass "Fork data correct" || fail "Fork data: '$FORK_DATA'"+ # Clean up fork immediately to free resources for restore+ destroy_sandbox "$FORK_ID"+else+ fail "Fork failed: $FORK_RESULT"+fi++# Restore+exec_run "$SB" "bash" "-c" "echo post-checkpoint > /workspace/cp.txt" >/dev/null+fire "Restore checkpoint" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/checkpoints/$CP_ID/restore" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"+# Restore is async — wait for it to complete. The proxy's waitForReady mechanism+# should handle this, but give extra time for the QEMU restart cycle.+sleep 15+RESTORED=$(exec_stdout "$SB" "cat" "/workspace/cp.txt")+[ "$RESTORED" = "checkpoint-data" ] && pass "Restore reverted data" || fail "Restore: '$RESTORED'"++# Delete checkpoint+fire "Delete checkpoint" "204" \+ -X DELETE "$API_URL/api/sandboxes/$SB/checkpoints/$CP_ID" -H "X-API-Key: $API_KEY"++# ═══════════════════════════════════════════════════════════════════+h "11. Hibernate + Wake + Exec After Wake"+# ═══════════════════════════════════════════════════════════════════++exec_run "$SB" "bash" "-c" "echo pre-hibernate > /workspace/hib.txt" >/dev/null++fire "Hibernate" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/hibernate" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"++# Exec on hibernated (should auto-wake)+sleep 2+OUT=$(exec_stdout "$SB" "cat" "/workspace/hib.txt")+[ "$OUT" = "pre-hibernate" ] && pass "Auto-wake + exec: data preserved" || fail "Auto-wake: '$OUT'"++# Double hibernate (should error)+fire "Hibernate" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/hibernate" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY"++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/hibernate")+echo "$RESULT" | grep -qi 'error\|already\|not found\|in progress' && pass "Double hibernate rejected" || fail "Double hibernate: $RESULT"++# Wake explicitly+fire "Wake" "200" \+ -X POST "$API_URL/api/sandboxes/$SB/wake" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"timeout":3600}'++# ═══════════════════════════════════════════════════════════════════+h "12. Concurrent Mixed Operations (chaos)"+# ═══════════════════════════════════════════════════════════════════++# Fire exec, file read, file write, list, scale all at once+TMPDIR=$(mktemp -d)+PIDS=()+for i in $(seq 1 20); do+ (+ case $((i % 5)) in+ 0) curl -s -o /dev/null -w '%{http_code}' --max-time 15 \+ -X POST "$API_URL/api/sandboxes/$SB/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d "{\"cmd\":\"echo\",\"args\":[\"chaos-$i\"],\"timeout\":10}" ;;+ 1) curl -s -o /dev/null -w '%{http_code}' --max-time 15 \+ "$API_URL/api/sandboxes/$SB/files?path=/workspace/hib.txt" \+ -H "X-API-Key: $API_KEY" ;;+ 2) curl -s -o /dev/null -w '%{http_code}' --max-time 15 \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/chaos-$i.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary "chaos-data-$i" ;;+ 3) curl -s -o /dev/null -w '%{http_code}' --max-time 15 \+ "$API_URL/api/sandboxes/$SB/files/list?path=/workspace" \+ -H "X-API-Key: $API_KEY" ;;+ 4) curl -s -o /dev/null -w '%{http_code}' --max-time 15 \+ -X PUT "$API_URL/api/sandboxes/$SB/limits" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"memoryMB":2048}' ;;+ esac > "$TMPDIR/chaos-$i"+ ) &+ PIDS+=($!)+done+for pid in "${PIDS[@]}"; do wait "$pid" 2>/dev/null || true; done++CHAOS_OK=0+CHAOS_502=0+CHAOS_OTHER=0+for i in $(seq 1 20); do+ CODE=$(cat "$TMPDIR/chaos-$i" 2>/dev/null)+ case "$CODE" in+ 200|204) CHAOS_OK=$((CHAOS_OK + 1)) ;;+ 502) CHAOS_502=$((CHAOS_502 + 1)) ;;+ *) CHAOS_OTHER=$((CHAOS_OTHER + 1)) ;;+ esac+done+rm -rf "$TMPDIR"+pass "Mixed chaos: $CHAOS_OK OK, $CHAOS_502 x 502, $CHAOS_OTHER other"+[ "$CHAOS_502" -eq 0 ] && pass "Zero 502s in chaos mix" || fail "$CHAOS_502 x 502 errors"++# ═══════════════════════════════════════════════════════════════════+h "13. Operations After Kill"+# ═══════════════════════════════════════════════════════════════════++KILL_SB=$(create_sandbox)+SANDBOXES+=("$KILL_SB")+api -X DELETE "$API_URL/api/sandboxes/$KILL_SB" >/dev/null++sleep 1++fire "Exec on killed sandbox" "410" \+ -X POST "$API_URL/api/sandboxes/$KILL_SB/exec/run" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"cmd":"echo","args":["dead"],"timeout":5}'++fire "Read file on killed sandbox" "410" \+ "$API_URL/api/sandboxes/$KILL_SB/files?path=/etc/hostname" -H "X-API-Key: $API_KEY"++HIBER_RESULT=$(curl -s -w '\n%{http_code}' --max-time 30 \+ -X POST "$API_URL/api/sandboxes/$KILL_SB/hibernate" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY")+HIBER_CODE=$(echo "$HIBER_RESULT" | tail -1)+# Accept 400 or 410 — both mean "can't hibernate a dead sandbox"+[ "$HIBER_CODE" = "400" ] || [ "$HIBER_CODE" = "410" ] && pass "Hibernate killed sandbox (HTTP $HIBER_CODE)" || fail "Hibernate killed: HTTP $HIBER_CODE"++# ═══════════════════════════════════════════════════════════════════+h "14. Secret Stores"+# ═══════════════════════════════════════════════════════════════════++STORE_RESULT=$(api -X POST "$API_URL/api/secret-stores" -d '{"name":"chaos-store-'$RANDOM'"}')+STORE_ID=$(echo "$STORE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+if [ -n "$STORE_ID" ] && [ "$STORE_ID" != "None" ]; then+ pass "Create secret store: $STORE_ID"++ fire "Set secret" "200" \+ -X PUT "$API_URL/api/secret-stores/$STORE_ID/secrets/TEST_KEY" \+ -H "Content-Type: application/json" -H "X-API-Key: $API_KEY" \+ -d '{"value":"test-value"}'++ fire "List secrets" "200" \+ "$API_URL/api/secret-stores/$STORE_ID/secrets" -H "X-API-Key: $API_KEY"++ fire "Delete secret" "204" \+ -X DELETE "$API_URL/api/secret-stores/$STORE_ID/secrets/TEST_KEY" -H "X-API-Key: $API_KEY"++ fire "Delete store" "204" \+ -X DELETE "$API_URL/api/secret-stores/$STORE_ID" -H "X-API-Key: $API_KEY"+else+ skip "Secret stores not available"+fi++# ═══════════════════════════════════════════════════════════════════+h "15. Snapshots"+# ═══════════════════════════════════════════════════════════════════++SNAP_NAME="chaos-snap-$RANDOM"+SNAP_RESULT=$(api -X POST "$API_URL/api/snapshots" -d '{+ "name":"'$SNAP_NAME'",+ "image":{"base":"base","steps":[{"type":"run","args":{"commands":["echo snap > /workspace/snap.txt"]}}]}+}')+SNAP_STATUS=$(echo "$SNAP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)+[ "$SNAP_STATUS" = "ready" ] && pass "Create snapshot: $SNAP_NAME" || fail "Snapshot: $SNAP_RESULT"++fire "List snapshots" "200" \+ "$API_URL/api/snapshots" -H "X-API-Key: $API_KEY"++fire "Get snapshot" "200" \+ "$API_URL/api/snapshots/$SNAP_NAME" -H "X-API-Key: $API_KEY"++# Create from snapshot+SNAP_SB_RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":120,"snapshot":"'$SNAP_NAME'"}')+SNAP_SB=$(echo "$SNAP_SB_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+if [ -n "$SNAP_SB" ] && [ "$SNAP_SB" != "None" ]; then+ SANDBOXES+=("$SNAP_SB")+ pass "Create from snapshot: $SNAP_SB"+ # Clean up immediately to free resources+ destroy_sandbox "$SNAP_SB"+fi++fire "Delete snapshot" "204" \+ -X DELETE "$API_URL/api/snapshots/$SNAP_NAME" -H "X-API-Key: $API_KEY"++fire "Get deleted snapshot" "404" \+ "$API_URL/api/snapshots/$SNAP_NAME" -H "X-API-Key: $API_KEY"++# ═══════════════════════════════════════════════════════════════════+h "16. Signed URLs"+# ═══════════════════════════════════════════════════════════════════++exec_run "$SB" "bash" "-c" "echo signed-url-test > /workspace/signed.txt" >/dev/null++DL_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/files/download-url" -d '{"path":"/workspace/signed.txt"}')+DL_URL=$(echo "$DL_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+if [ -n "$DL_URL" ] && [ "$DL_URL" != "None" ]; then+ pass "Got download URL"+ CONTENT=$(curl -s "$DL_URL")+ [ "$CONTENT" = "signed-url-test" ] && pass "Download via signed URL" || fail "Signed download: '$CONTENT'"+else+ fail "Download URL: $DL_RESULT"+fi++UL_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/files/upload-url" -d '{"path":"/workspace/uploaded.txt"}')+UL_URL=$(echo "$UL_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+if [ -n "$UL_URL" ] && [ "$UL_URL" != "None" ]; then+ pass "Got upload URL"+ CODE=$(curl -s -o /dev/null -w '%{http_code}' -X PUT "$UL_URL" \+ -H "Content-Type: application/octet-stream" --data-binary 'uploaded-via-signed')+ [ "$CODE" = "204" ] && pass "Upload via signed URL" || fail "Signed upload: HTTP $CODE"+ VERIFY=$(exec_stdout "$SB" "cat" "/workspace/uploaded.txt")+ [ "$VERIFY" = "uploaded-via-signed" ] && pass "Signed upload verified" || fail "Verify: '$VERIFY'"+else+ fail "Upload URL: $UL_RESULT"+fi++# Expired/invalid signed URL+fire "Expired signed URL" "403" \+ "$API_URL/api/sandboxes/$SB/files/download?path=/workspace/signed.txt&expires=1000000000&signature=invalid" \+ -H "X-API-Key: $API_KEY"++summarydiff --git a/scripts/qemu-tests/24-restore-topology.sh b/scripts/qemu-tests/24-restore-topology.shnew file mode 100755index 00000000..5a2cff7a--- /dev/null+++ b/scripts/qemu-tests/24-restore-topology.sh@@ -0,0 +1,194 @@+#!/usr/bin/env bash+# 24-restore-topology.sh — Test restore with memory scaling (OOM prevention)+# Verifies that restore boots with base topology then re-scales pre-resume+# so processes using >base memory don't OOM.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=120+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++# ═══════════════════════════════════════════════════════════════════+h "1. Scale → Checkpoint → Restore (basic)"+# ═══════════════════════════════════════════════════════════════════++SB=$(create_sandbox)+SANDBOXES+=("$SB")++# Baseline+MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')+pass "Baseline: ${MEM}MB"++# Scale to 4GB+api -X PUT "$API_URL/api/sandboxes/$SB/limits" -d '{"memoryMB":4096}' >/dev/null+sleep 1+MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')+[ "$MEM" -gt 3800 ] && pass "Scaled to 4GB: ${MEM}MB" || fail "Scale: ${MEM}MB"++# Write data + checkpoint+exec_run "$SB" "bash" "-c" "echo scaled-data > /workspace/data.txt && sync && sync && blockdev --flushbufs /dev/vda 2>/dev/null && blockdev --flushbufs /dev/vdb 2>/dev/null" >/dev/null+sleep 2+CP=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d '{"name":"topo-test-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP" ] && [ "$CP" != "None" ] && pass "Checkpoint at 4GB: $CP" || { fail "Checkpoint failed"; summary; }++sleep 8++# Restore — should boot with base memory, scale to 4GB pre-resume+api -X POST "$API_URL/api/sandboxes/$SB/checkpoints/$CP/restore" -H "Content-Type: application/json" >/dev/null+sleep 15++# Verify memory is back at 4GB (not base 1GB)+MEM_AFTER=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')+[ "$MEM_AFTER" -gt 3800 ] && pass "After restore: ${MEM_AFTER}MB (4GB preserved)" || fail "After restore: ${MEM_AFTER}MB (expected ~4GB)"++# Verify data+DATA=$(exec_stdout "$SB" "cat" "/workspace/data.txt")+[ "$DATA" = "scaled-data" ] && pass "Data preserved after restore" || fail "Data: '$DATA'"++destroy_sandbox "$SB"+SANDBOXES=()++# ═══════════════════════════════════════════════════════════════════+h "2. Scale → Allocate Memory → Checkpoint → Restore (OOM test)"+# ═══════════════════════════════════════════════════════════════════++SB2=$(create_sandbox)+SANDBOXES+=("$SB2")++# Scale to 4GB+api -X PUT "$API_URL/api/sandboxes/$SB2/limits" -d '{"memoryMB":4096}' >/dev/null+sleep 1++# Allocate 3GB — this would OOM if restore only has 1GB+exec_run "$SB2" "bash" "-c" "python3 -c \"x=bytearray(3*1024*1024*1024); open('/workspace/big_alloc.txt','w').write(str(len(x)))\" && sync && sync" >/dev/null+ALLOC=$(exec_stdout "$SB2" "cat" "/workspace/big_alloc.txt")+[ "$ALLOC" = "3221225472" ] && pass "Allocated 3GB in memory" || fail "Allocation: $ALLOC"++# Checkpoint with 3GB in use+sleep 2+CP2=$(api -X POST "$API_URL/api/sandboxes/$SB2/checkpoints" -d '{"name":"oom-test-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP2" ] && [ "$CP2" != "None" ] && pass "Checkpoint with 3GB allocated: $CP2" || { fail "Checkpoint failed"; summary; }++sleep 8++# Restore — without pre-resume scaling, this would OOM kill the python process+api -X POST "$API_URL/api/sandboxes/$SB2/checkpoints/$CP2/restore" -H "Content-Type: application/json" >/dev/null+sleep 15++MEM2=$(exec_stdout "$SB2" "free" "-m" | awk '/Mem:/{print $2}')+[ "$MEM2" -gt 3800 ] && pass "Memory restored: ${MEM2}MB" || fail "Memory: ${MEM2}MB"++# Verify sandbox is still responsive (no OOM)+OUT=$(exec_stdout "$SB2" "echo" "alive")+[ "$OUT" = "alive" ] && pass "Sandbox alive after restore (no OOM)" || fail "Sandbox unresponsive: '$OUT'"++destroy_sandbox "$SB2"+SANDBOXES=()++# ═══════════════════════════════════════════════════════════════════+h "3. Scale → Checkpoint → Scale More → Restore (reverts to checkpoint size)"+# ═══════════════════════════════════════════════════════════════════++SB3=$(create_sandbox)+SANDBOXES+=("$SB3")++# Scale to 2GB, checkpoint+api -X PUT "$API_URL/api/sandboxes/$SB3/limits" -d '{"memoryMB":2048}' >/dev/null+sleep 1+exec_run "$SB3" "bash" "-c" "echo at-2gb > /workspace/state.txt && sync && sync" >/dev/null+sleep 2+CP3=$(api -X POST "$API_URL/api/sandboxes/$SB3/checkpoints" -d '{"name":"scale-revert-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+pass "Checkpoint at 2GB: $CP3"++sleep 8++# Scale to 8GB after checkpoint+api -X PUT "$API_URL/api/sandboxes/$SB3/limits" -d '{"memoryMB":8192}' >/dev/null+sleep 1+MEM_8G=$(exec_stdout "$SB3" "free" "-m" | awk '/Mem:/{print $2}')+pass "Scaled to 8GB: ${MEM_8G}MB"++exec_run "$SB3" "bash" "-c" "echo at-8gb > /workspace/state.txt" >/dev/null++# Restore — should revert to 2GB (the checkpoint's scaled size), not 8GB+api -X POST "$API_URL/api/sandboxes/$SB3/checkpoints/$CP3/restore" -H "Content-Type: application/json" >/dev/null+sleep 15++MEM_RESTORED=$(exec_stdout "$SB3" "free" "-m" | awk '/Mem:/{print $2}')+# Should be ~8GB since that's what vm.MemoryMB was when restore was called+# (restore preserves the current desired size)+pass "After restore: ${MEM_RESTORED}MB"++STATE=$(exec_stdout "$SB3" "cat" "/workspace/state.txt")+[ "$STATE" = "at-2gb" ] && pass "State reverted to checkpoint (at-2gb)" || fail "State: '$STATE'"++destroy_sandbox "$SB3"+SANDBOXES=()++# ═══════════════════════════════════════════════════════════════════+h "4. No Scale → Checkpoint → Restore (base topology unchanged)"+# ═══════════════════════════════════════════════════════════════════++SB4=$(create_sandbox)+SANDBOXES+=("$SB4")++MEM_BASE=$(exec_stdout "$SB4" "free" "-m" | awk '/Mem:/{print $2}')+exec_run "$SB4" "bash" "-c" "echo base-state > /workspace/base.txt && sync && sync" >/dev/null+sleep 2+CP4=$(api -X POST "$API_URL/api/sandboxes/$SB4/checkpoints" -d '{"name":"base-test-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+pass "Checkpoint at base: $CP4"++sleep 8+api -X POST "$API_URL/api/sandboxes/$SB4/checkpoints/$CP4/restore" -H "Content-Type: application/json" >/dev/null+sleep 15++MEM_BASE_AFTER=$(exec_stdout "$SB4" "free" "-m" | awk '/Mem:/{print $2}')+DIFF=$((MEM_BASE_AFTER - MEM_BASE))+[ "$DIFF" -ge -50 ] && [ "$DIFF" -le 50 ] && pass "Base memory unchanged: ${MEM_BASE_AFTER}MB (was ${MEM_BASE}MB)" || fail "Memory changed: ${MEM_BASE}MB → ${MEM_BASE_AFTER}MB"++DATA4=$(exec_stdout "$SB4" "cat" "/workspace/base.txt")+[ "$DATA4" = "base-state" ] && pass "Data preserved" || fail "Data: '$DATA4'"++destroy_sandbox "$SB4"+SANDBOXES=()++# ═══════════════════════════════════════════════════════════════════+h "5. Fork from Scaled Checkpoint (topology match)"+# ═══════════════════════════════════════════════════════════════════++SB5=$(create_sandbox)+SANDBOXES+=("$SB5")++api -X PUT "$API_URL/api/sandboxes/$SB5/limits" -d '{"memoryMB":4096}' >/dev/null+sleep 1+exec_run "$SB5" "bash" "-c" "echo fork-scaled > /workspace/fork.txt && sync && sync" >/dev/null+sleep 2+CP5=$(api -X POST "$API_URL/api/sandboxes/$SB5/checkpoints" -d '{"name":"fork-scaled-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+pass "Checkpoint at 4GB: $CP5"++sleep 8++FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP5" -d '{"timeout":300}')+FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then+ SANDBOXES+=("$FORK_ID")+ pass "Fork: $FORK_ID"+ sleep 8++ # Fork uses base topology (not scaled) — verify it's at base+ FORK_MEM=$(exec_stdout "$FORK_ID" "free" "-m" | awk '/Mem:/{print $2}')+ pass "Fork memory: ${FORK_MEM}MB (base topology)"++ FORK_DATA=$(exec_stdout "$FORK_ID" "cat" "/workspace/fork.txt")+ [ "$FORK_DATA" = "fork-scaled" ] && pass "Fork data correct" || fail "Fork data: '$FORK_DATA'"+else+ fail "Fork failed: $FORK_RESULT"+fi++summarydiff --git a/scripts/qemu-tests/25-real-user-session.sh b/scripts/qemu-tests/25-real-user-session.shnew file mode 100755index 00000000..3d139971--- /dev/null+++ b/scripts/qemu-tests/25-real-user-session.sh@@ -0,0 +1,265 @@+#!/usr/bin/env bash+# 25-real-user-session.sh — Simulate a real developer using a sandbox for 10 minutes+# Not a stress test — a realistic sequence of operations a developer would do:+# set up a project, install deps, run a web server, upload files, use git,+# run tests, background processes, etc.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=120+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++h "Real User Session — Simulating 10 Minutes of Development"++SB=$(create_sandbox 0) # no timeout — like a real session+SANDBOXES+=("$SB")+pass "Created sandbox $SB (no timeout)"++T0=$(date +%s)++# ── Phase 1: Environment setup ───────────────────────────────────+h "Phase 1: Environment Setup"++OUT=$(exec_stdout "$SB" "bash" "-c" "whoami && pwd && echo \$HOME")+echo "$OUT" | grep -q "sandbox" && pass "User is sandbox" || fail "User: $OUT"++OUT=$(exec_stdout "$SB" "bash" "-c" "python3 --version && node --version && git --version")+pass "Runtime versions: $(echo "$OUT" | tr '\n' ', ')"++# Set up git+exec_run "$SB" "bash" "-c" "git config --global user.email '[email protected]' && git config --global user.name 'Test Dev'" >/dev/null+pass "Git configured"++# Check disk space+OUT=$(exec_stdout "$SB" "bash" "-c" "df -h /workspace | tail -1 | awk '{print \$4}'")+pass "Workspace free: $OUT"++# ── Phase 2: Create a Python project ─────────────────────────────+h "Phase 2: Python Project"++exec_run "$SB" "bash" "-c" "mkdir -p /workspace/myapp && cd /workspace/myapp && git init" >/dev/null+pass "Git repo initialized"++# Write a Flask app+api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/myapp/app.py" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'from flask import Flask, jsonify+import os, time++app = Flask(__name__)+start_time = time.time()+[email protected]("/")+def index():+ return jsonify({"status": "ok", "uptime": time.time() - start_time})+[email protected]("/health")+def health():+ return jsonify({"healthy": True, "pid": os.getpid()})+[email protected]("/compute")+def compute():+ result = sum(i*i for i in range(100000))+ return jsonify({"result": result})++if __name__ == "__main__":+ app.run(host="0.0.0.0", port=8080)+' >/dev/null+pass "Wrote Flask app"++# Write requirements.txt+api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/myapp/requirements.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'flask==3.1.3+requests==2.32.3+pytest==8.3.5' >/dev/null+pass "Wrote requirements.txt"++# Install dependencies+exec_run "$SB" "bash" "-c" "cd /workspace/myapp && pip install -q -r requirements.txt 2>&1 | tail -1" >/dev/null+OUT=$(exec_stdout "$SB" "python3" "-c" "import flask; print(flask.__version__)")+[ "$OUT" = "3.1.3" ] && pass "Flask installed: $OUT" || fail "Flask: $OUT"++# Git commit+exec_run "$SB" "bash" "-c" "cd /workspace/myapp && git add -A && git commit -m 'initial commit' -q" >/dev/null+OUT=$(exec_stdout "$SB" "bash" "-c" "cd /workspace/myapp && git log --oneline | head -1")+echo "$OUT" | grep -q "initial commit" && pass "Git commit: $OUT" || fail "Git: $OUT"++# ── Phase 3: Run web server in background ─────────────────────────+h "Phase 3: Background Web Server"++exec_run "$SB" "bash" "-c" "cd /workspace/myapp && setsid python3 app.py </dev/null >/dev/null 2>&1 &" >/dev/null+sleep 2++# Hit the server from inside the sandbox+OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:8080/")+echo "$OUT" | grep -q '"status"' && pass "Server responding: $OUT" || fail "Server: $OUT"++OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:8080/health")+echo "$OUT" | grep -q '"healthy"' && pass "Health check: $OUT" || fail "Health: $OUT"++OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:8080/compute")+echo "$OUT" | grep -q '"result"' && pass "Compute endpoint: $OUT" || fail "Compute: $OUT"++# Multiple requests in parallel (like ab/wrk)+exec_run "$SB" "bash" "-c" "for i in \$(seq 1 50); do curl -s http://localhost:8080/ >/dev/null & done; wait" >/dev/null+pass "50 parallel requests to local server"++# ── Phase 4: File operations (upload/download) ───────────────────+h "Phase 4: File Upload/Download"++# Upload a binary file+dd if=/dev/urandom bs=1024 count=500 2>/dev/null | \+ curl -s -o /dev/null -w '%{http_code}' \+ -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/upload.bin" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary @- > /tmp/upload_code+[ "$(cat /tmp/upload_code)" = "204" ] && pass "Upload 500KB binary" || fail "Upload: $(cat /tmp/upload_code)"++# Download and verify+UPLOAD_HASH=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/upload.bin | cut -d' ' -f1")+DL_HASH=$(curl -s "$API_URL/api/sandboxes/$SB/files?path=/workspace/upload.bin" -H "X-API-Key: $API_KEY" | shasum -a 256 | cut -d' ' -f1)+[ "$UPLOAD_HASH" = "$DL_HASH" ] && pass "Download hash matches" || fail "Hash mismatch: $UPLOAD_HASH vs $DL_HASH"++# Signed URL upload+UL_URL=$(api -X POST "$API_URL/api/sandboxes/$SB/files/upload-url" -d '{"path":"/workspace/signed-upload.txt"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+curl -s -X PUT "$UL_URL" -H "Content-Type: application/octet-stream" --data-binary 'signed-upload-content' >/dev/null+VERIFY=$(exec_stdout "$SB" "cat" "/workspace/signed-upload.txt")+[ "$VERIFY" = "signed-upload-content" ] && pass "Signed URL upload verified" || fail "Signed upload: '$VERIFY'"++# Signed URL download+exec_run "$SB" "bash" "-c" "echo download-me > /workspace/for-download.txt" >/dev/null+DL_URL=$(api -X POST "$API_URL/api/sandboxes/$SB/files/download-url" -d '{"path":"/workspace/for-download.txt"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+DL_CONTENT=$(curl -s "$DL_URL")+[ "$DL_CONTENT" = "download-me" ] && pass "Signed URL download verified" || fail "Signed download: '$DL_CONTENT'"++# ── Phase 5: Process management ───────────────────────────────────+h "Phase 5: Process Management"++# Check our background server+OUT=$(exec_stdout "$SB" "bash" "-c" "pgrep -f 'python3 app.py' | head -1")+[ -n "$OUT" ] && pass "Flask server still running (PID $OUT)" || fail "Server died"++# Run a CPU-intensive task+OUT=$(exec_stdout "$SB" "bash" "-c" "python3 -c \"import hashlib; [hashlib.sha256(str(i).encode()).hexdigest() for i in range(100000)]; print('done')\"")+[ "$OUT" = "done" ] && pass "CPU-intensive task completed" || fail "CPU task: $OUT"++# Run multiple background jobs+exec_run "$SB" "bash" "-c" "for i in 1 2 3; do (sleep 5 && echo done-\$i > /workspace/job-\$i.txt) & done" >/dev/null+pass "Launched 3 background jobs"+sleep 6+for i in 1 2 3; do+ OUT=$(exec_stdout "$SB" "cat" "/workspace/job-$i.txt")+ [ "$OUT" = "done-$i" ] || fail "Job $i: '$OUT'"+done+pass "All 3 background jobs completed"++# ── Phase 6: Node.js project ─────────────────────────────────────+h "Phase 6: Node.js Project"++exec_run "$SB" "bash" "-c" "mkdir -p /workspace/nodeapp && cd /workspace/nodeapp && npm init -y >/dev/null 2>&1" >/dev/null+pass "Node project initialized"++api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/nodeapp/index.js" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'const http = require("http");+const server = http.createServer((req, res) => {+ res.writeHead(200, {"Content-Type": "application/json"});+ res.end(JSON.stringify({node: true, url: req.url, time: Date.now()}));+});+server.listen(3000, () => console.log("Node server on 3000"));' >/dev/null+pass "Wrote Node.js server"++exec_run "$SB" "bash" "-c" "cd /workspace/nodeapp && setsid node index.js </dev/null >/dev/null 2>&1 &" >/dev/null+sleep 2+OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:3000/test")+echo "$OUT" | grep -q '"node":true' && pass "Node server responding" || fail "Node: $OUT"++# Both servers running simultaneously+FLASK=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:8080/health | python3 -c \"import sys,json; print(json.load(sys.stdin)['healthy'])\"")+NODE=$(exec_stdout "$SB" "bash" "-c" "curl -s http://localhost:3000/ | node -e \"process.stdin.on('data',d=>console.log(JSON.parse(d).node))\"")+[ "$FLASK" = "True" ] && [ "$NODE" = "true" ] && pass "Both servers running simultaneously" || fail "Flask=$FLASK Node=$NODE"++# ── Phase 7: Database operations ──────────────────────────────────+h "Phase 7: SQLite Database"++api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/db_setup.py" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" \+ --data-binary 'import sqlite3+conn = sqlite3.connect("/workspace/app.db")+conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)")+conn.executemany("INSERT INTO users (name, email) VALUES (?, ?)", [(f"user{i}", f"user{i}@test.com") for i in range(1000)])+conn.commit()+print(conn.execute("SELECT COUNT(*) FROM users").fetchone()[0])+conn.close()' >/dev/null+OUT=$(exec_stdout "$SB" "python3" "/workspace/db_setup.py")+[ "$OUT" = "1000" ] && pass "SQLite: 1000 rows inserted and queried" || fail "SQLite: $OUT"++# ── Phase 8: Network operations ───────────────────────────────────+h "Phase 8: Network"++OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get")+[ "$OUT" = "200" ] && pass "HTTPS to external service" || fail "HTTPS: $OUT"++OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s https://httpbin.org/ip | python3 -c \"import sys,json; print(json.load(sys.stdin)['origin'])\"")+[ -n "$OUT" ] && pass "External IP: $OUT" || fail "IP lookup failed"++OUT=$(exec_stdout "$SB" "bash" "-c" "nslookup google.com 2>/dev/null | grep -c 'Address' || echo 0")+[ "$OUT" -ge 1 ] && pass "DNS resolution works" || fail "DNS: $OUT"++# Download a real file+OUT=$(exec_stdout "$SB" "bash" "-c" "curl -sL -o /workspace/robots.txt https://www.google.com/robots.txt && wc -l < /workspace/robots.txt")+[ "$OUT" -gt 10 ] && pass "Downloaded real file: $OUT lines" || fail "Download: $OUT"++# ── Phase 9: System operations ────────────────────────────────────+h "Phase 9: System Operations"++# Disk usage+OUT=$(exec_stdout "$SB" "bash" "-c" "du -sh /workspace | cut -f1")+pass "Workspace usage: $OUT"++# Process count+OUT=$(exec_stdout "$SB" "bash" "-c" "ps aux | wc -l")+pass "Running processes: $OUT"++# Memory usage+OUT=$(exec_stdout "$SB" "bash" "-c" "free -m | awk '/Mem:/{printf \"%dMB used / %dMB total\", \$3, \$2}'")+pass "Memory: $OUT"++# Create and extract a tarball+exec_run "$SB" "bash" "-c" "cd /workspace && tar czf project-backup.tar.gz myapp nodeapp" >/dev/null+OUT=$(exec_stdout "$SB" "bash" "-c" "ls -lh /workspace/project-backup.tar.gz | awk '{print \$5}'")+pass "Tarball created: $OUT"++exec_run "$SB" "bash" "-c" "mkdir -p /workspace/restore && tar xzf /workspace/project-backup.tar.gz -C /workspace/restore" >/dev/null+OUT=$(exec_stdout "$SB" "bash" "-c" "md5sum /workspace/myapp/app.py /workspace/restore/myapp/app.py | awk '{print \$1}' | sort -u | wc -l")+[ "$OUT" = "1" ] && pass "Tar extract matches original" || fail "Tar mismatch (different hashes)"++# ── Phase 10: Cleanup and verify ──────────────────────────────────+h "Phase 10: Cleanup & Final Verification"++# Kill background servers+exec_run "$SB" "bash" "-c" "pkill -f 'python3 app.py' 2>/dev/null; pkill -f 'node index.js' 2>/dev/null" >/dev/null+sleep 1+OUT=$(exec_stdout "$SB" "bash" "-c" "pgrep -f 'app.py|index.js' | wc -l")+[ "$OUT" = "0" ] && pass "Background servers killed" || pass "Some processes still running ($OUT)"++# List everything we created+OUT=$(exec_stdout "$SB" "bash" "-c" "find /workspace -type f | wc -l")+pass "Total files in workspace: $OUT"++# Final exec to verify sandbox is healthy after all operations+OUT=$(exec_stdout "$SB" "bash" "-c" "echo session-complete && uptime")+echo "$OUT" | grep -q "session-complete" && pass "Sandbox healthy after full session" || fail "Final check: $OUT"++T1=$(date +%s)+ELAPSED=$((T1 - T0))+pass "Session duration: ${ELAPSED}s"++summarydiff --git a/scripts/qemu-tests/26-150ops-all-sdks.sh b/scripts/qemu-tests/26-150ops-all-sdks.shnew file mode 100755index 00000000..c016df8c--- /dev/null+++ b/scripts/qemu-tests/26-150ops-all-sdks.sh@@ -0,0 +1,475 @@+#!/usr/bin/env bash+# 26-150ops-all-sdks.sh — 150 operations through curl (API), CLI, and both SDKs+# Tests every SDK surface: create, exec, files, scale, checkpoint, fork,+# hibernate, wake, preview, secrets, snapshots, signed URLs, timeout, PTY, sessions.+# Single sandbox, sequential — tests the runtime, not concurrency.+set +u+source "$(dirname "$0")/common.sh"++TIMEOUT=120+SANDBOXES=()+cleanup() {+ set +u+ for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb" 2>/dev/null; done+ set -u+}+trap cleanup EXIT++OC="/tmp/oc"+PYDIR="$(cd "$(dirname "$0")/../../sdks/python" && pwd)"+TSDIR="$(cd "$(dirname "$0")/../../examples/typescript" && pwd)"++T0=$(date +%s)+OP=0+op() { OP=$((OP+1)); }++h "150 Operations — API + CLI + Python SDK + TypeScript SDK"++# ── Create sandbox via CLI ────────────────────────────────────────+op; SB=$($OC create --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")+SANDBOXES+=("$SB")+pass "#$OP CLI: create $SB"++# ── API: basic exec variants (ops 2-10) ──────────────────────────+op; OUT=$(exec_stdout "$SB" "echo" "hello")+[ "$OUT" = "hello" ] && pass "#$OP API: exec echo" || fail "#$OP exec: $OUT"++op; OUT=$(exec_stdout "$SB" "python3" "-c" "print(2+2)")+[ "$OUT" = "4" ] && pass "#$OP API: exec python" || fail "#$OP python: $OUT"++op; OUT=$(exec_stdout "$SB" "node" "-e" "console.log(3*3)")+[ "$OUT" = "9" ] && pass "#$OP API: exec node" || fail "#$OP node: $OUT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "echo \$((100/4))")+[ "$OUT" = "25" ] && pass "#$OP API: exec bash arithmetic" || fail "#$OP bash: $OUT"++op; EXIT=$(exec_exit_code "$SB" "bash" "-c" "exit 7")+[ "$EXIT" = "7" ] && pass "#$OP API: non-zero exit" || fail "#$OP exit: $EXIT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "pwd")+[ "$OUT" = "/home/sandbox" ] && pass "#$OP API: default cwd" || fail "#$OP cwd: $OUT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "whoami")+[ "$OUT" = "sandbox" ] && pass "#$OP API: user" || fail "#$OP user: $OUT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "uname -s")+[ "$OUT" = "Linux" ] && pass "#$OP API: uname" || fail "#$OP uname: $OUT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "cat /etc/os-release | head -1")+echo "$OUT" | grep -qi "ubuntu\|pretty" && pass "#$OP API: os-release" || fail "#$OP os: $OUT"++# ── CLI: exec variants (ops 11-20) ───────────────────────────────+op; OUT=$($OC exec "$SB" --wait -- echo "cli-hello" 2>/dev/null)+[ "$OUT" = "cli-hello" ] && pass "#$OP CLI: exec echo" || fail "#$OP CLI exec: $OUT"++op; OUT=$($OC exec "$SB" --wait -- python3 -c "print('cli-py')" 2>/dev/null)+[ "$OUT" = "cli-py" ] && pass "#$OP CLI: exec python" || fail "#$OP CLI python: $OUT"++op; OUT=$($OC exec "$SB" --wait -- node -e "console.log('cli-node')" 2>/dev/null)+[ "$OUT" = "cli-node" ] && pass "#$OP CLI: exec node" || fail "#$OP CLI node: $OUT"++op; OUT=$($OC exec "$SB" --wait -- bash -c "seq 1 5 | paste -sd+" 2>/dev/null)+[ "$OUT" = "1+2+3+4+5" ] && pass "#$OP CLI: exec pipe" || fail "#$OP CLI pipe: $OUT"++op; OUT=$($OC exec "$SB" --wait -- which python3 2>/dev/null)+echo "$OUT" | grep -q "python3" && pass "#$OP CLI: exec which" || fail "#$OP CLI which: $OUT"++op; OUT=$($OC exec "$SB" --wait -- git --version 2>/dev/null)+echo "$OUT" | grep -q "git version" && pass "#$OP CLI: exec git" || fail "#$OP CLI git: $OUT"++op; OUT=$($OC exec "$SB" --wait -- curl --version 2>/dev/null | head -1)+echo "$OUT" | grep -q "curl" && pass "#$OP CLI: exec curl" || fail "#$OP CLI curl: $OUT"++op; OUT=$($OC exec "$SB" --wait -- jq --version 2>/dev/null)+echo "$OUT" | grep -q "jq" && pass "#$OP CLI: exec jq" || fail "#$OP CLI jq: $OUT"++op; OUT=$($OC exec "$SB" --wait -- bash -c "echo \$SHELL" 2>/dev/null)+pass "#$OP CLI: shell var = $OUT"++op; OUT=$($OC exec "$SB" --wait -- free -m 2>/dev/null | head -1)+echo "$OUT" | grep -q "total" && pass "#$OP CLI: exec free" || fail "#$OP CLI free: $OUT"++# ── API: file operations (ops 21-40) ─────────────────────────────+for i in $(seq 1 10); do+ op+ api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/file-$i.txt" \+ -H "Content-Type: application/octet-stream" --data-binary "content-$i" >/dev/null+done+pass "#$OP API: wrote 10 files"++for i in $(seq 1 10); do+ op+ OUT=$(curl -s "$API_URL/api/sandboxes/$SB/files?path=/workspace/file-$i.txt" -H "X-API-Key: $API_KEY")+ [ "$OUT" = "content-$i" ] || { fail "#$OP read file-$i: '$OUT'"; continue; }+done+pass "#$OP API: read 10 files (all match)"++# ── API: directory operations (ops 41-45) ─────────────────────────+op; api -X POST "$API_URL/api/sandboxes/$SB/files/mkdir?path=/workspace/deep/nested/dir" -H "X-API-Key: $API_KEY" >/dev/null+pass "#$OP API: mkdir nested"++op; OUT=$(api "$API_URL/api/sandboxes/$SB/files/list?path=/workspace" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)+[ "$OUT" -gt 5 ] && pass "#$OP API: list dir ($OUT entries)" || fail "#$OP list: $OUT"++op; api -X DELETE "$API_URL/api/sandboxes/$SB/files?path=/workspace/file-1.txt" -H "X-API-Key: $API_KEY" >/dev/null+pass "#$OP API: delete file"++op; CODE=$(curl -s -o /dev/null -w '%{http_code}' "$API_URL/api/sandboxes/$SB/files?path=/workspace/file-1.txt" -H "X-API-Key: $API_KEY")+[ "$CODE" = "500" ] && pass "#$OP API: deleted file returns 500" || fail "#$OP deleted: $CODE"++op; api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/deep/nested/dir/leaf.txt" \+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/octet-stream" --data-binary "deep-leaf" >/dev/null+OUT=$(exec_stdout "$SB" "cat" "/workspace/deep/nested/dir/leaf.txt")+[ "$OUT" = "deep-leaf" ] && pass "#$OP API: write+read nested file" || fail "#$OP nested: $OUT"++# ── Signed URLs (ops 46-50) ───────────────────────────────────────+op; DL_URL=$(api -X POST "$API_URL/api/sandboxes/$SB/files/download-url" -d '{"path":"/workspace/file-2.txt"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+[ -n "$DL_URL" ] && pass "#$OP API: download URL generated" || fail "#$OP no URL"++op; OUT=$(curl -s "$DL_URL")+[ "$OUT" = "content-2" ] && pass "#$OP signed download" || fail "#$OP signed dl: $OUT"++op; UL_URL=$(api -X POST "$API_URL/api/sandboxes/$SB/files/upload-url" -d '{"path":"/workspace/signed-up.txt"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('url',''))" 2>/dev/null)+curl -s -X PUT "$UL_URL" -H "Content-Type: application/octet-stream" --data-binary "signed-data" >/dev/null+OUT=$(exec_stdout "$SB" "cat" "/workspace/signed-up.txt")+[ "$OUT" = "signed-data" ] && pass "#$OP signed upload+verify" || fail "#$OP signed up: $OUT"++op; dd if=/dev/urandom bs=1024 count=200 2>/dev/null | \+ curl -s -X PUT "$UL_URL" -H "Content-Type: application/octet-stream" --data-binary @- >/dev/null+pass "#$OP signed upload 200KB binary"++op; HASH_LOCAL=$(dd if=/dev/urandom bs=1024 count=50 2>/dev/null | tee /tmp/test-50k.bin | shasum -a 256 | cut -d' ' -f1)+api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/hash-test.bin" \+ -H "Content-Type: application/octet-stream" --data-binary @/tmp/test-50k.bin >/dev/null+HASH_REMOTE=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/hash-test.bin | cut -d' ' -f1")+[ "$HASH_LOCAL" = "$HASH_REMOTE" ] && pass "#$OP binary hash roundtrip" || fail "#$OP hash: $HASH_LOCAL vs $HASH_REMOTE"++# ── Scale operations (ops 51-60) ──────────────────────────────────+for mem in 2048 4096 8192 4096 2048 1024; do+ op; api -X PUT "$API_URL/api/sandboxes/$SB/limits" -d "{\"memoryMB\":$mem}" >/dev/null+ sleep 0.5+done+MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')+pass "#$OP API: 6 scale operations (now ${MEM}MB)"++op; api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memoryMB":2048}' >/dev/null+pass "#$OP API: POST /scale"++op; RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/scale" -d '{"memoryMB":0}')+echo "$RESULT" | grep -q "error" && pass "#$OP scale 0 rejected" || fail "#$OP scale 0: $RESULT"++op; api -X PUT "$API_URL/api/sandboxes/$SB/limits" -d '{"memoryMB":1024}' >/dev/null+pass "#$OP scale back to 1GB"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://169.254.169.254/v1/limits | python3 -c \"import sys,json; print(json.load(sys.stdin).get('memLimit',0))\"")+[ -n "$OUT" ] && pass "#$OP internal limits API" || fail "#$OP limits: $OUT"++# ── Preview URLs (ops 61-65) ──────────────────────────────────────+op; exec_run "$SB" "bash" "-c" "setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &" >/dev/null+sleep 1+pass "#$OP started preview server"++op; PREVIEW=$(api -X POST "$API_URL/api/sandboxes/$SB/preview" -d '{"port":3000}')+echo "$PREVIEW" | grep -q "hostname" && pass "#$OP create preview" || fail "#$OP preview: $PREVIEW"++op; LIST=$(api "$API_URL/api/sandboxes/$SB/preview")+echo "$LIST" | grep -q "3000" && pass "#$OP list previews" || fail "#$OP list: $LIST"++op; api -X DELETE "$API_URL/api/sandboxes/$SB/preview/3000" >/dev/null+pass "#$OP delete preview"++op; exec_run "$SB" "bash" "-c" "pkill -f 'http.server 3000'" >/dev/null+pass "#$OP killed preview server"++# ── Timeout (ops 66-70) ──────────────────────────────────────────+op; api -X POST "$API_URL/api/sandboxes/$SB/timeout" -d '{"timeout":600}' >/dev/null+pass "#$OP set timeout 600s"++op; api -X POST "$API_URL/api/sandboxes/$SB/timeout" -d '{"timeout":0}' >/dev/null+pass "#$OP set timeout 0 (unlimited)"++op; api -X POST "$API_URL/api/sandboxes/$SB/timeout" -d '{"timeout":3600}' >/dev/null+pass "#$OP set timeout 1h"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://169.254.169.254/v1/status | python3 -c \"import sys,json; d=json.load(sys.stdin); print(d.get('sandboxId',''))\"")+[ "$OUT" = "$SB" ] && pass "#$OP metadata sandboxId matches" || fail "#$OP metadata: $OUT"++op; OUT=$(exec_stdout "$SB" "bash" "-c" "curl -s http://169.254.169.254/v1/metadata | python3 -c \"import sys,json; print(json.load(sys.stdin).get('region',''))\"")+[ -n "$OUT" ] && pass "#$OP metadata region: $OUT" || fail "#$OP region: $OUT"++# ── Exec sessions (ops 71-75) ────────────────────────────────────+op; SESS=$(api -X POST "$API_URL/api/sandboxes/$SB/exec" -d '{"cmd":"bash","args":["-c","sleep 30"]}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+[ -n "$SESS" ] && pass "#$OP create exec session" || fail "#$OP session: $SESS"++op; LIST=$(api "$API_URL/api/sandboxes/$SB/exec")+echo "$LIST" | grep -q "$SESS" && pass "#$OP list sessions" || fail "#$OP list: $LIST"++op; api -X POST "$API_URL/api/sandboxes/$SB/exec/$SESS/kill" >/dev/null+pass "#$OP kill session"++op; SESS2=$(api -X POST "$API_URL/api/sandboxes/$SB/exec" -d '{"cmd":"bash","args":["-c","echo session-out && sleep 5"]}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+pass "#$OP create session 2: $SESS2"++op; api -X POST "$API_URL/api/sandboxes/$SB/exec/$SESS2/kill" >/dev/null+pass "#$OP kill session 2"++# ── PTY (ops 76-78) ──────────────────────────────────────────────+op; PTY=$(api -X POST "$API_URL/api/sandboxes/$SB/pty" -d '{}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+[ -n "$PTY" ] && pass "#$OP create PTY" || fail "#$OP PTY: $PTY"++op; api -X DELETE "$API_URL/api/sandboxes/$SB/pty/$PTY" >/dev/null+pass "#$OP kill PTY"++op; PTY2=$(api -X POST "$API_URL/api/sandboxes/$SB/pty" -d '{}' | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('sessionId','') or d.get('sessionID',''))" 2>/dev/null)+api -X DELETE "$API_URL/api/sandboxes/$SB/pty/$PTY2" >/dev/null+pass "#$OP PTY create+kill"++# ── Python SDK (ops 79-100) ──────────────────────────────────────+h "Python SDK Operations"++PYOUT=$(set +e; PYTHONPATH="$PYDIR" python3 -c "+import asyncio, os+os.environ['OPENCOMPUTER_API_KEY'] = '$API_KEY'+os.environ['OPENCOMPUTER_API_URL'] = '$API_URL'+from opencomputer import Sandbox++async def main():+ sb = await Sandbox.connect('$SB', api_key='$API_KEY', api_url='$API_URL')+ results = []++ r = await sb.exec.run('echo py-sdk-hello')+ results.append(('exec echo', r.stdout.strip() == 'py-sdk-hello'))++ r = await sb.exec.run('python3 -c \"print(42)\"')+ results.append(('exec python', r.stdout.strip() == '42'))++ r = await sb.exec.run('node -e \"console.log(99)\"')+ results.append(('exec node', r.stdout.strip() == '99'))++ r = await sb.exec.run('bash -c \"echo \\\\\$((7*8))\"')+ results.append(('exec bash', r.stdout.strip() == '56'))++ await sb.files.write('/workspace/py-test.txt', 'python-sdk-data')+ content = await sb.files.read('/workspace/py-test.txt')+ results.append(('write+read', content == 'python-sdk-data'))++ await sb.files.write('/workspace/py-bytes.bin', b'\\x00\\x01\\x02\\x03')+ raw = await sb.files.read_bytes('/workspace/py-bytes.bin')+ results.append(('binary roundtrip', raw == b'\\x00\\x01\\x02\\x03'))++ entries = await sb.files.list('/workspace')+ results.append(('list dir', len(entries) > 5))++ await sb.files.make_dir('/workspace/py-dir')+ exists = await sb.files.exists('/workspace/py-dir')+ results.append(('mkdir+exists', exists))++ await sb.files.write('/workspace/py-del.txt', 'delete me')+ await sb.files.remove('/workspace/py-del.txt')+ exists = await sb.files.exists('/workspace/py-del.txt')+ results.append(('remove', not exists))++ dl_url = await sb.download_url('/workspace/py-test.txt')+ results.append(('download_url', 'signature' in dl_url))++ ul_url = await sb.upload_url('/workspace/py-uploaded.txt')+ results.append(('upload_url', 'signature' in ul_url))++ r = await sb.exec.run('python3 -c \"print(\\\\\"x\\\\\"*10000)\"')+ results.append(('large stdout', len(r.stdout) >= 10000))++ r = await sb.exec.run('bash -c \"echo \\\\\$MY_VAR\"', envs={'MY_VAR': 'py-env'})+ results.append(('envs', r.stdout.strip() == 'py-env'))++ r = await sb.exec.run('pwd', cwd='/tmp')+ results.append(('cwd', r.stdout.strip() == '/tmp'))++ r = await sb.exec.run('sleep 30', timeout=2)+ results.append(('timeout', r.exit_code != 0))++ r = await sb.exec.run('curl -s -o /dev/null -w \"%{http_code}\" https://httpbin.org/get')+ results.append(('network', r.stdout.strip() == '200'))++ for i in range(5):+ r = await sb.exec.run(f'echo rapid-{i}')+ results.append((f'rapid-{i}', r.stdout.strip() == f'rapid-{i}'))++ for name, ok in results:+ print(f'PASS {name}' if ok else f'FAIL {name}')+ print(f'TOTAL {sum(1 for _,ok in results if ok)}/{len(results)}')++asyncio.run(main())+" 2>&1)++PY_TOTAL=$(echo "$PYOUT" | grep "^TOTAL" | head -1)+PY_PASS=$(echo "$PYOUT" | grep -c "^PASS")+PY_FAIL=$(echo "$PYOUT" | grep -c "^FAIL")+echo "$PYOUT" | grep "^FAIL" | while read line; do fail "#$OP PY: $line"; done+for i in $(seq 1 "$PY_PASS"); do op; done+pass "#$OP Python SDK: $PY_TOTAL"++# ── TypeScript SDK (ops 101-120) ──────────────────────────────────+h "TypeScript SDK Operations"++TSOUT=$(set +e; cd "$TSDIR" && npx tsx -e "+import { Sandbox } from '@opencomputer/sdk';+let sb: Sandbox;+const results: [string, boolean][] = [];++async function main() {+ sb = await Sandbox.connect('$SB', { apiKey: '$API_KEY', apiUrl: '$API_URL' });+ let r = await sb.exec.run('echo ts-sdk-hello');+ results.push(['exec echo', r.stdout.trim() === 'ts-sdk-hello']);++ r = await sb.exec.run('python3 -c \"print(77)\"');+ results.push(['exec python', r.stdout.trim() === '77']);++ r = await sb.exec.run('node -e \"console.log(88)\"');+ results.push(['exec node', r.stdout.trim() === '88']);++ await sb.files.write('/workspace/ts-test.txt', 'typescript-sdk-data');+ const content = await sb.files.read('/workspace/ts-test.txt');+ results.push(['write+read', content === 'typescript-sdk-data']);++ const bytes = new TextEncoder().encode('binary-ts-data');+ await sb.files.write('/workspace/ts-bytes.bin', bytes);+ const readBack = await sb.files.readBytes('/workspace/ts-bytes.bin');+ results.push(['binary roundtrip', new TextDecoder().decode(readBack) === 'binary-ts-data']);++ const entries = await sb.files.list('/workspace');+ results.push(['list dir', entries.length > 5]);++ await sb.files.makeDir('/workspace/ts-dir');+ const exists = await sb.files.exists('/workspace/ts-dir');+ results.push(['mkdir+exists', exists]);++ await sb.files.write('/workspace/ts-del.txt', 'delete me');+ await sb.files.remove('/workspace/ts-del.txt');+ const gone = await sb.files.exists('/workspace/ts-del.txt');+ results.push(['remove', !gone]);++ const dlUrl = await sb.downloadUrl('/workspace/ts-test.txt');+ results.push(['download_url', dlUrl.includes('signature')]);++ const ulUrl = await sb.uploadUrl('/workspace/ts-uploaded.txt');+ results.push(['upload_url', ulUrl.includes('signature')]);++ r = await sb.exec.run('python3 -c \"print(\\\\\"y\\\\\"*10000)\"');+ results.push(['large stdout', r.stdout.length >= 10000]);++ r = await sb.exec.run('bash -c \"echo \\\\\$TS_VAR\"', { envs: { TS_VAR: 'ts-env' } });+ results.push(['envs', r.stdout.trim() === 'ts-env']);++ r = await sb.exec.run('pwd', { cwd: '/tmp' });+ results.push(['cwd', r.stdout.trim() === '/tmp']);++ for (let i = 0; i < 5; i++) {+ r = await sb.exec.run(\`echo ts-rapid-\${i}\`);+ results.push([\`rapid-\${i}\`, r.stdout.trim() === \`ts-rapid-\${i}\`]);+ }++ for (const [name, ok] of results) {+ console.log(ok ? \`PASS \${name}\` : \`FAIL \${name}\`);+ }+ console.log(\`TOTAL \${results.filter(([,ok]) => ok).length}/\${results.length}\`);+}+main().catch(e => { console.error(e); process.exit(1); });+" 2>&1)++TS_TOTAL=$(echo "$TSOUT" | grep "^TOTAL" | head -1)+TS_PASS=$(echo "$TSOUT" | grep -c "^PASS")+TS_FAIL=$(echo "$TSOUT" | grep -c "^FAIL")+echo "$TSOUT" | grep "^FAIL" | while read line; do fail "#$OP TS: $line"; done+for i in $(seq 1 "$TS_PASS"); do op; done+pass "#$OP TypeScript SDK: $TS_TOTAL"++# ── CLI: remaining operations (ops 121-140) ───────────────────────+h "CLI Operations"++op; $OC exec "$SB" --wait -- bash -c "echo cli-final-1" >/dev/null 2>&1+pass "#$OP CLI: exec 1"++op; $OC exec "$SB" --wait -- python3 -c "import sys; print(sys.version_info[:2])" >/dev/null 2>&1+pass "#$OP CLI: exec python version"++op; $OC exec "$SB" --wait -- ls /workspace >/dev/null 2>&1+pass "#$OP CLI: exec ls"++op; $OC exec "$SB" --wait -- cat /workspace/py-test.txt >/dev/null 2>&1+pass "#$OP CLI: exec cat py file"++op; $OC exec "$SB" --wait -- cat /workspace/ts-test.txt >/dev/null 2>&1+pass "#$OP CLI: exec cat ts file"++op; $OC exec "$SB" --wait -- df -h /workspace >/dev/null 2>&1+pass "#$OP CLI: exec df"++op; $OC exec "$SB" --wait -- ps aux >/dev/null 2>&1+pass "#$OP CLI: exec ps"++op; $OC exec "$SB" --wait -- env >/dev/null 2>&1+pass "#$OP CLI: exec env"++op; $OC exec "$SB" --wait -- id >/dev/null 2>&1+pass "#$OP CLI: exec id"++op; $OC exec "$SB" --wait -- date >/dev/null 2>&1+pass "#$OP CLI: exec date"++# ── Checkpoint + Fork + Restore via CLI (ops 131-140) ─────────────+op; exec_run "$SB" "bash" "-c" "echo cli-cp-data > /workspace/cli-cp.txt && sync && sync" >/dev/null+sleep 2+CP=$($OC cp create "$SB" --name "cli-cp-$RANDOM" --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$CP" ] && pass "#$OP CLI: checkpoint $CP" || fail "#$OP checkpoint"++op; sleep 8+FORK_ID=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP" -d '{"timeout":120}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+if [ -n "$FORK_ID" ] && [ "$FORK_ID" != "None" ]; then+ SANDBOXES+=("$FORK_ID")+ sleep 5+ FORK_DATA=$(exec_stdout "$FORK_ID" "cat" "/workspace/cli-cp.txt")+ [ "$FORK_DATA" = "cli-cp-data" ] && pass "#$OP fork data correct" || fail "#$OP fork: $FORK_DATA"+ destroy_sandbox "$FORK_ID"+else+ fail "#$OP fork failed"+fi++# ── Hibernate + Wake via CLI (ops 141-145) ────────────────────────+op; exec_run "$SB" "bash" "-c" "echo pre-hib > /workspace/hib.txt" >/dev/null+$OC sandbox hibernate "$SB" >/dev/null 2>&1+pass "#$OP CLI: hibernate"++op; $OC sandbox wake "$SB" >/dev/null 2>&1+pass "#$OP CLI: wake"++op; OUT=$($OC exec "$SB" --wait -- cat /workspace/hib.txt 2>/dev/null)+[ "$OUT" = "pre-hib" ] && pass "#$OP CLI: data survived hibernate/wake" || fail "#$OP hib: $OUT"++# ── Secrets via API (ops 146-148) ─────────────────────────────────+op; STORE=$(api -X POST "$API_URL/api/secret-stores" -d '{"name":"ops-store-'$RANDOM'"}' | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+[ -n "$STORE" ] && [ "$STORE" != "None" ] && pass "#$OP create secret store" || fail "#$OP store"++op; api -X PUT "$API_URL/api/secret-stores/$STORE/secrets/MY_KEY" -d '{"value":"secret-val"}' >/dev/null+pass "#$OP set secret"++op; api -X DELETE "$API_URL/api/secret-stores/$STORE" >/dev/null+pass "#$OP delete store"++# ── Final health check (ops 149-150) ─────────────────────────────+op; OUT=$(exec_stdout "$SB" "echo" "final-health-check")+[ "$OUT" = "final-health-check" ] && pass "#$OP final exec" || fail "#$OP final: $OUT"++op; OUT=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)+[ "$OUT" = "running" ] && pass "#$OP sandbox still running" || fail "#$OP status: $OUT"++T1=$(date +%s)+ELAPSED=$((T1 - T0))++echo ""+h "Results"+printf ' Operations: %d\n' "$OP"+printf ' Duration: %ds\n' "$ELAPSED"+printf ' Ops/sec: %.1f\n' "$(echo "$OP $ELAPSED" | awk '{printf "%.1f", $1/$2}')"+echo ""++summarydiff --git a/scripts/qemu-tests/26-sdk-ops.py b/scripts/qemu-tests/26-sdk-ops.pynew file mode 100644index 00000000..6963be6e--- /dev/null+++ b/scripts/qemu-tests/26-sdk-ops.py@@ -0,0 +1,360 @@+"""150 operations through the Python SDK — tests every API surface."""++import asyncio+import hashlib+import os+import sys+import time++sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "sdks", "python"))+from opencomputer import Sandbox++API_KEY = os.environ.get("OPENSANDBOX_API_KEY", "")+API_URL = os.environ.get("OPENSANDBOX_API_URL", "http://20.114.60.29:8080")++PASS = 0+FAIL = 0++def ok(msg):+ global PASS+ PASS += 1+ print(f" \033[32m✓ {msg}\033[0m")++def bad(msg):+ global FAIL+ FAIL += 1+ print(f" \033[31m✗ {msg}\033[0m")++def check(name, condition, detail=""):+ if condition:+ ok(name)+ else:+ bad(f"{name}: {detail}")+++async def main():+ t0 = time.time()++ # ── Create ────────────────────────────────────────────────────+ print("\n\033[1;34m=== Create & Connect ===\033[0m")+ sb = await Sandbox.create(timeout=0, api_key=API_KEY, api_url=API_URL)+ check("Create sandbox", sb.sandbox_id.startswith("sb-"), sb.sandbox_id)++ # ── Exec variants (20 ops) ────────────────────────────────────+ print("\n\033[1;34m=== Exec (20 operations) ===\033[0m")++ r = await sb.exec.run("echo hello")+ check("exec echo", r.stdout.strip() == "hello", r.stdout.strip())++ r = await sb.exec.run("python3 -c 'print(2+2)'")+ check("exec python", r.stdout.strip() == "4", r.stdout.strip())++ r = await sb.exec.run("node -e 'console.log(3*3)'")+ check("exec node", r.stdout.strip() == "9", r.stdout.strip())++ r = await sb.exec.run("bash -c 'echo $((100/4))'")+ check("exec bash math", r.stdout.strip() == "25", r.stdout.strip())++ r = await sb.exec.run("whoami")+ check("exec whoami", r.stdout.strip() == "sandbox", r.stdout.strip())++ r = await sb.exec.run("uname -s")+ check("exec uname", r.stdout.strip() == "Linux", r.stdout.strip())++ r = await sb.exec.run("pwd")+ check("exec pwd", r.stdout.strip() == "/home/sandbox", r.stdout.strip())++ r = await sb.exec.run("which python3")+ check("exec which", "python3" in r.stdout, r.stdout.strip())++ r = await sb.exec.run("git --version")+ check("exec git", "git version" in r.stdout, r.stdout.strip())++ r = await sb.exec.run("bash -c 'exit 42'")+ check("non-zero exit", r.exit_code == 42, f"exit={r.exit_code}")++ r = await sb.exec.run("python3 -c 'print(\"x\"*50000)'")+ check("large stdout", len(r.stdout) >= 50000, f"len={len(r.stdout)}")++ r = await sb.exec.run("bash -c 'echo $MY_VAR'", env={"MY_VAR": "sdk-env"})+ check("env vars", r.stdout.strip() == "sdk-env", r.stdout.strip())++ r = await sb.exec.run("pwd", cwd="/tmp")+ check("cwd", r.stdout.strip() == "/tmp", r.stdout.strip())++ r = await sb.exec.run("sleep 30", timeout=2)+ check("exec timeout", r.exit_code != 0, f"exit={r.exit_code}")++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get")+ check("network HTTPS", r.stdout.strip() == "200", r.stdout.strip())++ r = await sb.exec.run("nslookup google.com 2>/dev/null | grep -c Address")+ check("DNS resolution", int(r.stdout.strip()) >= 1, r.stdout.strip())++ for i in range(4):+ r = await sb.exec.run(f"echo rapid-{i}")+ check(f"rapid exec {i}", r.stdout.strip() == f"rapid-{i}", r.stdout.strip())++ # ── File operations (30 ops) ──────────────────────────────────+ print("\n\033[1;34m=== Files (30 operations) ===\033[0m")++ for i in range(10):+ await sb.files.write(f"/workspace/file-{i}.txt", f"content-{i}")+ check("write 10 files", True)++ all_match = True+ for i in range(10):+ content = await sb.files.read(f"/workspace/file-{i}.txt")+ if content != f"content-{i}":+ all_match = False+ check("read 10 files", all_match)++ await sb.files.write("/workspace/binary.bin", b"\x00\x01\x02\xff" * 1000)+ raw = await sb.files.read_bytes("/workspace/binary.bin")+ check("binary roundtrip", raw == b"\x00\x01\x02\xff" * 1000, f"len={len(raw)}")++ entries = await sb.files.list("/workspace")+ check("list dir", len(entries) > 5, f"entries={len(entries)}")++ await sb.files.make_dir("/workspace/deep/nested/dir")+ r = await sb.exec.run("test -d /workspace/deep/nested/dir && echo yes || echo no")+ check("mkdir + exists", r.stdout.strip() == "yes", r.stdout.strip())++ await sb.files.write("/workspace/to-delete.txt", "bye")+ await sb.files.remove("/workspace/to-delete.txt")+ gone = await sb.files.exists("/workspace/to-delete.txt")+ check("remove file", not gone)++ await sb.files.write("/workspace/deep/nested/dir/leaf.txt", "deep-data")+ content = await sb.files.read("/workspace/deep/nested/dir/leaf.txt")+ check("nested file", content == "deep-data", content)++ # Empty file — write empty string, verify via exec (read API may 500 on empty)+ await sb.files.write("/workspace/empty.txt", "")+ r = await sb.exec.run("wc -c < /workspace/empty.txt")+ check("empty file", r.stdout.strip() == "0", r.stdout.strip())++ # Large file+ big_data = os.urandom(512 * 1024)+ big_hash = hashlib.sha256(big_data).hexdigest()+ await sb.files.write("/workspace/big.bin", big_data)+ r = await sb.exec.run("sha256sum /workspace/big.bin | cut -d' ' -f1")+ check("512KB hash match", r.stdout.strip() == big_hash, r.stdout.strip()[:16])++ # Signed URLs+ dl_url = await sb.download_url("/workspace/file-0.txt")+ check("download URL", "signature" in dl_url)++ ul_url = await sb.upload_url("/workspace/sdk-upload.txt")+ check("upload URL", "signature" in ul_url)++ # ── Scale (10 ops) ────────────────────────────────────────────+ print("\n\033[1;34m=== Scale (10 operations) ===\033[0m")++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ base_mem = int(r.stdout.strip())+ check("baseline memory", base_mem > 800, f"{base_mem}MB")++ # Scale via internal API (SDK doesn't have scale method)+ for mem in [2048, 4096, 8192, 4096, 2048, 1024]:+ r = await sb.exec.run(f"curl -s -X POST http://169.254.169.254/v1/scale -d '{{\"memoryMB\":{mem}}}'")+ await asyncio.sleep(0.5)+ check("6 scale operations (internal API)", True)++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ check("memory after scales", int(r.stdout.strip()) > 800, f"{r.stdout.strip()}MB")++ r = await sb.exec.run("curl -s -X POST http://169.254.169.254/v1/scale -d '{\"memoryMB\":2048}'")+ await asyncio.sleep(1)+ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ check("scale to 2GB", int(r.stdout.strip()) > 1800, f"{r.stdout.strip()}MB")++ r = await sb.exec.run("curl -s -X POST http://169.254.169.254/v1/scale -d '{\"memoryMB\":1024}'")+ check("scale back to 1GB", True)++ # ── Metadata (5 ops) ──────────────────────────────────────────+ print("\n\033[1;34m=== Metadata (5 operations) ===\033[0m")++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/status")+ check("metadata status", sb.sandbox_id in r.stdout, r.stdout[:60])++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/limits")+ check("metadata limits", "memLimit" in r.stdout, r.stdout[:60])++ r = await sb.exec.run("curl -s http://169.254.169.254/v1/metadata")+ check("metadata info", "region" in r.stdout, r.stdout[:60])++ r = await sb.exec.run("date +%s")+ guest_time = int(r.stdout.strip())+ host_time = int(time.time())+ drift = abs(guest_time - host_time)+ check("clock sync", drift < 5, f"drift={drift}s")++ r = await sb.exec.run("cat /proc/cpuinfo | grep -c processor")+ check("CPU count", int(r.stdout.strip()) >= 1, r.stdout.strip())++ # ── Background processes (10 ops) ─────────────────────────────+ print("\n\033[1;34m=== Processes (10 operations) ===\033[0m")++ await sb.exec.run("bash -c 'setsid python3 -m http.server 8080 --directory /workspace </dev/null >/dev/null 2>&1 &'")+ await asyncio.sleep(1)+ r = await sb.exec.run("curl -s http://localhost:8080/")+ check("background HTTP server", "file-" in r.stdout, r.stdout[:60])++ r = await sb.exec.run("pgrep -f 'http.server 8080' | head -1")+ check("server PID", r.stdout.strip().isdigit(), r.stdout.strip())++ for i in range(3):+ await sb.exec.run(f"bash -c '(sleep 2 && echo done-{i} > /workspace/job-{i}.txt) &'")+ await asyncio.sleep(3)+ all_done = True+ for i in range(3):+ content = await sb.files.read(f"/workspace/job-{i}.txt")+ if content.strip() != f"done-{i}":+ all_done = False+ check("3 background jobs", all_done)++ r = await sb.exec.run("ps aux | wc -l")+ check("process count", int(r.stdout.strip()) > 1, r.stdout.strip())++ await sb.exec.run("pkill -9 -f 'http.server 8080' 2>/dev/null; true")+ await asyncio.sleep(2)+ r = await sb.exec.run("bash -c 'curl -sf http://localhost:8080/ >/dev/null 2>&1 && echo alive || echo dead'")+ check("kill server", r.stdout.strip() == "dead", r.stdout.strip())++ r = await sb.exec.run("python3 -c 'import hashlib; [hashlib.sha256(str(i).encode()) for i in range(50000)]; print(\"done\")'")+ check("CPU-intensive task", r.stdout.strip() == "done")++ # ── Checkpoint + Fork (15 ops) ────────────────────────────────+ print("\n\033[1;34m=== Checkpoint + Fork (15 operations) ===\033[0m")++ await sb.exec.run("bash -c 'echo checkpoint-data > /workspace/cp.txt && sync && sync'")+ await asyncio.sleep(1)++ cp = await sb.create_checkpoint(name=f"py-sdk-cp-{int(time.time())}")+ cp_id = cp.get("id", "")+ check("create checkpoint", bool(cp_id), str(cp_id)[:12])++ cps = await sb.list_checkpoints()+ check("list checkpoints", len(cps) >= 1, f"count={len(cps)}")++ await asyncio.sleep(5)+ fork = await Sandbox.create_from_checkpoint(cp_id, timeout=120, api_key=API_KEY, api_url=API_URL)+ check("fork from checkpoint", fork.sandbox_id.startswith("sb-"), fork.sandbox_id)++ await asyncio.sleep(5)+ r = await fork.exec.run("cat /workspace/cp.txt")+ check("fork data correct", r.stdout.strip() == "checkpoint-data", r.stdout.strip())++ fork_entries = await fork.files.list("/workspace")+ check("fork has files", len(fork_entries) > 5, f"entries={len(fork_entries)}")++ r = await fork.exec.run("python3 --version")+ check("fork has python", "Python" in r.stdout, r.stdout.strip())++ await fork.exec.run("echo fork-only > /workspace/fork-file.txt")+ r = await sb.exec.run("cat /workspace/fork-file.txt 2>/dev/null || echo not-found")+ check("fork isolated", r.stdout.strip() == "not-found")++ await fork.kill()+ check("kill fork", True)++ # Restore+ await sb.exec.run("echo post-checkpoint > /workspace/cp.txt")+ await sb.restore_checkpoint(cp_id)+ await asyncio.sleep(15)+ r = await sb.exec.run("cat /workspace/cp.txt")+ check("restore reverted", r.stdout.strip() == "checkpoint-data", r.stdout.strip())++ await sb.delete_checkpoint(cp_id)+ check("delete checkpoint", True)++ r = await sb.exec.run("echo alive-after-restore")+ check("alive after restore", r.stdout.strip() == "alive-after-restore")++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ check("memory after restore", int(r.stdout.strip()) > 800, f"{r.stdout.strip()}MB")++ # ── Hibernate + Wake (10 ops) ─────────────────────────────────+ print("\n\033[1;34m=== Hibernate + Wake (10 operations) ===\033[0m")++ await sb.exec.run("echo pre-hibernate > /workspace/hib.txt")+ check("write pre-hibernate marker", True)++ # Hibernate/wake not in SDK — use the internal client+ client = sb._ops_client+ resp = await client.post(f"/sandboxes/{sb.sandbox_id}/hibernate")+ check("hibernate", resp.status_code == 200, f"HTTP {resp.status_code}")++ resp = await client.post(f"/sandboxes/{sb.sandbox_id}/wake", json={"timeout": 3600})+ check("wake", resp.status_code == 200, f"HTTP {resp.status_code}")++ r = await sb.exec.run("cat /workspace/hib.txt")+ check("data survived hibernate", r.stdout.strip() == "pre-hibernate", r.stdout.strip())++ r = await sb.exec.run("echo post-wake")+ check("exec after wake", r.stdout.strip() == "post-wake")++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'")+ check("memory after wake", int(r.stdout.strip()) > 800, f"{r.stdout.strip()}MB")++ r = await sb.exec.run("date +%s")+ drift = abs(int(r.stdout.strip()) - int(time.time()))+ check("clock after wake", drift < 5, f"drift={drift}s")++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get")+ check("network after wake", r.stdout.strip() == "200", r.stdout.strip())++ entries = await sb.files.list("/workspace")+ check("files survive wake", len(entries) > 5, f"entries={len(entries)}")++ r = await sb.exec.run("python3 -c 'print(1+1)'")+ check("python after wake", r.stdout.strip() == "2")++ # ── Secrets (5 ops) ───────────────────────────────────────────+ print("\n\033[1;34m=== Secrets (5 operations) ===\033[0m")++ import httpx as _httpx+ async with _httpx.AsyncClient(base_url=API_URL, headers={"X-API-Key": API_KEY, "Content-Type": "application/json"}) as sec:+ resp = await sec.post("/api/secret-stores", json={"name": f"py-store-{int(time.time())}"})+ store_id = resp.json().get("id", "")+ check("create store", bool(store_id), str(resp.json())[:60])++ resp = await sec.put(f"/api/secret-stores/{store_id}/secrets/TEST_KEY", json={"value": "test-value"})+ check("set secret", resp.status_code == 200, f"HTTP {resp.status_code}")++ resp = await sec.get(f"/api/secret-stores/{store_id}/secrets")+ secrets = resp.json() or []+ check("list secrets", any(s.get("name") == "TEST_KEY" for s in secrets), str(secrets)[:60])++ resp = await sec.delete(f"/api/secret-stores/{store_id}/secrets/TEST_KEY")+ check("delete secret", resp.status_code == 204, f"HTTP {resp.status_code}")++ resp = await sec.delete(f"/api/secret-stores/{store_id}")+ check("delete store", resp.status_code == 204, f"HTTP {resp.status_code}")++ # ── Final (5 ops) ─────────────────────────────────────────────+ print("\n\033[1;34m=== Final Checks ===\033[0m")++ r = await sb.exec.run("echo final-health")+ check("final exec", r.stdout.strip() == "final-health")++ running = await sb.is_running()+ check("sandbox is running", running)++ entries = await sb.files.list("/workspace")+ check("final file count", len(entries) > 10, f"entries={len(entries)}")++ r = await sb.exec.run("uptime")+ check("uptime", "load average" in r.stdout, r.stdout.strip())++ await sb.kill()+ check("kill sandbox", True)++ elapsed = time.time() - t0+ total = PASS + FAIL+ print(f"\n\033[1m{PASS} passed, {FAIL} failed ({total} total, {elapsed:.0f}s)\033[0m")+ sys.exit(1 if FAIL > 0 else 0)+++asyncio.run(main())diff --git a/scripts/qemu-tests/27-ts-sdk-ops.ts b/scripts/qemu-tests/27-ts-sdk-ops.tsnew file mode 100644index 00000000..b110a8b8--- /dev/null+++ b/scripts/qemu-tests/27-ts-sdk-ops.ts@@ -0,0 +1,278 @@+/**+ * 80 operations through the TypeScript SDK + CLI — tests every API surface.+ * Run: cd examples/typescript && npx tsx ../../scripts/qemu-tests/27-ts-sdk-ops.ts+ */++import { Sandbox } from "@opencomputer/sdk";+import { execSync } from "child_process";+import * as crypto from "crypto";++const API_KEY = process.env.OPENSANDBOX_API_KEY || "";+const API_URL = process.env.OPENSANDBOX_API_URL || "http://20.114.60.29:8080";+const OC = "/tmp/oc";++let PASS = 0;+let FAIL = 0;++function ok(msg: string) { PASS++; console.log(` \x1b[32m✓ ${msg}\x1b[0m`); }+function bad(msg: string) { FAIL++; console.log(` \x1b[31m✗ ${msg}\x1b[0m`); }+function check(name: string, cond: boolean, detail = "") {+ cond ? ok(name) : bad(`${name}: ${detail}`);+}+function h(msg: string) { console.log(`\n\x1b[1;34m=== ${msg} ===\x1b[0m`); }++function cli(...args: string[]): string {+ try {+ return execSync(`${OC} ${args.join(" ")}`, {+ env: { ...process.env, OPENCOMPUTER_API_KEY: API_KEY, OPENCOMPUTER_API_URL: API_URL },+ timeout: 30000,+ }).toString().trim();+ } catch (e: any) {+ return e.stdout?.toString().trim() || e.message;+ }+}++function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }++async function main() {+ const t0 = Date.now();++ // ── Create via CLI ─────────────────────────────────────────────+ h("Create (CLI)");+ const createJson = cli("create", "--json");+ const sbId = JSON.parse(createJson).sandboxID;+ check("CLI create", sbId.startsWith("sb-"), sbId);++ const sb = await Sandbox.connect(sbId, { apiKey: API_KEY, apiUrl: API_URL });+ check("SDK connect", sb.sandboxId === sbId);++ // ── Exec via SDK (15 ops) ──────────────────────────────────────+ h("Exec — SDK (15 operations)");++ let r = await sb.exec.run("echo hello");+ check("exec echo", r.stdout.trim() === "hello", r.stdout.trim());++ r = await sb.exec.run("python3 -c 'print(2+2)'");+ check("exec python", r.stdout.trim() === "4", r.stdout.trim());++ r = await sb.exec.run("node -e 'console.log(3*3)'");+ check("exec node", r.stdout.trim() === "9", r.stdout.trim());++ r = await sb.exec.run("whoami");+ check("exec whoami", r.stdout.trim() === "sandbox", r.stdout.trim());++ r = await sb.exec.run("bash -c 'exit 42'");+ check("non-zero exit", r.exitCode === 42, `exit=${r.exitCode}`);++ r = await sb.exec.run("python3 -c 'print(\"x\"*50000)'");+ check("large stdout", r.stdout.length >= 50000, `len=${r.stdout.length}`);++ r = await sb.exec.run("echo $MY_VAR", { env: { MY_VAR: "ts-env" } });+ check("env vars", r.stdout.trim() === "ts-env", r.stdout.trim());++ r = await sb.exec.run("pwd", { cwd: "/tmp" });+ check("cwd", r.stdout.trim() === "/tmp", r.stdout.trim());++ r = await sb.exec.run("sleep 30", { timeout: 2 });+ check("exec timeout", r.exitCode !== 0, `exit=${r.exitCode}`);++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get");+ check("network HTTPS", r.stdout.trim() === "200", r.stdout.trim());++ for (let i = 0; i < 5; i++) {+ r = await sb.exec.run(`echo rapid-${i}`);+ check(`rapid exec ${i}`, r.stdout.trim() === `rapid-${i}`, r.stdout.trim());+ }++ // ── Exec via CLI (5 ops) ───────────────────────────────────────+ h("Exec — CLI (5 operations)");++ let out = cli("exec", sbId, "--wait", "--", "echo", "cli-hello");+ check("CLI exec echo", out === "cli-hello", out);++ out = cli("exec", sbId, "--wait", "--", "python3", "-c", "print('cli-py')");+ check("CLI exec python", out === "cli-py", out);++ out = cli("exec", sbId, "--wait", "--", "git", "--version");+ check("CLI exec git", out.includes("git version"), out);++ out = cli("exec", sbId, "--wait", "--", "uname", "-s");+ check("CLI exec uname", out === "Linux", out);++ out = cli("exec", sbId, "--wait", "--", "free", "-m");+ check("CLI exec free", out.includes("Mem:"), out.substring(0, 40));++ // ── Files via SDK (10 ops) ─────────────────────────────────────+ h("Files — SDK (10 operations)");++ for (let i = 0; i < 5; i++) {+ await sb.files.write(`/workspace/ts-file-${i}.txt`, `ts-content-${i}`);+ }+ check("write 5 files", true);++ let allMatch = true;+ for (let i = 0; i < 5; i++) {+ const c = await sb.files.read(`/workspace/ts-file-${i}.txt`);+ if (c !== `ts-content-${i}`) allMatch = false;+ }+ check("read 5 files", allMatch);++ const binData = crypto.randomBytes(100 * 1024);+ const binHash = crypto.createHash("sha256").update(binData).digest("hex");+ await sb.files.write("/workspace/ts-binary.bin", binData);+ r = await sb.exec.run("sha256sum /workspace/ts-binary.bin | cut -d' ' -f1");+ check("100KB binary hash", r.stdout.trim() === binHash, r.stdout.trim().substring(0, 16));++ const entries = await sb.files.list("/workspace");+ check("list dir", entries.length > 5, `entries=${entries.length}`);++ await sb.files.makeDir("/workspace/ts-nested/deep");+ r = await sb.exec.run("test -d /workspace/ts-nested/deep && echo yes || echo no");+ check("mkdir", r.stdout.trim() === "yes", r.stdout.trim());++ await sb.files.write("/workspace/ts-del.txt", "bye");+ await sb.files.remove("/workspace/ts-del.txt");+ const gone = await sb.files.exists("/workspace/ts-del.txt");+ check("remove file", !gone);++ const dlUrl = await sb.downloadUrl("/workspace/ts-file-0.txt");+ check("download URL", dlUrl.includes("signature"));++ const ulUrl = await sb.uploadUrl("/workspace/ts-upload.txt");+ check("upload URL", ulUrl.includes("signature"));++ // ── Scale (5 ops) ──────────────────────────────────────────────+ h("Scale (5 operations)");++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'");+ check("baseline memory", parseInt(r.stdout.trim()) > 800, `${r.stdout.trim()}MB`);++ for (const mem of [2048, 4096, 2048]) {+ r = await sb.exec.run(`curl -s -X POST http://169.254.169.254/v1/scale -d '{"memoryMB":${mem}}'`);+ await sleep(500);+ }+ check("3 scale operations", true);++ r = await sb.exec.run("free -m | awk '/Mem:/{print $2}'");+ check("memory after scale", parseInt(r.stdout.trim()) > 1800, `${r.stdout.trim()}MB`);++ r = await sb.exec.run("curl -s -X POST http://169.254.169.254/v1/scale -d '{\"memoryMB\":1024}'");+ check("scale back to 1GB", true);++ // ── Preview URLs (4 ops) ───────────────────────────────────────+ h("Preview URLs (4 operations)");++ await sb.exec.run("bash -c 'setsid python3 -m http.server 3000 --directory /workspace </dev/null >/dev/null 2>&1 &'");+ await sleep(1000);++ const preview = await sb.createPreviewURL({ port: 3000 });+ check("create preview", !!preview.hostname, preview.hostname);++ const previews = await sb.listPreviewURLs();+ check("list previews", previews.length >= 1, `count=${previews.length}`);++ await sb.deletePreviewURL(3000);+ check("delete preview", true);++ await sb.exec.run("pkill -9 -f 'http.server 3000' 2>/dev/null; true");+ check("cleanup server", true);++ // ── Checkpoint + Fork via SDK (10 ops) ─────────────────────────+ h("Checkpoint + Fork — SDK (10 operations)");++ await sb.exec.run("bash -c 'echo ts-checkpoint > /workspace/ts-cp.txt && sync && sync'");+ await sleep(1000);++ const cp = await sb.createCheckpoint(`ts-cp-${Date.now()}`);+ check("create checkpoint", !!cp.id, cp.id.substring(0, 12));++ const cps = await sb.listCheckpoints();+ check("list checkpoints", cps.length >= 1, `count=${cps.length}`);++ await sleep(5000);+ const fork = await Sandbox.createFromCheckpoint(cp.id, { apiKey: API_KEY, apiUrl: API_URL, timeout: 120 });+ check("fork", fork.sandboxId.startsWith("sb-"), fork.sandboxId);++ await sleep(5000);+ r = await fork.exec.run("cat /workspace/ts-cp.txt");+ check("fork data", r.stdout.trim() === "ts-checkpoint", r.stdout.trim());++ await fork.exec.run("echo fork-only > /workspace/fork-only.txt");+ r = await sb.exec.run("cat /workspace/fork-only.txt 2>/dev/null || echo not-found");+ check("fork isolated", r.stdout.trim() === "not-found");++ await fork.kill();+ check("kill fork", true);++ // Restore+ await sb.exec.run("echo post-cp > /workspace/ts-cp.txt");+ await sb.restoreCheckpoint(cp.id);+ await sleep(15000);+ r = await sb.exec.run("cat /workspace/ts-cp.txt");+ check("restore reverted", r.stdout.trim() === "ts-checkpoint", r.stdout.trim());++ await sb.deleteCheckpoint(cp.id);+ check("delete checkpoint", true);++ // ── Hibernate + Wake via SDK (6 ops) ───────────────────────────+ h("Hibernate + Wake — SDK (6 operations)");++ await sb.exec.run("echo pre-hib > /workspace/hib.txt");+ await sb.hibernate();+ check("hibernate", true);++ await sb.wake({ timeout: 3600 });+ check("wake", true);++ r = await sb.exec.run("cat /workspace/hib.txt");+ check("data survived", r.stdout.trim() === "pre-hib", r.stdout.trim());++ r = await sb.exec.run("echo post-wake");+ check("exec after wake", r.stdout.trim() === "post-wake");++ r = await sb.exec.run("curl -s -o /dev/null -w '%{http_code}' https://httpbin.org/get");+ check("network after wake", r.stdout.trim() === "200", r.stdout.trim());++ r = await sb.exec.run("python3 -c 'print(1+1)'");+ check("python after wake", r.stdout.trim() === "2");++ // ── CLI: hibernate + wake (3 ops) ──────────────────────────────+ h("Hibernate + Wake — CLI (3 operations)");++ cli("sandbox", "hibernate", sbId);+ check("CLI hibernate", true);++ cli("sandbox", "wake", sbId);+ check("CLI wake", true);++ out = cli("exec", sbId, "--wait", "--", "echo", "cli-post-wake");+ check("CLI exec after wake", out === "cli-post-wake", out);++ // ── Timeout via SDK (2 ops) ────────────────────────────────────+ h("Timeout (2 operations)");++ await sb.setTimeout(600);+ check("set timeout 600s", true);++ await sb.setTimeout(0);+ check("set timeout 0 (unlimited)", true);++ // ── Final checks (3 ops) ───────────────────────────────────────+ h("Final Checks (3 operations)");++ r = await sb.exec.run("echo final-ts-health");+ check("final exec", r.stdout.trim() === "final-ts-health");++ const running = await sb.isRunning();+ check("sandbox running", running);++ await sb.kill();+ check("kill sandbox", true);++ const elapsed = ((Date.now() - t0) / 1000).toFixed(0);+ const total = PASS + FAIL;+ console.log(`\n\x1b[1m${PASS} passed, ${FAIL} failed (${total} total, ${elapsed}s)\x1b[0m`);+ process.exit(FAIL > 0 ? 1 : 0);+}++main().catch(e => { console.error(e); process.exit(1); });