Spaces:
Running on Zero

openhands commited on
Commit
7711b55
·
1 Parent(s): ab658f8

fix(sandbox): reap dev servers, cap heap, expose rss_mb

Browse files
Files changed (2) hide show
  1. README.md +74 -26
  2. app.py +94 -6
README.md CHANGED
@@ -1,36 +1,84 @@
1
  ---
2
  title: EXELYN Sandbox
3
  emoji: 🧪
4
- colorFrom: purple
5
- colorTo: indigo
6
  sdk: gradio
 
7
  app_file: app.py
8
  pinned: false
9
- license: mit
10
  ---
11
 
12
  # EXELYN Sandbox Engine
13
 
14
- Server-side execution backend for [EXELYN AI](https://exelyn-ai.vercel.app): a
15
- 16 GB RAM Hugging Face Space that runs project files, shells and dev servers so
16
- the browser no longer has to boot WebContainers.
17
-
18
- ## Endpoints
19
-
20
- All `/api/*` routes require `Authorization: Bearer $SANDBOX_SECRET_KEY`.
21
-
22
- | Method | Path | Purpose |
23
- | --- | --- | --- |
24
- | GET | `/api/health` | Liveness, node version, active previews |
25
- | POST | `/api/files/list` | `{project_id, path?}` → entries |
26
- | POST | `/api/files/read` | `{project_id, path}` → `content` |
27
- | POST | `/api/files/write` | `{project_id, path, content}` |
28
- | POST | `/api/files/edit` | `{project_id, path, old_text, new_text, replace_all?}` |
29
- | POST | `/api/files/delete` | `{project_id, path}` |
30
- | POST | `/api/terminal/exec` | `{project_id, command, cwd?, timeout?}` → `{output, exit_code}` |
31
- | POST | `/api/preview/start` | `{project_id, force?}` → `{url, port}` |
32
- | POST | `/api/preview/stop` | `{project_id}` |
33
- | GET | `/preview/{project_id}/{path}` | Reverse proxy to the project dev server |
34
-
35
- Workspaces live in `/tmp/workspaces/{project_id}`; every path is resolved and
36
- checked against that root before it is touched.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: EXELYN Sandbox
3
  emoji: 🧪
4
+ colorFrom: indigo
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 6.32.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  # EXELYN Sandbox Engine
13
 
14
+ FastAPI workspace sandbox (files, shell, dev-server preview) served on port 7860
15
+ through Gradio, with bearer auth via `SANDBOX_SECRET_KEY`.
16
+
17
+ Set `SANDBOX_SECRET_KEY` as a Space secret; the Next.js app authenticates with it
18
+ and never exposes it to the browser.
19
+
20
+ ## Routing
21
+
22
+ The Gradio front proxy only forwards `/gradio_api/*` to the Python app, so the
23
+ same REST routes are mounted twice:
24
+
25
+ - `/api/*`, `/preview/*` — direct access (uvicorn, Docker, CPU Spaces)
26
+ - `/gradio_api/sandbox/api/*`, `/gradio_api/sandbox/preview/*` — behind Gradio
27
+
28
+ The Next.js proxy sets `HF_SANDBOX_PREFIX=/gradio_api/sandbox` for the second form.
29
+
30
+ ## Notes for ZeroGPU Spaces
31
+
32
+ Free accounts can only run Gradio Spaces on ZeroGPU hardware, which reports
33
+ roughly 2 GB of RAM and refuses to start without a module-level `@spaces.GPU`
34
+ function (`gpu_marker`). After pushing code the Space occasionally lands in
35
+ `RUNTIME_ERROR` with "No @spaces.GPU function detected"; a plain restart clears it.
36
+
37
+ ## Memory budget (measured, not estimated)
38
+
39
+ Measured on the repo's own Python 3.11 environment with `ru_maxrss`:
40
+
41
+ | State | RSS |
42
+ | --- | --- |
43
+ | bare interpreter | 7.9 MB |
44
+ | `fastapi` + `uvicorn` + `httpx` | 50.0 MB |
45
+ | `import gradio` | 127.7 MB |
46
+ | this `app.py` imported, no preview running | **134.5 MB** |
47
+
48
+ Gradio alone is ~128 MB because it pulls pandas (65.7 MB), numpy (24.7 MB) and
49
+ Pillow (12.5 MB) at import time. That is the floor of this process: no code in
50
+ `app.py` can go below it while the Space keeps `sdk: gradio`.
51
+
52
+ What this means for the RAM target:
53
+
54
+ - Idle with no preview: ~135-150 MB. The dev servers, not Python, were the
55
+ reason the Space sat at 356 MB.
56
+ - With one Next dev server running: add that process's RSS (not measured in this
57
+ repo; roughly 150-250 MB for `next dev`). The janitor and `kill_preview`
58
+ changes below are what keep this from accumulating per project.
59
+ - To go below ~134 MB this process would have to stop importing Gradio. It
60
+ cannot: the Space runs on `zero-a10g`, and ZeroGPU only accepts the Gradio
61
+ SDK (and refuses to start without a module-level `@spaces.GPU`). Getting lower
62
+ means a different Space on CPU hardware with `sdk: docker` + plain uvicorn,
63
+ which is a deployment decision, not a code change here.
64
+
65
+ ### What keeps the process small
66
+
67
+ - `kill_preview` signals the whole process group (SIGTERM, then SIGKILL after
68
+ `SANDBOX_PREVIEW_STOP_GRACE_S`) and reaps it. `npm run dev` spawns node as a
69
+ child, and killing only npm used to leave node running.
70
+ - `preview_janitor` stops any preview idle for `SANDBOX_PREVIEW_IDLE_S`
71
+ (default 600 s, swept every 60 s). Every status poll and proxied request
72
+ refreshes that timer.
73
+ - Dev servers run with `--max-old-space-size=512` so one project cannot grow a
74
+ multi-gigabyte heap.
75
+ - `GET /api/health` now returns `rss_mb`, `child_processes` and per-preview
76
+ `idle_s`, so the numbers above can be reproduced on the Space itself:
77
+
78
+ ```bash
79
+ curl -s -H "Authorization: Bearer $SANDBOX_SECRET_KEY" \
80
+ https://<space>.hf.space/api/health | jq '{rss_mb, child_processes, previews}'
81
+ ```
82
+
83
+ `MALLOC_ARENA_MAX=2` is worth setting in a Docker Space (glibc keeps one arena
84
+ per thread); it cannot be set from code for the Gradio SDK.
app.py CHANGED
@@ -51,6 +51,11 @@ MAX_FILE_BYTES = 5 * 1024 * 1024
51
  DEFAULT_EXEC_TIMEOUT = 120
52
  MAX_EXEC_TIMEOUT = 600
53
  PREVIEW_BOOT_TIMEOUT = float(os.environ.get("SANDBOX_PREVIEW_TIMEOUT", "240"))
 
 
 
 
 
54
  PROJECT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
55
 
56
  # ZeroGPU hardware refuses to start unless at least one GPU-decorated function
@@ -133,6 +138,13 @@ class PreviewState:
133
  self.process: subprocess.Popen[str] | None = None
134
  self.task: asyncio.Task[None] | None = None
135
  self.started_at = time.time()
 
 
 
 
 
 
 
136
 
137
  def running(self) -> bool:
138
  return self.state == "ready" and self.process is not None and self.process.poll() is None
@@ -147,6 +159,7 @@ class PreviewState:
147
  "url": self.url(),
148
  "error": self.error,
149
  "uptime_s": round(time.time() - self.started_at, 1),
 
150
  }
151
 
152
 
@@ -210,6 +223,8 @@ def spawn_dev_server(project_id: str, port: int) -> subprocess.Popen[str]:
210
  "NEXT_TELEMETRY_DISABLED": "1",
211
  "BROWSER": "none",
212
  "CI": "1",
 
 
213
  }
214
  return subprocess.Popen( # noqa: S603 - fixed argv, never a shell string
215
  dev_command(project_id, port),
@@ -222,21 +237,57 @@ def spawn_dev_server(project_id: str, port: int) -> subprocess.Popen[str]:
222
  )
223
 
224
 
 
 
 
 
 
 
 
 
 
 
225
  def kill_preview(project_id: str) -> bool:
 
 
226
  preview = PREVIEWS.pop(project_id, None)
227
  if not preview:
228
  return False
229
  if preview.task and not preview.task.done():
230
  preview.task.cancel()
231
- if preview.process and preview.process.poll() is None:
 
 
232
  try:
233
- os.killpg(os.getpgid(preview.process.pid), signal.SIGTERM)
234
- except (ProcessLookupError, PermissionError):
235
- preview.process.terminate()
 
 
 
 
 
 
236
  preview.state = "stopped"
237
  return True
238
 
239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  async def boot_preview(project_id: str, preview: PreviewState) -> None:
241
  """Installs dependencies (once) and starts the dev server without blocking a request."""
242
  root = workspace(project_id)
@@ -254,7 +305,7 @@ async def boot_preview(project_id: str, preview: PreviewState) -> None:
254
  preview.state = "installing"
255
  install = await run_in_threadpool(
256
  subprocess.run, # noqa: S603
257
- ["npm", "install", "--no-audit", "--no-fund"],
258
  cwd=str(root),
259
  capture_output=True,
260
  text=True,
@@ -499,6 +550,35 @@ def build_repo_map(root: Path) -> str:
499
  # --------------------------------------------------------------------------- #
500
  # API: health + filesystem
501
  # --------------------------------------------------------------------------- #
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  @app.get("/api/health")
503
  async def health(_: None = Depends(require_secret)) -> dict[str, Any]:
504
  node = subprocess.run(["node", "--version"], capture_output=True, text=True, check=False)
@@ -507,7 +587,12 @@ async def health(_: None = Depends(require_secret)) -> dict[str, Any]:
507
  "service": "exelyn-sandbox",
508
  "node": (node.stdout or "").strip() or None,
509
  "workspaces": len([p for p in WORKSPACE_ROOT.glob("*") if p.is_dir()]),
510
- "previews": {pid: {"port": item.port, "state": item.state} for pid, item in PREVIEWS.items()},
 
 
 
 
 
511
  "uptime_s": round(time.time() - STARTED_AT, 1),
512
  }
513
 
@@ -689,6 +774,7 @@ async def preview_start(payload: dict[str, Any], _: None = Depends(require_secre
689
  """Kicks off the boot in the background and returns immediately (no long request)."""
690
  project_id = str(require_field(payload, "project_id"))
691
  preview = start_preview(project_id, force=bool(payload.get("force")))
 
692
  return {"success": True, "project_id": project_id, **preview.as_dict()}
693
 
694
 
@@ -704,6 +790,7 @@ async def preview_status(payload: dict[str, Any], _: None = Depends(require_secr
704
  preview = PREVIEWS.get(project_id)
705
  if not preview:
706
  return {"success": True, "project_id": project_id, "state": "idle", "url": None, "port": None, "error": None}
 
707
  return {"success": True, "project_id": project_id, **preview.as_dict()}
708
 
709
 
@@ -750,6 +837,7 @@ async def preview_proxy(project_id: str, path: str, request: Request) -> Respons
750
  preview = PREVIEWS.get(project_id)
751
  if not preview or not preview.running() or preview.port is None:
752
  raise HTTPException(status_code=404, detail="Preview is not running for this project")
 
753
 
754
  prefix = request.headers.get("x-forwarded-prefix", "").rstrip("/")
755
  if not prefix:
 
51
  DEFAULT_EXEC_TIMEOUT = 120
52
  MAX_EXEC_TIMEOUT = 600
53
  PREVIEW_BOOT_TIMEOUT = float(os.environ.get("SANDBOX_PREVIEW_TIMEOUT", "240"))
54
+ # Idle dev servers are the main RAM cost here; 10 minutes matches the client's
55
+ # own idle teardown so a backgrounded tab does not keep node alive forever.
56
+ PREVIEW_IDLE_TIMEOUT_S = float(os.environ.get("SANDBOX_PREVIEW_IDLE_S", "600"))
57
+ PREVIEW_SWEEP_INTERVAL_S = float(os.environ.get("SANDBOX_PREVIEW_SWEEP_S", "60"))
58
+ PREVIEW_STOP_GRACE_S = float(os.environ.get("SANDBOX_PREVIEW_STOP_GRACE_S", "3"))
59
  PROJECT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
60
 
61
  # ZeroGPU hardware refuses to start unless at least one GPU-decorated function
 
138
  self.process: subprocess.Popen[str] | None = None
139
  self.task: asyncio.Task[None] | None = None
140
  self.started_at = time.time()
141
+ self.last_seen = time.time()
142
+
143
+ def touch(self) -> None:
144
+ self.last_seen = time.time()
145
+
146
+ def idle_seconds(self) -> float:
147
+ return round(time.time() - self.last_seen, 1)
148
 
149
  def running(self) -> bool:
150
  return self.state == "ready" and self.process is not None and self.process.poll() is None
 
159
  "url": self.url(),
160
  "error": self.error,
161
  "uptime_s": round(time.time() - self.started_at, 1),
162
+ "idle_s": self.idle_seconds(),
163
  }
164
 
165
 
 
223
  "NEXT_TELEMETRY_DISABLED": "1",
224
  "BROWSER": "none",
225
  "CI": "1",
226
+ # Without a cap a single dev server can grow the heap past 1 GB.
227
+ "NODE_OPTIONS": os.environ.get("NODE_OPTIONS", "--max-old-space-size=512"),
228
  }
229
  return subprocess.Popen( # noqa: S603 - fixed argv, never a shell string
230
  dev_command(project_id, port),
 
237
  )
238
 
239
 
240
+ def _signal_group(process: subprocess.Popen[str], sig: int) -> None:
241
+ try:
242
+ os.killpg(os.getpgid(process.pid), sig)
243
+ except (ProcessLookupError, PermissionError):
244
+ try:
245
+ process.send_signal(sig)
246
+ except (ProcessLookupError, OSError):
247
+ pass
248
+
249
+
250
  def kill_preview(project_id: str) -> bool:
251
+ """Stops the whole process group: `npm run dev` spawns node, and leaving it
252
+ behind kept 150-250 MB alive for every project the user ever opened."""
253
  preview = PREVIEWS.pop(project_id, None)
254
  if not preview:
255
  return False
256
  if preview.task and not preview.task.done():
257
  preview.task.cancel()
258
+ process = preview.process
259
+ if process and process.poll() is None:
260
+ _signal_group(process, signal.SIGTERM)
261
  try:
262
+ process.wait(timeout=PREVIEW_STOP_GRACE_S)
263
+ except subprocess.TimeoutExpired:
264
+ _signal_group(process, signal.SIGKILL)
265
+ try:
266
+ process.wait(timeout=5)
267
+ except subprocess.TimeoutExpired:
268
+ pass
269
+ except Exception: # noqa: BLE001 - best effort teardown
270
+ pass
271
  preview.state = "stopped"
272
  return True
273
 
274
 
275
+ async def preview_janitor() -> None:
276
+ """Reaps dev servers nobody is watching. Idle previews are the single
277
+ biggest RAM consumer in this Space, and nothing else ever stops them."""
278
+ while True:
279
+ await asyncio.sleep(PREVIEW_SWEEP_INTERVAL_S)
280
+ try:
281
+ for project_id, preview in list(PREVIEWS.items()):
282
+ if preview.state not in {"ready", "starting", "installing"}:
283
+ continue
284
+ if preview.idle_seconds() < PREVIEW_IDLE_TIMEOUT_S:
285
+ continue
286
+ kill_preview(project_id)
287
+ except Exception as error: # noqa: BLE001 - the janitor must never die
288
+ print(f"[preview-janitor] {error}", flush=True)
289
+
290
+
291
  async def boot_preview(project_id: str, preview: PreviewState) -> None:
292
  """Installs dependencies (once) and starts the dev server without blocking a request."""
293
  root = workspace(project_id)
 
305
  preview.state = "installing"
306
  install = await run_in_threadpool(
307
  subprocess.run, # noqa: S603
308
+ ["npm", "install", "--no-audit", "--no-fund", "--prefer-offline", "--loglevel=error"],
309
  cwd=str(root),
310
  capture_output=True,
311
  text=True,
 
550
  # --------------------------------------------------------------------------- #
551
  # API: health + filesystem
552
  # --------------------------------------------------------------------------- #
553
+ def read_rss_mb() -> float | None:
554
+ """Process RSS from /proc, so the Space metrics can be reproduced locally."""
555
+ try:
556
+ with open("/proc/self/status", encoding="utf-8") as handle:
557
+ for line in handle:
558
+ if line.startswith("VmRSS:"):
559
+ return round(int(line.split()[1]) / 1024, 1)
560
+ except OSError:
561
+ return None
562
+ return None
563
+
564
+
565
+ def child_process_count() -> int:
566
+ """Surviving node/npm processes: the leak this service must not have."""
567
+ try:
568
+ output = subprocess.run(
569
+ ["ps", "-eo", "ppid=,comm="], capture_output=True, text=True, check=False
570
+ ).stdout
571
+ except OSError:
572
+ return 0
573
+ me = os.getpid()
574
+ return sum(1 for line in output.splitlines() if line.split()[:1] == [str(me)])
575
+
576
+
577
+ @app.on_event("startup")
578
+ async def start_background_tasks() -> None:
579
+ asyncio.create_task(preview_janitor())
580
+
581
+
582
  @app.get("/api/health")
583
  async def health(_: None = Depends(require_secret)) -> dict[str, Any]:
584
  node = subprocess.run(["node", "--version"], capture_output=True, text=True, check=False)
 
587
  "service": "exelyn-sandbox",
588
  "node": (node.stdout or "").strip() or None,
589
  "workspaces": len([p for p in WORKSPACE_ROOT.glob("*") if p.is_dir()]),
590
+ "previews": {
591
+ pid: {"port": item.port, "state": item.state, "idle_s": item.idle_seconds()}
592
+ for pid, item in PREVIEWS.items()
593
+ },
594
+ "rss_mb": read_rss_mb(),
595
+ "child_processes": child_process_count(),
596
  "uptime_s": round(time.time() - STARTED_AT, 1),
597
  }
598
 
 
774
  """Kicks off the boot in the background and returns immediately (no long request)."""
775
  project_id = str(require_field(payload, "project_id"))
776
  preview = start_preview(project_id, force=bool(payload.get("force")))
777
+ preview.touch()
778
  return {"success": True, "project_id": project_id, **preview.as_dict()}
779
 
780
 
 
790
  preview = PREVIEWS.get(project_id)
791
  if not preview:
792
  return {"success": True, "project_id": project_id, "state": "idle", "url": None, "port": None, "error": None}
793
+ preview.touch()
794
  return {"success": True, "project_id": project_id, **preview.as_dict()}
795
 
796
 
 
837
  preview = PREVIEWS.get(project_id)
838
  if not preview or not preview.running() or preview.port is None:
839
  raise HTTPException(status_code=404, detail="Preview is not running for this project")
840
+ preview.touch()
841
 
842
  prefix = request.headers.get("x-forwarded-prefix", "").rstrip("/")
843
  if not prefix: