An open-source, faster Devin alternative
TypeScript
feat(xcell): capacity-aware cell cascade (CP reporter + events-ingest + edge pickCell)
Brian Reardon669e6a88d518
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex d175c529..3b4467ef 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -113,18 +113,124 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {interface CellRow {cell_id: string;+ cloud: string;+ region: string;base_url: string;status: string;+ available_workers: number;+ capacity_updated_at: number | null;}async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {return env.OPENCOMPUTER_DB.prepare(- "SELECT cell_id, base_url, status FROM cells WHERE cell_id = ?1",+ `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at+ FROM cells WHERE cell_id = ?1`,).bind(cellID).first<CellRow>();}+// Freshness window — the CP emits capacity events every ~30s; 120s is a+// generous 4× margin that covers a missed sample without flapping.+const CAPACITY_FRESH_SEC = 120;++function isHealthy(cell: CellRow, nowSec: number): boolean {+ if (cell.status !== "active") return false;+ if (cell.capacity_updated_at == null) return false;+ if (nowSec - cell.capacity_updated_at > CAPACITY_FRESH_SEC) return false;+ if (cell.available_workers <= 0) return false;+ return true;+}++// Continent buckets used by distanceRank when cells span clouds. Coarse on+// purpose — we just need "near" vs "far" for the cascade. Unknown regions+// fall through to tier 3 (global).+const REGION_CONTINENT: Record<string, string> = {+ // Azure NA+ westus: "na", westus2: "na", westus3: "na",+ eastus: "na", eastus2: "na", centralus: "na", northcentralus: "na", southcentralus: "na",+ canadacentral: "na", canadaeast: "na",+ // Azure EU+ westeurope: "eu", northeurope: "eu", francecentral: "eu", germanywestcentral: "eu",+ uksouth: "eu", ukwest: "eu",+ // Azure APAC+ japaneast: "ap", japanwest: "ap", koreacentral: "ap",+ southeastasia: "ap", eastasia: "ap",+ australiaeast: "ap", australiasoutheast: "ap",+ // AWS NA+ "us-east-1": "na", "us-east-2": "na", "us-west-1": "na", "us-west-2": "na",+ "ca-central-1": "na",+ // AWS EU+ "eu-west-1": "eu", "eu-west-2": "eu", "eu-central-1": "eu", "eu-north-1": "eu",+ // AWS APAC+ "ap-southeast-1": "ap", "ap-southeast-2": "ap", "ap-northeast-1": "ap", "ap-northeast-2": "ap",+};++// Tier distance from `a` to `b`. Lower is closer.+// 0 — same cloud + same region (cell siblings)+// 1 — same cloud, different region+// 2 — different cloud, same continent+// 3 — anywhere else (different continent, or unknown region)+function distanceRank(a: CellRow, b: CellRow): number {+ if (a.cloud === b.cloud && a.region === b.region) return 0;+ if (a.cloud === b.cloud) return 1;+ const aCont = REGION_CONTINENT[a.region];+ const bCont = REGION_CONTINENT[b.region];+ if (aCont && bCont && aCont === bCont) return 2;+ return 3;+}++// pickCell — layered placement.+// 0. Hard pin from request body (cellId) — strict; if pinned cell is+// unhealthy/missing, fail rather than silently fall back.+// 1. Healthy candidates (status+freshness+available_workers gates).+// 2. Home cell first, then siblings ordered by tier-distance from home.+// 3. First candidate with capacity wins.+// Returns null if nothing is eligible — caller turns that into 503.+async function pickCell(+ env: Env,+ homeCell: string,+ requestedCellID: string | null,+): Promise<CellRow | null> {+ const nowSec = Math.floor(Date.now() / 1000);++ // 0. Hard pin+ if (requestedCellID) {+ const c = await lookupCell(env, requestedCellID);+ return c && isHealthy(c, nowSec) ? c : null;+ }++ // Look up home regardless of health — we still want its {cloud, region}+ // as the distance anchor even if home itself is currently loaded.+ const home = await lookupCell(env, homeCell);++ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at+ FROM cells WHERE status = 'active'`,+ ).all<CellRow>();+ const healthy = (results ?? []).filter((c) => isHealthy(c, nowSec));+ if (healthy.length === 0) return null;++ if (home) {+ healthy.sort((a, b) => {+ const da = distanceRank(home, a);+ const db = distanceRank(home, b);+ if (da !== db) return da - db;+ // Tie-break: home wins ties (distance 0 to itself), then alphabetical for+ // deterministic ordering across cells the same distance from home.+ if (a.cell_id === home.cell_id) return -1;+ if (b.cell_id === home.cell_id) return 1;+ return a.cell_id.localeCompare(b.cell_id);+ });+ } else {+ // Home cell not registered in the table at all — degenerate config; pick+ // alphabetically rather than randomly so behavior is at least deterministic.+ healthy.sort((a, b) => a.cell_id.localeCompare(b.cell_id));+ }++ return healthy[0] ?? null;+}+// ── route handlers ───────────────────────────────────────────────────────async function createSandbox(req: Request, env: Env): Promise<Response> {@@ -136,13 +242,29 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {.first<{ home_cell: string }>();if (!org) return json({ error: "org not found" }, 401);- const cell = await lookupCell(env, org.home_cell);- if (!cell) return json({ error: `home cell ${org.home_cell} not registered` }, 503);- if (cell.status !== "active") return json({ error: `cell ${cell.cell_id} is ${cell.status}` }, 503);+ // Read body once — used for the hard-pin peek + forwarded to the CP verbatim.+ const bodyText = await req.text();+ let requestedCellID: string | null = null;+ try {+ if (bodyText) {+ const parsed = JSON.parse(bodyText) as { cellId?: unknown };+ if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;+ }+ } catch {+ /* malformed JSON — let the CP reject with a proper 400 */+ }- const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.userID);+ const cell = await pickCell(env, org.home_cell, requestedCellID);+ if (!cell) {+ return json(+ requestedCellID+ ? { error: `cell ${requestedCellID} is not available` }+ : { error: "no cells available with capacity" },+ 503,+ );+ }- const bodyText = await req.text();+ const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.userID);let cpResp: Response;try {cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 45de2075..017ce5d2 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -125,8 +125,37 @@ export default {JSON.stringify(e.payload ?? {}),),);++ // cell_capacity events: UPSERT the cells row so the api-edge's pickCell()+ // cascade sees fresh placement metrics. Each event's payload carries the+ // CP's view at sample time; we just write it through. Idempotent — re-+ // applying the same event writes the same values. capacity_updated_at+ // gates freshness (edge ignores cells stale beyond ~120s).+ const capUpdate = env.OPENCOMPUTER_DB.prepare(+ `UPDATE cells SET healthy_workers = ?1, available_workers = ?2,+ running_sandboxes = ?3, capacity_updated_at = ?4+ WHERE cell_id = ?5`,+ );+ const nowSec = Math.floor(Date.now() / 1000);+ const capacityBatches = fresh+ .filter((e) => e.type === "cell_capacity")+ .map((e) => {+ const p = (e.payload ?? {}) as {+ healthy_workers?: number;+ available_workers?: number;+ running_sandboxes?: number;+ };+ return capUpdate.bind(+ p.healthy_workers ?? 0,+ p.available_workers ?? 0,+ p.running_sandboxes ?? 0,+ nowSec,+ e.cell_id,+ );+ });+try {- await env.OPENCOMPUTER_DB.batch(batches);+ await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches]);} catch (err) {// Database errors are retryable — return 5xx so the CP forwarder// leaves the batch in the PEL.diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sqlindex 10373da0..eed849a9 100644--- a/cloudflare-workers/schema.sql+++ b/cloudflare-workers/schema.sql@@ -111,6 +111,21 @@ CREATE TABLE IF NOT EXISTS cells (region TEXT NOT NULL,base_url TEXT NOT NULL, -- regional CP base URL (scheme+host[:port])status TEXT NOT NULL DEFAULT 'active', -- active | draining | down+ -- Capacity-aware placement (updated by cell_capacity events; see+ -- internal/controlplane/capacity_reporter.go + events-ingest worker).+ -- The CP aggregates per-worker memory pressure from WorkerEntry. A cell is+ -- placement-eligible iff available_workers > 0 AND capacity_updated_at is+ -- within the freshness window (~120s). NULL/stale capacity_updated_at ⇒ the+ -- reporting CP is dead, treat the cell as unhealthy regardless of `status`.+ --+ -- "available" = worker where committed_memory_mb/total_memory_mb < 85%.+ -- Single-worker-below-threshold is the right gate because a sandbox lands+ -- on one worker, not striped across workers — aggregating across the cell+ -- would wrongly skip a cell with 1 free worker and 9 loaded ones.+ healthy_workers INTEGER NOT NULL DEFAULT 0, -- alive workers in this cell+ available_workers INTEGER NOT NULL DEFAULT 0, -- workers under the mem threshold+ running_sandboxes INTEGER NOT NULL DEFAULT 0, -- observability only, not in placement+ capacity_updated_at INTEGER,created_at INTEGER NOT NULL);diff --git a/cmd/server/main.go b/cmd/server/main.goindex c2a431c4..435eb8c3 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -190,6 +190,22 @@ func main() {} else if cfg.Mode == "server" {log.Printf("opensandbox: CF event forwarder NOT started (CFEventEndpoint/Secret/CellID unset)")}++ // Capacity reporter — periodically pushes a cell_capacity event onto the+ // same events:{cell_id} stream the forwarder drains. Feeds the edge's+ // pickCell() cascade via D1. Inert when CellID is empty.+ if cfg.CellID != "" {+ cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{+ Redis: redisRegistry.RedisClient(),+ Registry: redisRegistry,+ CellID: cfg.CellID,+ })+ if err != nil {+ log.Fatalf("capacity_reporter: %v", err)+ }+ cr.Start(context.Background())+ defer cr.Stop()+ }}// Initialize compute pool + autoscaler (server mode)diff --git a/internal/controlplane/capacity_reporter.go b/internal/controlplane/capacity_reporter.gonew file mode 100644index 00000000..e0fc19a6--- /dev/null+++ b/internal/controlplane/capacity_reporter.go@@ -0,0 +1,186 @@+package controlplane++import (+ "context"+ "encoding/json"+ "errors"+ "log"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/redis/go-redis/v9"+)++// CapacityReporter periodically aggregates worker memory pressure from the+// local RedisWorkerRegistry and pushes a `cell_capacity` event onto the+// events:{cell_id} Redis stream — the same stream EventForwarder drains. The+// events-ingest Worker keys off type=="cell_capacity" to UPSERT the cell's+// row in D1 with healthy_workers / available_workers / running_sandboxes /+// capacity_updated_at, which the api-edge consults in its pickCell() cascade.+//+// "available" = worker whose CommittedMemoryMB / TotalMemoryMB is below the+// pressure threshold (~85%). Single-worker-below-threshold is the right+// placement gate because a sandbox lands on one worker — aggregating across+// the cell would wrongly skip a cell with 1 free worker and 9 loaded ones.+//+// Reuses the existing event pipe so there's no second transport, no new HMAC+// path, no new ingest endpoint. Cost: one extra event per cell per+// ReportInterval, opaque JSON bytes through the same forwarder.++const (+ memPressureThresholdPct = 85+ defaultReportInterval = 30 * time.Second+ // reporterStreamMaxLen caps the Redis stream so capacity events don't+ // accumulate if the forwarder is down. Sized small — only the most recent+ // sample matters for placement, older ones are stale anyway.+ reporterStreamMaxLen = 10_000+)++// capacityEnvelope mirrors worker.SandboxEventEnvelope on the wire. Defined+// locally to avoid an import of internal/worker from internal/controlplane;+// the forwarder treats stream entries as opaque JSON, so wire-format match is+// all that matters. JSON tags MUST match SandboxEventEnvelope; cross-check+// internal/worker/redis_event_publisher.go if either side changes.+type capacityEnvelope struct {+ ID string `json:"id"`+ Type string `json:"type"`+ SandboxID string `json:"sandbox_id"`+ CellID string `json:"cell_id"`+ WorkerID string `json:"worker_id"`+ Payload json.RawMessage `json:"payload"`+ Timestamp time.Time `json:"timestamp"`+}++type capacityPayload struct {+ HealthyWorkers int `json:"healthy_workers"`+ AvailableWorkers int `json:"available_workers"`+ RunningSandboxes int `json:"running_sandboxes"`+}++// CapacityReporter periodically XADDs cell_capacity events.+type CapacityReporter struct {+ rdb *redis.Client+ registry *RedisWorkerRegistry+ cellID string+ streamKey string+ interval time.Duration++ stopCh chan struct{}+ doneCh chan struct{}+ once sync.Once+}++// CapacityReporterConfig configures the reporter.+type CapacityReporterConfig struct {+ Redis *redis.Client+ Registry *RedisWorkerRegistry+ CellID string+ Interval time.Duration // default 30s+}++// NewCapacityReporter constructs a reporter. Returns an error if required+// fields are missing.+func NewCapacityReporter(cfg CapacityReporterConfig) (*CapacityReporter, error) {+ if cfg.Redis == nil {+ return nil, errors.New("capacity_reporter: Redis required")+ }+ if cfg.Registry == nil {+ return nil, errors.New("capacity_reporter: Registry required")+ }+ if cfg.CellID == "" {+ return nil, errors.New("capacity_reporter: CellID required")+ }+ iv := cfg.Interval+ if iv == 0 {+ iv = defaultReportInterval+ }+ return &CapacityReporter{+ rdb: cfg.Redis,+ registry: cfg.Registry,+ cellID: cfg.CellID,+ streamKey: "events:" + cfg.CellID,+ interval: iv,+ stopCh: make(chan struct{}),+ doneCh: make(chan struct{}),+ }, nil+}++// Start launches the report loop. Emits one sample immediately so D1 sees a+// fresh capacity_updated_at without waiting a full interval.+func (r *CapacityReporter) Start(ctx context.Context) {+ go r.runLoop(ctx)+ log.Printf("capacity_reporter: started (cell=%s interval=%s threshold=%d%%)",+ r.cellID, r.interval, memPressureThresholdPct)+}++// Stop signals the loop to exit and waits for it to finish.+func (r *CapacityReporter) Stop() {+ r.once.Do(func() { close(r.stopCh) })+ <-r.doneCh+}++func (r *CapacityReporter) runLoop(ctx context.Context) {+ defer close(r.doneCh)+ r.emit(ctx)+ t := time.NewTicker(r.interval)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-r.stopCh:+ return+ case <-t.C:+ r.emit(ctx)+ }+ }+}++func (r *CapacityReporter) emit(ctx context.Context) {+ workers := r.registry.GetAllWorkers()+ var healthy, available, running int+ for _, w := range workers {+ if w == nil || w.Draining {+ continue+ }+ healthy+++ running += w.Current+ if w.TotalMemoryMB > 0 && (w.CommittedMemoryMB*100)/w.TotalMemoryMB < memPressureThresholdPct {+ available+++ }+ }++ payload, err := json.Marshal(capacityPayload{+ HealthyWorkers: healthy,+ AvailableWorkers: available,+ RunningSandboxes: running,+ })+ if err != nil {+ log.Printf("capacity_reporter: marshal payload: %v", err)+ return+ }+ body, err := json.Marshal(capacityEnvelope{+ ID: uuid.NewString(),+ Type: "cell_capacity",+ CellID: r.cellID,+ Payload: payload,+ Timestamp: time.Now(),+ })+ if err != nil {+ log.Printf("capacity_reporter: marshal envelope: %v", err)+ return+ }++ xaddCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ if err := r.rdb.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: r.streamKey,+ MaxLen: reporterStreamMaxLen,+ Approx: true,+ Values: map[string]interface{}{"event": string(body)},+ }).Err(); err != nil {+ log.Printf("capacity_reporter: XADD failed: %v (cell=%s)", err, r.cellID)+ return+ }+}diff --git a/scripts/seed_dev_xcell.sh b/scripts/seed_dev_xcell.shindex e4e032d4..922c9d20 100755--- a/scripts/seed_dev_xcell.sh+++ b/scripts/seed_dev_xcell.sh@@ -17,6 +17,11 @@set -euo pipefail+# The CF account that owns `opencomputer-dev` (same as api-edge/wrangler.toml).+# wrangler can't pick between multiple accounts non-interactively, so pin it.+: "${CLOUDFLARE_ACCOUNT_ID:=1241f114453e32d292197e3fb36210b2}"+export CLOUDFLARE_ACCOUNT_ID+D1_DB="opencomputer-dev"DEV2_CP_URL="${1:?usage: seed_dev_xcell.sh <DEV2_CP_URL> [DEV3_CP_URL]}"DEV3_CP_URL="${2:-http://DEV3-CP-NOT-PROVISIONED-YET:8080}"