Skip to content

Commit f0df3cc

Browse files
authored
improvement(sandbox): warm capacity, startup timings, and clearer capacity errors for Kubernetes sandboxes (#10724)
* improvement(sandbox): warm capacity, startup timings, and clearer capacity errors for Kubernetes sandboxes * fix(sandbox): count startup timings from the first create request * fix(sandbox): time the running step from the sandbox container's own state
1 parent 4a0c73d commit f0df3cc

14 files changed

Lines changed: 396 additions & 15 deletions

File tree

‎apps/docs/content/docs/platform/self-hosting/sandboxes.mdx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ A kind with no image fails closed with a configuration error. The Chat code-tool
357357

358358
Each sandbox gets the limits in `sandbox.kubernetes.resources` (1 CPU, 2 GiB memory, and 4 GiB ephemeral storage by default), and requests at half of each. The same values become the sandbox namespace's LimitRange maximum, so no container there can ask for more.
359359

360-
The ResourceQuota caps concurrent sandboxes at `quota.pods` (20 by default) and their total limits at `quota.cpu`, `quota.memory`, and `quota.ephemeralStorage`. A sandbox started past the quota fails with a provider-limit error instead of waiting. Size the quota and the sandbox nodes together: nodes that cannot fit the quota leave sandboxes pending until their start times out.
360+
The ResourceQuota caps concurrent sandboxes at `quota.pods` (20 by default) and their total limits at `quota.cpu`, `quota.memory`, and `quota.ephemeralStorage`. It counts each sandbox's limits, not its requests, so the defaults admit exactly 20 sandboxes on every dimension (20 × 1 CPU, 2 GiB, and 4 GiB). Raising `sandbox.kubernetes.resources` without raising the matching quota lowers that count: with `resources.cpu: "2"`, the CPU quota stops at 10 sandboxes. Set each quota to `quota.pods` times the matching resource. A RuntimeClass `overhead` (VM runtimes have one) counts against the quota too, so add it to each sandbox's share. Session sandboxes (chat workbenches and Pi) hold their share until they expire. A sandbox started past the quota fails at once with a "Sandbox limit reached" error instead of waiting. Size the quota and the sandbox nodes together: nodes that cannot fit the quota leave sandboxes pending until their start times out.
361361

362362
Sim records no sandbox cost for this provider: you pay for the nodes. Set the kubelet's `podPidsLimit` on sandbox nodes (for example `4096`): the memory limit does not bound processes, so a fork bomb in user code otherwise exhausts the node's PIDs for every pod on it ([Kubernetes: Process ID limits](https://kubernetes.io/docs/concepts/policy/pid-limiting/)). Per-platform density:
363363

@@ -371,6 +371,18 @@ A sandbox's start time is dominated by the first image pull on its node. `sandbo
371371

372372
On VM runtimes the image is loaded into each pod's VM at start (an EKS Nitro Sandbox runs its own containerd inside the guest), so measure how much pre-pulling helps on your platform before relying on it.
373373

374+
Each sandbox that starts logs one `Kubernetes sandbox pod ready` line with, in milliseconds from the create request, when each step was reached: the request accepted (`acceptedMs`), the pod scheduled to a node (`scheduledMs`), its agent copied in (`initializedMs`), the container running (`runningMs`), and the agent answering (`agentMs`). A sandbox that does not start logs `Kubernetes sandbox pod did not start` with the steps it reached. Use them to see where your start time goes before tuning anything.
375+
376+
### Warm capacity
377+
378+
When no sandbox node has room, a sandbox waits for your node autoscaler to add one, about 2 minutes on EKS Auto Mode, and may run into its 3-minute start deadline. `sandbox.kubernetes.warmCapacity.sandboxes: N` keeps room for N sandboxes free. The chart runs N placeholder pods in the release namespace at priority -10. Each one has a sandbox pod's requests and limits, and runs under the sandbox RuntimeClass (so its overhead is reserved too) with the same node selector and tolerations. When a sandbox needs the room, the scheduler evicts a placeholder and the sandbox starts on a running node. The evicted placeholder goes pending, and your autoscaler adds the next node in the background. This is the standard [cluster-autoscaler overprovisioning](https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md#how-can-i-configure-overprovisioning-with-cluster-autoscaler) pattern, and it works with cluster-autoscaler, Karpenter, EKS Auto Mode, and GKE.
379+
380+
- You pay for N idle sandbox slots. Under a VM runtime each placeholder is an idle VM, and on GKE Autopilot the placeholders are billed.
381+
- The placeholders run outside the sandbox namespace, so they never count against `quota`. The chart refuses more room than `quota.pods`, which could never be used.
382+
- Sandbox pods set no priority class, so they run at 0 and preempt the placeholders. A cluster whose default PriorityClass (`globalDefault: true`) is -10 or lower defeats this.
383+
- Any pod at default priority can take the room. Give sandboxes dedicated nodes (`nodeSelector` and `tolerations`) so the room stays theirs.
384+
- A placeholder holds room, not the image. The first sandbox on a newly added node still pulls the Function image unless `prePull` is on, and on VM runtimes the image also loads into each pod's VM at start, so measure the gain on your platform.
385+
374386
### Amazon EKS Auto Mode
375387

376388
What Sim's sandboxes need on EKS Auto Mode with Nitro Sandboxes (`runtimeClass.preset: isolated-sandbox`), beyond the chart:
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { findCause } from '@sim/utils/errors'
2+
3+
/**
4+
* The provider could not start a sandbox in time: a quota is spent, the API server is throttling,
5+
* or the sandbox could not be scheduled, pulled, or reached before its deadline. Its message says
6+
* which, so callers report it as is rather than as a crash; a later attempt may succeed.
7+
*/
8+
export class SandboxCapacityError extends Error {
9+
constructor(message: string, options?: ErrorOptions) {
10+
super(message, options)
11+
this.name = 'SandboxCapacityError'
12+
}
13+
}
14+
15+
/** The {@link SandboxCapacityError} that `error` is or was caused by, if any. */
16+
export function findSandboxCapacityError(error: unknown): SandboxCapacityError | undefined {
17+
return findCause(
18+
error,
19+
(cause): cause is SandboxCapacityError => cause instanceof SandboxCapacityError
20+
)
21+
}

‎apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import { isRecordLike, toRecord } from '@sim/utils/object'
33
import { NonRetryableExecutionError } from '@/lib/execution/non-retryable-error'
4+
import { SandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error'
45

56
/** Kubernetes sandbox provider docs, named in every configuration error. */
67
const KUBERNETES_SANDBOX_DOCS_URL =
78
'https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party'
9+
/** How sandbox concurrency is sized, named when the namespace's quota is spent. */
10+
const KUBERNETES_SANDBOX_CAPACITY_DOCS_URL =
11+
'https://docs.sim.ai/platform/self-hosting/sandboxes#capacity-and-cost'
812

913
/**
1014
* The deployment is configured in a way no retry can fix: an unset or non-isolating RuntimeClass,
@@ -23,7 +27,7 @@ export class KubernetesSandboxConfigError extends NonRetryableExecutionError {
2327
* the API server is throttling, or no node could run the pod before the create deadline. Unlike a
2428
* configuration error, a later attempt may succeed.
2529
*/
26-
export class KubernetesSandboxCapacityError extends Error {
30+
export class KubernetesSandboxCapacityError extends SandboxCapacityError {
2731
constructor(message: string, options?: ErrorOptions) {
2832
super(message, options)
2933
this.name = 'KubernetesSandboxCapacityError'
@@ -100,7 +104,7 @@ export function isRetryableKubernetesFailure(failure: KubernetesApiFailure): boo
100104
export function toPodCreateError(failure: KubernetesApiFailure, namespace: string): Error {
101105
if (failure.status === 403 && /exceeded quota/i.test(failure.message)) {
102106
return new KubernetesSandboxCapacityError(
103-
`The Kubernetes sandbox namespace "${namespace}" has reached its ResourceQuota, so no new sandbox can start until running ones finish. Raise the quota or lower concurrent sandbox use. Cluster detail: ${failure.message}`
107+
`Sandbox limit reached: the Kubernetes sandbox namespace "${namespace}" has used its ResourceQuota, so no new sandbox can start until running ones finish. Raise sandbox.kubernetes.quota (pods, cpu, memory, ephemeralStorage) in the Helm values, or the namespace's ResourceQuota directly, or run fewer sandboxes at once. See ${KUBERNETES_SANDBOX_CAPACITY_DOCS_URL}. Cluster detail: ${failure.message}`
104108
)
105109
}
106110
if (failure.status === 429) {

‎apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,8 @@ export function createKubernetesSandboxProvider(): SandboxProvider {
170170
await guard.assertIsolated(deadline)
171171

172172
const sessionLabel = options?.sessionKey ? sessionLabelValue(options.sessionKey) : undefined
173-
logger.info('Creating Kubernetes sandbox pod', { kind, image, namespace: settings.namespace })
174173
options?.onProviderRequestStarted?.(requestedAtMs)
174+
const createStartedAt = performance.now()
175175
const created = await createPod(
176176
cluster,
177177
settings,
@@ -187,8 +187,24 @@ export function createKubernetesSandboxProvider(): SandboxProvider {
187187
}),
188188
deadline
189189
)
190+
const acceptedMs = Math.round(performance.now() - createStartedAt)
190191
try {
191-
const ready = await waitUntilReady(cluster, created, kind, settings, deadline)
192+
const { timings, ...ready } = await waitUntilReady(
193+
cluster,
194+
created,
195+
kind,
196+
settings,
197+
deadline,
198+
createStartedAt
199+
)
200+
logger.info('Kubernetes sandbox pod ready', {
201+
name: created.name,
202+
kind,
203+
image,
204+
namespace: settings.namespace,
205+
acceptedMs,
206+
...timings,
207+
})
192208
return connect(
193209
cluster,
194210
{ ...ready, name: created.name, token: created.token },

‎apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ const MAX_CREATE_ATTEMPTS = 3
3939
const CREATE_BACKOFF = { baseMs: 500, maxMs: 5_000 }
4040
/** Pause before re-watching a pod whose watch ended without news; an API outage must not spin. */
4141
const WATCH_BACKOFF = { baseMs: 250, maxMs: 5_000 }
42-
const HEALTH_BACKOFF = { baseMs: 100, maxMs: 1_000 }
42+
/** Short and capped low: the agent listens within moments of its container starting. */
43+
const HEALTH_BACKOFF = { baseMs: 50, maxMs: 250 }
4344
const HEALTH_REQUEST_TIMEOUT_MS = 2_000
4445

4546
/** Names what could stand between Sim and a pod's agent, for errors about an unreachable one. */
@@ -91,6 +92,14 @@ type PodProgress =
9192
| { state: 'pending'; detail?: string; pullError?: string }
9293
| { state: 'failed'; error: Error }
9394

95+
function isSandboxContainerRunning(pod: V1Pod): boolean {
96+
return Boolean(
97+
pod.status?.containerStatuses?.some(
98+
(status) => status.name === SANDBOX_CONTAINER_NAME && status.state?.running
99+
)
100+
)
101+
}
102+
94103
/**
95104
* Where a starting pod stands. `failed` when it can no longer become ready: it finished, is being
96105
* deleted, or a container is stuck on a problem no retry fixes. A transient pull failure stays
@@ -136,11 +145,9 @@ function podProgress(pod: V1Pod, kind: SandboxKind): PodProgress {
136145
pullError = `${waiting.reason} for ${variable}: ${message}`
137146
}
138147
}
139-
const sandboxRunning = pod.status?.containerStatuses?.some(
140-
(status) => status.name === SANDBOX_CONTAINER_NAME && status.state?.running
141-
)
142148
const baseUrl = agentBaseUrl(pod)
143-
if (phase === 'Running' && sandboxRunning && baseUrl) return { state: 'ready', baseUrl }
149+
if (phase === 'Running' && isSandboxContainerRunning(pod) && baseUrl)
150+
return { state: 'ready', baseUrl }
144151
const unscheduled = pod.status?.conditions?.find(
145152
(condition) => condition.type === 'PodScheduled' && condition.status === 'False'
146153
)
@@ -156,6 +163,18 @@ function missingRuntimeHandler(events: readonly CoreV1Event[]): CoreV1Event | un
156163
)
157164
}
158165

166+
/**
167+
* Milliseconds from the first create request to when Sim first saw each startup step: the pod
168+
* scheduled to a node, its init container done, the sandbox container running, and its agent
169+
* answering. Pod timestamps have one-second resolution, too coarse for this.
170+
*/
171+
interface PodStartupTimings {
172+
scheduledMs?: number
173+
initializedMs?: number
174+
runningMs?: number
175+
agentMs?: number
176+
}
177+
159178
/** Polls the agent's `/healthz` until it answers as a compatible agent or `signal` aborts. */
160179
export async function waitForAgent(client: SandboxAgentClient, signal: AbortSignal): Promise<void> {
161180
for (let attempt = 1; ; attempt++) {
@@ -245,20 +264,31 @@ export async function createPod(
245264
* A watch that ends without news is re-read and re-watched after a back-off, so an API server
246265
* that refuses or drops watches is never hammered. After each re-read of a scheduled pod, its
247266
* events are checked for a node that has no runtime for the RuntimeClass, which never clears.
267+
* `startedAt` is the `performance.now()` of the first create request, which the timings count from.
248268
*/
249269
export async function waitUntilReady(
250270
cluster: SandboxCluster,
251271
created: { pod: V1Pod; name: string; token: string },
252272
kind: SandboxKind,
253273
settings: KubernetesSandboxSettings,
254-
signal: AbortSignal
255-
): Promise<{ pod: V1Pod; baseUrl: string }> {
274+
signal: AbortSignal,
275+
startedAt: number
276+
): Promise<{ pod: V1Pod; baseUrl: string; timings: PodStartupTimings }> {
256277
const { name } = created
257278
let pod = created.pod
258279
let detail: string | undefined
259280
let pullError: string | undefined
281+
const timings: PodStartupTimings = {}
282+
const mark = (step: keyof PodStartupTimings) => {
283+
timings[step] ??= Math.round(performance.now() - startedAt)
284+
}
260285
const observe = (update: V1Pod): PodProgress => {
261286
pod = update
287+
if (update.spec?.nodeName) mark('scheduledMs')
288+
if (update.status?.conditions?.some((c) => c.type === 'Initialized' && c.status === 'True')) {
289+
mark('initializedMs')
290+
}
291+
if (isSandboxContainerRunning(update)) mark('runningMs')
262292
const progress = podProgress(update, kind)
263293
if (progress.state === 'pending') {
264294
detail = progress.detail
@@ -272,7 +302,8 @@ export async function waitUntilReady(
272302
if (progress.state === 'failed') throw progress.error
273303
if (progress.state === 'ready') {
274304
await waitForAgent(new SandboxAgentClient(progress.baseUrl, created.token), signal)
275-
return { pod, baseUrl: progress.baseUrl }
305+
mark('agentMs')
306+
return { pod, baseUrl: progress.baseUrl, timings }
276307
}
277308
const end = await cluster.watchPod(
278309
name,
@@ -302,6 +333,7 @@ export async function waitUntilReady(
302333
}
303334
}
304335
} catch (error) {
336+
logger.warn('Kubernetes sandbox pod did not start', { name, ...timings })
305337
if (!signal.aborted) throw error
306338
const reached = agentBaseUrl(pod)
307339
throw new KubernetesSandboxCapacityError(

‎apps/sim/lib/function-execution/execute-request.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
PRIVATE_SECRET_PROVENANCE_FIELD,
3535
PRIVATE_SECRET_PROVENANCE_HEADER,
3636
} from '@/lib/execution/private-tool-metadata'
37+
import { KubernetesSandboxCapacityError } from '@/lib/execution/remote-sandbox/kubernetes/errors'
3738
import {
3839
attachTrustedSandboxOutputCost,
3940
MAX_SANDBOX_OUTPUT_BYTES,
@@ -1541,6 +1542,25 @@ describe('Function execution request', () => {
15411542
expect(mockWriteWorkspaceFileByPath).not.toHaveBeenCalled()
15421543
})
15431544

1545+
it('reports a sandbox that found no capacity as is, not as a crash', async () => {
1546+
envFlagsMock.isRemoteSandboxEnabled = true
1547+
const message =
1548+
'Sandbox pod sim-sbx-a did not start before its create deadline (Unschedulable). The cluster may be out of capacity for sandboxes.'
1549+
mockExecuteInSandbox.mockRejectedValueOnce(new KubernetesSandboxCapacityError(message))
1550+
1551+
const response = await POST(
1552+
createMockRequest('POST', {
1553+
code: 'print("done")',
1554+
language: 'python',
1555+
workspaceId: 'workspace-1',
1556+
})
1557+
)
1558+
const data = await response.json()
1559+
1560+
expect(response.status).toBe(503)
1561+
expect(data.error).toBe(message)
1562+
})
1563+
15441564
it('rejects non-regular sandbox output paths as a client error', async () => {
15451565
envFlagsMock.isRemoteSandboxEnabled = true
15461566
mockExecuteInSandbox.mockRejectedValueOnce(new SandboxOutputFileError('/out/link.json'))

‎apps/sim/lib/function-execution/execute-request.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import {
8282
executeShellInSandbox,
8383
SIM_RESULT_PREFIX,
8484
} from '@/lib/execution/remote-sandbox'
85+
import { findSandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error'
8586
import { isBinarySandboxPath } from '@/lib/execution/remote-sandbox/encoding'
8687
import { sandboxSessionInputProvenance } from '@/lib/execution/remote-sandbox/observer'
8788
import {
@@ -3529,6 +3530,23 @@ export async function executeFunctionRequest(
35293530
)
35303531
}
35313532

3533+
// Reported as is: the crash heuristic below would read its "deadline" as an OOM or time-limit kill.
3534+
const capacityError = findSandboxCapacityError(error)
3535+
if (capacityError) {
3536+
const capacityResponse = {
3537+
success: false,
3538+
error: capacityError.message,
3539+
output: { result: null, stdout: cleanStdout(stdout), executionTime },
3540+
}
3541+
return routeContext
3542+
? functionJsonResponse(capacityResponse, routeContext, { status: 503 })
3543+
: appendPrivateResolvedSecretNames(
3544+
NextResponse.json(capacityResponse, { status: 503 }),
3545+
includePrivateResolvedSecretNames ? [] : null,
3546+
privateResolvedSecretNamesMetadataType
3547+
)
3548+
}
3549+
35323550
if (isLikelySandboxKill(error)) {
35333551
const underlying = scrubInternalIdentifiers(
35343552
(error?.message || String(error)).slice(0, 300),

‎helm/sim/Chart.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ apiVersion: v2
22
name: sim
33
description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents
44
type: application
5-
version: 1.17.1
5+
version: 1.18.0
66
appVersion: "v0.8.26"
77
kubeVersion: ">=1.25.0-0"
88
home: https://sim.ai

‎helm/sim/ci/sandbox-kubernetes-values.yaml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# CI-only values: the Kubernetes sandbox provider with every optional object it
22
# renders (created RuntimeClass, quota, LimitRange, admission policy, pre-pull
3-
# DaemonSet) plus the app NetworkPolicy, so lint and kubeconform cover them.
3+
# DaemonSet, warm-capacity placeholders) plus the app NetworkPolicy, so lint and
4+
# kubeconform cover them.
45
# Standalone, because ct lint renders each ci/*-values.yaml file on its own. Dummy
56
# values — never use in a deployment.
67
app:
@@ -37,3 +38,5 @@ sandbox:
3738
- "198.18.0.0/15"
3839
prePull:
3940
enabled: true
41+
warmCapacity:
42+
sandboxes: 1

‎helm/sim/templates/_helpers.tpl‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -993,6 +993,9 @@ refuse or that would weaken isolation.
993993
{{- if and $sbx.prePull.enabled (not (include "sim.sandbox.image" (dict "root" . "kind" "function"))) -}}
994994
{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest, so the DaemonSet holds the exact image the app runs" -}}
995995
{{- end -}}
996+
{{- if and $sbx.quota.enabled (gt (int $sbx.warmCapacity.sandboxes) (int $sbx.quota.pods)) -}}
997+
{{- fail (printf "sandbox.kubernetes.warmCapacity.sandboxes (%d) is above quota.pods (%d): room for more sandboxes than the quota admits is never used" (int $sbx.warmCapacity.sandboxes) (int $sbx.quota.pods)) -}}
998+
{{- end -}}
996999
{{- end -}}
9971000
{{- end }}
9981001

@@ -1067,3 +1070,22 @@ Kubernetes sandbox provider: env entries for the app container.
10671070
value: {{ . | quote }}
10681071
{{- end }}
10691072
{{- end }}
1073+
1074+
{{/*
1075+
Kubernetes sandbox provider: what one sandbox pod requests of a resource, as the
1076+
scheduler counts it: half the limit (halfQuantity in kubernetes/settings.ts), or
1077+
the agent init container's request when that is larger (pod.ts), since a pod
1078+
requests the larger of its init containers and the sum of its containers.
1079+
Usage: {{ include "sim.sandbox.podRequest" (dict "limit" "1" "unit" "cpu" "init" "10m") }}
1080+
*/}}
1081+
{{- define "sim.sandbox.podRequest" -}}
1082+
{{- $limit := float64 (include "sim.quantity" (toString .limit)) -}}
1083+
{{- $init := float64 (include "sim.quantity" .init) -}}
1084+
{{- if eq .unit "cpu" -}}
1085+
{{- $half := max 1 (int64 (ceil (divf (round (mulf $limit 1000) 0) 2))) -}}
1086+
{{- printf "%dm" (max $half (int64 (round (mulf $init 1000) 0))) -}}
1087+
{{- else -}}
1088+
{{- $half := max 1 (int64 (ceil (divf (round $limit 0) 2))) -}}
1089+
{{- printf "%d" (max $half (int64 (round $init 0))) -}}
1090+
{{- end -}}
1091+
{{- end }}

0 commit comments

Comments
 (0)