Skip to content

feat(sandbox): Sandbox page, scale-to-zero and capacity cap for the Kubernetes backend - #791

Open
thecorporatetractor wants to merge 6 commits into
BaaRai:mainfrom
thecorporatetractor:feat/sandbox-view-autoscaling
Open

thecorporatetractor wants to merge 6 commits into
BaaRai:mainfrom
thecorporatetractor:feat/sandbox-view-autoscaling

Conversation

@thecorporatetractor

Copy link
Copy Markdown
Contributor

Problem

With the Kubernetes backend and the chart, operators cannot see what the sandbox is doing: which tasks have pods, which scope each proxy enforces, what egress was allowed or refused. Every task also keeps its two pods until it is deleted, so an idle task holds node resources forever and nothing bounds how many tasks run at once.

Change

Runner status API and panel overview (feat(sandbox): read-only task status ...):

  • Runner: GET /v1/tasks (same bearer auth), for the Kubernetes backend (one label-selected pod list) and the Docker backend (list + inspect). sandbox.Client.Tasks().
  • Panel: GET /api/sandbox/overview: sandbox mode, runner health, the runner's task list, and per task a bounded tail of the egress audit log. Audit reads go through os.Root, refuse symlinks and cap bytes, line length and entries. The panel still talks to the cluster only through the runner.
  • ValidateTaskID no longer trims: " 42" was accepted and became a different task from "42".

Kubernetes scaling (feat(sandbox): scale-to-zero, capacity cap and placement ...):

  • Idle scale-to-zero after sandbox.scaling.idleTimeout (ARTEX_KUBE_IDLE_TIMEOUT, default 15m). Pods are deleted; Service, NetworkPolicies and workspace stay. The next command starts the pods again through the normal readiness and network checks.
  • Capacity cap sandbox.scaling.maxActive (ARTEX_KUBE_MAX_ACTIVE, default 10): the least recently used idle task is scaled to zero, otherwise the command waits in FIFO order for queueTimeout and fails with HTTP 429 sandbox at capacity (the panel does not pause the task).
  • Slot accounting: a deleted task holds its slot until its pods are gone. A start that fails after creating pods deletes them, frees the slot and records scale_up_failed.
  • Cluster autoscaler: a task pod still Unschedulable at sandbox.podReadyTimeout fails with 429 instead of 500. Its pods and slot are kept, and the next command reuses pending or ready pods instead of recreating them. Without a retry, the idle reaper removes them, and for a start that never succeeded also its Service and policies.
  • Status: per-task scaling state, health, scope_known / scope_source (live or last_applied from the proxy NetworkPolicy of a task scaled to zero), a summary, the last 100 scale events, totals, cold start p50/p95.
  • With ARTEX_KUBE_STATE_DIR (chart: runner-state on the data volume) events, totals and cold-start samples survive a runner restart (scaling.json, versioned, atomic, debounced). The overview honours ARTEX_AUDIT_ROOT.
  • Chart: sandbox.scaling.*, worker CPU/memory requests, sandbox.nodeSelector / tolerations / priorityClassName, PostgreSQL nodeSelector / tolerations, podAnnotations for panel, runner and PostgreSQL (values always quoted).
  • scripts/capd-autoscaler-e2e.sh: the official cluster-autoscaler on a Cluster API (CAPD) cluster with Calico and NFS. The chart README documents the measured timings and recommended values.

Sandbox page (feat(web): Sandbox page under System):

  • System > Sandbox: graph view (xyflow, pan/zoom, live links, a Blocked node for refused egress, dimmed scaled-to-zero tasks) and a list view (operator tables for tasks and egress destinations; what phones get). Every node and row opens a details drawer. Scaling section: capacity against the cap, cold start p50/p95, idle countdowns, scale event timeline. Works with the Docker backend and with a runner that is down.
  • Logic in lib/sandbox-topology.ts with node tests (test:sandbox-topology, added to CI). Mock data for Kubernetes, Docker, and ?tasks=N for a crowded graph.
  • Translations for tr, vi, zh-CN and pt-BR.

App shell a11y (fix(web): name the app shell's icon buttons ...): an axe-core audit of the page found violations only in the shared shell (unnamed preferences button, account trigger as a span with aria-expanded, redundant logo alt, sidebar outside a landmark). Fixed; the page has no axe violations.

Depends on

Depends on #783 (Helm chart), which depends on #780. The diff includes their commits until they merge. Review the last 4 commits.

Tests

Run on this branch before the last rebase onto the updated chart PR. The rebase changed nothing in this PR's own diff except the CHANGELOG context; after it, go build ./..., go vet ./..., gofmt, and go test -p 1 ./sandbox ./server ./db ./cmd/... with PostgreSQL were rerun and pass (the new base brings #775 and #779 in server/db).

  • go build ./..., go vet ./..., gofmt clean, cross-builds for darwin/arm64, darwin/amd64, windows/amd64: OK.
  • go test -race -count=1 ./sandbox ./server ./cmd/...: all OK.
  • go test -p 1 ./... against a throwaway PostgreSQL 16 container: 25 packages OK, 0 failures.
  • Web, as in CI: biome ci, tsc --noEmit, all 18 test:* scripts (including the new test:sandbox-topology, 46 tests, and test:i18n with pt-BR), build:static: all pass.
  • helm lint --strict, chart render tests (placement values, scaling values, runner-state mount), shellcheck -S warning on scripts/k3d-e2e.sh and scripts/capd-autoscaler-e2e.sh: clean.
  • Unit tests for the scaling logic run against a fake API server, including under -race: FIFO queue, eviction, cap never exceeded under churn, Delete holding its slot until the pods are gone, every failed-start mode releasing its slot, persisted state. A mutation check of the scaling code (27 mutations, go test -race -count=2): 21 killed, 5 survive (late in-flight count, evicting busy or starting tasks, a brief slot release in Delete, a Delete that won the task lock), 1 no longer applies.
  • New test for the combined behaviour of the autoscaler fixes and the slot accounting: TestKubeCapacityFailureKeepsPendingPodsAndSlot (pods still unschedulable at the ready timeout keep their slot; the retry reuses them; the reaper removes an abandoned first start with its Service and policies; a queued task can evict them; Delete frees the slot once the pods are gone). TestKubeRetryKeepsPendingPods and TestKubeFailedStartCleanupFailureKeepsSlot cover the rest.
  • Live on a new k3d cluster, images built from this branch:
    • RUNNER_ONLY=1 ARTEX_E2E_INTERNET=1 scripts/k3d-e2e.sh: TestKubeSandboxE2E passed, 12/12 subtests in 142 s. Scaled to zero 33 s after the last command (idle timeout 30 s), resume cold start 3.6 s, queued exec waited 12.1 s for a slot at maxActive=2.
    • Full mode (with the panel): helm test Succeeded, isolation self-test passed, TestKubeSandboxE2E 12/12 in 140 s. runner-state/scaling.json was written on the data volume.
  • Earlier live runs (evidence files from the branch before the history rewrite):
    • Runner restart on k3d: scale events, totals and cold-start samples identical before and after kubectl rollout restart (state-persist-across-runner-restart.txt).
    • Docker backend GET /v1/tasks (docker-v1-tasks.json): scaling reported as unsupported.
    • Cluster autoscaler on Cluster API (CAPD, Kubernetes v1.36.4, cluster-autoscaler v1.36.2, Calico, NFS RWX), scripts/capd-autoscaler-e2e.sh: helm test and TestKubeSandboxE2E 12/12 on Calico; a burst of 6 tasks scaled a tainted task pool from 0 to 3 nodes, 6/6 commands ran (cold start p50 111.6 s, p95 113.1 s); task pods gone 63 s after the burst (idle timeout 60 s), pool back to 0 machines after 186 s; resume from a zero-node pool kept the workspace and isolation (106 s); with ReadWriteOnce the autoscaler did not scale up and 3 of 5 commands got HTTP 429. A task scaled to zero reports its last-applied scope after a runner restart. These runs used the runner before the slot-accounting merge; the merged behaviour for unschedulable pods (pods and slot kept, retry reuses them) is the one those runs exercised.

Screenshots

Kubernetes, graph view:

graph light
graph dark

List view:

list light
list dark
list expanded

Scaling section and details drawer:

scaling
drawer

Phone:

mobile dark

Docker backend:

docker graph
docker list

Runner down:

runner down

Notes

  • The Docker backend's DELETE /v1/tasks/{id} still answers 500 on main because the worker container stays attached to the task network. This PR does not include a fix: fix(sandbox): remove the worker container in Delete #778 (and fix(sandbox): remove workers on failed execs and task deletion #764) fix it.
  • sidequestion has a pre-existing flaky test that also fails on main; it is not touched here.
  • The runner stays a single replica (single writer of task pods). Live scaling state is rebuilt from the cluster on restart; only history is persisted.
  • With a ReadWriteOnce data volume every task pod is pinned to the runner's node, so a cluster autoscaler cannot help. Use ReadWriteMany on autoscaled clusters (documented).

Part of #781.

ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own
egress-proxy pod, created through the Kubernetes API with no container runtime
socket. Per-task NetworkPolicies are applied before the pods and removed after
them; the runner waits until they are in effect before the first command, runs
commands through pods/exec under env -i and artex-exec-wrap, and re-adopts task
pods after a restart. Unit tests run against a fake API server; a live test
(TestKubeSandboxE2E) drives a deployed runner.
deploy/helm/artex deploys the panel, PostgreSQL and artex-runner with a
namespace-scoped Role, default-deny NetworkPolicies and a values schema. A
volume-permissions init container restores root ownership of /app/data and
/app/keys, fixing the isolation self-test failure on world-writable volumes
(BaaRai#620). scripts/k3d-e2e.sh and the kubernetes CI job test it live on k3d.
…ew API

The runner gains GET /v1/tasks (same bearer auth) backed by an optional
StatusReporter interface, implemented for the Kubernetes backend (one
label-selected pod list) and the Docker backend (list + inspect).
sandbox.Client gains Tasks().

The panel exposes GET /api/sandbox/overview: sandbox mode, runner health,
the runner task list, and per task a bounded tail of the egress audit log.
Audit reads go through os.Root, refuse symlinked task directories and log
files, and cap the bytes, line length and entry count. The panel still
talks to the cluster only through the runner.

ValidateTaskID no longer trims: " 42" was accepted by the runner and became
a different task from "42". Ids are checked as given; the runner answers 400
and the client refuses before sending.
…rnetes backend

The runner scales an idle task to zero after ARTEX_KUBE_IDLE_TIMEOUT: its
worker and proxy pods are deleted, the proxy Service, NetworkPolicies and
workspace stay, and the next command starts the pods again. ARTEX_KUBE_MAX_ACTIVE
caps the tasks with pods: at the cap the least recently used idle task is
scaled to zero, otherwise the command waits in arrival order for
ARTEX_KUBE_QUEUE_TIMEOUT and fails with 429 sandbox at capacity.

Capacity slots: a deleted task holds its slot until its pods are gone, and a
start that fails after creating pods deletes them, frees the slot and records
a scale_up_failed event. A pod still unschedulable at the ready timeout (a
cluster autoscaler adding a node) fails with ErrCapacity (429, the task is not
paused) and keeps its pods and slot; the next command reuses pending or ready
pods instead of recreating them. If no command comes, the idle reaper removes
the pods, and for a start that never succeeded also its Service and policies.

GET /v1/tasks and /api/sandbox/overview report per-task scaling state, health,
the scope last applied to the proxy NetworkPolicy for tasks scaled to zero
(scope_known, scope_source), a summary, the last 100 scale events, totals and
cold start p50/p95. With ARTEX_KUBE_STATE_DIR (chart: runner-state on the data
volume) events, totals and cold-start samples survive a runner restart. The
overview honours ARTEX_AUDIT_ROOT.

Chart: sandbox.scaling.*, worker requests, sandbox.nodeSelector, tolerations,
priorityClassName, postgres nodeSelector/tolerations and podAnnotations.
scripts/capd-autoscaler-e2e.sh tests the official cluster-autoscaler on a
Cluster API (CAPD) cluster; the chart README documents the measured timings
and recommended values.
System > Sandbox shows the panel, the runner, each task with its worker and
egress proxy, and the internet, from /api/sandbox/overview every 3 s. The
graph view (xyflow) can be panned and zoomed; links move while a command runs
or traffic passes, refused egress goes to a Blocked node, and scaled-to-zero
tasks are dimmed. The list view is an operator table with per-task health,
scope, policies and recent egress, and is what phones get. Every node and row
opens a details drawer. The Scaling section shows capacity against the cap,
cold start p50/p95 and trend, per-task idle countdowns and the scale event
timeline. The page also fits the Docker backend (which does not scale) and a
runner that is down.

The topology and summary logic lives in lib/sandbox-topology.ts with node
tests (test:sandbox-topology, added to CI). The mock backend serves Kubernetes
and Docker overviews, and ?tasks=N for a crowded graph. Strings are
translated for tr, vi, zh-CN and pt-BR.
… tech

An axe-core audit of System > Sandbox (graph and list, light and dark)
found its only violations in the shared shell: the preferences button had
no accessible name, the account menu trigger was a span carrying
aria-expanded (not allowed on it) without a name, the sidebar logo's alt
repeated the product name next to it, and the sidebar content sat outside
any landmark. The trigger is now a named button, the settings button is
labelled Preferences, the logo is decorative, and the sidebar is a named
navigation landmark. The page now has no axe violations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant