Skip to content

Commit 45fa90f

Browse files
committed
fix(self-hosting): fit the self-check to cold EKS Nitro starts, schedule pre-pull where sandboxes run, and keep sandboxes from consolidation
1 parent 3323435 commit 45fa90f

22 files changed

Lines changed: 394 additions & 74 deletions

File tree

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,22 @@ The Helm chart deploys the app, realtime, migrations (as an init container on th
1414
- An ingress controller and a TLS certificate for public access.
1515
- `metrics-server` for autoscaling, and the External Secrets Operator if you use it.
1616

17+
EKS Auto Mode has no default StorageClass, so the bundled PostgreSQL's volume stays Pending. Create one with Auto Mode's EBS provisioner (the name `gp3` is the one `values-aws.yaml` selects), or set `postgresql.persistence.storageClass` to a class you have:
18+
19+
```yaml
20+
apiVersion: storage.k8s.io/v1
21+
kind: StorageClass
22+
metadata:
23+
name: gp3
24+
annotations:
25+
storageclass.kubernetes.io/is-default-class: "true"
26+
provisioner: ebs.csi.eks.amazonaws.com
27+
volumeBindingMode: WaitForFirstConsumer
28+
parameters:
29+
type: gp3
30+
encrypted: "true"
31+
```
32+
1733
## 1. Pin the chart
1834
1935
Each chart version installs one Sim release, its `appVersion`. Resolve the newest chart once and reuse the version for every later command:

‎apps/docs/content/docs/platform/self-hosting/reference-architectures.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,14 @@ Each tab names the chart's example values file. Fetch it at your chart's `helm-c
3535
| You provision | Notes |
3636
| --- | --- |
3737
| EKS cluster | Kubernetes 1.25 or later |
38-
| EBS CSI driver and a `gp3` StorageClass | The example selects `gp3`; confirm it exists with the installed provisioner |
38+
| EBS CSI driver and a `gp3` StorageClass | The example selects `gp3`; confirm it exists with the installed provisioner. EKS Auto Mode has no default StorageClass; create one as in [Kubernetes prerequisites](/platform/self-hosting/kubernetes#prerequisites) |
3939
| AWS Load Balancer Controller | ALB ingress |
4040
| ACM certificate | ALB discovers it from the ingress hosts, or pin it with `alb.ingress.kubernetes.io/certificate-arn`. ALB cannot use a Kubernetes TLS Secret |
4141
| RDS or Aurora PostgreSQL | Reachable from the cluster subnets |
4242
| S3 buckets | One per file purpose |
4343
| ElastiCache | Optional; the bundled Redis also works |
4444

45-
**Identity.** Bind an IAM role to the ServiceAccount with IRSA. Grant it access to your buckets and to anything else you enable, such as Bedrock or SES. **Timeouts.** Raise the ALB idle timeout; see [Networking](/platform/self-hosting/networking#aws-alb-ingress). **Sandboxes.** EKS sandboxes run under Nitro Sandboxes; see [Kubernetes sandboxes](/platform/self-hosting/sandboxes#kubernetes-no-third-party).
45+
**Identity.** Bind an IAM role to the ServiceAccount with IRSA. Grant it access to your buckets and to anything else you enable, such as Bedrock or SES. **Timeouts.** Raise the ALB idle timeout; see [Networking](/platform/self-hosting/networking#aws-alb-ingress). **Sandboxes.** EKS sandboxes run under Nitro Sandboxes; see [Kubernetes sandboxes](/platform/self-hosting/sandboxes#kubernetes-no-third-party). On Auto Mode they also need the `amazon-vpc-cni` ConfigMap that turns on NetworkPolicy enforcement ([Amazon EKS Auto Mode](/platform/self-hosting/sandboxes#amazon-eks-auto-mode)).
4646

4747
#### AWS GovCloud (US)
4848

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,16 +151,20 @@ Two values turn it on: `sandbox.kubernetes.enabled` and the `runtimeClass.preset
151151
<Tabs items={['EKS Auto Mode', 'GKE', 'AKS', 'Self-managed gVisor']}>
152152
<Tab value="EKS Auto Mode">
153153

154-
Kubernetes 1.36 or later. Turn on NetworkPolicy enforcement first ([Amazon EKS Auto Mode](#amazon-eks-auto-mode)).
154+
Kubernetes 1.36 or later. Turn on NetworkPolicy enforcement first, and create a default StorageClass for the bundled PostgreSQL ([Amazon EKS Auto Mode](#amazon-eks-auto-mode)). A cold sandbox takes about 2 minutes (a new node, the image pull, the microVM load), so keep one or two warm:
155155

156156
```yaml
157157
sandbox:
158158
kubernetes:
159159
enabled: true
160160
runtimeClass:
161161
preset: isolated-sandbox
162+
warmCapacity:
163+
sandboxes: 1
162164
```
163165
166+
On a cold cluster `helm test` can take several minutes, since each of its two sandboxes may wait for a node.
167+
164168
</Tab>
165169
<Tab value="GKE">
166170

@@ -373,7 +377,7 @@ Sim records no sandbox cost for this provider: you pay for the nodes. Set the ku
373377

374378
### Cold start and pre-pull
375379

376-
A sandbox's start time is dominated by the first image pull on its node. `sandbox.kubernetes.prePull.enabled: true` renders a DaemonSet that keeps the Function image on every node a sandbox can land on, under the same RuntimeClass, node selector, and tolerations. The RuntimeClass is deliberate: it carries the scheduling that places pods on sandbox nodes (GKE Sandbox's, or `runtimeClass.scheduling`), and the holder then pulls the image the way a sandbox does. With `images.function` tag and digest empty, a published chart holds the image its appVersion runs. From a git checkout, or with `app.image.tag` or `digest` overridden, set `images.function.tag` or `digest`. Each node then runs one idle pod; under a VM runtime that pod is a small VM, which counts against the node's sandbox density.
380+
A sandbox's start time is dominated by the first image pull on its node. `sandbox.kubernetes.prePull.enabled: true` renders a DaemonSet that keeps the Function image on every node a sandbox can land on, under the same RuntimeClass, so the holder pulls the image the way a sandbox does. A DaemonSet places a pod on every node it selects before the RuntimeClass's scheduling applies, so the chart selects the RuntimeClass's nodes itself: a chart-created class's `runtimeClass.scheduling`, or the platform's node label for the `isolated-sandbox` (EKS), `gvisor` (GKE Sandbox, with its taint tolerated), and `kata` (AKS) presets, merged with `nodeSelector` and `tolerations` (yours win). A `custom` class the chart does not create needs `nodeSelector`. With `images.function` tag and digest empty, a published chart holds the image its appVersion runs. From a git checkout, or with `app.image.tag` or `digest` overridden, set `images.function.tag` or `digest`. Each node then runs one idle pod; under a VM runtime that pod is a small VM that occupies one sandbox slot on the node (EKS Nitro Sandboxes cap sandboxes per node).
377381

378382
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.
379383

@@ -406,10 +410,13 @@ What Sim's sandboxes need on EKS Auto Mode with Nitro Sandboxes (`runtimeClass.p
406410
```
407411

408412
Then confirm enforcement before running untrusted code, as above.
413+
- **Storage.** Auto Mode has no default StorageClass, so the bundled PostgreSQL's volume stays Pending until you create one; see [Kubernetes prerequisites](/platform/self-hosting/kubernetes#prerequisites).
414+
- **Warm capacity.** Set `warmCapacity.sandboxes` to 1 or 2. A sandbox that needs a new node takes about 2 minutes (the node, the image pull, and the microVM load), which is close to its 3-minute start deadline; a warm slot starts it in seconds. `helm test` on a cold cluster can take several minutes for the same reason.
415+
- **Consolidation.** Sandbox pods and the `helm test` pods carry `karpenter.sh/do-not-disrupt: "true"`, so Auto Mode does not consolidate a node away under a running sandbox.
409416
- **DNS.** Auto Mode runs CoreDNS on each node at the `.10` address of the cluster's Service CIDR (`10.100.0.10` or `172.20.0.10` with EKS's default Service CIDRs) and creates no `kube-dns` Service or pods. The `internet` profile's default `egress.dns` already allows it. Under `restricted`, the default `kube-dns` selector matches nothing here, so set `egress.dns` to an `ipBlock` for that address, for example `- ipBlock: {cidr: 172.20.0.10/32}`.
410417
- **Ephemeral storage.** Nitro Sandboxes report emptyDir and writable-layer usage as zero, so the kubelet cannot enforce `resources.ephemeralStorage` there: a sandbox that fills its disk is not evicted. Size the nodes' disks for it.
411418
- **Policy at pod start.** The VPC CNI programs a new pod's policies while the pod starts, and until they are in place the pod's traffic is allowed: user code that runs in those first seconds may reach what the policy would deny. On the self-managed VPC CNI, strict mode (`NETWORK_POLICY_ENFORCING_MODE=strict`) starts pods denied instead ([AWS: network policy at pod startup](https://docs.aws.amazon.com/eks/latest/userguide/cni-network-policy-configure.html)). AWS does not document that setting for Auto Mode, so treat the window as present there.
412-
- **Instance metadata.** A Nitro Sandbox serves its own IMDSv2-only metadata at `169.254.169.254` from inside the guest, where NetworkPolicy does not apply. It answers only region, Availability Zone, and partition paths; instance ID, user data, and IAM credentials return 404 ([AWS: Pod Identity and credentials](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-metadata-credentials.html)). EKS Pod Identity's endpoint is also served in the guest; sandbox pods mount no service account token, so it gives them no credentials as long as you do not inject one (for example with a Pod Identity association on the sandbox namespace). AWS lets a pod turn the metadata surrogate off with a Cedar policy generated with `eks-nitro-sandbox-genpolicy --deny-imds` and attached as the `sandbox.amazonaws.com/policy` annotation; Sim does not set pod annotations yet, so sandboxes keep the surrogate.
419+
- **Instance metadata.** A Nitro Sandbox serves its own IMDSv2-only metadata at `169.254.169.254` from inside the guest, where NetworkPolicy does not apply. It answers only region, Availability Zone, and partition paths; instance ID, user data, and IAM credentials return 404 ([AWS: Pod Identity and credentials](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-metadata-credentials.html)). EKS Pod Identity's endpoint is also served in the guest; sandbox pods mount no service account token, so it gives them no credentials as long as you do not inject one (for example with a Pod Identity association on the sandbox namespace). AWS lets a pod turn the metadata surrogate off with a Cedar policy generated with `eks-nitro-sandbox-genpolicy --deny-imds` and attached as the `sandbox.amazonaws.com/policy` annotation; Sim does not set that annotation, so sandboxes keep the surrogate.
413420
- **Capacity.** The scheduler counts each sandbox's requests plus the RuntimeClass overhead (check yours with `kubectl get runtimeclass isolated-sandbox -o yaml`; it was 256Mi on our test cluster). With `resources.memory: 1Gi` (a 512Mi request), a `c8a.large` node (about 2.3 GiB allocatable) fits three sandboxes.
414421
- **Start times.** Measured on Kubernetes 1.37 with `c8a.large` nodes: about 6 seconds from create to first command on a node that already has the image, and about 2 minutes when Auto Mode must launch a node first. Pre-pulling helps less than on gVisor: after a 31-second pull, loading the 840 MB Function image into the microVM took another 53 seconds.
415422

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173480,6 +173480,13 @@
173480173480
],
173481173481
"expressions": [],
173482173482
"codeFences": [
173483+
{
173484+
"lang": "yaml",
173485+
"meta": null,
173486+
"sha256": "5332014ec1087e70604503756fcd9554d2974bf71fe0da7bc59be3013dd9c6ab",
173487+
"bytes": 264,
173488+
"line": 19
173489+
},
173483173490
{
173484173491
"lang": "bash",
173485173492
"meta": null,
@@ -174888,8 +174895,8 @@
174888174895
{
174889174896
"lang": "yaml",
174890174897
"meta": null,
174891-
"sha256": "bdac8bd2b3fd1b79fff8cfc0d0eae5b903d64cd870472fcb924dd8363edb2b69",
174892-
"bytes": 89,
174898+
"sha256": "7e0b03f45c173041b7369dce7ee04146a198c1e851b3797f43310f5f2f70e403",
174899+
"bytes": 126,
174893174900
"line": 156
174894174901
},
174895174902
{

‎apps/sim/app/api/cron/self-check/route.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { runSelfCheck } from '@/lib/self-check/run'
77

88
export const dynamic = 'force-dynamic'
99
/** Above the sandbox check's own budget, so a slow sandbox start still reports. */
10-
export const maxDuration = 180
10+
export const maxDuration = 300
1111

1212
/**
1313
* Post-install self-check for self-hosted deployments, called by the Helm chart's `helm test`

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ describe('sandbox pod isolation', () => {
123123
expect(build().spec?.shareProcessNamespace).toBe(true)
124124
})
125125

126+
it('asks Karpenter not to consolidate its node away while it runs', () => {
127+
expect(build().metadata?.annotations?.['karpenter.sh/do-not-disrupt']).toBe('true')
128+
})
129+
126130
it('never restarts and is ended by Kubernetes at the 24-hour cap', () => {
127131
const spec = build().spec
128132
expect(spec?.restartPolicy).toBe('Never')

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ export const EXPIRES_AT_ANNOTATION = 'sim.ai/expires-at'
2626
* lease. Session lookups skip it; its deadline and the reaper treat it like any other pod.
2727
*/
2828
export const RETIRED_ANNOTATION = 'sim.ai/retired'
29+
/**
30+
* Keeps Karpenter (and EKS Auto Mode) from consolidating a node out from under a running sandbox,
31+
* which would end the user's code mid-run. The pod's own deadline still bounds how long it holds a node.
32+
*/
33+
const DO_NOT_DISRUPT_ANNOTATION = 'karpenter.sh/do-not-disrupt'
2934

3035
/** Pod label selector for every sandbox pod Sim manages. */
3136
export const MANAGED_SELECTOR = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}`
@@ -142,7 +147,10 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod {
142147
[SANDBOX_KIND_LABEL]: input.kind,
143148
...(input.sessionLabel ? { [SESSION_LABEL]: input.sessionLabel } : {}),
144149
},
145-
annotations: { [EXPIRES_AT_ANNOTATION]: String(input.expiresAtMs) },
150+
annotations: {
151+
[EXPIRES_AT_ANNOTATION]: String(input.expiresAtMs),
152+
[DO_NOT_DISRUPT_ANNOTATION]: 'true',
153+
},
146154
},
147155
spec: {
148156
...(settings.runtimeClassName ? { runtimeClassName: settings.runtimeClassName } : {}),

‎apps/sim/lib/self-check/outcome.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ export interface CheckOutcome {
2727
* HTTP, so it names the error's code and points there.
2828
*/
2929
export function failedWith(check: SelfCheckName, error: unknown): CheckOutcome {
30-
logger.warn('Self-check failed', { check, error: getErrorMessage(error) })
30+
logger.error('Self-check failed', { check, error: getErrorMessage(error) })
3131
return { status: 'fail', detail: `error: ${errorCode(error)}; see app logs` }
3232
}
3333

‎apps/sim/lib/self-check/run.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ export async function runSelfCheck(options: SelfCheckOptions): Promise<SelfCheck
5757
])
5858
const checks = groups.flat()
5959
const report = { ok: checks.every((check) => check.status !== 'fail'), checks }
60-
logger.info('Self-check completed', {
61-
ok: report.ok,
62-
failed: checks.filter((check) => check.status === 'fail').map((check) => check.name),
63-
})
60+
// At error, so a failure reaches the app log under production's default LOG_LEVEL.
61+
const failed = checks.filter((check) => check.status === 'fail').map((check) => check.name)
62+
if (report.ok) logger.info('Self-check completed', { ok: true })
63+
else logger.error('Self-check found failures', { failed })
6464
return report
6565
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { remoteSandboxMock } from '@sim/testing/mocks/remote-sandbox.mock'
2+
import {
3+
remoteSandboxProviderMock,
4+
remoteSandboxProviderMockFns,
5+
} from '@sim/testing/mocks/remote-sandbox-provider.mock'
6+
import { afterEach, describe, expect, it, vi } from 'vitest'
7+
8+
vi.mock('@/lib/execution/remote-sandbox', () => remoteSandboxMock)
9+
vi.mock('@/lib/execution/remote-sandbox/provider', () => remoteSandboxProviderMock)
10+
vi.mock('@/lib/core/config/env-capabilities.server', () => ({
11+
getSelectedSandboxProviderId: () => 'kubernetes',
12+
}))
13+
vi.mock('@/lib/execution/remote-sandbox/kubernetes/settings', () => ({
14+
readKubernetesSandboxSettings: () => ({ namespace: 'sim-sandboxes' }),
15+
}))
16+
17+
import { checkSandbox } from '@/lib/self-check/sandbox'
18+
19+
interface FakeSandbox {
20+
podAddress: string
21+
kill: ReturnType<typeof vi.fn>
22+
runCode: ReturnType<typeof vi.fn>
23+
}
24+
25+
function fakeSandbox(address: string): FakeSandbox {
26+
return {
27+
podAddress: address,
28+
kill: vi.fn(async () => {}),
29+
runCode: vi.fn(async () => ({
30+
text: '',
31+
stdout: '',
32+
stderr: '',
33+
error: { name: 'RuntimeError', value: 'probe crashed', traceback: '' },
34+
})),
35+
}
36+
}
37+
38+
/** A provider whose creates settle only when the test says so, in call order. */
39+
function controlledProvider() {
40+
const pending: Array<{
41+
resolve: (sandbox: FakeSandbox) => void
42+
reject: (error: Error) => void
43+
}> = []
44+
const create = vi.fn(
45+
() =>
46+
new Promise<FakeSandbox>((resolve, reject) => {
47+
pending.push({ resolve, reject })
48+
})
49+
)
50+
remoteSandboxProviderMockFns.mockResolveProvider.mockReturnValue({ id: 'kubernetes', create })
51+
return { create, pending }
52+
}
53+
54+
async function flush(): Promise<void> {
55+
for (let i = 0; i < 20; i++) await Promise.resolve()
56+
}
57+
58+
afterEach(() => {
59+
remoteSandboxProviderMockFns.mockResolveProvider.mockReset()
60+
})
61+
62+
describe('checkSandbox', () => {
63+
it('starts the neighbor and the probe sandbox together, so two cold starts share the budget', async () => {
64+
const { create, pending } = controlledProvider()
65+
const running = checkSandbox()
66+
await flush()
67+
68+
expect(create).toHaveBeenCalledTimes(2)
69+
70+
const neighbor = fakeSandbox('10.0.0.11')
71+
const prober = fakeSandbox('10.0.0.12')
72+
pending[0].resolve(neighbor)
73+
pending[1].resolve(prober)
74+
const results = await running
75+
76+
expect(prober.runCode).toHaveBeenCalledTimes(1)
77+
expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail')
78+
expect(neighbor.kill).toHaveBeenCalled()
79+
expect(prober.kill).toHaveBeenCalled()
80+
})
81+
82+
it('kills the neighbor when the probe sandbox fails to start', async () => {
83+
const { pending } = controlledProvider()
84+
const running = checkSandbox()
85+
await flush()
86+
87+
const neighbor = fakeSandbox('10.0.0.11')
88+
pending[0].resolve(neighbor)
89+
pending[1].reject(new Error('no capacity'))
90+
const results = await running
91+
92+
expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail')
93+
expect(neighbor.kill).toHaveBeenCalled()
94+
})
95+
96+
it('kills the probe sandbox when the neighbor fails to start', async () => {
97+
const { pending } = controlledProvider()
98+
const running = checkSandbox()
99+
await flush()
100+
101+
const prober = fakeSandbox('10.0.0.12')
102+
pending[0].reject(new Error('no capacity'))
103+
pending[1].resolve(prober)
104+
const results = await running
105+
106+
expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail')
107+
expect(prober.runCode).not.toHaveBeenCalled()
108+
expect(prober.kill).toHaveBeenCalled()
109+
})
110+
})

0 commit comments

Comments
 (0)