An open-source, faster Devin alternative
TypeScript
add elasticity docs and additional validation on sizes being set by users (#84)
Mohamed Habib2d06ae1433bc
diff --git a/docs/api-reference/sandboxes/create.mdx b/docs/api-reference/sandboxes/create.mdxindex 12ee183e..ef78ebab 100644--- a/docs/api-reference/sandboxes/create.mdx+++ b/docs/api-reference/sandboxes/create.mdx@@ -14,13 +14,25 @@ Create a new sandbox.</ParamField><ParamField body="cpuCount" type="integer">- CPU cores, 1–4 (default: `1`)+ CPU cores. Must match an allowed tier: `1`, `2`, `4`, `8`, or `16`. If omitted but `memoryMB` is set, inferred automatically.</ParamField><ParamField body="memoryMB" type="integer">- Memory in MB, up to 2048 (default: `512`)+ Memory in MB. Must match an allowed tier: `4096`, `8192`, `16384`, `32768`, or `65536`. If omitted but `cpuCount` is set, inferred automatically.</ParamField>+The allowed CPU/memory combinations are:++| Memory | vCPU |+| --- | --- |+| 4096 MB (4 GB) | 1 |+| 8192 MB (8 GB) | 2 |+| 16384 MB (16 GB) | 4 |+| 32768 MB (32 GB) | 8 |+| 65536 MB (64 GB) | 16 |++If both `cpuCount` and `memoryMB` are provided, they must match one of these tiers.+<ParamField body="envs" type="object">Environment variables as key-value pairs</ParamField>diff --git a/docs/how-it-works.mdx b/docs/how-it-works.mdxindex eac5f601..e2081e74 100644--- a/docs/how-it-works.mdx+++ b/docs/how-it-works.mdx@@ -63,6 +63,10 @@ const sandbox = await Sandbox.create({ snapshot: 'my-custom-stack' });See [Templates](/sandboxes/templates) for the full guide.+## Elasticity++Sandboxes can scale memory at runtime via an internal metadata endpoint (`http://169.254.169.254/v1/scale`) accessible from inside the VM. CPU scales proportionally. This lets workloads request more resources before heavy tasks and release them after. See [Elasticity](/sandboxes/elasticity) for details.+## NetworkingEvery sandbox gets full outbound internet access via a TAP device with NAT. No firewall or allowlist to configure.diff --git a/docs/mint.json b/docs/mint.jsonindex 8fc447cd..1259f547 100644--- a/docs/mint.json+++ b/docs/mint.json@@ -78,7 +78,8 @@"sandboxes/templates","sandboxes/secrets","sandboxes/patches",- "sandboxes/preview-urls"+ "sandboxes/preview-urls",+ "sandboxes/elasticity"]},{diff --git a/docs/sandboxes/elasticity.mdx b/docs/sandboxes/elasticity.mdxnew file mode 100644index 00000000..b9a4bcb4--- /dev/null+++ b/docs/sandboxes/elasticity.mdx@@ -0,0 +1,111 @@+---+title: "Elasticity"+description: "Dynamically scale sandbox memory and CPU from inside the VM"+---++Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale memory up or down on the fly. CPU scales proportionally to memory.++This is useful for workloads with variable resource needs — scale up before a heavy compilation or ML inference, then scale back down to save resources.++<Note>+ The elasticity endpoint is only accessible from inside the sandbox. It is not exposed through the control plane API or SDKs.+</Note>++## Scale Memory++Send a `POST` to `/v1/scale` with the desired memory in MB:++```bash+curl -s -X POST http://169.254.169.254/v1/scale \+ -H "Content-Type: application/json" \+ -d '{"memoryMB": 4096}'+```++CPU is adjusted proportionally — you only need to specify memory. The permissible sizes are:++| Memory | vCPU |+| --- | --- |+| 4GB | 1 |+| 8GB | 2 |+| 16GB | 4 |+| 32GB | 8 |+| 64GB | 16 |++## Check Current Limits++```bash+curl -s http://169.254.169.254/v1/limits+```++## Example: Rust Compilation++Rust builds are memory-hungry. You can alias `cargo` to scale up before compilation and scale back down after:++```bash+alias cargo='_cargo_scaled'+_cargo_scaled() {+ # Scale up to 16GB / 4 vCPU before build+ curl -sf -X POST http://169.254.169.254/v1/scale \+ -H "Content-Type: application/json" -d '{"memoryMB": 16384}'++ # Run the actual cargo command+ command cargo "$@"+ local exit_code=$?++ # Scale back down to 4GB / 1 vCPU+ curl -sf -X POST http://169.254.169.254/v1/scale \+ -H "Content-Type: application/json" -d '{"memoryMB": 4096}'++ return $exit_code+}+```++Add this to your sandbox's `~/.bashrc` or inject it via `sandbox.exec.run` so every `cargo build`, `cargo test`, etc. automatically gets the extra resources.++## Example: Auto-Scaling Script++A simple shell script that monitors memory pressure and scales automatically:++```bash+#!/bin/sh+SCALE_API="http://169.254.169.254/v1/scale"+MIN_MB=1024+MAX_MB=8192+SCALE_UP_THRESHOLD=80+SCALE_DOWN_THRESHOLD=30+COOLDOWN=30+last_scale=0++while true; do+ mem_total=$(awk '/MemTotal/{print $2}' /proc/meminfo)+ mem_avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo)+ usage_pct=$(( (mem_total - mem_avail) * 100 / mem_total ))+ total_mb=$((mem_total / 1024))+ now=$(date +%s)+ elapsed=$((now - last_scale))++ if [ $usage_pct -gt $SCALE_UP_THRESHOLD ] && [ $elapsed -gt $COOLDOWN ]; then+ new_mb=$((total_mb * 2))+ [ $new_mb -gt $MAX_MB ] && new_mb=$MAX_MB+ if [ $new_mb -gt $total_mb ]; then+ echo "usage=$usage_pct% -> scaling UP to ${new_mb}MB"+ curl -sf -X POST "$SCALE_API" \+ -H "Content-Type: application/json" \+ -d "{\"memoryMB\":$new_mb}"+ last_scale=$now+ fi+ elif [ $usage_pct -lt $SCALE_DOWN_THRESHOLD ] && [ $total_mb -gt $MIN_MB ] && [ $elapsed -gt $COOLDOWN ]; then+ new_mb=$((total_mb / 2))+ [ $new_mb -lt $MIN_MB ] && new_mb=$MIN_MB+ if [ $new_mb -lt $total_mb ]; then+ echo "usage=$usage_pct% -> scaling DOWN to ${new_mb}MB"+ curl -sf -X POST "$SCALE_API" \+ -H "Content-Type: application/json" \+ -d "{\"memoryMB\":$new_mb}"+ last_scale=$now+ fi+ fi++ sleep 5+done+```diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 4576fe79..9059d03b 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -26,23 +26,13 @@ func (s *Server) createSandbox(c echo.Context) error {})}- // Validate and clamp CPU/memory limits- if cfg.CpuCount < 0 {- cfg.CpuCount = 0- }- if cfg.CpuCount > 16 {+ // Validate CPU/memory against allowed tiers.+ // Allowed tiers (memoryMB → vCPU): 4096→1, 8192→2, 16384→4, 32768→8, 65536→16.+ if err := types.ValidateResourceTier(&cfg); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{- "error": "cpuCount must not exceed 16",- })- }- if cfg.MemoryMB > 16384 {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "memoryMB must not exceed 16384",+ "error": err.Error(),})}- if cfg.MemoryMB < 0 {- cfg.MemoryMB = 0- }ctx := c.Request().Context()@@ -776,11 +766,14 @@ func (s *Server) setLimits(c echo.Context) error {})}- // Auto-calculate CPU from memory: 1 vCPU per 4GB- if req.MemoryMB > 0 && req.CPUPercent == 0 {- req.CPUPercent = (req.MemoryMB * 100) / 4096- if req.CPUPercent < 100 {- req.CPUPercent = 100+ // Validate memory against allowed tiers+ if req.MemoryMB > 0 {+ vcpus, err := types.ValidateMemoryMB(req.MemoryMB)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+ if req.CPUPercent == 0 {+ req.CPUPercent = vcpus * 100}}@@ -824,11 +817,12 @@ func (s *Server) scaleSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": "memoryMB is required and must be positive"})}- // Auto-calculate: 1 vCPU per 4GB = 100% CPU per 4096MB- cpuPercent := (req.MemoryMB * 100) / 4096- if cpuPercent < 100 {- cpuPercent = 100+ // Validate memory against allowed tiers+ vcpus, err := types.ValidateMemoryMB(req.MemoryMB)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}+ cpuPercent := vcpus * 100maxMemoryBytes := int64(req.MemoryMB) * 1024 * 1024cpuMaxUsec := int64(cpuPercent) * 1000cpuPeriodUsec := int64(100000)diff --git a/internal/worker/metadata.go b/internal/worker/metadata.goindex 7183328e..cb9db9e6 100644--- a/internal/worker/metadata.go+++ b/internal/worker/metadata.go@@ -12,6 +12,7 @@ import ("time""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/pkg/types")// MetadataServer serves the instance metadata API at 169.254.169.254:80 (via DNAT to :8888).@@ -206,11 +207,15 @@ func (ms *MetadataServer) handleScale(w http.ResponseWriter, r *http.Request) {return}- // Auto-calculate CPU from memory: 1 vCPU per 4GB- if req.MemoryMB > 0 && req.CPUPercent == 0 {- req.CPUPercent = (req.MemoryMB * 100) / 4096- if req.CPUPercent < 100 {- req.CPUPercent = 100+ // Validate memory against allowed tiers and auto-calculate CPU+ if req.MemoryMB > 0 {+ vcpus, err := types.ValidateMemoryMB(req.MemoryMB)+ if err != nil {+ http.Error(w, err.Error(), http.StatusBadRequest)+ return+ }+ if req.CPUPercent == 0 {+ req.CPUPercent = vcpus * 100}}diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex 62789b1d..50932265 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -2,6 +2,7 @@ package typesimport ("encoding/json"+ "fmt""time")@@ -76,6 +77,80 @@ type SandboxConfig struct {CheckpointID string `json:"-"`}+// ResourceTier defines an allowed memory/CPU combination.+type ResourceTier struct {+ MemoryMB int+ VCPUs int+}++// AllowedResourceTiers lists the valid memory→vCPU combinations.+var AllowedResourceTiers = []ResourceTier{+ {MemoryMB: 4096, VCPUs: 1},+ {MemoryMB: 8192, VCPUs: 2},+ {MemoryMB: 16384, VCPUs: 4},+ {MemoryMB: 32768, VCPUs: 8},+ {MemoryMB: 65536, VCPUs: 16},+}++// ValidateMemoryMB checks that memoryMB matches an allowed tier and returns the corresponding vCPU count.+// Returns 0, nil if memoryMB is 0 (use defaults).+func ValidateMemoryMB(memoryMB int) (vcpus int, err error) {+ if memoryMB == 0 {+ return 0, nil+ }+ for _, t := range AllowedResourceTiers {+ if memoryMB == t.MemoryMB {+ return t.VCPUs, nil+ }+ }+ return 0, fmt.Errorf("memoryMB must be one of: 4096, 8192, 16384, 32768, 65536 (got %d)", memoryMB)+}++// ValidateCPUCount checks that cpuCount matches an allowed tier and returns the corresponding memoryMB.+// Returns 0, nil if cpuCount is 0 (use defaults).+func ValidateCPUCount(cpuCount int) (memoryMB int, err error) {+ if cpuCount == 0 {+ return 0, nil+ }+ for _, t := range AllowedResourceTiers {+ if cpuCount == t.VCPUs {+ return t.MemoryMB, nil+ }+ }+ return 0, fmt.Errorf("cpuCount must be one of: 1, 2, 4, 8, 16 (got %d)", cpuCount)+}++// ValidateResourceTier validates and normalizes CPU/memory on a SandboxConfig.+// If only one is set, the other is inferred from the tier. If both are set, they must match.+func ValidateResourceTier(cfg *SandboxConfig) error {+ if cfg.MemoryMB == 0 && cfg.CpuCount == 0 {+ return nil // use defaults+ }+ if cfg.MemoryMB > 0 && cfg.CpuCount == 0 {+ vcpus, err := ValidateMemoryMB(cfg.MemoryMB)+ if err != nil {+ return err+ }+ cfg.CpuCount = vcpus+ return nil+ }+ if cfg.CpuCount > 0 && cfg.MemoryMB == 0 {+ mem, err := ValidateCPUCount(cfg.CpuCount)+ if err != nil {+ return err+ }+ cfg.MemoryMB = mem+ return nil+ }+ // Both set — verify they match a tier+ for _, t := range AllowedResourceTiers {+ if cfg.MemoryMB == t.MemoryMB && cfg.CpuCount == t.VCPUs {+ return nil+ }+ }+ return fmt.Errorf("cpuCount %d and memoryMB %d do not match an allowed tier; valid combinations: 1/4096, 2/8192, 4/16384, 8/32768, 16/65536", cfg.CpuCount, cfg.MemoryMB)+}+// SandboxListResponse is the response for listing sandboxes.type SandboxListResponse struct {Sandboxes []Sandbox `json:"sandboxes"`