An open-source, faster Devin alternative
TypeScript
add python suite, remove s3 autosave
Brian Reardon321e5feaa183
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 8fc7482b..e61ef3f2 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -149,12 +149,44 @@ func main() {defer store.Close()log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")- // Startup reconciliation: mark stale "running" sessions from a previous crash- hibernated, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)+ // Kill orphaned Firecracker processes + TAP devices from previous run+ fcMgr.CleanupOrphanedProcesses()++ // Local NVMe recovery: scan for sandbox data left from a previous run+ recoveries := fcMgr.RecoverLocalSandboxes()+ if len(recoveries) > 0 {+ snapshotCount, workspaceCount := 0, 0+ for _, r := range recoveries {+ session, err := store.GetSandboxSession(ctx, r.SandboxID)+ if err != nil {+ log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)+ continue+ }+ if r.HasSnapshot {+ // Full snapshot on NVMe — create checkpoint record so doWake finds local files+ _, _ = store.CreateCheckpoint(ctx, r.SandboxID, session.OrgID,+ "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)+ snapshotCount+++ } else {+ // Workspace only — create local sentinel checkpoint for cold boot+ _, _ = store.CreateCheckpoint(ctx, r.SandboxID, session.OrgID,+ "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)+ workspaceCount+++ }+ }+ if snapshotCount+workspaceCount > 0 {+ log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)+ }+ }++ // Mark any remaining stale "running" sessions (no local data) as stopped+ _, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)if err != nil {log.Printf("opensandbox-worker: warning: session reconciliation failed: %v", err)- } else if hibernated+stopped > 0 {- log.Printf("opensandbox-worker: reconciled stale sessions: %d hibernated, %d stopped", hibernated, stopped)+ } else if stopped > 0 {+ log.Printf("opensandbox-worker: reconciled %d unrecoverable sessions as stopped", stopped)}}}@@ -277,12 +309,9 @@ func main() {}}- // Start periodic workspace autosave for crash recovery- var autosaver *worker.WorkspaceAutosaver- if checkpointStore != nil && store != nil {- autosaver = worker.NewWorkspaceAutosaver(mgr, fcMgr, checkpointStore, store, cfg.WorkerID, cfg.Region, 5*time.Minute)- autosaver.Start()- }+ // Start periodic SyncFS to keep workspace.ext4 crash-consistent on NVMe+ autosaver := worker.NewWorkspaceAutosaver(mgr, fcMgr, 5*time.Minute)+ autosaver.Start()quit := make(chan os.Signal, 1)signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)@@ -297,9 +326,7 @@ func main() {}// Stop autosaver before hibernating- if autosaver != nil {- autosaver.Stop()- }+ autosaver.Stop()// 2. Hibernate all running sandboxes for seamless resumeif checkpointStore != nil {diff --git a/internal/agent/exec.go b/internal/agent/exec.goindex 597f91d6..fb6bf836 100644--- a/internal/agent/exec.go+++ b/internal/agent/exec.go@@ -4,13 +4,29 @@ import ("bytes""context""fmt"+ "os""os/exec"+ "strings""syscall""time"pb "github.com/opensandbox/opensandbox/proto/agent")+// baseEnv returns the current OS environment with HOME replaced to /workspace+// so tools (npm, pip, git, etc.) use the NVMe-backed workspace for caches.+func baseEnv() []string {+ var env []string+ for _, e := range os.Environ() {+ if strings.HasPrefix(e, "HOME=") {+ continue+ }+ env = append(env, e)+ }+ env = append(env, "HOME=/workspace")+ return env+}+// Exec runs a command synchronously and returns stdout/stderr/exit code.func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponse, error) {timeout := time.Duration(req.TimeoutSeconds) * time.Second@@ -30,9 +46,8 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponscmd.Dir = "/workspace"}- // Set environment variables — always set HOME=/workspace so tools- // (npm, pip, etc.) use the NVMe-backed workspace for caches.- cmd.Env = append(cmd.Environ(), "HOME=/workspace")+ // Set environment variables with HOME=/workspace+ cmd.Env = baseEnv()if len(req.Envs) > 0 {cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)}@@ -86,7 +101,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrecmd.Dir = "/workspace"}- cmd.Env = append(cmd.Environ(), "HOME=/workspace")+ cmd.Env = baseEnv()if len(req.Envs) > 0 {cmd.Env = append(cmd.Env, mapToEnv(req.Envs)...)}diff --git a/internal/agent/pty.go b/internal/agent/pty.goindex fdddfd90..b8cafa47 100644--- a/internal/agent/pty.go+++ b/internal/agent/pty.go@@ -50,8 +50,7 @@ func (s *Server) PTYCreate(ctx context.Context, req *pb.PTYCreateRequest) (*pb.Pcmd := exec.CommandContext(sessCtx, shell)cmd.Dir = "/workspace"- cmd.Env = append(os.Environ(),- "HOME=/workspace",+ cmd.Env = append(baseEnv(),"TERM=xterm-256color",fmt.Sprintf("COLUMNS=%d", req.Cols),fmt.Sprintf("LINES=%d", req.Rows),diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex f56668a7..98bdb17b 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -5,11 +5,13 @@ package firecrackerimport ("context"+ "encoding/json""fmt""log""os""os/exec""path/filepath"+ "strings""sync""time"@@ -49,6 +51,17 @@ type VMInstance struct {bootArgs string // kernel boot args}+// SandboxMeta is persisted to sandbox-meta.json in each sandbox directory.+// It records VM config so that on hard kill recovery, a sandbox can be+// cold-booted from template + existing workspace without needing DB access.+type SandboxMeta struct {+ SandboxID string `json:"sandboxId"`+ Template string `json:"template"`+ CpuCount int `json:"cpuCount"`+ MemoryMB int `json:"memoryMB"`+ GuestPort int `json:"guestPort"`+}+// Config holds configuration for the Firecracker Manager.type Config struct {DataDir string // base data directory (e.g., /data)@@ -348,6 +361,18 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.Sm.vms[id] = vmm.mu.Unlock()+ // Write sandbox-meta.json for local NVMe recovery after hard kill+ sbMeta := SandboxMeta{+ SandboxID: id,+ Template: template,+ CpuCount: cpus,+ MemoryMB: memMB,+ GuestPort: guestPort,+ }+ if metaJSON, err := json.Marshal(sbMeta); err == nil {+ _ = os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644)+ }+log.Printf("firecracker: created VM %s (template=%s, cpu=%d, mem=%dMB, port=%d→%d, tap=%s, mac=%s)",id, template, cpus, memMB, hostPort, guestPort, netCfg.TAPName, guestMAC)@@ -824,3 +849,111 @@ func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {}return vm.agent.SyncFS(ctx)}++// CleanupOrphanedProcesses kills any Firecracker processes and TAP devices+// left over from a previous worker run. Must be called before RecoverLocalSandboxes+// so TAP devices are free for re-allocation.+func (m *Manager) CleanupOrphanedProcesses() {+ // Kill all firecracker processes not tracked by this manager+ out, err := exec.Command("pgrep", "-f", "firecracker").Output()+ if err == nil && len(out) > 0 {+ count := 0+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {+ if line == "" {+ continue+ }+ _ = exec.Command("kill", "-9", line).Run()+ count+++ }+ if count > 0 {+ log.Printf("firecracker: killed %d orphaned firecracker process(es)", count)+ }+ }++ // Clean up orphaned TAP devices (fc-tap0, fc-tap1, ...)+ out, err = exec.Command("ip", "-o", "link", "show").Output()+ if err == nil {+ for _, line := range strings.Split(string(out), "\n") {+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ // format: "3: fc-tap0: <flags> ..."+ tapName := strings.TrimSuffix(fields[1], ":")+ if strings.HasPrefix(tapName, "fc-") {+ _ = exec.Command("ip", "link", "del", tapName).Run()+ log.Printf("firecracker: cleaned up orphaned TAP %s", tapName)+ }+ }+ }+}++// LocalRecovery describes a sandbox found on disk that can be recovered.+type LocalRecovery struct {+ SandboxID string+ HasSnapshot bool // true = full snapshot (mem+vmstate), false = workspace only+ Meta SandboxMeta // from sandbox-meta.json or snapshot-meta.json+}++// RecoverLocalSandboxes scans the sandboxes directory for sandbox data left+// on NVMe from a previous run. Returns recoverable sandboxes.+func (m *Manager) RecoverLocalSandboxes() []LocalRecovery {+ sandboxesDir := filepath.Join(m.cfg.DataDir, "sandboxes")+ entries, err := os.ReadDir(sandboxesDir)+ if err != nil {+ log.Printf("firecracker: no sandboxes dir to scan: %v", err)+ return nil+ }++ var recoveries []LocalRecovery+ for _, entry := range entries {+ if !entry.IsDir() || !strings.HasPrefix(entry.Name(), "sb-") {+ continue+ }+ sandboxID := entry.Name()+ sandboxDir := filepath.Join(sandboxesDir, sandboxID)++ // Check for full snapshot (graceful shutdown completed)+ snapshotMetaPath := filepath.Join(sandboxDir, "snapshot", "snapshot-meta.json")+ if fileExists(filepath.Join(sandboxDir, "snapshot", "mem")) &&+ fileExists(filepath.Join(sandboxDir, "snapshot", "vmstate")) &&+ fileExists(snapshotMetaPath) {+ var snapMeta SnapshotMeta+ if data, err := os.ReadFile(snapshotMetaPath); err == nil {+ if json.Unmarshal(data, &snapMeta) == nil {+ recoveries = append(recoveries, LocalRecovery{+ SandboxID: sandboxID,+ HasSnapshot: true,+ Meta: SandboxMeta{+ SandboxID: sandboxID,+ Template: snapMeta.Template,+ CpuCount: snapMeta.CpuCount,+ MemoryMB: snapMeta.MemoryMB,+ GuestPort: snapMeta.GuestPort,+ },+ })+ continue+ }+ }+ }++ // Check for workspace-only (hard kill, no snapshot)+ if fileExists(filepath.Join(sandboxDir, "workspace.ext4")) {+ sbMetaPath := filepath.Join(sandboxDir, "sandbox-meta.json")+ var meta SandboxMeta+ if data, err := os.ReadFile(sbMetaPath); err == nil {+ if json.Unmarshal(data, &meta) == nil {+ recoveries = append(recoveries, LocalRecovery{+ SandboxID: sandboxID,+ HasSnapshot: false,+ Meta: meta,+ })+ continue+ }+ }+ // No readable meta — skip (can't determine template)+ log.Printf("firecracker: skipping %s: workspace exists but no sandbox-meta.json", sandboxID)+ }+ }+ return recoveries+}diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.goindex 0c6e6e9a..c13ce4a5 100644--- a/internal/firecracker/snapshot.go+++ b/internal/firecracker/snapshot.go@@ -222,7 +222,17 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cvmstateExists := fileExists(vmstateFile)log.Printf("firecracker: wake %s: checking local files: mem=%s (exists=%v) vmstate=%s (exists=%v)",sandboxID, memFile, memExists, vmstateFile, vmstateExists)++ // Local workspace-only recovery: no snapshot files, just workspace.ext4 on NVMe.+ // This happens after a hard kill where the worker didn't get to hibernate.+ isLocalWorkspace := strings.HasPrefix(checkpointKey, "local://")+if !memExists || !vmstateExists {+ if isLocalWorkspace {+ // No snapshot to download — cold boot from local workspace.ext4.+ log.Printf("firecracker: wake %s: local workspace recovery (no snapshot)", sandboxID)+ return m.coldBootLocal(ctx, sandboxID, timeout)+ }log.Printf("firecracker: wake %s: local snapshot missing, downloading from S3 (key=%s)", sandboxID, checkpointKey)if err := os.MkdirAll(sandboxDir, 0755); err != nil {return nil, fmt.Errorf("mkdir sandbox dir: %w", err)@@ -481,6 +491,193 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn vmToSandbox(vm), nil}+// coldBootLocal boots a fresh VM using an existing workspace.ext4 on NVMe.+// Used for hard kill recovery — processes are lost but /workspace files are preserved.+func (m *Manager) coldBootLocal(ctx context.Context, sandboxID string, timeout int) (*types.Sandbox, error) {+ sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)+ workspacePath := filepath.Join(sandboxDir, "workspace.ext4")+ rootfsPath := filepath.Join(sandboxDir, "rootfs.ext4")++ if !fileExists(workspacePath) {+ return nil, fmt.Errorf("workspace not found at %s", workspacePath)+ }++ // Read sandbox-meta.json for template + config+ sbMetaPath := filepath.Join(sandboxDir, "sandbox-meta.json")+ metaJSON, err := os.ReadFile(sbMetaPath)+ if err != nil {+ return nil, fmt.Errorf("read sandbox-meta.json: %w", err)+ }+ var meta SandboxMeta+ if err := json.Unmarshal(metaJSON, &meta); err != nil {+ return nil, fmt.Errorf("parse sandbox-meta.json: %w", err)+ }++ // Recreate rootfs from template if missing+ if !fileExists(rootfsPath) {+ baseImage, err := ResolveBaseImage(m.cfg.ImagesDir, meta.Template)+ if err != nil {+ return nil, fmt.Errorf("resolve base image: %w", err)+ }+ if err := PrepareRootfs(baseImage, rootfsPath); err != nil {+ return nil, fmt.Errorf("prepare rootfs: %w", err)+ }+ log.Printf("firecracker: cold-boot-local %s: rootfs recreated from template %q", sandboxID, meta.Template)+ }++ // Allocate fresh network+ netCfg, err := m.subnets.Allocate()+ if err != nil {+ return nil, fmt.Errorf("allocate subnet: %w", err)+ }+ if err := CreateTAP(netCfg); err != nil {+ m.subnets.Release(netCfg.TAPName)+ return nil, fmt.Errorf("create TAP: %w", err)+ }++ hostPort, err := FindFreePort()+ if err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return nil, fmt.Errorf("find free port: %w", err)+ }+ guestPort := meta.GuestPort+ if guestPort == 0 {+ guestPort = 80+ }+ netCfg.HostPort = hostPort+ netCfg.GuestPort = guestPort++ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return nil, fmt.Errorf("add DNAT: %w", err)+ }++ cpus := meta.CpuCount+ if cpus <= 0 {+ cpus = m.cfg.DefaultCPUs+ }+ memMB := meta.MemoryMB+ if memMB <= 0 {+ memMB = m.cfg.DefaultMemoryMB+ }++ vsockPath := filepath.Join(sandboxDir, "vsock.sock")+ guestCID := m.allocateCID()+ guestMAC := generateMAC(sandboxID)+ bootArgs := fmt.Sprintf(+ "keep_bootcon console=ttyS0 reboot=k panic=1 pci=off "++ "ip=%s::%s:%s::eth0:off "++ "init=/sbin/init "++ "osb.gateway=%s",+ netCfg.GuestIP, netCfg.HostIP, netCfg.Mask, netCfg.HostIP,+ )++ apiSockPath := filepath.Join(sandboxDir, "firecracker.sock")+ os.Remove(apiSockPath)+ os.Remove(vsockPath)++ logPath := filepath.Join(sandboxDir, "firecracker.log")+ logFile, err := os.Create(logPath)+ if err != nil {+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("create log file: %w", err)+ }++ cmd := exec.Command(m.cfg.FirecrackerBin, "--api-sock", apiSockPath)+ cmd.Stdout = logFile+ cmd.Stderr = logFile+ if err := cmd.Start(); err != nil {+ logFile.Close()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("start firecracker: %w", err)+ }+ logFile.Close()++ fcClient := NewFirecrackerClient(apiSockPath)+ if err := fcClient.WaitForSocket(5 * time.Second); err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("wait for API socket: %w", err)+ }++ // Configure and start VM+ if err := fcClient.PutMachineConfig(cpus, memMB); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put machine config: %w", err)+ }+ if err := fcClient.PutBootSource(m.cfg.KernelPath, bootArgs); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put boot source: %w", err)+ }+ if err := fcClient.PutDrive("rootfs", rootfsPath, true, false); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put rootfs drive: %w", err)+ }+ if err := fcClient.PutDrive("workspace", workspacePath, false, false); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put workspace drive: %w", err)+ }+ if err := fcClient.PutNetworkInterface("eth0", guestMAC, netCfg.TAPName); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put network interface: %w", err)+ }+ if err := fcClient.PutVsock(guestCID, vsockPath); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("put vsock: %w", err)+ }+ if err := fcClient.StartInstance(); err != nil {+ cmd.Process.Kill(); cmd.Wait(); m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("start instance: %w", err)+ }++ now := time.Now()+ ttl := time.Duration(timeout) * time.Second+ if ttl <= 0 {+ ttl = 300 * time.Second+ }++ vm := &VMInstance{+ ID: sandboxID,+ Template: meta.Template,+ Status: types.SandboxStatusRunning,+ StartedAt: now,+ EndAt: now.Add(ttl),+ CpuCount: cpus,+ MemoryMB: memMB,+ HostPort: hostPort,+ GuestPort: guestPort,+ pid: cmd.Process.Pid,+ cmd: cmd,+ network: netCfg,+ vsockPath: vsockPath,+ sandboxDir: sandboxDir,+ apiSockPath: apiSockPath,+ fcClient: fcClient,+ guestMAC: guestMAC,+ guestCID: guestCID,+ bootArgs: bootArgs,+ }++ agentClient, err := m.waitForAgent(context.Background(), vsockPath, 30*time.Second)+ if err != nil {+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, "")+ return nil, fmt.Errorf("agent not ready after cold boot: %w", err)+ }+ vm.agent = agentClient++ m.mu.Lock()+ m.vms[sandboxID] = vm+ m.mu.Unlock()++ log.Printf("firecracker: cold-boot-local %s (template=%s, port=%d, tap=%s)", sandboxID, meta.Template, hostPort, netCfg.TAPName)+ return vmToSandbox(vm), nil+}+// createArchive creates a tar.zst archive of specific files from a directory.func createArchive(archivePath, baseDir string, files []string) error {args := []string{diff --git a/internal/worker/autosave.go b/internal/worker/autosave.goindex 3ed53bb7..9a868a0f 100644--- a/internal/worker/autosave.go+++ b/internal/worker/autosave.go@@ -2,59 +2,44 @@ package workerimport ("context"- "fmt""log"- "os""sync""time"fc "github.com/opensandbox/opensandbox/internal/firecracker"- "github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox"- "github.com/opensandbox/opensandbox/internal/storage")-// WorkspaceAutosaver periodically backs up workspace drives to S3.-// On hard kill recovery, a sandbox can cold-boot from template + latest-// workspace backup (processes lost, but user files in /workspace are safe).+// WorkspaceAutosaver periodically flushes filesystem buffers inside each+// running VM. This ensures workspace.ext4 on the host NVMe is crash-consistent.+// On hard kill recovery, the worker cold-boots from template + existing+// workspace.ext4 on disk (processes lost, but user files in /workspace are safe).type WorkspaceAutosaver struct {- manager sandbox.Manager- fcMgr *fc.Manager- checkpointStore *storage.CheckpointStore- store *db.Store- workerID string- region string- interval time.Duration- concurrency int- stop chan struct{}- done chan struct{}+ manager sandbox.Manager+ fcMgr *fc.Manager+ interval time.Duration+ concurrency int+ stop chan struct{}+ done chan struct{}}// NewWorkspaceAutosaver creates a new autosaver.func NewWorkspaceAutosaver(mgr sandbox.Manager,fcMgr *fc.Manager,- checkpointStore *storage.CheckpointStore,- store *db.Store,- workerID string,- region string,interval time.Duration,) *WorkspaceAutosaver {return &WorkspaceAutosaver{- manager: mgr,- fcMgr: fcMgr,- checkpointStore: checkpointStore,- store: store,- workerID: workerID,- region: region,- interval: interval,- concurrency: 10,- stop: make(chan struct{}),- done: make(chan struct{}),+ manager: mgr,+ fcMgr: fcMgr,+ interval: interval,+ concurrency: 10,+ stop: make(chan struct{}),+ done: make(chan struct{}),}}-// Start begins the periodic backup loop.+// Start begins the periodic SyncFS loop.func (a *WorkspaceAutosaver) Start() {go a.loop()log.Printf("autosave: started (interval=%s, concurrency=%d)", a.interval, a.concurrency)@@ -74,14 +59,14 @@ func (a *WorkspaceAutosaver) loop() {for {select {case <-ticker.C:- a.backupAll()+ a.syncAll()case <-a.stop:return}}}-func (a *WorkspaceAutosaver) backupAll() {+func (a *WorkspaceAutosaver) syncAll() {sandboxes, err := a.manager.List(context.Background())if err != nil {log.Printf("autosave: failed to list sandboxes: %v", err)@@ -91,9 +76,6 @@ func (a *WorkspaceAutosaver) backupAll() {return}- log.Printf("autosave: backing up %d sandboxes", len(sandboxes))- t0 := time.Now()-sem := make(chan struct{}, a.concurrency)var wg sync.WaitGroupvar successCount, failCount int32@@ -102,7 +84,6 @@ func (a *WorkspaceAutosaver) backupAll() {for _, sb := range sandboxes {select {case <-a.stop:- log.Printf("autosave: interrupted, skipping remaining backups")breakdefault:}@@ -113,8 +94,10 @@ func (a *WorkspaceAutosaver) backupAll() {defer wg.Done()defer func() { <-sem }()- if err := a.backupOne(sandboxID); err != nil {- log.Printf("autosave: backup failed for %s: %v", sandboxID, err)+ syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := a.fcMgr.SyncFS(syncCtx, sandboxID); err != nil {+ log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)mu.Lock()failCount++mu.Unlock()@@ -127,59 +110,7 @@ func (a *WorkspaceAutosaver) backupAll() {}wg.Wait()- log.Printf("autosave: completed in %dms (%d ok, %d failed)",- time.Since(t0).Milliseconds(), successCount, failCount)-}--func (a *WorkspaceAutosaver) backupOne(sandboxID string) error {- // 1. SyncFS — flush disk buffers (VM keeps running)- syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)- defer cancel()- if err := a.fcMgr.SyncFS(syncCtx, sandboxID); err != nil {- return fmt.Errorf("syncfs: %w", err)- }-- // 2. Get workspace path- wsPath, err := a.fcMgr.GetWorkspacePath(sandboxID)- if err != nil {- return fmt.Errorf("workspace path: %w", err)- }-- // Check file exists and get size- info, err := os.Stat(wsPath)- if err != nil {- return fmt.Errorf("stat workspace: %w", err)+ if failCount > 0 {+ log.Printf("autosave: syncfs complete (%d ok, %d failed)", successCount, failCount)}-- // 3. Upload workspace.ext4 directly to S3 (no archiving needed for workspace-only backup)- backupKey := fmt.Sprintf("workspace-backups/%s/%d.ext4", sandboxID, time.Now().Unix())- uploadCtx, uploadCancel := context.WithTimeout(context.Background(), 5*time.Minute)- defer uploadCancel()-- if _, err := a.checkpointStore.Upload(uploadCtx, backupKey, wsPath); err != nil {- return fmt.Errorf("s3 upload: %w", err)- }-- // 4. Update DB with backup record- if a.store != nil {- session, err := a.store.GetSandboxSession(context.Background(), sandboxID)- if err != nil {- log.Printf("autosave: warning: no session for %s, skipping DB record: %v", sandboxID, err)- return nil- }- if err := a.store.UpsertWorkspaceBackup(- context.Background(),- sandboxID,- session.OrgID,- backupKey,- info.Size(),- a.region,- session.Template,- session.Config,- ); err != nil {- log.Printf("autosave: warning: failed to record backup for %s: %v", sandboxID, err)- }- }-- return nil}diff --git a/sdks/python/examples/run_all_tests.py b/sdks/python/examples/run_all_tests.pynew file mode 100644index 00000000..716c4d48--- /dev/null+++ b/sdks/python/examples/run_all_tests.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""+OpenSandbox Production Test Suite Runner (Python)++Runs all production tests in sequence, with a summary at the end.+Tests are ordered from fast/simple to slow/complex.++Usage:+ python examples/run_all_tests.py # Run all tests+ python examples/run_all_tests.py --skip-slow # Skip timeout test (waits ~2min)++Individual tests:+ python examples/test_environment.py+ python examples/test_commands.py+ python examples/test_file_ops.py+ python examples/test_python_sdk.py+ python examples/test_multi_template.py+ python examples/test_reconnect.py+ python examples/test_domain_tls.py+ python examples/test_concurrent.py+ python examples/test_timeout.py+"""++import os+import subprocess+import sys+import time++BOLD = "\033[1m"+GREEN = "\033[32m"+RED = "\033[31m"+DIM = "\033[2m"+CYAN = "\033[36m"+RESET = "\033[0m"++SUITES = [+ {+ "name": "Environment",+ "file": "test_environment.py",+ "description": "HOME=/workspace, npm/pip cache dirs, dotfiles",+ },+ {+ "name": "Commands",+ "file": "test_commands.py",+ "description": "Shell commands, stderr, exit codes, pipes, concurrency",+ },+ {+ "name": "File Ops",+ "file": "test_file_ops.py",+ "description": "Large files, special chars, nested dirs, deletion",+ },+ {+ "name": "Python SDK",+ "file": "test_python_sdk.py",+ "description": "Python template, stdlib, file ops from Python",+ },+ {+ "name": "Multi-Template",+ "file": "test_multi_template.py",+ "description": "base, python, node templates",+ },+ {+ "name": "Reconnect",+ "file": "test_reconnect.py",+ "description": "Sandbox.connect(), state persistence, multi-conn",+ },+ {+ "name": "Domain/TLS",+ "file": "test_domain_tls.py",+ "description": "Subdomains, HTTPS requests, routing isolation",+ },+ {+ "name": "Concurrent",+ "file": "test_concurrent.py",+ "description": "5 sandboxes in parallel, isolation, parallel ops",+ },+ {+ "name": "Timeout",+ "file": "test_timeout.py",+ "slow": True,+ "description": "30s timeout, rolling timeout (takes ~2min)",+ },+]+++def main() -> None:+ print(f"{BOLD}")+ print("╔════════════════════════════════════════════════════════╗")+ print("║ OpenSandbox Production Test Suite (Python) ║")+ print(f"╚════════════════════════════════════════════════════════╝{RESET}\n")++ skip_slow = "--skip-slow" in sys.argv+ filtered = [s for s in SUITES if not (skip_slow and s.get("slow"))]++ print(f'{DIM}Running {len(filtered)} test suites{"(slow tests skipped)" if skip_slow else ""}{RESET}')+ print(f"{DIM}{'─' * 60}{RESET}\n")++ results: list[dict] = []+ total_start = time.time()+ script_dir = os.path.dirname(os.path.abspath(__file__))++ for i, suite in enumerate(filtered):+ file_path = os.path.join(script_dir, suite["file"])++ print(f"{BOLD}[{i + 1}/{len(filtered)}] {suite['name']}{RESET}")+ print(f"{DIM} {suite['description']}{RESET}")+ print(f"{DIM} Running: python {suite['file']}{RESET}\n")++ start = time.time()+ try:+ subprocess.run(+ [sys.executable, file_path],+ check=True,+ env={**os.environ},+ timeout=300, # 5 min max per suite+ )+ duration_ms = (time.time() - start) * 1000+ results.append({"name": suite["name"], "passed": True, "duration_ms": duration_ms})+ print(f"{GREEN}── {suite['name']}: PASSED ({duration_ms / 1000:.1f}s) ──{RESET}\n")+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:+ duration_ms = (time.time() - start) * 1000+ results.append({"name": suite["name"], "passed": False, "duration_ms": duration_ms, "error": str(e)})+ print(f"{RED}── {suite['name']}: FAILED ({duration_ms / 1000:.1f}s) ──{RESET}\n")++ total_ms = (time.time() - total_start) * 1000++ # ── Summary ──+ print(f"\n{BOLD}╔════════════════════════════════════════════════════════╗")+ print("║ Test Results ║")+ print(f"╠════════════════════════════════════════════════════════╣{RESET}")++ max_name = max(len(r["name"]) for r in results) if results else 0+ for r in results:+ icon = f"{GREEN}✓{RESET}" if r["passed"] else f"{RED}✗{RESET}"+ name = r["name"].ljust(max_name)+ duration = f"{r['duration_ms'] / 1000:.1f}s".rjust(7)+ print(f" {icon} {name} {duration}")++ passed_count = sum(1 for r in results if r["passed"])+ failed_count = sum(1 for r in results if not r["passed"])++ print(f"\n{BOLD}╠════════════════════════════════════════════════════════╣")+ print(f"║ {passed_count} passed, {failed_count} failed | Total: {total_ms / 1000:.1f}s")+ print(f"╚════════════════════════════════════════════════════════╝{RESET}\n")++ if failed_count > 0:+ print(f"{RED}Failed suites:{RESET}")+ for r in results:+ if not r["passed"]:+ print(f" {RED}✗ {r['name']}{RESET}")+ print()+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/sdks/python/examples/test_commands.py b/sdks/python/examples/test_commands.pynew file mode 100644index 00000000..dc2a8d8e--- /dev/null+++ b/sdks/python/examples/test_commands.py@@ -0,0 +1,240 @@+#!/usr/bin/env python3+"""+Command Edge Cases Test++Tests:+ 1. Basic commands+ 2. stderr handling+ 3. Non-zero exit codes+ 4. Large stdout output+ 5. Environment variable passing+ 6. Working directory+ 7. Shell features (pipes, redirects, subshells)+ 8. Concurrent commands on same sandbox+ 9. Command timeout++Usage:+ python examples/test_commands.py+"""++import asyncio+import sys+import time++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Command Edge Cases Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandbox = None++ try:+ sandbox = await Sandbox.create(template="base", timeout=120)+ green(f"Created sandbox: {sandbox.sandbox_id}")+ print()++ # ── Test 1: Basic commands ──+ bold("━━━ Test 1: Basic commands ━━━\n")++ echo = await sandbox.commands.run("echo hello-world")+ check("Echo returns correct output", echo.stdout.strip() == "hello-world")+ check("Echo exit code is 0", echo.exit_code == 0)++ multi = await sandbox.commands.run("echo line1 && echo line2 && echo line3")+ lines = multi.stdout.strip().split("\n")+ check("Multi-command outputs 3 lines", len(lines) == 3)+ check("Multi-command content correct", lines[0] == "line1" and lines[2] == "line3")+ print()++ # ── Test 2: stderr handling ──+ bold("━━━ Test 2: stderr handling ━━━\n")++ stderr_cmd = await sandbox.commands.run("echo error-msg >&2")+ check("stderr captured", stderr_cmd.stderr.strip() == "error-msg")+ check("stdout empty when writing to stderr", stderr_cmd.stdout.strip() == "")+ check("Exit code 0 even with stderr", stderr_cmd.exit_code == 0)++ mixed = await sandbox.commands.run("echo stdout-data && echo stderr-data >&2")+ check("Mixed: stdout captured", "stdout-data" in mixed.stdout)+ check("Mixed: stderr captured", "stderr-data" in mixed.stderr)+ print()++ # ── Test 3: Non-zero exit codes ──+ bold("━━━ Test 3: Non-zero exit codes ━━━\n")++ exit1 = await sandbox.commands.run("exit 1")+ check("Exit code 1 captured", exit1.exit_code == 1, f"got {exit1.exit_code}")++ exit42 = await sandbox.commands.run("exit 42")+ check("Exit code 42 captured", exit42.exit_code == 42, f"got {exit42.exit_code}")++ false_cmd = await sandbox.commands.run("false")+ check("'false' returns exit code 1", false_cmd.exit_code == 1, f"got {false_cmd.exit_code}")++ not_found = await sandbox.commands.run("nonexistent-command-xyz 2>&1 || true")+ check("Non-existent command handled", not_found.exit_code == 0)+ print()++ # ── Test 4: Large stdout ──+ bold("━━━ Test 4: Large stdout output ━━━\n")++ large_out = await sandbox.commands.run("seq 1 10000")+ line_count = len(large_out.stdout.strip().split("\n"))+ check("10000 lines of output captured", line_count == 10000, f"got {line_count} lines")+ dim(f"Output size: {len(large_out.stdout)} chars")++ large_lines = large_out.stdout.strip().split("\n")+ check("First line is 1", large_lines[0] == "1")+ check("Last line is 10000", large_lines[-1] == "10000")+ print()++ # ── Test 5: Environment variables ──+ bold("━━━ Test 5: Environment variable passing ━━━\n")++ env_result = await sandbox.commands.run("echo $MY_VAR",+ env={"MY_VAR": "secret-value-123"})+ check("Env var passed correctly", env_result.stdout.strip() == "secret-value-123")++ multi_env = await sandbox.commands.run('echo "$A:$B:$C"',+ env={"A": "alpha", "B": "beta", "C": "gamma"})+ check("Multiple env vars", multi_env.stdout.strip() == "alpha:beta:gamma")++ special_env = await sandbox.commands.run("echo $SPECIAL",+ env={"SPECIAL": "hello world with spaces & stuff"})+ check("Env var with special chars",+ special_env.stdout.strip() == "hello world with spaces & stuff")+ print()++ # ── Test 6: Working directory ──+ bold("━━━ Test 6: Working directory ━━━\n")++ await sandbox.commands.run("mkdir -p /tmp/workdir/sub")+ await sandbox.files.write("/tmp/workdir/sub/data.txt", "found-it")++ cwd_result = await sandbox.commands.run("cat data.txt", cwd="/tmp/workdir/sub")+ check("Working directory respected", cwd_result.stdout.strip() == "found-it")++ pwd_result = await sandbox.commands.run("pwd", cwd="/tmp/workdir")+ check("pwd reflects cwd", pwd_result.stdout.strip() == "/tmp/workdir")+ print()++ # ── Test 7: Shell features ──+ bold("━━━ Test 7: Shell features (pipes, redirects, subshells) ━━━\n")++ pipe_result = await sandbox.commands.run("echo 'hello world' | tr ' ' '-'")+ check("Pipe works", pipe_result.stdout.strip() == "hello-world")++ subshell = await sandbox.commands.run("echo $(hostname)")+ check("Command substitution works", len(subshell.stdout.strip()) > 0, subshell.stdout.strip())++ await sandbox.commands.run("echo redirect-test > /tmp/redirect.txt")+ redirect_content = await sandbox.files.read("/tmp/redirect.txt")+ check("Redirect to file works", redirect_content.strip() == "redirect-test")++ await sandbox.commands.run("touch /tmp/wc-a.txt /tmp/wc-b.txt /tmp/wc-c.txt")+ wc_result = await sandbox.commands.run("ls /tmp/wc-*.txt | wc -l")+ check("Wildcard expansion works", wc_result.stdout.strip() == "3")++ arith = await sandbox.commands.run("echo $((42 * 7))")+ check("Arithmetic expansion works", arith.stdout.strip() == "294")++ here_str = await sandbox.commands.run("bash -c \"cat <<< 'here-string-data'\"")+ check("Here string works", here_str.stdout.strip() == "here-string-data")+ print()++ # ── Test 8: Concurrent commands ──+ bold("━━━ Test 8: Concurrent commands on same sandbox ━━━\n")++ concurrent_start = time.time()++ async def run_concurrent(i: int) -> dict:+ r = await sandbox.commands.run(f"echo concurrent-{i}")+ return {"index": i, "output": r.stdout.strip(), "exit_code": r.exit_code}++ tasks = [run_concurrent(i) for i in range(10)]+ concurrent_results = await asyncio.gather(*tasks)+ concurrent_ms = (time.time() - concurrent_start) * 1000++ all_correct = True+ for r in concurrent_results:+ if r["output"] != f"concurrent-{r['index']}" or r["exit_code"] != 0:+ all_correct = False+ dim(f"Command {r['index']}: expected \"concurrent-{r['index']}\", "+ f"got \"{r['output']}\" (exit {r['exit_code']})")++ check("10 concurrent commands all returned correctly", all_correct)+ dim(f"Total concurrent time: {concurrent_ms:.0f}ms")+ print()++ # ── Test 9: Command timeout ──+ bold("━━━ Test 9: Command timeout ━━━\n")++ timeout_start = time.time()+ try:+ result = await sandbox.commands.run("sleep 30", timeout=3)+ timeout_ms = (time.time() - timeout_start) * 1000+ check("Command timed out within ~3s", timeout_ms < 10000, f"took {timeout_ms:.0f}ms")+ except Exception as e:+ timeout_ms = (time.time() - timeout_start) * 1000+ check("Command timed out within ~3s", timeout_ms < 10000,+ f"took {timeout_ms:.0f}ms, error: {e}")+ print()++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ if sandbox:+ await sandbox.kill()+ green("Sandbox killed")++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_concurrent.py b/sdks/python/examples/test_concurrent.pynew file mode 100644index 00000000..7ccfeb93--- /dev/null+++ b/sdks/python/examples/test_concurrent.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""+Concurrent Sandbox Test++Tests:+ 1. Create 5 sandboxes simultaneously+ 2. Run commands on all in parallel+ 3. Verify each sandbox is isolated+ 4. Parallel file operations+ 5. Verify all sandboxes visible via API+ 6. Kill all in parallel++Usage:+ python examples/test_concurrent.py+"""++import asyncio+import sys+import time++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0++SANDBOX_COUNT = 5+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Concurrent Sandbox Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandboxes: list[Sandbox] = []++ try:+ # ── Test 1: Create N sandboxes simultaneously ──+ bold(f"━━━ Test 1: Create {SANDBOX_COUNT} sandboxes simultaneously ━━━\n")++ create_start = time.time()++ async def create_one(i: int) -> Sandbox:+ sb = await Sandbox.create(template="base", timeout=120)+ dim(f"Sandbox {i + 1}: {sb.sandbox_id} ({sb.domain})")+ return sb++ results = await asyncio.gather(+ *[create_one(i) for i in range(SANDBOX_COUNT)],+ return_exceptions=True,+ )+ create_ms = (time.time() - create_start) * 1000++ for i, r in enumerate(results):+ if isinstance(r, Exception):+ check(f"Sandbox {i + 1} created", False, str(r))+ else:+ sandboxes.append(r)+ check(f"Sandbox {i + 1} created", True)++ dim(f"Total create time: {create_ms:.0f}ms ({create_ms / SANDBOX_COUNT:.0f}ms avg)")+ print()++ # ── Test 2: Run commands on all in parallel ──+ bold("━━━ Test 2: Run commands on all sandboxes in parallel ━━━\n")++ cmd_start = time.time()++ async def run_echo(sb: Sandbox, i: int) -> dict:+ r = await sb.commands.run(f'echo "sandbox-{i}-{sb.sandbox_id}"')+ return {"index": i, "id": sb.sandbox_id, "result": r}++ cmd_results = await asyncio.gather(+ *[run_echo(sb, i) for i, sb in enumerate(sandboxes)],+ return_exceptions=True,+ )+ cmd_ms = (time.time() - cmd_start) * 1000++ for r in cmd_results:+ if isinstance(r, Exception):+ check("Command execution", False, str(r))+ else:+ expected = f"sandbox-{r['index']}-{r['id']}"+ check(f"Sandbox {r['index'] + 1} echo correct",+ r["result"].stdout.strip() == expected,+ r["result"].stdout.strip())++ dim(f"Total command time: {cmd_ms:.0f}ms")+ print()++ # ── Test 3: Verify isolation ──+ bold("━━━ Test 3: Verify sandbox isolation ━━━\n")++ await asyncio.gather(+ *[sb.files.write("/tmp/identity.txt", f"sandbox-{i}")+ for i, sb in enumerate(sandboxes)]+ )++ read_results = await asyncio.gather(+ *[sb.files.read("/tmp/identity.txt") for sb in sandboxes]+ )++ for i, content in enumerate(read_results):+ check(f"Sandbox {i + 1} sees only its own data",+ content == f"sandbox-{i}", content)++ pid_results = await asyncio.gather(+ *[sb.commands.run("echo $$") for sb in sandboxes]+ )++ for i, r in enumerate(pid_results):+ dim(f"Sandbox {i + 1} shell PID: {r.stdout.strip()}")++ check("PID namespace isolation (low PIDs)",+ all(int(r.stdout.strip()) < 1000 for r in pid_results),+ f"PIDs: {', '.join(r.stdout.strip() for r in pid_results)}")+ print()++ # ── Test 4: Parallel file operations ──+ bold("━━━ Test 4: Parallel file operations across sandboxes ━━━\n")++ async def file_ops(sb: Sandbox, i: int) -> dict:+ # Write 10 files+ await asyncio.gather(+ *[sb.files.write(f"/tmp/file-{j}.txt", f"sb{i}-file{j}")+ for j in range(10)]+ )+ # Read them back+ contents = await asyncio.gather(+ *[sb.files.read(f"/tmp/file-{j}.txt") for j in range(10)]+ )+ return {+ "index": i,+ "all_correct": all(c == f"sb{i}-file{j}" for j, c in enumerate(contents)),+ "count": len(contents),+ }++ file_results = await asyncio.gather(+ *[file_ops(sb, i) for i, sb in enumerate(sandboxes)]+ )++ for r in file_results:+ check(f"Sandbox {r['index'] + 1}: {r['count']} files written and verified",+ r["all_correct"])+ print()++ # ── Test 5: Verify all sandboxes visible via API ──+ bold("━━━ Test 5: Verify all sandboxes visible via API ━━━\n")++ statuses = await asyncio.gather(+ *[sb.is_running() for sb in sandboxes]+ )++ for i, running in enumerate(statuses):+ check(f"Sandbox {i + 1} still running", running)+ print()++ # ── Test 6: Kill all in parallel ──+ bold(f"━━━ Test 6: Kill all {SANDBOX_COUNT} sandboxes simultaneously ━━━\n")++ kill_start = time.time()++ async def kill_one(sb: Sandbox, i: int) -> dict:+ try:+ await sb.kill()+ return {"index": i, "success": True}+ except Exception as e:+ return {"index": i, "success": False, "error": str(e)}++ kill_results = await asyncio.gather(+ *[kill_one(sb, i) for i, sb in enumerate(sandboxes)]+ )+ kill_ms = (time.time() - kill_start) * 1000++ for r in kill_results:+ check(f"Sandbox {r['index'] + 1} killed", r["success"],+ r.get("error", ""))++ dim(f"Total kill time: {kill_ms:.0f}ms")++ await asyncio.sleep(1)++ post_kill = await asyncio.gather(+ *[sb.is_running() for sb in sandboxes]+ )++ for i, running in enumerate(post_kill):+ check(f"Sandbox {i + 1} confirmed stopped", not running)+ print()++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_domain_tls.py b/sdks/python/examples/test_domain_tls.pynew file mode 100644index 00000000..60367c66--- /dev/null+++ b/sdks/python/examples/test_domain_tls.py@@ -0,0 +1,236 @@+#!/usr/bin/env python3+"""+Domain & TLS Verification Test++Tests:+ 1. Each sandbox gets a unique subdomain+ 2. HTTPS works with valid cert+ 3. HTTP server inside sandbox is reachable via subdomain+ 4. Subdomain routes to correct sandbox+ 5. Multiple HTTP methods through TLS++Usage:+ python examples/test_domain_tls.py+"""++import asyncio+import ssl+import sys++import httpx++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++def get_tls_cert_info(hostname: str) -> dict:+ """Get TLS certificate info for a hostname."""+ import socket+ context = ssl.create_default_context()+ with socket.create_connection((hostname, 443), timeout=10) as sock:+ with context.wrap_socket(sock, server_hostname=hostname) as ssock:+ cert = ssock.getpeercert()+ issuer = dict(x[0] for x in cert.get("issuer", ()))+ subject = dict(x[0] for x in cert.get("subject", ()))+ return {+ "issuer": issuer.get("organizationName", "unknown"),+ "subject": subject.get("commonName", "unknown"),+ "valid_to": cert.get("notAfter", "unknown"),+ "valid": True,+ }+++HTTP_SERVER = """+const http = require('http');+const os = require('os');+const server = http.createServer((req, res) => {+ res.writeHead(200, {'Content-Type':'application/json'});+ res.end(JSON.stringify({+ path: req.url,+ hostname: os.hostname(),+ sandboxId: process.env.SANDBOX_ID || 'unknown',+ timestamp: Date.now()+ }));+});+server.listen(80, '0.0.0.0', () => console.log('Server ready'));+"""+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Domain & TLS Verification Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandboxes: list[Sandbox] = []++ try:+ # ── Test 1: Unique subdomains ──+ bold("━━━ Test 1: Unique subdomain assignment ━━━\n")++ for i in range(3):+ sb = await Sandbox.create(template="node", timeout=120)+ sandboxes.append(sb)+ dim(f"Sandbox {i + 1}: {sb.sandbox_id} → {sb.domain}")++ domains = [s.domain for s in sandboxes]+ unique_domains = set(domains)+ check("All 3 sandboxes got unique domains", len(unique_domains) == 3)+ check("All domains end with .workers.opensandbox.ai",+ all(d.endswith(".workers.opensandbox.ai") for d in domains))+ check("All domains are subdomains (single level)",+ all("." not in d.split(".workers.opensandbox.ai")[0] for d in domains))+ print()++ # ── Test 2: TLS certificate validation ──+ bold("━━━ Test 2: TLS certificate validation ━━━\n")++ # Start HTTP servers on all sandboxes+ for i, sb in enumerate(sandboxes):+ await sb.files.write("/tmp/server.js", HTTP_SERVER)+ await sb.commands.run(+ f"SANDBOX_ID={sb.sandbox_id} nohup node /tmp/server.js > /tmp/server.log 2>&1 &")++ await asyncio.sleep(2)++ try:+ cert_info = get_tls_cert_info(sandboxes[0].domain)+ check("TLS certificate is valid", cert_info["valid"])+ issuer = cert_info["issuer"]+ check("Certificate issued by Let's Encrypt or similar",+ any(s in issuer for s in ["Let's Encrypt", "R3", "R10", "R11", "E5", "E6"]),+ issuer)+ dim(f"Issuer: {cert_info['issuer']}")+ dim(f"Subject: {cert_info['subject']}")+ dim(f"Valid to: {cert_info['valid_to']}")+ except Exception as e:+ check("TLS connection succeeded", False, str(e))+ print()++ # ── Test 3: HTTPS requests work ──+ bold("━━━ Test 3: HTTPS requests to sandbox servers ━━━\n")++ async with httpx.AsyncClient(timeout=10.0) as client:+ for i, sb in enumerate(sandboxes):+ try:+ resp = await client.get(f"https://{sb.domain}/test-path")+ check(f"Sandbox {i + 1}: HTTPS 200", resp.status_code == 200,+ f"status {resp.status_code}")+ if resp.status_code == 200:+ data = resp.json()+ check(f"Sandbox {i + 1}: correct path",+ data["path"] == "/test-path", data["path"])+ check(f"Sandbox {i + 1}: has hostname", bool(data.get("hostname")))+ except Exception as e:+ check(f"Sandbox {i + 1}: HTTPS request", False, str(e))+ print()++ # ── Test 4: Subdomain routing isolation ──+ bold("━━━ Test 4: Subdomain routing isolation ━━━\n")++ async with httpx.AsyncClient(timeout=10.0) as client:+ routing_results = []+ for i, sb in enumerate(sandboxes):+ try:+ resp = await client.get(f"https://{sb.domain}/")+ data = resp.json()+ routing_results.append({+ "index": i,+ "sandbox_id": sb.sandbox_id,+ "returned_id": data.get("sandboxId", "error"),+ })+ except Exception as e:+ routing_results.append({+ "index": i,+ "sandbox_id": sb.sandbox_id,+ "returned_id": f"error: {e}",+ })++ for r in routing_results:+ check(f"Sandbox {r['index'] + 1}: routed to correct container",+ r["returned_id"] == r["sandbox_id"],+ f"expected {r['sandbox_id']}, got {r['returned_id']}")++ if len(sandboxes) >= 2:+ resp1 = await client.get(f"https://{sandboxes[0].domain}/")+ resp2 = await client.get(f"https://{sandboxes[1].domain}/")+ data1 = resp1.json()+ data2 = resp2.json()+ check("Cross-routing: different sandboxes return different IDs",+ data1["sandboxId"] != data2["sandboxId"])+ print()++ # ── Test 5: Multiple methods ──+ bold("━━━ Test 5: HTTP methods through TLS ━━━\n")++ domain = sandboxes[0].domain+ async with httpx.AsyncClient(timeout=10.0) as client:+ get_resp = await client.get(f"https://{domain}/get-test")+ check("GET request works", get_resp.status_code == 200)++ post_resp = await client.post(f"https://{domain}/post-test",+ json={"test": True})+ check("POST request works", post_resp.status_code == 200)++ put_resp = await client.put(f"https://{domain}/put-test",+ content=b"put-data")+ check("PUT request works", put_resp.status_code == 200)+ print()++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ for sb in sandboxes:+ try:+ await sb.kill()+ except Exception:+ pass+ if sandboxes:+ green(f"{len(sandboxes)} sandboxes killed")++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_environment.py b/sdks/python/examples/test_environment.pynew file mode 100644index 00000000..b310ee24--- /dev/null+++ b/sdks/python/examples/test_environment.py@@ -0,0 +1,178 @@+#!/usr/bin/env python3+"""+Environment & HOME Directory Test++Verifies that HOME=/workspace inside sandboxes so that tools like npm, pip,+git etc. use the NVMe-backed workspace drive for caches and config.++Tests:+ 1. HOME is set to /workspace+ 2. Tilde (~) expands to /workspace+ 3. npm cache dir is under /workspace+ 4. npm install writes cache to /workspace (not /root)+ 5. Dotfiles and configs use /workspace+ 6. /workspace is NVMe-backed++Usage:+ python examples/test_environment.py+"""++import asyncio+import sys++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Environment & HOME Directory Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandbox = None++ try:+ sandbox = await Sandbox.create(template="node", timeout=120)+ green(f"Created sandbox: {sandbox.sandbox_id}")+ print()++ # ── Test 1: HOME is /workspace ──+ bold("━━━ Test 1: HOME environment variable ━━━\n")++ result = await sandbox.commands.run("echo $HOME")+ check("HOME is /workspace", result.stdout.strip() == "/workspace",+ f'got "{result.stdout.strip()}"')++ # ── Test 2: Tilde expansion ──+ bold("━━━ Test 2: Tilde (~) expansion ━━━\n")++ result = await sandbox.commands.run("echo ~")+ check("~ expands to /workspace", result.stdout.strip() == "/workspace",+ f'got "{result.stdout.strip()}"')++ result = await sandbox.commands.run("echo ~/test")+ check("~/test expands to /workspace/test",+ result.stdout.strip() == "/workspace/test",+ f'got "{result.stdout.strip()}"')+ print()++ # ── Test 3: npm cache directory ──+ bold("━━━ Test 3: npm cache directory ━━━\n")++ result = await sandbox.commands.run("npm config get cache")+ npm_cache = result.stdout.strip()+ check("npm cache is under /workspace", npm_cache.startswith("/workspace"),+ f'got "{npm_cache}"')+ check("npm cache is NOT under /root", not npm_cache.startswith("/root"),+ f'got "{npm_cache}"')+ dim(f"npm cache dir: {npm_cache}")+ print()++ # ── Test 4: npm install writes to workspace ──+ bold("━━━ Test 4: npm install uses workspace for cache ━━━\n")++ await sandbox.commands.run("mkdir -p /workspace/npm-test")+ await sandbox.files.write("/workspace/npm-test/package.json",+ '{"name":"test","version":"1.0.0","dependencies":{"is-odd":"3.0.1"}}')++ install_result = await sandbox.commands.run(+ "cd /workspace/npm-test && npm install --prefer-offline 2>&1",+ timeout=30)+ dim(f"npm install exit code: {install_result.exit_code}")++ root_check = await sandbox.commands.run(+ "du -sh /root/.npm 2>/dev/null || echo 'no /root/.npm'")+ check("No npm cache in /root/.npm",+ "no /root/.npm" in root_check.stdout,+ f'got "{root_check.stdout.strip()}"')++ workspace_cache = await sandbox.commands.run(+ "test -d /workspace/.npm && echo 'exists' || echo 'missing'")+ check("npm cache exists at /workspace/.npm",+ workspace_cache.stdout.strip() == "exists",+ f'got "{workspace_cache.stdout.strip()}"')+ print()++ # ── Test 5: Dotfiles go to workspace ──+ bold("━━━ Test 5: Dotfiles and configs use /workspace ━━━\n")++ result = await sandbox.commands.run("bash -c 'echo $HOME/.bashrc'")+ check(".bashrc path is /workspace/.bashrc",+ result.stdout.strip() == "/workspace/.bashrc",+ f'got "{result.stdout.strip()}"')++ await sandbox.commands.run("git config --global user.name 'Test User'")+ result = await sandbox.commands.run(+ "git config --global --list --show-origin 2>/dev/null | head -1")+ check("git config is under /workspace",+ "/workspace" in result.stdout,+ f'got "{result.stdout.strip()}"')+ print()++ # ── Test 6: /workspace is on the right filesystem ──+ bold("━━━ Test 6: /workspace is NVMe-backed ━━━\n")++ result = await sandbox.commands.run("df -h /workspace | tail -1")+ df_line = result.stdout.strip()+ dim(f"df output: {df_line}")+ check("/workspace is NOT on /dev/root", not df_line.startswith("/dev/root"),+ f'got "{df_line}"')+ print()++ # Clean up+ await sandbox.commands.run("rm -rf /workspace/npm-test")++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ if sandbox:+ await sandbox.kill()+ green("Sandbox killed")++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_file_ops.py b/sdks/python/examples/test_file_ops.pynew file mode 100644index 00000000..1191ec33--- /dev/null+++ b/sdks/python/examples/test_file_ops.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""+File Operations Edge Cases Test++Tests:+ 1. Large file write/read (1MB)+ 2. Special characters in content+ 3. Deeply nested directories+ 4. File deletion and overwrite+ 5. Large directory listing+ 6. Empty file handling+ 7. File exists / not exists+ 8. Write via commands + read via SDK++Usage:+ python examples/test_file_ops.py+"""++import asyncio+import json+import sys+import time++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ File Operations Edge Cases Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandbox = None++ try:+ sandbox = await Sandbox.create(template="base", timeout=120)+ green(f"Created sandbox: {sandbox.sandbox_id}")+ print()++ # ── Test 1: Large file ──+ bold("━━━ Test 1: Large file (1MB) ━━━\n")++ one_mb = "X" * (1024 * 1024)+ write_start = time.time()+ await sandbox.files.write("/tmp/large.txt", one_mb)+ write_ms = (time.time() - write_start) * 1000+ dim(f"Write: {write_ms:.0f}ms")++ read_start = time.time()+ large_content = await sandbox.files.read("/tmp/large.txt")+ read_ms = (time.time() - read_start) * 1000+ dim(f"Read: {read_ms:.0f}ms")++ check("1MB file size preserved", len(large_content) == len(one_mb),+ f"{len(large_content)} bytes")+ check("1MB file content intact", large_content == one_mb)+ print()++ # ── Test 2: Special characters ──+ bold("━━━ Test 2: Special characters ━━━\n")++ special_content = 'Hello "world" & <tag> \'quotes\' \\ newline\nTab\there 日本語 emoji🎉 nullish ?? chain?.'+ await sandbox.files.write("/tmp/special.txt", special_content)+ special_read = await sandbox.files.read("/tmp/special.txt")+ check("Special characters preserved", special_read == special_content,+ f"got: {special_read[:50]}...")++ json_content = json.dumps({"key": "value", "nested": {"arr": [1, 2, 3]}, "unicode": "日本語"}, indent=2)+ await sandbox.files.write("/tmp/data.json", json_content)+ json_read = await sandbox.files.read("/tmp/data.json")+ check("JSON content preserved", json_read == json_content)++ multiline = "\n".join(f"Line {i + 1}: Some content here" for i in range(100))+ await sandbox.files.write("/tmp/multiline.txt", multiline)+ multi_read = await sandbox.files.read("/tmp/multiline.txt")+ check("100-line file preserved", multi_read == multiline,+ f"lines: {len(multi_read.split(chr(10)))}")+ print()++ # ── Test 3: Deeply nested directories ──+ bold("━━━ Test 3: Deeply nested directories ━━━\n")++ deep_path = "/tmp/a/b/c/d/e/f/g/h"+ await sandbox.commands.run(f"mkdir -p {deep_path}")+ await sandbox.files.write(f"{deep_path}/deep.txt", "bottom-of-tree")+ deep_content = await sandbox.files.read(f"{deep_path}/deep.txt")+ check("8-level nested file created and read", deep_content == "bottom-of-tree")++ mid_entries = await sandbox.files.list("/tmp/a/b/c/d")+ check("Intermediate dir lists correctly",+ any(e.name == "e" and e.is_dir for e in mid_entries))+ print()++ # ── Test 4: File deletion and overwrite ──+ bold("━━━ Test 4: File deletion and overwrite ━━━\n")++ await sandbox.files.write("/tmp/overwrite.txt", "original")+ content = await sandbox.files.read("/tmp/overwrite.txt")+ check("Original content written", content == "original")++ await sandbox.files.write("/tmp/overwrite.txt", "overwritten")+ content = await sandbox.files.read("/tmp/overwrite.txt")+ check("Overwritten content correct", content == "overwritten")++ await sandbox.files.write("/tmp/overwrite.txt", "short")+ content = await sandbox.files.read("/tmp/overwrite.txt")+ check("Shorter overwrite correct (no trailing data)", content == "short")++ exists_before = await sandbox.files.exists("/tmp/overwrite.txt")+ check("File exists before delete", exists_before)++ await sandbox.files.remove("/tmp/overwrite.txt")+ exists_after = await sandbox.files.exists("/tmp/overwrite.txt")+ check("File gone after delete", not exists_after)++ await sandbox.files.remove("/tmp/a")+ dir_gone = await sandbox.files.exists(f"{deep_path}/deep.txt")+ check("Recursive directory deletion", not dir_gone)+ print()++ # ── Test 5: Large directory listing ──+ bold("━━━ Test 5: Large directory listing ━━━\n")++ await sandbox.commands.run(+ "for i in $(seq 1 50); do echo content-$i > /tmp/listtest-$i.txt; done")+ entries = await sandbox.files.list("/tmp")+ list_test_files = [e for e in entries if e.name.startswith("listtest-")]+ check("50 files visible in listing", len(list_test_files) == 50,+ f"found {len(list_test_files)}")++ entry = list_test_files[0]+ check("Entry has name", bool(entry.name))+ check("Entry has is_dir=False", entry.is_dir is False)+ check("Entry has size > 0", entry.size > 0, f"size={entry.size}")+ print()++ # ── Test 6: Empty file ──+ bold("━━━ Test 6: Empty file handling ━━━\n")++ await sandbox.files.write("/tmp/empty.txt", "")+ empty_content = await sandbox.files.read("/tmp/empty.txt")+ check("Empty file returns empty string", empty_content == "",+ f'got: "{empty_content}"')+ check("Empty file exists", await sandbox.files.exists("/tmp/empty.txt"))+ print()++ # ── Test 7: File exists checks ──+ bold("━━━ Test 7: File exists checks ━━━\n")++ check("Existing file → true", await sandbox.files.exists("/tmp/special.txt"))+ check("Non-existent file → false", not await sandbox.files.exists("/tmp/nope-no-way.txt"))+ check("Non-existent deep path → false",+ not await sandbox.files.exists("/tmp/no/such/path/file.txt"))+ print()++ # ── Test 8: Write via commands + read via SDK ──+ bold("━━━ Test 8: Write via commands + read via SDK ━━━\n")++ await sandbox.commands.run(+ "dd if=/dev/urandom bs=256 count=1 2>/dev/null | base64 > /tmp/random.b64")+ b64_content = await sandbox.files.read("/tmp/random.b64")+ check("Base64 random data readable", len(b64_content) > 100,+ f"{len(b64_content)} chars")++ await sandbox.commands.run('echo -n "command-written" > /tmp/cmd-file.txt')+ cmd_file_content = await sandbox.files.read("/tmp/cmd-file.txt")+ check("Command-written file readable via SDK",+ cmd_file_content == "command-written")+ print()++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ if sandbox:+ await sandbox.kill()+ green("Sandbox killed")++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_multi_template.py b/sdks/python/examples/test_multi_template.pynew file mode 100644index 00000000..55963b92--- /dev/null+++ b/sdks/python/examples/test_multi_template.py@@ -0,0 +1,162 @@+#!/usr/bin/env python3+"""+Multi-Template Production Test++Verifies all 3 templates (base, python, node) create, run commands,+and have the expected runtimes available.++Usage:+ python examples/test_multi_template.py+"""++import asyncio+import sys+import time++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++TEMPLATES = [+ {+ "template": "base",+ "expected_binary": "bash",+ "version_cmd": "bash --version | head -1",+ "version_prefix": "GNU bash",+ "test_cmd": "echo 'hello from base'",+ "test_expected": "hello from base",+ },+ {+ "template": "python",+ "expected_binary": "python3",+ "version_cmd": "python3 --version",+ "version_prefix": "Python 3",+ "test_cmd": 'python3 -c "print(2 + 2)"',+ "test_expected": "4",+ },+ {+ "template": "node",+ "expected_binary": "node",+ "version_cmd": "node --version",+ "version_prefix": "v",+ "test_cmd": 'node -e "console.log(JSON.stringify({ok:true}))"',+ "test_expected": '{"ok":true}',+ },+]+++async def test_template(t: dict, index: int) -> tuple[int, int]:+ p = 0+ f = 0++ def local_check(desc: str, condition: bool, detail: str = "") -> None:+ nonlocal p, f+ if condition:+ green(desc)+ p += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ f += 1++ bold(f'\n━━━ Template {index + 1}/3: "{t["template"]}" ━━━\n')+ sandbox = None++ try:+ start = time.time()+ sandbox = await Sandbox.create(template=t["template"], timeout=120)+ create_ms = (time.time() - start) * 1000+ local_check(f"Created {t['template']} sandbox ({create_ms:.0f}ms)", True)+ dim(f"ID: {sandbox.sandbox_id}")+ dim(f"Domain: {sandbox.domain}")++ local_check("Domain assigned", bool(sandbox.domain))++ which = await sandbox.commands.run(f"which {t['expected_binary']}")+ local_check(f"{t['expected_binary']} binary exists",+ which.exit_code == 0, which.stderr.strip())++ version = await sandbox.commands.run(t["version_cmd"])+ local_check(f'Version starts with "{t["version_prefix"]}"',+ version.stdout.strip().startswith(t["version_prefix"]),+ version.stdout.strip())+ dim(f"Version: {version.stdout.strip()}")++ test = await sandbox.commands.run(t["test_cmd"])+ local_check("Test command output correct",+ test.stdout.strip() == t["test_expected"],+ f'expected "{t["test_expected"]}", got "{test.stdout.strip()}"')++ await sandbox.files.write("/tmp/template-test.txt", f"from-{t['template']}")+ content = await sandbox.files.read("/tmp/template-test.txt")+ local_check("File ops work", content == f"from-{t['template']}")++ uname = await sandbox.commands.run("uname -s")+ local_check("Running on Linux", uname.stdout.strip() == "Linux")++ except Exception as e:+ red(f" Error testing {t['template']}: {e}")+ f += 1+ finally:+ if sandbox:+ await sandbox.kill()+ dim("Sandbox killed")++ return p, f+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Multi-Template Production Test ║")+ bold("╚══════════════════════════════════════════════════╝")++ for i, t in enumerate(TEMPLATES):+ p, f = await test_template(t, i)+ passed += p+ failed += f++ print()+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_python_sdk.py b/sdks/python/examples/test_python_sdk.pynew file mode 100644index 00000000..43fdfb70--- /dev/null+++ b/sdks/python/examples/test_python_sdk.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""+Python SDK Production Test++Validates that the Python template works end-to-end by running a Python+test script inside a sandbox that exercises stdlib, file ops, env vars, etc.++Usage:+ python examples/test_python_sdk.py+"""++import asyncio+import json+import sys++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++PYTHON_TEST_SCRIPT = '''+import json+import os++results = {}++# Test 1: Basic echo+import subprocess+r = subprocess.run(["echo", "hello-from-python"], capture_output=True, text=True)+results["echo"] = r.stdout.strip()++# Test 2: File write + read+with open("/tmp/py-test.txt", "w") as f:+ f.write("python-sdk-data")+with open("/tmp/py-test.txt", "r") as f:+ results["file_content"] = f.read()++# Test 3: Environment variables+results["home"] = os.environ.get("HOME", "unknown")+results["path_exists"] = "PATH" in os.environ++# Test 4: Nested directory+os.makedirs("/tmp/py-nested/deep/dir", exist_ok=True)+with open("/tmp/py-nested/deep/dir/file.txt", "w") as f:+ f.write("nested-content")+with open("/tmp/py-nested/deep/dir/file.txt", "r") as f:+ results["nested"] = f.read()++# Test 5: Python-specific features+import sys+results["python_version"] = sys.version.split()[0]+results["platform"] = sys.platform++# Test 6: Math/stdlib+import math+results["pi"] = str(round(math.pi, 5))++# Test 7: JSON handling+data = {"key": "value", "number": 42, "nested": {"a": True}}+results["json_roundtrip"] = json.loads(json.dumps(data)) == data++print(json.dumps(results))+'''+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Python SDK Production Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandbox = None++ try:+ # --- Create sandbox with Python template ---+ bold("[1/4] Creating Python sandbox...")+ sandbox = await Sandbox.create(template="python", timeout=120)+ green(f"Created: {sandbox.sandbox_id}")+ dim(f"Domain: {sandbox.domain}")+ print()++ # --- Write and run Python test script ---+ bold("[2/4] Writing Python test script...")+ await sandbox.files.write("/tmp/test_sdk.py", PYTHON_TEST_SCRIPT)+ green("Script written to /tmp/test_sdk.py")+ print()++ bold("[3/4] Running Python tests inside sandbox...")+ result = await sandbox.commands.run("python3 /tmp/test_sdk.py", timeout=30)+ check("Python script exited cleanly", result.exit_code == 0,+ f"exit code: {result.exit_code}")++ if result.exit_code != 0:+ dim(f"stderr: {result.stderr}")+ dim(f"stdout: {result.stdout}")+ else:+ data = json.loads(result.stdout.strip())+ check("Echo command works", data["echo"] == "hello-from-python", data["echo"])+ check("File write/read works", data["file_content"] == "python-sdk-data", data["file_content"])+ check("HOME env var present", data["home"] != "unknown", data["home"])+ check("PATH env var exists", data["path_exists"] is True)+ check("Nested directory file works", data["nested"] == "nested-content", data["nested"])+ check("Python version detected", data["python_version"].startswith("3."), data["python_version"])+ check("Platform is Linux", data["platform"] == "linux", data["platform"])+ check("Math.pi correct", data["pi"] == "3.14159", data["pi"])+ check("JSON roundtrip works", data["json_roundtrip"] is True)+ dim(f"Python {data['python_version']} on {data['platform']}")+ print()++ # --- Verify file ops from SDK side ---+ bold("[4/4] Verifying files from Python SDK...")+ content = await sandbox.files.read("/tmp/py-test.txt")+ check("SDK can read Python-written file", content == "python-sdk-data", content)++ entries = await sandbox.files.list("/tmp/py-nested/deep/dir")+ check("SDK can list Python-created directory",+ any(e.name == "file.txt" for e in entries))+ print()++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ if sandbox:+ await sandbox.kill()+ green("Sandbox killed")++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_reconnect.py b/sdks/python/examples/test_reconnect.pynew file mode 100644index 00000000..1785981a--- /dev/null+++ b/sdks/python/examples/test_reconnect.py@@ -0,0 +1,200 @@+#!/usr/bin/env python3+"""+SDK Connect/Reconnect Test++Tests:+ 1. Create sandbox, disconnect, reconnect via Sandbox.connect()+ 2. Verify state persists across connections+ 3. Multiple connect() calls to same sandbox+ 4. Operations work on reconnected instance++Usage:+ python examples/test_reconnect.py+"""++import asyncio+import sys++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ SDK Connect/Reconnect Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ sandbox_id = ""++ try:+ # ── Test 1: Create and store ID ──+ bold("━━━ Test 1: Create sandbox and store ID ━━━\n")++ original = await Sandbox.create(template="base", timeout=120)+ sandbox_id = original.sandbox_id+ green(f"Created: {sandbox_id}")+ dim(f"Domain: {original.domain}")++ await original.files.write("/tmp/reconnect-test.txt", "original-data")+ await original.commands.run("echo 'state-marker' > /tmp/marker.txt")+ green("State written to sandbox")+ print()++ # ── Test 2: Reconnect via Sandbox.connect() ──+ bold("━━━ Test 2: Reconnect via Sandbox.connect() ━━━\n")++ reconnected = await Sandbox.connect(sandbox_id)+ check("Reconnect succeeded", reconnected is not None)+ check("Same sandbox ID", reconnected.sandbox_id == sandbox_id)+ check("Domain matches", reconnected.domain == original.domain, reconnected.domain)+ check("Status is running", reconnected.status == "running", reconnected.status)+ print()++ # ── Test 3: Read state from reconnected instance ──+ bold("━━━ Test 3: State persists across connections ━━━\n")++ file_content = await reconnected.files.read("/tmp/reconnect-test.txt")+ check("File from original instance readable", file_content == "original-data", file_content)++ marker_content = await reconnected.files.read("/tmp/marker.txt")+ check("Command output file persisted", marker_content.strip() == "state-marker")++ await reconnected.files.write("/tmp/reconnect-new.txt", "from-reconnected")+ new_content = await reconnected.files.read("/tmp/reconnect-new.txt")+ check("Write from reconnected instance works", new_content == "from-reconnected")+ print()++ # ── Test 4: Commands work on reconnected instance ──+ bold("━━━ Test 4: Commands work on reconnected instance ━━━\n")++ echo = await reconnected.commands.run("echo reconnected-echo")+ check("Echo command works", echo.stdout.strip() == "reconnected-echo")+ check("Exit code is 0", echo.exit_code == 0)++ uname = await reconnected.commands.run("uname -s")+ check("Uname returns Linux", uname.stdout.strip() == "Linux")++ env_result = await reconnected.commands.run("echo $TEST_VAR",+ env={"TEST_VAR": "reconnected-env"})+ check("Env vars work on reconnected instance",+ env_result.stdout.strip() == "reconnected-env")++ entries = await reconnected.files.list("/tmp")+ check("File listing works",+ any(e.name == "reconnect-test.txt" for e in entries))+ check("New file visible in listing",+ any(e.name == "reconnect-new.txt" for e in entries))+ print()++ # ── Test 5: Multiple simultaneous connections ──+ bold("━━━ Test 5: Multiple simultaneous connections ━━━\n")++ conn1 = await Sandbox.connect(sandbox_id)+ conn2 = await Sandbox.connect(sandbox_id)+ conn3 = await Sandbox.connect(sandbox_id)++ check("3 connections to same sandbox succeeded",+ conn1 is not None and conn2 is not None and conn3 is not None)++ read1, read2, read3 = await asyncio.gather(+ conn1.files.read("/tmp/reconnect-test.txt"),+ conn2.files.read("/tmp/reconnect-test.txt"),+ conn3.files.read("/tmp/reconnect-test.txt"),+ )++ check("All connections read same data",+ read1 == "original-data" and read2 == "original-data" and read3 == "original-data")++ await conn1.files.write("/tmp/cross-conn.txt", "from-conn1")+ cross_read = await conn2.files.read("/tmp/cross-conn.txt")+ check("Write from conn1 visible to conn2", cross_read == "from-conn1")+ print()++ # ── Test 6: is_running on reconnected instance ──+ bold("━━━ Test 6: is_running on reconnected instance ━━━\n")++ running = await reconnected.is_running()+ check("is_running returns True", running)+ print()++ # ── Test 7: Kill from reconnected instance ──+ bold("━━━ Test 7: Kill from reconnected instance ━━━\n")++ await reconnected.kill()+ green("Killed from reconnected instance")++ await asyncio.sleep(0.5)++ still_running = await original.is_running()+ check("Original ref sees sandbox as stopped", not still_running)++ try:+ dead_conn = await Sandbox.connect(sandbox_id)+ dead_running = await dead_conn.is_running()+ check("Connect to killed sandbox: is_running=False", not dead_running)+ except Exception as e:+ check("Connect to killed sandbox: throws or returns not running", True)+ dim(f"Error: {e}")+ print()++ # Clear sandbox_id so cleanup doesn't try to kill again+ sandbox_id = ""++ except Exception as e:+ red(f"Fatal error: {e}")+ failed += 1+ finally:+ if sandbox_id:+ try:+ cleanup = await Sandbox.connect(sandbox_id)+ await cleanup.kill()+ green("Sandbox killed in cleanup")+ except Exception:+ pass++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/sdks/python/examples/test_timeout.py b/sdks/python/examples/test_timeout.pynew file mode 100644index 00000000..99d5a55d--- /dev/null+++ b/sdks/python/examples/test_timeout.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""+Timeout Behavior Test++Tests:+ 1. Activity resets the rolling timeout (sandbox stays alive with pokes)+ 2. Sandbox with short timeout eventually auto-hibernates when idle+ 3. Different timeout values accepted++Usage:+ python examples/test_timeout.py+"""++import asyncio+import sys++from opensandbox import Sandbox++GREEN = "\033[32m"+RED = "\033[31m"+BOLD = "\033[1m"+DIM = "\033[2m"+CYAN = "\033[36m"+YELLOW = "\033[33m"+RESET = "\033[0m"++passed = 0+failed = 0+++def green(msg: str) -> None:+ print(f"{GREEN}✓ {msg}{RESET}")+++def red(msg: str) -> None:+ print(f"{RED}✗ {msg}{RESET}")+++def bold(msg: str) -> None:+ print(f"{BOLD}{msg}{RESET}")+++def dim(msg: str) -> None:+ print(f"{DIM} {msg}{RESET}")+++def cyan(msg: str) -> None:+ print(f"{CYAN}→ {msg}{RESET}")+++def yellow(msg: str) -> None:+ print(f"{YELLOW}⚠ {msg}{RESET}")+++def check(desc: str, condition: bool, detail: str = "") -> None:+ global passed, failed+ if condition:+ green(desc)+ passed += 1+ else:+ red(f"{desc} ({detail})" if detail else desc)+ failed += 1+++async def main() -> None:+ global passed, failed++ bold("\n╔══════════════════════════════════════════════════╗")+ bold("║ Timeout Behavior Test ║")+ bold("╚══════════════════════════════════════════════════╝\n")++ # ── Test 1: Activity resets rolling timeout ──+ bold("━━━ Test 1: Activity resets rolling timeout ━━━\n")+ dim("Timeout=60s, pokes every 15s × 8 = 120s total elapsed")+ dim("Without rolling reset, sandbox would die at 60s")++ sb = await Sandbox.create(template="base", timeout=60)+ green(f"Created: {sb.sandbox_id} (timeout: 60s)")++ for i in range(8):+ dim(f"Poke {i + 1}/8: waiting 15s then running command...")+ await asyncio.sleep(15)+ try:+ result = await sb.commands.run(f"echo poke-{i + 1}")+ check(f"Poke {i + 1} at {(i + 1) * 15}s: sandbox still alive",+ result.stdout.strip() == f"poke-{i + 1}",+ f'got: "{result.stdout.strip()}"')+ except Exception as e:+ check(f"Poke {i + 1} at {(i + 1) * 15}s: sandbox still alive", False, str(e))++ dim("Total elapsed: ~120s (2× the 60s timeout, proving rolling reset)")+ running = await sb.is_running()+ check("Sandbox alive after 120s with activity (rolling timeout proven)", running)++ await sb.kill()+ green("Sandbox killed")+ print()++ # ── Test 2: Idle sandbox eventually times out ──+ bold("━━━ Test 2: Idle sandbox times out ━━━\n")++ sb = await Sandbox.create(template="base", timeout=30)+ green(f"Created: {sb.sandbox_id} (timeout: 30s)")++ result = await sb.commands.run("echo alive")+ check("Commands work while alive", result.stdout.strip() == "alive")++ dim("Leaving sandbox completely idle for 40 seconds...")+ await asyncio.sleep(40)++ running = await sb.is_running()+ dim(f"is_running after 40s idle: {running}")++ if running:+ try:+ reconnected = await Sandbox.connect(sb.sandbox_id)+ after_result = await reconnected.commands.run("echo after-timeout")+ dim(f'Command after idle: "{after_result.stdout.strip()}"')+ yellow("Sandbox still responds after idle — timeout may auto-hibernate + auto-wake on command")+ except Exception as e:+ dim(f"Command after idle failed: {e}")+ green("Sandbox appears to have timed out (command failed)")+ else:+ green("Sandbox no longer running after idle period")++ check("Idle timeout test completed", True)++ try:+ await sb.kill()+ except Exception:+ pass+ green("Sandbox cleaned up")+ print()++ # ── Test 3: Different timeout values accepted ──+ bold("━━━ Test 3: Different timeout values accepted ━━━\n")++ timeouts = [30, 60, 300, 600]+ for t in timeouts:+ sb = await Sandbox.create(template="base", timeout=t)+ check(f"Sandbox created with timeout={t}s", sb.status == "running")+ result = await sb.commands.run("echo ok")+ check(f"Commands work with timeout={t}s", result.stdout.strip() == "ok")+ await sb.kill()+ print()++ # --- Summary ---+ bold("========================================")+ bold(f" Results: {passed} passed, {failed} failed")+ bold("========================================\n")+ if failed > 0:+ sys.exit(1)+++if __name__ == "__main__":+ asyncio.run(main())