From f7a56f11eaf88229938daa5eb125b2f4f647f4cd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 10:16:44 -0600 Subject: [PATCH 1/5] fix(sandbox): show Shell when a sandbox provider is ready, clearer setup failures, and chart-derived sandbox defaults --- .github/workflows/helm.yml | 21 ++ .gitignore | 5 + .../docs/platform/self-hosting/sandboxes.mdx | 43 +++- .../docs/workflows/blocks/function.mdx | 5 +- apps/sim/blocks/blocks/function.test.ts | 26 ++ apps/sim/blocks/blocks/function.ts | 2 +- apps/sim/instrumentation-node.ts | 3 + apps/sim/lib/api/contracts/workspaces.ts | 3 + .../config/deployment-projection.dom.test.ts | 3 + apps/sim/lib/core/config/deployment-shape.ts | 5 +- .../config/env-capabilities.server.test.ts | 48 ++++ .../core/config/env-capabilities.server.ts | 19 ++ apps/sim/lib/core/config/env-flags.ts | 9 +- apps/sim/lib/execution/remote-sandbox/docs.ts | 2 + .../remote-sandbox/kubernetes/errors.test.ts | 31 +++ .../remote-sandbox/kubernetes/errors.ts | 21 +- .../remote-sandbox/kubernetes/pod.ts | 9 +- .../remote-sandbox/kubernetes/startup.test.ts | 189 +++++++++++++++ .../remote-sandbox/kubernetes/startup.ts | 110 +++++++-- .../execute-request.test.ts | 17 ++ .../lib/function-execution/execute-request.ts | 7 +- helm/sim/Chart.yaml | 2 +- helm/sim/templates/NOTES.txt | 10 + helm/sim/templates/_helpers.tpl | 117 ++++++++- .../templates/daemonset-sandbox-prepull.yaml | 2 +- helm/sim/templates/sandbox-kubernetes.yaml | 18 +- helm/sim/tests/sandbox-kubernetes_test.yaml | 226 +++++++++++++++++- helm/sim/values.schema.json | 24 +- helm/sim/values.yaml | 53 ++-- scripts/write-chart-sandbox-images.ts | 134 +++++++++++ 30 files changed, 1095 insertions(+), 69 deletions(-) create mode 100644 apps/sim/blocks/blocks/function.test.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/docs.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts create mode 100644 scripts/write-chart-sandbox-images.ts diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 06fefc3133f..960b1f08a83 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -11,6 +11,7 @@ on: # The image inventory is generated from the chart and checked here, so a # change to its generator has to run this workflow too. - 'scripts/generate-image-manifest.ts' + - 'scripts/write-chart-sandbox-images.ts' - 'package.json' pull_request: branches: [main, staging, dev] @@ -22,6 +23,7 @@ on: # The image inventory is generated from the chart and checked here, so a # change to its generator has to run this workflow too. - 'scripts/generate-image-manifest.ts' + - 'scripts/write-chart-sandbox-images.ts' - 'package.json' # Pull requests cancel a superseded run; pushes never do, so a newer push cannot cut off a chart @@ -341,6 +343,17 @@ jobs: APP_VERSION: ${{ needs.release-version.outputs.version }} run: bun run scripts/sync-chart-appversion.ts --version "${APP_VERSION}" + # The published chart pre-pulls the Function sandbox image its appVersion runs, + # read from the release tag; the file is gitignored, so only published charts + # carry it. --verify renders the chart and checks the DaemonSet holds that image. + - name: Bundle the release's sandbox Function image + env: + APP_VERSION: ${{ needs.release-version.outputs.version }} + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin "refs/tags/${APP_VERSION}:refs/tags/${APP_VERSION}" + bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify + - name: Package chart id: package run: | @@ -537,6 +550,14 @@ jobs: APP_VERSION: ${{ needs.release-version.outputs.version }} run: bun run scripts/sync-chart-appversion.ts --version "${APP_VERSION}" + # Same bundled sandbox image as the OCI publish, so both repos ship the same chart. + # The full-history checkout already has the release tag. + - name: Bundle the release's sandbox Function image + if: steps.pages.outputs.exists == 'true' + env: + APP_VERSION: ${{ needs.release-version.outputs.version }} + run: bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" + - name: Configure Git if: steps.pages.outputs.exists == 'true' env: diff --git a/.gitignore b/.gitignore index 920df52ee2c..758bc2b3cf0 100644 --- a/.gitignore +++ b/.gitignore @@ -110,3 +110,8 @@ __pycache__/ # `apps/sim/lib/uploads/` — 61 files of tracked source — and silently ignore # anything added there later. /uploads + +# Written by scripts/write-chart-sandbox-images.ts in the chart publish jobs from the +# release's sandbox image list, so a published chart pre-pulls the function image its +# appVersion runs. Never committed: from a checkout it would not match appVersion. +/helm/sim/files/sandbox-images.json diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index 10136ee4f69..9333ff493cb 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -116,7 +116,7 @@ DAYTONA_FUNCTION_SNAPSHOT_ID= |---|---| | `SANDBOXES_ENABLED=true` | Grants the server-side sandbox entitlement on a billing-disabled self-hosted deployment | -On a billing-disabled deployment, `ENTERPRISE_ENABLED=true` also grants the entitlement when `SANDBOXES_ENABLED` is unset. The server must verify provider credentials and the immutable Function base before offering Shell, the Function block's **Sandbox** selector, and the sandbox list. **Settings → Sandboxes** remains in the sidebar but shows an upgrade notice until access/readiness resolves. Python remains selectable; execution still requires the remote configuration. +Shell needs no entitlement: it appears in the Function block's language list once the server has verified the provider credentials and the immutable Function base. The custom sandboxes (the Function block's **Sandbox** selector and the sandbox list in **Settings → Sandboxes**) also need the entitlement, an enterprise feature: `SANDBOXES_ENABLED=true` on a billing-disabled deployment, or `ENTERPRISE_ENABLED=true` when `SANDBOXES_ENABLED` is unset. Until both hold, **Settings → Sandboxes** stays in the sidebar with an upgrade notice. Python remains selectable; execution still requires the remote configuration, and a run without it fails with an error linking to this page. When a provider is configured but incomplete or invalid, the app logs why at startup. ## Promote or roll back a build @@ -177,7 +177,7 @@ sandbox: -Add a node pool with `--workload-runtime KataVmIsolation --os-sku AzureLinux`, and create the cluster with a network policy engine (Azure, Cilium, or Calico). +Add a node pool with `--workload-runtime KataVmIsolation --os-sku AzureLinux`, and create the cluster with a network policy engine (Azure, Cilium, or Calico). The `kata-vm-isolation` RuntimeClass steers sandboxes onto that pool but does not keep other pods off it, so taint the pool (for example `--node-taints sim.ai/sandbox=true:NoSchedule`) and let sandboxes tolerate it: ```yaml sandbox: @@ -185,6 +185,10 @@ sandbox: enabled: true runtimeClass: preset: kata + tolerations: + - key: sim.ai/sandbox + operator: Exists + effect: NoSchedule ``` @@ -254,7 +258,9 @@ sandbox: effect: NoSchedule ``` -Leave `SANDBOX_PROVIDER` and the `E2B_*` and `DAYTONA_*` variables unset in `app.env`: the chart sets `SANDBOX_PROVIDER=kubernetes` itself. Leave `TRIGGER_DEV_ENABLED` unset too. Sandboxes are created by the app, which reaches each pod's agent directly, and Trigger.dev workers cannot; with it set, Sim reports the provider as misconfigured and keeps sandbox features off. On a billing-disabled deployment, also set `SANDBOXES_ENABLED=true` ([Enable sandbox access and controls](#enable-sandbox-access-and-controls)). +Leave `SANDBOX_PROVIDER` and the `E2B_*` and `DAYTONA_*` variables unset in `app.env`: the chart sets `SANDBOX_PROVIDER=kubernetes` itself. Leave `TRIGGER_DEV_ENABLED` unset too. Sandboxes are created by the app, which reaches each pod's agent directly, and Trigger.dev workers cannot; the chart refuses to render with it set. Keep `cronjobs.enabled` and `cronjobs.jobs.cleanupSessionSandboxes.enabled` on: without them idle session pods run until their 24-hour limit, and the install notes warn about it. Python and Shell work without an entitlement; for custom sandboxes on a billing-disabled deployment, also set `SANDBOXES_ENABLED=true` ([Enable sandbox access and controls](#enable-sandbox-access-and-controls)). + +Installing needs cluster-scoped rights as well as rights in the release namespace: the chart creates a ClusterRole and ClusterRoleBinding, the sandbox Namespace (with `namespace.create: true`) and a RuntimeClass (with `runtimeClass.create: true`), the ValidatingAdmissionPolicy and its binding, and, with `warmCapacity.sandboxes` above 0, a PriorityClass. With the provider enabled, the chart renders: @@ -263,7 +269,7 @@ With the provider enabled, the chart renders: - **A ClusterRole** allowing `get` on the configured RuntimeClass only, so the app can check its handler. - **A NetworkPolicy** that selects every pod in the sandbox namespace (see [Network access](#network-access)). - **A ResourceQuota and LimitRange** (see [Capacity and cost](#capacity-and-cost)). -- **A ValidatingAdmissionPolicy and its binding**, scoped to the sandbox namespace. It admits only pods shaped like the app's own: under the configured RuntimeClass, with `automountServiceAccountToken: false`, only `emptyDir` volumes, no host network, PID, or IPC namespace, and no sysctls; and in every init, regular, and ephemeral container, no privilege or privilege escalation, no capabilities beyond the six listed below, no `hostPort`, the `Default` procMount, and the `RuntimeDefault` seccomp profile (set on the container or the pod; an unset profile runs `Unconfined` on most clusters, so it is refused). It does not rely on Pod Security, so it holds in a namespace nobody labeled. It needs Kubernetes 1.30 or later. On an older cluster, set `sandbox.kubernetes.admissionPolicy.enabled: false` (which needs `namespace.create: true`), or the install fails on the unknown kind. +- **A ValidatingAdmissionPolicy and its binding**, scoped to the sandbox namespace. It admits only pods shaped like the app's own: under the configured RuntimeClass, with `automountServiceAccountToken: false`, only `emptyDir` volumes, no host network, PID, or IPC namespace, and no sysctls; and in every init, regular, and ephemeral container, no privilege or privilege escalation, no capabilities beyond the six listed below, no `hostPort`, the `Default` procMount, and the `RuntimeDefault` seccomp profile (set on the container or the pod; an unset profile runs `Unconfined` on most clusters, so it is refused). GKE Sandbox does not apply seccomp profiles, so there the seccomp rule is admission hygiene and gVisor is the boundary. It does not rely on Pod Security, so it holds in a namespace nobody labeled. When the app and chart come from different releases, the policy can refuse the app's pods; the error then names the policy, and upgrading both together fixes it. It needs Kubernetes 1.30 or later. On an older cluster, set `sandbox.kubernetes.admissionPolicy.enabled: false` (which needs `namespace.create: true`), or the install fails on the unknown kind. - **With `runtimeClass.create: true`, or a `runtimeClass.handler` named for an existing class, that handler** is passed to the app as `SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS`, so a VM runtime whose handler Sim does not recognise is accepted. The app still compares it with the RuntimeClass's real handler, and the chart refuses `runc` and `crun`. The app pod mounts its ServiceAccount token only when the provider is enabled; every other chart pod keeps it unmounted. With `networkPolicy.enabled: true`, the app's own policy also allows egress to the sandbox namespace on port 49983, and to the Kubernetes API on ports 443 and 6443. Narrow that to your API server addresses with `sandbox.kubernetes.apiServerEgress.cidrs`. @@ -290,7 +296,7 @@ Ingress to sandbox pods is denied except from the Sim app pods to the agent port DNS is TCP and UDP port 53, to `egress.dns` when it names resolvers. When it is empty, the default depends on the profile: - **`internet`** allows port 53 to any address. A cluster's resolver is often a node-local address or the DNS Service IP in a private range, which no pod selector matches (EKS Auto Mode and NodeLocal DNSCache both work this way), so this is the setting that works everywhere. It adds only port 53 on private and cluster addresses. -- **`restricted`** allows port 53 only to the `kube-system` pods labeled `k8s-app: kube-dns`, so port 53 never reaches an outside server. That matches CoreDNS on EKS managed node groups, GKE, AKS, and k3s. Where the resolver is node-local, DNS then fails until you set `egress.dns` to an `ipBlock` for the nameserver in a sandbox pod's `/etc/resolv.conf`: the `.10` address of the Service CIDR on EKS Auto Mode, or `169.254.20.10` with NodeLocal DNSCache. +- **`restricted`** allows port 53 only to the `kube-system` pods labeled `k8s-app: kube-dns` and to the well-known node-local caches: `169.254.20.10` (GKE NodeLocal DNSCache, on by default on Autopilot) and `169.254.10.10` and `169.254.10.11` (AKS LocalDNS). Port 53 never reaches an outside server. Where the resolver is somewhere else, DNS fails until you set `egress.dns` to an `ipBlock` for the nameserver in a sandbox pod's `/etc/resolv.conf`, such as the `.10` address of the Service CIDR on EKS Auto Mode; a non-empty `egress.dns` replaces these defaults. ```yaml sandbox: @@ -357,7 +363,7 @@ A kind with no image fails closed with a configuration error. The Chat code-tool 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. -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. +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 plus its RuntimeClass `overhead` (VM runtimes have one), not its requests. Left empty, as by default, each of the three is derived as `quota.pods` × (the matching `resources` value + overhead), so the quota admits `quota.pods` sandboxes whatever their size. The chart takes the overhead from `runtimeClass.overhead.podFixed` when it creates the RuntimeClass; for one your platform provides, set `quota.overheadPerPod` from `kubectl get runtimeclass -o jsonpath='{.overhead.podFixed}'`, or the derived quota admits fewer sandboxes than `quota.pods`. An explicit quota wins, and the chart refuses one below that derived floor. 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. 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: @@ -367,7 +373,7 @@ Sim records no sandbox cost for this provider: you pay for the nodes. Set the ku ### Cold start and pre-pull -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. It needs `images.function.tag` or `digest`, so it holds exactly the image the app runs. 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. +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's app runs by default, and moves with it on upgrade. A chart installed from a git checkout carries no default, so set `images.function.tag` or `digest` there, and also when `app.image.tag` or `digest` points the app at another release; the chart refuses to guess. 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. 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. @@ -401,6 +407,7 @@ What Sim's sandboxes need on EKS Auto Mode with Nitro Sandboxes (`runtimeClass.p Then confirm enforcement before running untrusted code, as above. - **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}`. +- **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. - **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. - **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. - **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. @@ -417,7 +424,27 @@ SANDBOX_K8S_E2E_REPORT_PATH=/tmp/sandbox-k8s-report.json \ bun run apps/sim/scripts/test-sandbox-kubernetes-e2e.ts --context ``` -Set `SANDBOX_K8S_RUNTIME_CLASS` to your RuntimeClass (`isolated-sandbox` is the default). Run it from inside the cluster network, since it reaches each sandbox at its pod IP, and point `SANDBOX_K8S_E2E_DENIED_TARGETS` at the app Service and database (`host:port,...`) so it proves user code cannot reach them. The header of [`test-sandbox-kubernetes-e2e.ts`](https://github.com/simstudioai/sim/blob/main/apps/sim/scripts/test-sandbox-kubernetes-e2e.ts) lists every option. Then run a Function block with Python in a workflow: it runs in a pod in the sandbox namespace (`kubectl get pods -n sim-sandboxes -w`). +Set `SANDBOX_K8S_RUNTIME_CLASS` to your RuntimeClass (`isolated-sandbox` is the default). Run it from inside the cluster network, since it reaches each sandbox at its pod IP. The chart's NetworkPolicy admits only the Sim app pods to the agent port, so while the suite runs, add a policy admitting the runner's address (policies add up), and delete it afterwards: + +```yaml +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: sandbox-e2e-runner + namespace: sim-sandboxes +spec: + podSelector: {} + policyTypes: [Ingress] + ingress: + - from: + - ipBlock: + cidr: /32 + ports: + - protocol: TCP + port: 49983 +``` + +Point `SANDBOX_K8S_E2E_DENIED_TARGETS` at the app Service and database (`host:port,...`) so it proves user code cannot reach them. The header of [`test-sandbox-kubernetes-e2e.ts`](https://github.com/simstudioai/sim/blob/main/apps/sim/scripts/test-sandbox-kubernetes-e2e.ts) lists every option. Then run a Function block with Python in a workflow: it runs in a pod in the sandbox namespace (`kubectl get pods -n sim-sandboxes -w`). ### Limitations diff --git a/apps/docs/content/docs/workflows/blocks/function.mdx b/apps/docs/content/docs/workflows/blocks/function.mdx index 17932ba1660..8c657e18256 100644 --- a/apps/docs/content/docs/workflows/blocks/function.mdx +++ b/apps/docs/content/docs/workflows/blocks/function.mdx @@ -68,8 +68,9 @@ the configured Debian repositories. JavaScript is the default. The language field is part of the saved workflow and is never removed when Sandbox configuration changes. Python remains available as a -language choice; Shell and custom Sandbox controls appear when a remote Function -sandbox provider is enabled. Reference an earlier output directly, with no quotes +language choice; Shell appears when a remote Function sandbox provider is ready. +The custom **Sandbox** selector also needs sandbox access (see +[Sandboxes](#sandboxes)). Reference an earlier output directly, with no quotes around the tag, and read an environment variable with `{{VAR}}`: diff --git a/apps/sim/blocks/blocks/function.test.ts b/apps/sim/blocks/blocks/function.test.ts new file mode 100644 index 00000000000..79cabfafe9e --- /dev/null +++ b/apps/sim/blocks/blocks/function.test.ts @@ -0,0 +1,26 @@ +import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { afterEach, describe, expect, it } from 'vitest' +import { CodeLanguage } from '@/lib/execution/languages' +import { FunctionBlock } from '@/blocks/blocks/function' + +afterEach(resetEnvFlagsMock) + +function languageIds(): string[] { + const options = FunctionBlock.subBlocks.find((subBlock) => subBlock.id === 'language')?.options + if (typeof options !== 'function') throw new Error('language options are static') + return options().map((option) => option.id) +} + +describe('Function language options', () => { + it('offers Shell when a remote provider is ready, without the custom-Sandbox entitlement', () => { + setEnvFlags({ isRemoteSandboxEnabled: true, isSandboxesEnabled: false }) + + expect(languageIds()).toContain(CodeLanguage.Shell) + }) + + it('hides Shell when no remote provider is ready, even with the entitlement', () => { + setEnvFlags({ isRemoteSandboxEnabled: false, isSandboxesEnabled: true }) + + expect(languageIds()).not.toContain(CodeLanguage.Shell) + }) +}) diff --git a/apps/sim/blocks/blocks/function.ts b/apps/sim/blocks/blocks/function.ts index 3dde96bf241..1b0e30ee8d3 100644 --- a/apps/sim/blocks/blocks/function.ts +++ b/apps/sim/blocks/blocks/function.ts @@ -36,7 +36,7 @@ export const FunctionBlock: BlockConfig = { options: () => [ { label: getLanguageDisplayName(CodeLanguage.JavaScript), id: CodeLanguage.JavaScript }, { label: getLanguageDisplayName(CodeLanguage.Python), id: CodeLanguage.Python }, - ...(getDeploymentShape().features.sandboxes + ...(getDeploymentShape().remoteCodeEnabled ? [{ label: getLanguageDisplayName(CodeLanguage.Shell), id: CodeLanguage.Shell }] : []), ], diff --git a/apps/sim/instrumentation-node.ts b/apps/sim/instrumentation-node.ts index 521e717722e..2847a9e8041 100644 --- a/apps/sim/instrumentation-node.ts +++ b/apps/sim/instrumentation-node.ts @@ -387,6 +387,9 @@ export async function register() { const { getConfiguredRedisUrl } = await import('@/lib/core/config/redis') getConfiguredRedisUrl() + const { reportSandboxConfiguration } = await import('@/lib/core/config/env-capabilities.server') + reportSandboxConfiguration() + await initializeOpenTelemetry() const { reportAccountTokenSealing } = await import('@sim/db/sealed-text') diff --git a/apps/sim/lib/api/contracts/workspaces.ts b/apps/sim/lib/api/contracts/workspaces.ts index 408010774d1..86b0bbc2dcf 100644 --- a/apps/sim/lib/api/contracts/workspaces.ts +++ b/apps/sim/lib/api/contracts/workspaces.ts @@ -278,8 +278,11 @@ export const deploymentShapeSchema = z.object({ * for rolling compatibility with app versions that predate projecting them; readers * treat absent as `false`. `e2bEnabled` means the selected sandbox provider runs Pi's * cloud modes; it keeps the name it had before providers were selectable. + * `remoteCodeEnabled` means the selected provider runs Function code (Python, Shell, + * JavaScript with imports), independent of the custom-Sandbox entitlement. */ e2bEnabled: z.boolean().optional(), + remoteCodeEnabled: z.boolean().optional(), slackExtendedScopes: z.boolean().optional(), invitationsDisabled: z.boolean().optional(), publicApiDisabled: z.boolean().optional(), diff --git a/apps/sim/lib/core/config/deployment-projection.dom.test.ts b/apps/sim/lib/core/config/deployment-projection.dom.test.ts index 31da642e4f0..154fea506da 100644 --- a/apps/sim/lib/core/config/deployment-projection.dom.test.ts +++ b/apps/sim/lib/core/config/deployment-projection.dom.test.ts @@ -28,6 +28,7 @@ vi.hoisted(() => { cohereConfigured: false, registrationMode: 'closed-no-email', e2bEnabled: true, + remoteCodeEnabled: true, slackExtendedScopes: true, invitationsDisabled: true, features: { @@ -55,6 +56,7 @@ import { isOrganizationsEnabled, isPiCloudEnabled, isPublicApiDisabled, + isRemoteSandboxEnabled, isSandboxesEnabled, isSelfServeRegistrationClosed, isSessionPoliciesEnabled, @@ -89,6 +91,7 @@ describe('browser registration flags', () => { describe('browser deployment switches', () => { it('take the projected server answer over the browser environment', () => { expect(isPiCloudEnabled).toBe(true) + expect(isRemoteSandboxEnabled).toBe(true) expect(isSlackExtendedScopesEnabled).toBe(true) expect(isInvitationsDisabled).toBe(true) }) diff --git a/apps/sim/lib/core/config/deployment-shape.ts b/apps/sim/lib/core/config/deployment-shape.ts index 98967f7648e..69a0adb3f5c 100644 --- a/apps/sim/lib/core/config/deployment-shape.ts +++ b/apps/sim/lib/core/config/deployment-shape.ts @@ -26,6 +26,7 @@ import { isOrganizationsEnabled, isPiCloudEnabled, isPublicApiDisabled, + isRemoteSandboxEnabled, isSandboxesEnabled, isScimEnabled, isSessionPoliciesEnabled, @@ -102,7 +103,8 @@ function browserFallbackShape(): DeploymentShape { * this is the `env-flags` fallback, used only when no projection exists. * * `features.sandboxes` is Sandbox *availability* (entitlement and a ready remote - * provider), not the entitlement alone. + * provider), not the entitlement alone. `remoteCodeEnabled` is provider readiness + * alone: the Function runtimes (Python, Shell) need a provider, not the entitlement. */ export function resolveDeploymentShape(): DeploymentShape { return { @@ -113,6 +115,7 @@ export function resolveDeploymentShape(): DeploymentShape { cohereConfigured: isCohereConfigured, registrationMode: getRegistrationMode(), e2bEnabled: isPiCloudEnabled, + remoteCodeEnabled: isRemoteSandboxEnabled, slackExtendedScopes: isSlackExtendedScopesEnabled, invitationsDisabled: isInvitationsDisabled, publicApiDisabled: isPublicApiDisabled, diff --git a/apps/sim/lib/core/config/env-capabilities.server.test.ts b/apps/sim/lib/core/config/env-capabilities.server.test.ts index d10ff373010..76bd5004967 100644 --- a/apps/sim/lib/core/config/env-capabilities.server.test.ts +++ b/apps/sim/lib/core/config/env-capabilities.server.test.ts @@ -1,11 +1,15 @@ import { resetEnvMock, setEnv } from '@sim/testing' +import { getMockLogger } from '@sim/testing/mocks/logger.mock' import { afterAll, beforeEach, describe, expect, expectTypeOf, it } from 'vitest' import { getSelectedSandboxProviderId, inspectConfiguredOAuthClient, + reportSandboxConfiguration, requireConfiguredOAuthClient, } from '@/lib/core/config/env-capabilities.server' +const capabilityLogger = getMockLogger('EnvCapabilities') + describe('server environment capabilities', () => { beforeEach(() => { setEnv({ @@ -79,4 +83,48 @@ describe('server environment capabilities', () => { 'Unknown SANDBOX_PROVIDER "modal". Expected one of: e2b, daytona' ) }) + + describe('sandbox configuration report at boot', () => { + beforeEach(() => { + capabilityLogger.warn.mockClear() + setEnv({ + SANDBOX_K8S_RUNTIME_CLASS: undefined, + SANDBOX_K8S_ALLOW_UNISOLATED: undefined, + TRIGGER_DEV_ENABLED: undefined, + E2B_ENABLED: undefined, + E2B_API_KEY: undefined, + }) + }) + + it('stays silent when no sandbox provider is configured', () => { + reportSandboxConfiguration() + + expect(capabilityLogger.warn).not.toHaveBeenCalled() + }) + + it('names the Trigger.dev conflict when Kubernetes sandboxes run with TRIGGER_DEV_ENABLED', () => { + setEnv({ + SANDBOX_PROVIDER: 'kubernetes', + SANDBOX_K8S_RUNTIME_CLASS: 'gvisor', + TRIGGER_DEV_ENABLED: 'true', + }) + + reportSandboxConfiguration() + + expect(capabilityLogger.warn).toHaveBeenCalledTimes(1) + expect(capabilityLogger.warn.mock.calls[0]?.[1]).toMatchObject({ + error: expect.stringContaining('TRIGGER_DEV_ENABLED'), + }) + }) + + it('names the missing field of a half-configured provider', () => { + setEnv({ SANDBOX_PROVIDER: 'daytona', DAYTONA_API_KEY: 'daytona-key' }) + + reportSandboxConfiguration() + + expect(capabilityLogger.warn.mock.calls[0]?.[1]).toMatchObject({ + error: expect.stringContaining('DAYTONA_FUNCTION_SNAPSHOT_ID'), + }) + }) + }) }) diff --git a/apps/sim/lib/core/config/env-capabilities.server.ts b/apps/sim/lib/core/config/env-capabilities.server.ts index 43a85bd8a43..d7bc018ccf3 100644 --- a/apps/sim/lib/core/config/env-capabilities.server.ts +++ b/apps/sim/lib/core/config/env-capabilities.server.ts @@ -19,7 +19,11 @@ import { type WireFallbackOptions, wireFallback, } from '@sim/deployment-config/env-capabilities' +import { createLogger } from '@sim/logger' import { env } from '@/lib/core/config/env' +import { SELF_HOSTED_SANDBOX_DOCS_URL } from '@/lib/execution/remote-sandbox/docs' + +const logger = createLogger('EnvCapabilities') export function getConfiguredStorageProviderId() { return requireCapability(STORAGE_CAPABILITY, env).providerId @@ -37,6 +41,21 @@ export function getSelectedSandboxProviderId() { throw new Error('Remote sandbox has no selected provider') } +/** + * Logs why the remote sandbox cannot run when it is configured but incomplete or invalid (a + * provider half set up, a bad image ref, Kubernetes sandboxes with `TRIGGER_DEV_ENABLED`). Python, + * Shell, and JavaScript with imports are refused on such a deployment, so the operator needs the + * reason at boot rather than from a failing run. Silent when no sandbox is configured at all. + */ +export function reportSandboxConfiguration(): void { + const { error } = inspectCapability(SANDBOX_CAPABILITY, env) + if (!error) return + logger.warn('Remote sandbox is configured but cannot run; remote code execution is disabled', { + error: error.message, + docs: SELF_HOSTED_SANDBOX_DOCS_URL, + }) +} + export function getConfiguredAsyncJobsProvider() { return requireCapability(ASYNC_JOBS_CAPABILITY, env).providerId } diff --git a/apps/sim/lib/core/config/env-flags.ts b/apps/sim/lib/core/config/env-flags.ts index 773e9a05e04..975c6a5cc13 100644 --- a/apps/sim/lib/core/config/env-flags.ts +++ b/apps/sim/lib/core/config/env-flags.ts @@ -452,15 +452,18 @@ export const isForkingEnabled = enterpriseFeatures.forking * (`SANDBOX_PROVIDER`, defaulting to E2B). Availability comes from THAT * provider's declared requirements, so a Daytona-only deployment (E2B unset) * still enables remote execution. - * Server-only: the browser cannot inspect provider credentials, and reads the - * combined Sandbox availability from the deployment-shape projection instead. + * The browser cannot inspect provider credentials, so it reads this answer from + * the deployment-shape projection (`remoteCodeEnabled`). * * Every provider requires its credential and dedicated Function base. The old * Mothership shell template/snapshot names are intentionally not fallbacks: a * deployment must build and configure the Function-owned image before exposing * the runtime. */ -export const isRemoteSandboxEnabled = isSandboxKindAvailable(env, 'function') +export const isRemoteSandboxEnabled = resolveServerSwitch( + isSandboxKindAvailable(env, 'function'), + 'remoteCodeEnabled' +) /** * Whether the complete custom-Sandbox feature is available on this deployment. diff --git a/apps/sim/lib/execution/remote-sandbox/docs.ts b/apps/sim/lib/execution/remote-sandbox/docs.ts new file mode 100644 index 00000000000..d5c4f4a9562 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/docs.ts @@ -0,0 +1,2 @@ +/** Self-hosted sandbox setup guide, named wherever a missing or broken sandbox stops a run. */ +export const SELF_HOSTED_SANDBOX_DOCS_URL = 'https://docs.sim.ai/platform/self-hosting/sandboxes' diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts new file mode 100644 index 00000000000..6d23e5cdd4a --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts @@ -0,0 +1,31 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { + KubernetesSandboxConfigError, + toPodCreateError, +} from '@/lib/execution/remote-sandbox/kubernetes/errors' + +const POLICY = 'sim-sim-sandbox-pods' + +describe('toPodCreateError for an admission policy denial', () => { + it.each([ + [ + 422, + `pods "sim-sbx-abc" is invalid: : ValidatingAdmissionPolicy '${POLICY}' with binding '${POLICY}' denied request: Every sandbox container must drop ALL capabilities.`, + ], + [ + 403, + `pods "sim-sbx-abc" is forbidden: ValidatingAdmissionPolicy '${POLICY}' with binding '${POLICY}' denied request: Sandbox pods must not set sysctls.`, + ], + ])('names the policy and the chart/app version skew on a %i', (status, message) => { + const error = toPodCreateError({ status, message }, 'sim-sandboxes') + + expect(error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(error.message).toContain(`ValidatingAdmissionPolicy "${POLICY}"`) + expect(error.message).toContain('upgrade the Helm chart and the app image together') + expect(error.message).not.toContain('SANDBOX_K8S_NODE_SELECTOR') + expect(error.message).not.toContain('sandbox Role') + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts index a1661cdfa8d..52d797fac08 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts @@ -2,13 +2,12 @@ import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike, toRecord } from '@sim/utils/object' import { NonRetryableExecutionError } from '@/lib/execution/non-retryable-error' import { SandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error' +import { SELF_HOSTED_SANDBOX_DOCS_URL } from '@/lib/execution/remote-sandbox/docs' /** Kubernetes sandbox provider docs, named in every configuration error. */ -const KUBERNETES_SANDBOX_DOCS_URL = - 'https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party' +const KUBERNETES_SANDBOX_DOCS_URL = `${SELF_HOSTED_SANDBOX_DOCS_URL}#kubernetes-no-third-party` /** How sandbox concurrency is sized, named when the namespace's quota is spent. */ -const KUBERNETES_SANDBOX_CAPACITY_DOCS_URL = - 'https://docs.sim.ai/platform/self-hosting/sandboxes#capacity-and-cost' +const KUBERNETES_SANDBOX_CAPACITY_DOCS_URL = `${SELF_HOSTED_SANDBOX_DOCS_URL}#capacity-and-cost` /** * The deployment is configured in a way no retry can fix: an unset or non-isolating RuntimeClass, @@ -88,6 +87,14 @@ export function credentialsRejectedError(options?: ErrorOptions): KubernetesSand ) } +/** + * A ValidatingAdmissionPolicy refusal. The API server phrases it as + * `ValidatingAdmissionPolicy '' with binding '' denied request: ` + * (kubernetes `staging/src/k8s.io/apiserver/pkg/admission/plugin/policy/validating/dispatcher.go`), + * under a 422 Invalid by default or a 403 when the policy sets `reason: Forbidden`. + */ +const ADMISSION_POLICY_DENIAL = /ValidatingAdmissionPolicy '([^']*)'.*denied request/ + /** Throttled or server-side failures; an unanswered request (no status) is retryable too. */ const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]) @@ -112,6 +119,12 @@ export function toPodCreateError(failure: KubernetesApiFailure, namespace: strin 'The Kubernetes API server is throttling sandbox creation; retry shortly.' ) } + const policy = ADMISSION_POLICY_DENIAL.exec(failure.message)?.[1] + if (policy !== undefined && (failure.status === 403 || failure.status === 422)) { + return new KubernetesSandboxConfigError( + `The ValidatingAdmissionPolicy "${policy}" refused the sandbox pod. When that is the chart's sandbox admission policy (sandbox.kubernetes.admissionPolicy), the policy and the app that builds the pod are from different releases: upgrade the Helm chart and the app image together. Cluster detail: ${failure.message}` + ) + } if (failure.status === 403 && /violates PodSecurity/i.test(failure.message)) { return new KubernetesSandboxConfigError( `The namespace "${namespace}" (SANDBOX_K8S_NAMESPACE) rejects sandbox pods under its Pod Security level. Sandbox pods run their agent as root inside the isolated runtime, so label the namespace pod-security.kubernetes.io/enforce=baseline. Cluster detail: ${failure.message}` diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts index 78d9db03007..58236a29c15 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -48,6 +48,8 @@ const AGENT_VOLUME_SIZE = '256Mi' /** * Writable scratch the sandbox user and dependency installs need. Each is an emptyDir capped at * the pod's ephemeral-storage limit, so a runaway write is evicted rather than filling the node. + * That relies on the kubelet measuring the usage: EKS Nitro Sandboxes report emptyDir and + * writable-layer usage as zero, so the kubelet cannot enforce the limit there. * * `/home/user` is deliberately not one: an emptyDir there is root-owned and hides the home the * image built for uid 1000 (its dotfiles and tool config), and the agent does not re-own an @@ -126,9 +128,10 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod { privileged: false, runAsUser: 0, runAsGroup: 0, - // Kept under every runtime: admission never sees the runtime, and gVisor's runsc enforces - // the OCI seccomp filter inside its sandbox (its `oci-seccomp` flag defaults on) rather than - // refusing the container. Under runc it is the usual host-kernel filter. + // Kept under every runtime: admission never sees the runtime, and the sandbox admission + // policy requires it. A self-managed gVisor runsc enforces the OCI seccomp filter inside its + // sandbox (its `oci-seccomp` flag); GKE Sandbox does not apply seccomp, so there it is + // admission hygiene only. Under runc it is the usual host-kernel filter. seccompProfile: { type: 'RuntimeDefault' }, } return { diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts new file mode 100644 index 00000000000..d4c7d3840e4 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts @@ -0,0 +1,189 @@ +/** + * @vitest-environment node + */ +import type { V1Pod } from '@kubernetes/client-node' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { SandboxCluster } from '@/lib/execution/remote-sandbox/kubernetes/cluster' +import { + KubernetesSandboxCapacityError, + KubernetesSandboxConfigError, +} from '@/lib/execution/remote-sandbox/kubernetes/errors' +import type { KubernetesSandboxSettings } from '@/lib/execution/remote-sandbox/kubernetes/settings' + +const { checkHealth } = vi.hoisted(() => ({ checkHealth: vi.fn() })) + +vi.mock('@/lib/execution/remote-sandbox/agent/client', () => ({ + SandboxAgentClient: class { + checkHealth = checkHealth + }, +})) + +import { waitUntilReady } from '@/lib/execution/remote-sandbox/kubernetes/startup' + +const CREATE_DEADLINE_MS = 180_000 + +const SETTINGS: KubernetesSandboxSettings = { + namespace: 'sim-sandboxes', + runtimeClassName: 'gvisor', + allowUnisolated: false, + trustedRuntimeHandlers: [], + images: { agent: 'registry/agent:1', function: 'registry/function:1', pi: 'registry/pi:1' }, + resources: { cpu: '1', memory: '2Gi', ephemeralStorage: '4Gi' }, + tokenSecret: 'internal-secret-internal-secret-0123456789', +} + +function runningPod(name: string): V1Pod { + return { + metadata: { name, resourceVersion: '1' }, + spec: { nodeName: 'node-a', containers: [] }, + status: { + phase: 'Running', + podIP: '10.0.0.7', + containerStatuses: [ + { + name: 'sandbox', + image: 'registry/function:1', + imageID: '', + ready: true, + restartCount: 0, + state: { running: { startedAt: new Date() } }, + }, + ], + }, + } +} + +function pendingPod(name: string): V1Pod { + return { + metadata: { name, resourceVersion: '1' }, + spec: { containers: [] }, + status: { + phase: 'Pending', + conditions: [ + { + type: 'PodScheduled', + status: 'False', + message: '0/3 nodes are available: 3 Insufficient cpu.', + }, + ], + }, + } +} + +/** A running pod whose sandbox container has crashed and restarted since it first ran. */ +function crashLoopingPod(name: string): V1Pod { + const pod = runningPod(name) + pod.status = { + ...pod.status, + containerStatuses: [ + { + name: 'sandbox', + image: 'registry/function:1', + imageID: '', + ready: false, + restartCount: 3, + state: { waiting: { reason: 'CrashLoopBackOff' } }, + lastState: { terminated: { reason: 'Error', exitCode: 127 } }, + }, + ], + } + return pod +} + +/** + * A cluster whose pod never changes: every watch ends quietly and every read returns `latest` + * (the created pod unless given). + */ +function staticCluster(pod: V1Pod, latest: V1Pod = pod): SandboxCluster { + return { + namespace: SETTINGS.namespace, + readRuntimeClassHandler: async () => 'runsc', + createPod: async () => pod, + readPod: async () => latest, + listPods: async () => [], + listPodEvents: async () => [], + watchPod: (_name, _version, _onUpdate, signal) => + new Promise((resolve, reject) => { + const timer = setTimeout(() => resolve('ended'), 30_000) + signal.addEventListener('abort', () => { + clearTimeout(timer) + reject(signal.reason) + }) + }), + retirePod: async () => {}, + extendExpiresAt: async () => {}, + deletePod: async () => {}, + } +} + +/** Starts `waitUntilReady` under a create deadline and records how it settled. */ +function start(pod: V1Pod, latest: V1Pod = pod) { + const deadline = new AbortController() + setTimeout(() => deadline.abort(), CREATE_DEADLINE_MS) + const name = pod.metadata?.name ?? '' + const outcome: { error?: unknown; settled: boolean } = { settled: false } + waitUntilReady( + staticCluster(pod, latest), + { pod, name, token: 'token' }, + 'code', + SETTINGS, + deadline.signal, + performance.now() + ).then( + () => { + outcome.settled = true + }, + (error: unknown) => { + outcome.error = error + outcome.settled = true + } + ) + return outcome +} + +beforeEach(() => { + vi.useFakeTimers() + checkHealth.mockReset() +}) + +afterEach(() => { + vi.useRealTimers() +}) + +describe('waitUntilReady for a pod that runs but whose agent never answers', () => { + it('fails as a non-retryable configuration error within a minute, naming the agent port', async () => { + checkHealth.mockResolvedValue(null) + const outcome = start(runningPod('sim-sbx-silent')) + + await vi.advanceTimersByTimeAsync(61_000) + + expect(outcome.settled).toBe(true) + expect(outcome.error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(String(outcome.error)).toContain('49983') + }) +}) + +describe('waitUntilReady for a pod whose sandbox container crashes before its agent answers', () => { + it('reports the crash and its exit, not the network path', async () => { + checkHealth.mockResolvedValue(null) + const outcome = start(runningPod('sim-sbx-crashing'), crashLoopingPod('sim-sbx-crashing')) + + await vi.advanceTimersByTimeAsync(61_000) + + expect(outcome.settled).toBe(true) + expect(outcome.error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(String(outcome.error)).toContain('Error, exit code 127') + expect(String(outcome.error)).not.toContain('NetworkPolicy') + }) +}) + +describe('waitUntilReady for a pod no node can schedule', () => { + it('fails as capacity at the create deadline', async () => { + const outcome = start(pendingPod('sim-sbx-unscheduled')) + + await vi.advanceTimersByTimeAsync(CREATE_DEADLINE_MS + 1_000) + + expect(outcome.settled).toBe(true) + expect(outcome.error).toBeInstanceOf(KubernetesSandboxCapacityError) + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts index 602fb6d5560..e8d27c65d30 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts @@ -6,6 +6,7 @@ */ import type { CoreV1Event, V1Pod } from '@kubernetes/client-node' import { createLogger } from '@sim/logger' +import { SANDBOX_AGENT_PORT } from '@sim/sandbox-agent-protocol' import { getErrorMessage } from '@sim/utils/errors' import { interruptibleSleep } from '@sim/utils/helpers' import { generateShortId } from '@sim/utils/id' @@ -44,8 +45,14 @@ const HEALTH_BACKOFF = { baseMs: 50, maxMs: 250 } const HEALTH_REQUEST_TIMEOUT_MS = 2_000 /** Names what could stand between Sim and a pod's agent, for errors about an unreachable one. */ -export const AGENT_PATH_HINT = - "Check that a NetworkPolicy lets Sim's pods reach the sandbox namespace on the agent port, and that no proxy or service mesh intercepts Sim's traffic to pod IPs." +export const AGENT_PATH_HINT = `Check that a NetworkPolicy lets Sim's pods reach the sandbox namespace on the agent port (TCP ${SANDBOX_AGENT_PORT}), and that no proxy or service mesh intercepts Sim's traffic to pod IPs.` + +/** + * How long a running sandbox container may go without its agent answering before the create + * fails as a configuration error. The agent listens within moments of its container starting, so + * a minute of silence means the network path is blocked, not that the cluster is busy. + */ +const AGENT_UNREACHABLE_MS = 60_000 /** Pod names: a fixed prefix plus 20 random lowercase alphanumerics (~103 bits). */ const POD_NAME_PREFIX = 'sim-sbx-' @@ -190,6 +197,55 @@ export async function waitForAgent(client: SandboxAgentClient, signal: AbortSign } } +/** + * Why the sandbox container stopped, when it has: its current or last termination (reason and + * exit code), or null while it has run without a restart. + */ +function sandboxContainerCrash(pod: V1Pod | null): string | null { + const status = pod?.status?.containerStatuses?.find(({ name }) => name === SANDBOX_CONTAINER_NAME) + if (!status) return null + const stillRunning = Boolean(status.state?.running) + if (stillRunning && !status.restartCount) return null + const terminated = status.state?.terminated ?? status.lastState?.terminated + const reason = terminated + ? `${terminated.reason ?? 'terminated'}, exit code ${terminated.exitCode}${terminated.message ? `: ${terminated.message}` : ''}` + : (status.state?.waiting?.reason ?? 'not running') + return `${reason}; ${status.restartCount ?? 0} restart(s)` +} + +/** + * {@link waitForAgent} for a pod whose sandbox container is running, bounded by `signal` and by + * {@link AGENT_UNREACHABLE_MS}. When the agent stays silent that long, the pod is re-read: a + * sandbox container that exited or restarted crashed (a broken image or agent), and one still + * running without a restart is behind a blocked network path. Neither is fixed by a retry, so + * both fail as configuration errors rather than waiting out the create deadline as capacity. + */ +async function waitForRunningAgent( + cluster: SandboxCluster, + client: SandboxAgentClient, + signal: AbortSignal, + name: string, + baseUrl: string +): Promise { + const unreachable = new AbortController() + const timer = setTimeout(() => unreachable.abort(), AGENT_UNREACHABLE_MS) + try { + await waitForAgent(client, AbortSignal.any([signal, unreachable.signal])) + } catch (error) { + if (signal.aborted || !unreachable.signal.aborted) throw error + const latest = await cluster.readPod(name, { signal }).catch(() => null) + const crash = sandboxContainerCrash(latest) + throw new KubernetesSandboxConfigError( + crash + ? `Sandbox pod ${name}'s sandbox container stopped before its agent answered (${crash}). Check that the sandbox image runs the agent the init container installs.` + : `Sandbox pod ${name} is running but its agent at ${baseUrl} did not answer within ${AGENT_UNREACHABLE_MS / 1000}s. ${AGENT_PATH_HINT}`, + { cause: error } + ) + } finally { + clearTimeout(timer) + } +} + /** Deletes pods a failed create may have left behind; the reaper catches any this misses. */ export async function discardPods(cluster: SandboxCluster, names: Iterable): Promise { const pending = [...names] @@ -259,6 +315,30 @@ export async function createPod( } } +/** + * The error for a pod the create deadline cut off. A pod still short of a running sandbox + * container is capacity, which a later attempt may get past. A container that only started + * running within the last {@link AGENT_UNREACHABLE_MS} may just have run out of time, so it is + * capacity too, naming the network path in case its agent is unreachable. + */ +function deadlineError( + pod: V1Pod, + name: string, + pullError: string | undefined, + detail: string | undefined, + cause: unknown +): Error { + const reached = isSandboxContainerRunning(pod) ? agentBaseUrl(pod) : null + return new KubernetesSandboxCapacityError( + reached + ? `Sandbox pod ${name} started running just before its create deadline and its agent at ${reached} had not answered yet. ${AGENT_PATH_HINT}` + : pullError + ? `Sandbox pod ${name} could not pull its image before its create deadline (${pullError}). Check the registry is reachable from the nodes.` + : `Sandbox pod ${name} did not start before its create deadline${detail ? ` (${detail})` : ''}. The cluster may be out of capacity for sandboxes.`, + { cause } + ) +} + /** * Follows the pod with a watch until it runs, then waits for its agent; bounded by `signal`. * A watch that ends without news is re-read and re-watched after a back-off, so an API server @@ -301,7 +381,13 @@ export async function waitUntilReady( const progress = observe(pod) if (progress.state === 'failed') throw progress.error if (progress.state === 'ready') { - await waitForAgent(new SandboxAgentClient(progress.baseUrl, created.token), signal) + await waitForRunningAgent( + cluster, + new SandboxAgentClient(progress.baseUrl, created.token), + signal, + name, + progress.baseUrl + ) mark('agentMs') return { pod, baseUrl: progress.baseUrl, timings } } @@ -333,16 +419,12 @@ export async function waitUntilReady( } } } catch (error) { - logger.warn('Kubernetes sandbox pod did not start', { name, ...timings }) - if (!signal.aborted) throw error - const reached = agentBaseUrl(pod) - throw new KubernetesSandboxCapacityError( - reached - ? `Sandbox pod ${name} is running but Sim could not reach its agent at ${reached}. ${AGENT_PATH_HINT}` - : pullError - ? `Sandbox pod ${name} could not pull its image before its create deadline (${pullError}). Check the registry is reachable from the nodes.` - : `Sandbox pod ${name} did not start before its create deadline${detail ? ` (${detail})` : ''}. The cluster may be out of capacity for sandboxes.`, - { cause: error } - ) + const failure = signal.aborted ? deadlineError(pod, name, pullError, detail, error) : error + logger.warn('Kubernetes sandbox pod did not start', { + name, + ...timings, + error: getErrorMessage(failure), + }) + throw failure } } diff --git a/apps/sim/lib/function-execution/execute-request.test.ts b/apps/sim/lib/function-execution/execute-request.test.ts index e7fb32079e2..d5c296a044f 100644 --- a/apps/sim/lib/function-execution/execute-request.test.ts +++ b/apps/sim/lib/function-execution/execute-request.test.ts @@ -405,6 +405,23 @@ describe('Function execution request', () => { expect(mockExecuteShellInSandbox).not.toHaveBeenCalled() }) + it.each([ + { language: 'python', code: 'return 42' }, + { language: 'shell', code: 'echo ready' }, + { language: 'javascript', code: "import _ from 'lodash'\nreturn 1" }, + ])( + 'points a $language run without a remote provider to the sandbox setup guide', + async ({ language, code }) => { + const response = await POST(createMockRequest('POST', { language, code })) + const data = await response.json() + + expect(data.success).toBe(false) + expect(data.error).toContain('https://docs.sim.ai/platform/self-hosting/sandboxes') + expect(mockExecuteInSandbox).not.toHaveBeenCalled() + expect(mockExecuteShellInSandbox).not.toHaveBeenCalled() + } + ) + it.each([ { language: 'python', code: 'return 42', kind: 'code' }, { language: 'shell', code: 'echo ready', kind: 'shell' }, diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 7725ff3403a..8fe162c3f4a 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -83,6 +83,7 @@ import { SIM_RESULT_PREFIX, } from '@/lib/execution/remote-sandbox' import { findSandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error' +import { SELF_HOSTED_SANDBOX_DOCS_URL } from '@/lib/execution/remote-sandbox/docs' import { isBinarySandboxPath } from '@/lib/execution/remote-sandbox/encoding' import { sandboxSessionInputProvenance } from '@/lib/execution/remote-sandbox/observer' import { @@ -2648,19 +2649,19 @@ export async function executeFunctionRequest( if (lang === CodeLanguage.Shell && !remoteSandboxEnabled) { throw new Error( - 'Shell execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it.' + `Shell execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` ) } if (lang === CodeLanguage.Python && !remoteSandboxEnabled) { throw new Error( - 'Python execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it, or use JavaScript instead.' + `Python execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it, or use JavaScript instead. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` ) } if (lang === CodeLanguage.JavaScript && hasImports && !remoteSandboxEnabled) { throw new Error( - 'JavaScript code with import statements requires a remote code sandbox to be enabled. Please remove the import statements, or contact your administrator to enable it.' + `JavaScript code with import statements requires a remote code sandbox to be enabled. Please remove the import statements, or contact your administrator to enable it. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` ) } diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 6a46f7c2b7b..2fa06122346 100644 --- a/helm/sim/Chart.yaml +++ b/helm/sim/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: sim description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents type: application -version: 1.20.0 +version: 1.21.0 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index 073e99de317..5b7f0d9b7d4 100644 --- a/helm/sim/templates/NOTES.txt +++ b/helm/sim/templates/NOTES.txt @@ -105,3 +105,13 @@ STORAGE_PROVIDER in values.yaml). * Troubleshooting: helm/sim/README.md (search "Troubleshooting") * Docs: https://docs.sim.ai * Issues: https://github.com/simstudioai/sim/issues +{{- if .Values.sandbox.kubernetes.enabled }} +{{- $cleanup := .Values.cronjobs.jobs.cleanupSessionSandboxes | default dict }} +{{- if not (and .Values.cronjobs.enabled $cleanup.enabled) }} + +WARNING: Kubernetes sandboxes are enabled but the cleanup-session-sandboxes +cron job is off (cronjobs.enabled or cronjobs.jobs.cleanupSessionSandboxes.enabled). +Idle chat-session sandbox pods then run until their 24-hour lifetime cap and +hold sandbox quota. Turn the job back on. +{{- end }} +{{- end }} diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index cc5dcaf7918..ae5b15867c4 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1236,7 +1236,33 @@ refuse or that would weaken isolation. {{- fail "sandbox.kubernetes.enabled=true binds pod-management RBAC to the app ServiceAccount, which resolves to \"default\". Set serviceAccount.create=true or serviceAccount.name to a dedicated ServiceAccount" -}} {{- end -}} {{- if and $sbx.prePull.enabled (not (include "sim.sandbox.image" (dict "root" . "kind" "function"))) -}} -{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest, so the DaemonSet holds the exact image the app runs" -}} +{{- $appImage := .Values.app.image -}} +{{- if or $appImage.digest (and $appImage.tag (ne (toString $appImage.tag) (toString .Chart.AppVersion))) -}} +{{- fail (printf "sandbox.kubernetes.prePull.enabled=true with app.image.tag or .digest overridden needs sandbox.kubernetes.images.function.tag or .digest: the function image the chart bundles is the one chart appVersion %s runs, so with a different app it would pre-pull an image the app never uses" (toString .Chart.AppVersion)) -}} +{{- end -}} +{{- if not (include "sim.sandbox.bundledFunctionImage" .) -}} +{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image. Published charts (oci://ghcr.io/simstudioai/charts/sim and the Helm repository) carry the one their appVersion runs; a chart installed from a git checkout does not" -}} +{{- end -}} +{{- end -}} +{{- $trigger := "" -}} +{{- if hasKey .Values.app.env "TRIGGER_DEV_ENABLED" -}} +{{- $trigger = toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}} +{{- else if hasKey (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED" -}} +{{- $trigger = toString (default "" (index .Values.app.envDefaults "TRIGGER_DEV_ENABLED")) -}} +{{- end -}} +{{- if has (lower $trigger) (list "true" "1") -}} +{{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env and app.envDefaults so executions run on the database-backed job queue" -}} +{{- end -}} +{{- if $sbx.quota.enabled -}} +{{- range $field := list "cpu" "memory" "ephemeralStorage" -}} +{{- $explicit := toString (index $sbx.quota $field | default "") -}} +{{- if $explicit -}} +{{- $needed := include "sim.sandbox.quotaFloor" (dict "root" $ "field" $field) -}} +{{- if lt (float64 (include "sim.quantity" $explicit)) (float64 (include "sim.quantity" $needed)) -}} +{{- fail (printf "sandbox.kubernetes.quota.%s %q is below %s, what quota.pods (%d) sandboxes of resources.%s plus their RuntimeClass overhead need: the quota would refuse sandboxes before quota.pods run. Raise it, or leave it empty to derive it" $field $explicit $needed (int $sbx.quota.pods) $field) -}} +{{- end -}} +{{- end -}} +{{- end -}} {{- end -}} {{- if and $sbx.quota.enabled (gt (int $sbx.warmCapacity.sandboxes) (int $sbx.quota.pods)) -}} {{- 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)) -}} @@ -1244,6 +1270,95 @@ refuse or that would weaken isolation. {{- end -}} {{- end }} +{{/* +Kubernetes sandbox provider: the overhead one sandbox pod carries for a resource, +as a quantity ("0" when none): the chart-created RuntimeClass's +overhead.podFixed, or quota.overheadPerPod for a RuntimeClass the chart does +not create. ResourceQuota counts a pod's overhead on top of its containers. +Usage: {{ include "sim.sandbox.podOverhead" (dict "root" . "field" "memory") }} +*/}} +{{- define "sim.sandbox.podOverhead" -}} +{{- $sbx := .root.Values.sandbox.kubernetes -}} +{{- $podFixedKeys := dict "cpu" "cpu" "memory" "memory" "ephemeralStorage" "ephemeral-storage" -}} +{{- $value := "" -}} +{{- if $sbx.runtimeClass.create -}} +{{- $podFixed := (($sbx.runtimeClass.overhead | default dict).podFixed) | default dict -}} +{{- $value = index $podFixed (get $podFixedKeys .field) | default "" -}} +{{- end -}} +{{- if not $value -}} +{{- $value = index ($sbx.quota.overheadPerPod | default dict) .field | default "" -}} +{{- end -}} +{{- toString (default "0" $value) -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the least quota for a resource that admits +quota.pods sandboxes, as a quantity: pods x (resources. + pod overhead). +Every sandbox container's request is at most its limit, which the quota caps +(limits.*), and the agent init container is smaller than the sandbox container. +CPU renders in whole cores or millicores, memory and storage in Gi, Mi, or bytes. +Usage: {{ include "sim.sandbox.quotaFloor" (dict "root" . "field" "memory") }} +*/}} +{{- define "sim.sandbox.quotaFloor" -}} +{{- $sbx := .root.Values.sandbox.kubernetes -}} +{{- $perPod := addf (include "sim.quantity" (toString (index $sbx.resources .field))) (include "sim.quantity" (include "sim.sandbox.podOverhead" .)) -}} +{{- if eq .field "cpu" -}} +{{- /* Rounded up per pod, as Kubernetes rounds a sub-millicore or fractional-byte quantity; the small tolerance keeps float error from bumping an exact value. */ -}} +{{- $millis := mul (int64 $sbx.quota.pods) (int64 (ceil (subf (mulf $perPod 1000) 0.000001))) -}} +{{- if eq (mod $millis 1000) 0 -}}{{ div $millis 1000 }}{{- else -}}{{ $millis }}m{{- end -}} +{{- else -}} +{{- $bytes := mul (int64 $sbx.quota.pods) (int64 (ceil (subf $perPod 0.001))) -}} +{{- if eq (mod $bytes 1073741824) 0 -}}{{ div $bytes 1073741824 }}Gi +{{- else if eq (mod $bytes 1048576) 0 -}}{{ div $bytes 1048576 }}Mi +{{- else -}}{{ $bytes }} +{{- end -}} +{{- end -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the ResourceQuota hard limit for a resource: the +explicit quota., or the derived sim.sandbox.quotaFloor when it is empty. +*/}} +{{- define "sim.sandbox.quota" -}} +{{- $explicit := toString (index .root.Values.sandbox.kubernetes.quota .field | default "") -}} +{{- if $explicit -}}{{ $explicit }}{{- else -}}{{ include "sim.sandbox.quotaFloor" . }}{{- end -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the function image the app of this chart's +appVersion runs by default, moved onto global.imageRegistry the way the app +moves it (publishedImage in kubernetes/settings.ts); empty when the chart +carries no files/sandbox-images.json. The publish jobs write that file from +the release's images.generated.json (scripts/write-chart-sandbox-images.ts); a +git checkout has none. +*/}} +{{- define "sim.sandbox.bundledFunctionImage" -}} +{{- $raw := .Files.Get "files/sandbox-images.json" -}} +{{- if $raw -}} +{{- $published := toString (get ($raw | fromJson) "function") -}} +{{- $registry := trimSuffix "/" (include "sim.sandbox.defaultImageRegistry" .) -}} +{{- if and $published $registry -}} +{{- printf "%s/%s" $registry (regexReplaceAll "^[^/]+/" $published "") -}} +{{- else -}} +{{- $published -}} +{{- end -}} +{{- end -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the function image the pre-pull DaemonSet holds: +an explicit images.function tag or digest, or else sim.sandbox.bundledFunctionImage. +Only the explicit one is exported to the app as SANDBOX_K8S_FUNCTION_IMAGE. +*/}} +{{- define "sim.sandbox.prePullImage" -}} +{{- $explicit := include "sim.sandbox.image" (dict "root" . "kind" "function") -}} +{{- if $explicit -}} +{{- $explicit -}} +{{- else -}} +{{- include "sim.sandbox.bundledFunctionImage" . -}} +{{- end -}} +{{- end }} + {{/* A Kubernetes quantity in base units, for comparison. Takes the grammar values.schema.json admits for sandbox resources: a decimal with an optional suffix. diff --git a/helm/sim/templates/daemonset-sandbox-prepull.yaml b/helm/sim/templates/daemonset-sandbox-prepull.yaml index 12c41a6a3c2..0625448db4a 100644 --- a/helm/sim/templates/daemonset-sandbox-prepull.yaml +++ b/helm/sim/templates/daemonset-sandbox-prepull.yaml @@ -51,7 +51,7 @@ spec: terminationGracePeriodSeconds: 0 containers: - name: hold-function-image - image: {{ include "sim.sandbox.image" (dict "root" . "kind" "function") }} + image: {{ include "sim.sandbox.prePullImage" . }} imagePullPolicy: IfNotPresent command: ["sleep", "infinity"] {{- include "sim.resources" $sbx.prePull | nindent 10 }} diff --git a/helm/sim/templates/sandbox-kubernetes.yaml b/helm/sim/templates/sandbox-kubernetes.yaml index 7d04ccf44db..1ec651d91b6 100644 --- a/helm/sim/templates/sandbox-kubernetes.yaml +++ b/helm/sim/templates/sandbox-kubernetes.yaml @@ -150,8 +150,10 @@ spec: {{- /* DNS goes to egress.dns when it names resolvers. Otherwise internet allows port 53 to any address, because node-local and Service-IP resolvers sit in ranges - that profile blocks; restricted allows only the cluster DNS pods, so port 53 - never reaches an outside server. + that profile blocks; restricted allows only the cluster DNS pods and the + well-known node-local cache addresses (GKE NodeLocal DNSCache 169.254.20.10, + the default on Autopilot; AKS LocalDNS 169.254.10.10 and 169.254.10.11), so + port 53 never reaches an outside server. */}} - ports: - protocol: UDP @@ -169,6 +171,12 @@ spec: podSelector: matchLabels: k8s-app: kube-dns + - ipBlock: + cidr: 169.254.20.10/32 + - ipBlock: + cidr: 169.254.10.10/32 + - ipBlock: + cidr: 169.254.10.11/32 {{- end }} {{- if eq $sbx.egress.profile "internet" }} {{- $blocked := concat $sbx.egress.blockedCidrs $sbx.egress.clusterCidrs }} @@ -224,9 +232,9 @@ metadata: spec: hard: pods: {{ $sbx.quota.pods | toString | quote }} - limits.cpu: {{ $sbx.quota.cpu | toString | quote }} - limits.memory: {{ $sbx.quota.memory | toString | quote }} - limits.ephemeral-storage: {{ $sbx.quota.ephemeralStorage | toString | quote }} + limits.cpu: {{ include "sim.sandbox.quota" (dict "root" . "field" "cpu") | quote }} + limits.memory: {{ include "sim.sandbox.quota" (dict "root" . "field" "memory") | quote }} + limits.ephemeral-storage: {{ include "sim.sandbox.quota" (dict "root" . "field" "ephemeralStorage") | quote }} {{- end }} {{- if $sbx.limitRange.enabled }} --- diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index f3a6d135499..6bdf48c331a 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -568,6 +568,12 @@ tests: podSelector: matchLabels: k8s-app: kube-dns + - ipBlock: + cidr: 169.254.20.10/32 + - ipBlock: + cidr: 169.254.10.10/32 + - ipBlock: + cidr: 169.254.10.11/32 - equal: path: spec.egress[1] value: @@ -588,7 +594,7 @@ tests: path: spec.egress count: 1 - - it: sends restricted DNS only to the cluster DNS pods by default, never to an outside server + - it: sends restricted DNS only to the cluster DNS pods and the GKE and AKS node-local caches by default, never to an outside server template: sandbox-kubernetes.yaml set: <<: *enabled @@ -606,6 +612,12 @@ tests: podSelector: matchLabels: k8s-app: kube-dns + - ipBlock: + cidr: 169.254.20.10/32 + - ipBlock: + cidr: 169.254.10.10/32 + - ipBlock: + cidr: 169.254.10.11/32 - it: sends internet DNS to any address by default, since node-local and Service-IP resolvers sit in blocked ranges template: sandbox-kubernetes.yaml @@ -807,6 +819,121 @@ tests: limits.memory: 40Gi limits.ephemeral-storage: 80Gi + - it: derives the quota from pods and non-default sandbox resources + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.pods: 7 + sandbox.kubernetes.resources.cpu: 500m + sandbox.kubernetes.resources.memory: 1536Mi + sandbox.kubernetes.resources.ephemeralStorage: 3G + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard + value: + pods: "7" + limits.cpu: 3500m + limits.memory: 10752Mi + limits.ephemeral-storage: "21000000000" + + - it: adds the overhead of a RuntimeClass the chart creates to each sandbox's share of the quota + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.overhead: + podFixed: + cpu: 250m + memory: 512Mi + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard + value: + pods: "20" + limits.cpu: "25" + limits.memory: 50Gi + limits.ephemeral-storage: 80Gi + + - it: adds overheadPerPod for a RuntimeClass the cloud provider manages + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.overheadPerPod.cpu: 100m + sandbox.kubernetes.quota.overheadPerPod.ephemeralStorage: 1Gi + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard + value: + pods: "20" + limits.cpu: "22" + limits.memory: 40Gi + limits.ephemeral-storage: 100Gi + + - it: rounds each sandbox's sub-millicore and fractional-byte share up, as Kubernetes does + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.overheadPerPod.cpu: "0.0004" + sandbox.kubernetes.quota.overheadPerPod.memory: "0.4" + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard["limits.cpu"] + value: 20020m + - equal: + path: spec.hard["limits.memory"] + value: "42949672980" + + - it: keeps an explicit quota at or above what the sandboxes need + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.cpu: "32" + sandbox.kubernetes.quota.memory: 64Gi + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard["limits.cpu"] + value: "32" + - equal: + path: spec.hard["limits.memory"] + value: 64Gi + - equal: + path: spec.hard["limits.ephemeral-storage"] + value: 80Gi + + - it: refuses an explicit quota below pods x resources, which would refuse sandboxes before quota.pods run + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.memory: 39Gi + asserts: + - failedTemplate: + errorPattern: "quota.memory \"39Gi\" is below 40Gi" + + - it: counts RuntimeClass overhead in the floor an explicit quota must meet + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.cpu: "20" + sandbox.kubernetes.quota.overheadPerPod.cpu: 250m + asserts: + - failedTemplate: + errorPattern: "quota.cpu \"20\" is below 25" + - it: caps any container at the configured sandbox size and sets no defaults template: sandbox-kubernetes.yaml set: @@ -865,14 +992,107 @@ tests: - failedTemplate: errorPattern: "apiServerEgress.ports" - - it: refuses pre-pull without a pinned function image + - it: refuses pre-pull without a pinned function image when the chart carries no default, as from a checkout + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + asserts: + - failedTemplate: + errorPattern: "needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image" + + - it: refuses the bundled pre-pull image when the app image is pinned to another release + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + app.image.tag: v0.0.1-other + asserts: + - failedTemplate: + errorPattern: "app.image.tag or .digest overridden needs sandbox.kubernetes.images.function.tag or .digest" + + - it: refuses the bundled pre-pull image when the app image is pinned by digest template: sandbox-kubernetes.yaml set: <<: *enabled sandbox.kubernetes.prePull.enabled: true + app.image.digest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + asserts: + - failedTemplate: + errorPattern: "app.image.tag or .digest overridden" + + - it: pre-pulls a pinned function image for an app pinned to another release + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + app.image.tag: v0.0.1-other + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/simstudioai/sandbox-function:abc123 + + - it: refuses TRIGGER_DEV_ENABLED in app.env, since Trigger.dev workers cannot reach sandbox pods + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.env.TRIGGER_DEV_ENABLED: "true" asserts: - failedTemplate: - errorPattern: "needs sandbox.kubernetes.images.function.tag or .digest" + errorPattern: "TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers" + + - it: refuses TRIGGER_DEV_ENABLED=1 from app.envDefaults + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.envDefaults.TRIGGER_DEV_ENABLED: "1" + asserts: + - failedTemplate: + errorPattern: "TRIGGER_DEV_ENABLED set" + + - it: lets app.env turn off a TRIGGER_DEV_ENABLED default + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.envDefaults.TRIGGER_DEV_ENABLED: "true" + app.env.TRIGGER_DEV_ENABLED: "false" + asserts: + - notFailedTemplate: {} + + - it: warns, without refusing to render, when cron jobs are off, since idle session sandbox pods would never be cleaned up + template: NOTES.txt + set: + <<: *enabled + cronjobs.enabled: false + asserts: + - matchRegexRaw: + pattern: "WARNING: Kubernetes sandboxes are enabled but the cleanup-session-sandboxes" + + - it: warns when the session sandbox cleanup job alone is off + template: NOTES.txt + set: + <<: *enabled + cronjobs.jobs.cleanupSessionSandboxes.enabled: false + asserts: + - matchRegexRaw: + pattern: "cleanup-session-sandboxes\\s+cron job is off" + + - it: renders the sandbox objects with the cleanup job off + template: sandbox-kubernetes.yaml + set: + <<: *enabled + cronjobs.jobs.cleanupSessionSandboxes.enabled: false + asserts: + - notFailedTemplate: {} + + - it: does not warn about session cleanup when the job runs + template: NOTES.txt + set: + <<: *enabled + asserts: + - notMatchRegexRaw: + pattern: "cleanup-session-sandboxes" - it: pre-pulls the pinned function image on sandbox nodes under the sandbox runtime template: daemonset-sandbox-prepull.yaml diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index c9a39856efe..64402a9413d 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -1511,15 +1511,33 @@ }, "cpu": { "type": "string", - "pattern": "^([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" }, "memory": { "type": "string", - "pattern": "^([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" }, "ephemeralStorage": { "type": "string", - "pattern": "^([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" + }, + "overheadPerPod": { + "type": "object", + "additionalProperties": false, + "properties": { + "cpu": { + "type": "string", + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" + }, + "memory": { + "type": "string", + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" + }, + "ephemeralStorage": { + "type": "string", + "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" + } + } } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 59a92287a0d..9797c466517 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1222,8 +1222,10 @@ sandbox: # Enabling sets SANDBOX_PROVIDER=kubernetes on the app, so do not also set it # in app.env. # The app creates and reaches the pods itself, so leave TRIGGER_DEV_ENABLED - # unset: Trigger.dev workers cannot reach them, and Sim reports the provider - # misconfigured while it is set. + # unset: Trigger.dev workers cannot reach them, and the chart refuses to + # render with it set. Keep cronjobs.enabled and + # cronjobs.jobs.cleanupSessionSandboxes.enabled on: that job deletes idle + # session pods, and the install notes warn when it is off. enabled: false # Namespace that holds sandbox pods. It must differ from the release namespace: @@ -1313,13 +1315,25 @@ sandbox: tolerations: [] # Namespace-wide ceiling on concurrent sandboxes. Past it, new sandboxes fail - # with a quota error instead of queueing. Keep pods x resources within it. + # with a quota error instead of queueing. cpu, memory, and ephemeralStorage + # cap the pods' summed limits, which include each pod's RuntimeClass + # overhead. Left empty, each is derived: pods x (resources + overhead), where + # overhead is runtimeClass.overhead.podFixed for a RuntimeClass the chart + # creates, or else overheadPerPod. A value set here wins, and the chart + # refuses one below that derived floor. quota: enabled: true pods: 20 - cpu: "20" - memory: 40Gi - ephemeralStorage: 80Gi + cpu: "" + memory: "" + ephemeralStorage: "" + # Overhead of a RuntimeClass the chart does not create (EKS, GKE, AKS), + # as `kubectl get runtimeclass -o jsonpath='{.overhead.podFixed}'` + # shows it, e.g. cpu: 250m, memory: 256Mi. Empty counts as none. + overheadPerPod: + cpu: "" + memory: "" + ephemeralStorage: "" limitRange: enabled: true @@ -1351,13 +1365,15 @@ sandbox: # node-local address no pod selector matches) and adds only # port 53 on private and cluster addresses. # restricted port 53 to the kube-system pods labeled k8s-app=kube-dns - # only, so it cannot reach an outside server. Where the - # resolver is node-local (EKS Auto Mode, NodeLocal DNSCache), - # DNS then fails: set this to an ipBlock for the nameserver in - # a sandbox pod's /etc/resolv.conf (169.254.20.10 for - # NodeLocal DNSCache; the Service CIDR's .10 on Auto Mode): + # and to the well-known node-local caches: 169.254.20.10 + # (GKE NodeLocal DNSCache, on by default on Autopilot) and + # 169.254.10.10 and 169.254.10.11 (AKS LocalDNS). It cannot + # reach an outside server. Where the resolver is elsewhere + # (EKS Auto Mode uses the Service CIDR's .10), DNS fails: set + # this to an ipBlock for the nameserver in a sandbox pod's + # /etc/resolv.conf, which replaces the defaults: # - ipBlock: - # cidr: 169.254.20.10/32 + # cidr: 172.20.0.10/32 dns: [] # Excluded from the internet profile: RFC 1918, CGNAT, link-local, Azure's # WireServer (168.63.129.16), IPv6 unique-local and link-local, and the @@ -1409,10 +1425,15 @@ sandbox: digest: "" # Keeps the function image on every sandbox node so a sandbox does not pull it - # on first use. Needs images.function.tag or digest, so it holds exactly the - # image the app runs. It runs in the release namespace, so it pulls with - # global.imagePullSecrets, not imagePullSecret. Each node runs one idle pod under the sandbox RuntimeClass, - # so it schedules where sandboxes do and pulls the way they do. + # on first use. With images.function tag and digest empty, a published chart + # holds the image its appVersion's app runs by default (files/sandbox-images.json, + # written at publish), on global.imageRegistry, and moves with every upgrade. + # A chart from a git checkout carries no default and needs images.function.tag + # or digest. If app.image.tag or digest points the app at another release, + # set images.function.tag or digest too: the chart refuses to guess. It runs in the release namespace, + # so it pulls with global.imagePullSecrets, not imagePullSecret. Each node + # runs one idle pod under the sandbox RuntimeClass, so it schedules where + # sandboxes do and pulls the way they do. prePull: enabled: false priorityClassName: "" diff --git a/scripts/write-chart-sandbox-images.ts b/scripts/write-chart-sandbox-images.ts new file mode 100644 index 00000000000..7eb7878aa6c --- /dev/null +++ b/scripts/write-chart-sandbox-images.ts @@ -0,0 +1,134 @@ +#!/usr/bin/env bun +/** + * Writes `helm/sim/files/sandbox-images.json` for a chart about to be published: the + * Function sandbox image the chart's appVersion runs by default, read from + * `apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json` at the + * release tag. The pre-pull DaemonSet then holds exactly that image without the + * operator pinning `sandbox.kubernetes.images.function`, which would also pin the app. + * + * The file is gitignored and written only here, next to `sync-chart-appversion.ts` in + * the publish jobs. Committing it would tie every sandbox image change to a chart + * version bump, and from a checkout it would not match appVersion anyway; a chart + * rendered from a checkout has no file, and pre-pull then needs an explicit tag. + * + * `--verify` then renders the chart with pre-pull on and fails unless the DaemonSet + * holds the written image, so a template regression cannot publish a chart whose + * default pre-pull silently pulls something else. It needs `helm` on PATH. + * + * Only node builtins are imported so this runs on a CI job with no dependencies + * installed, matching `sync-chart-appversion.ts`; for the same reason it reports + * with `console` rather than `@sim/logger`. + * + * The release tag must be present locally (a shallow checkout fetches it first). A release + * that predates the list (v0.9.72 and earlier) gets a notice and no file, so its chart + * behaves like a checkout: pre-pull needs an explicit function image. + * + * @example + * ``` + * bun run scripts/write-chart-sandbox-images.ts --version v0.9.73 --verify + * ``` + */ +import { spawnSync } from 'node:child_process' +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const CHART_DIR = resolve(ROOT, 'helm/sim') +const OUTPUT_PATH = resolve(CHART_DIR, 'files/sandbox-images.json') +const IMAGE_LIST_PATH = 'apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json' + +/** A release tag as this repository cuts them: `v1.2.3`. */ +const RELEASE_TAG = /^v\d+\.\d+\.\d+$/ + +/** The content-addressed reference `generate-sandbox-dockerfiles.ts` writes for the Function image. */ +const FUNCTION_IMAGE = /^ghcr\.io\/simstudioai\/sandbox-function:[0-9a-f]{16}$/ + +function parseArgs(argv: string[]): { version: string; verify: boolean } { + const versionIndex = argv.indexOf('--version') + const version = versionIndex === -1 ? '' : (argv[versionIndex + 1] ?? '') + if (!RELEASE_TAG.test(version)) { + throw new Error( + `--version must be a release tag like v1.2.3, got ${version ? `"${version}"` : ''}` + ) + } + return { version, verify: argv.includes('--verify') } +} + +function run(command: string, args: string[]): string { + const result = spawnSync(command, args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 << 20 }) + if (result.status !== 0) { + throw new Error(`${command} ${args[0]} failed: ${result.stderr || result.error}`) + } + return result.stdout +} + +/** True when `path` exists at `revision`; throws when the revision itself is unknown. */ +function existsAt(revision: string, path: string): boolean { + const commit = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${revision}^{commit}`], { + cwd: ROOT, + }) + if (commit.status !== 0) throw new Error(`Release tag ${revision} is not present locally`) + return spawnSync('git', ['cat-file', '-e', `${revision}:${path}`], { cwd: ROOT }).status === 0 +} + +function releaseFunctionImage(version: string): string { + const list: unknown = JSON.parse(run('git', ['show', `${version}:${IMAGE_LIST_PATH}`])) + const image = + typeof list === 'object' && list !== null && 'function' in list ? list.function : undefined + if (typeof image !== 'string' || !FUNCTION_IMAGE.test(image)) { + throw new Error(`${IMAGE_LIST_PATH} at ${version} names no Function image: ${String(image)}`) + } + return image +} + +/** Renders the pre-pull DaemonSet as a published chart would and returns its image. */ +function renderedPrePullImage(): string { + const manifest = run('helm', [ + 'template', + 'verify', + CHART_DIR, + '--namespace', + 'sim', + '--show-only', + 'templates/daemonset-sandbox-prepull.yaml', + '--set', + [ + 'app.env.BETTER_AUTH_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + 'app.env.ENCRYPTION_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + 'app.env.INTERNAL_API_SECRET=x', + 'app.env.CRON_SECRET=x', + 'postgresql.auth.password=xxxxxxxx', + 'sandbox.kubernetes.enabled=true', + 'sandbox.kubernetes.runtimeClass.preset=gvisor', + 'sandbox.kubernetes.prePull.enabled=true', + ].join(','), + ]) + const image = /^\s*image:\s*"?([^"\s]+)"?\s*$/m.exec(manifest)?.[1] + if (!image) throw new Error('The rendered pre-pull DaemonSet has no image') + return image +} + +async function main() { + const { version, verify } = parseArgs(process.argv.slice(2)) + if (!existsAt(version, IMAGE_LIST_PATH)) { + console.log( + `Notice: ${version} has no ${IMAGE_LIST_PATH}, so the chart carries no default sandbox Function image; sandbox.kubernetes.prePull needs images.function.tag or digest with it.` + ) + return + } + const image = releaseFunctionImage(version) + await mkdir(dirname(OUTPUT_PATH), { recursive: true }) + await writeFile(OUTPUT_PATH, `${JSON.stringify({ function: image }, null, 2)}\n`) + console.log(`Wrote ${image} to helm/sim/files/sandbox-images.json.`) + + if (!verify) return + const rendered = renderedPrePullImage() + if (rendered !== image) { + console.error(`The chart pre-pulls ${rendered}, not the release's ${image}.`) + process.exit(1) + } + console.log('The chart pre-pulls the release Function image by default.') +} + +if (import.meta.main) await main() From 7c8868e098ebe819d478335f1006fc06e79b7837 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 10:45:39 -0600 Subject: [PATCH 2/5] fix(sandbox): tolerate an untagged release commit at publish, keep Kubernetes read errors honest, and resolve the effective TRIGGER_DEV_ENABLED --- .github/workflows/helm.yml | 8 +-- .../scripts/fixtures/content-baseline.json | 7 +- .../remote-sandbox/kubernetes/startup.test.ts | 44 ++++++++++-- .../remote-sandbox/kubernetes/startup.ts | 18 +++-- helm/sim/templates/_helpers.tpl | 20 ++++-- helm/sim/tests/sandbox-kubernetes_test.yaml | 34 ++++++++++ scripts/write-chart-sandbox-images.test.ts | 30 ++++++++ scripts/write-chart-sandbox-images.ts | 68 +++++++++++++++---- 8 files changed, 194 insertions(+), 35 deletions(-) create mode 100644 scripts/write-chart-sandbox-images.test.ts diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 960b1f08a83..4cff18c2592 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -349,10 +349,9 @@ jobs: - name: Bundle the release's sandbox Function image env: APP_VERSION: ${{ needs.release-version.outputs.version }} - run: | - set -euo pipefail - git fetch --no-tags --depth=1 origin "refs/tags/${APP_VERSION}:refs/tags/${APP_VERSION}" - bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify + # The script fetches the tag itself, and reads HEAD when this is the release commit + # whose tag the release job has not cut yet. + run: bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify - name: Package chart id: package @@ -551,7 +550,6 @@ jobs: run: bun run scripts/sync-chart-appversion.ts --version "${APP_VERSION}" # Same bundled sandbox image as the OCI publish, so both repos ship the same chart. - # The full-history checkout already has the release tag. - name: Bundle the release's sandbox Function image if: steps.pages.outputs.exists == 'true' env: diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 0b21f0d55e7..dc39fd0f631 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -175501,7 +175501,7 @@ { "lang": "yaml", "meta": null, - "sha256": "7682823a0d915778f2433bbd40d57c0fb2abd8ffdc82774a2ad8e0716b51b5df", + "sha256": "367c0b8cc996a8dc240d3285d9bb77f38ad15eee8380c1477bcd84957dc25ec1", "bytes": 77, "line": 182 }, @@ -175553,6 +175553,11 @@ "sha256": "df790200d0bf869d634b8a6fb573356b2f2114cfada800837daf28aacac46198", "bytes": 208, "line": 401 + }, + { + "lang": "yaml", + "meta": null, + "sha256": "eecfe88b395d0c94f2b4b11d6c58d51fed7914a1bc13cca199dae94c55c9ae56" } ], "links": [ diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts index d4c7d3840e4..9decacb160a 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.test.ts @@ -91,15 +91,18 @@ function crashLoopingPod(name: string): V1Pod { } /** - * A cluster whose pod never changes: every watch ends quietly and every read returns `latest` + * A cluster whose pod never changes: every watch ends quietly and every read answers with `read` * (the created pod unless given). */ -function staticCluster(pod: V1Pod, latest: V1Pod = pod): SandboxCluster { +function staticCluster( + pod: V1Pod, + read: () => Promise = async () => pod +): SandboxCluster { return { namespace: SETTINGS.namespace, readRuntimeClassHandler: async () => 'runsc', createPod: async () => pod, - readPod: async () => latest, + readPod: read, listPods: async () => [], listPodEvents: async () => [], watchPod: (_name, _version, _onUpdate, signal) => @@ -117,13 +120,13 @@ function staticCluster(pod: V1Pod, latest: V1Pod = pod): SandboxCluster { } /** Starts `waitUntilReady` under a create deadline and records how it settled. */ -function start(pod: V1Pod, latest: V1Pod = pod) { +function start(pod: V1Pod, read: () => Promise = async () => pod) { const deadline = new AbortController() setTimeout(() => deadline.abort(), CREATE_DEADLINE_MS) const name = pod.metadata?.name ?? '' const outcome: { error?: unknown; settled: boolean } = { settled: false } waitUntilReady( - staticCluster(pod, latest), + staticCluster(pod, read), { pod, name, token: 'token' }, 'code', SETTINGS, @@ -166,7 +169,9 @@ describe('waitUntilReady for a pod that runs but whose agent never answers', () describe('waitUntilReady for a pod whose sandbox container crashes before its agent answers', () => { it('reports the crash and its exit, not the network path', async () => { checkHealth.mockResolvedValue(null) - const outcome = start(runningPod('sim-sbx-crashing'), crashLoopingPod('sim-sbx-crashing')) + const outcome = start(runningPod('sim-sbx-crashing'), async () => + crashLoopingPod('sim-sbx-crashing') + ) await vi.advanceTimersByTimeAsync(61_000) @@ -177,6 +182,33 @@ describe('waitUntilReady for a pod whose sandbox container crashes before its ag }) }) +describe('waitUntilReady when the re-read after a silent agent does not show the container', () => { + it('keeps a Kubernetes read failure in the error rather than blaming the network', async () => { + checkHealth.mockResolvedValue(null) + const outcome = start(runningPod('sim-sbx-unreadable'), async () => { + throw new Error('Kubernetes readPod failed: etcdserver: request timed out') + }) + + await vi.advanceTimersByTimeAsync(61_000) + + expect(outcome.settled).toBe(true) + expect(outcome.error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(String(outcome.error)).toContain('etcdserver: request timed out') + expect(String(outcome.error)).not.toContain('NetworkPolicy') + }) + + it('reports a pod deleted while its agent was starting', async () => { + checkHealth.mockResolvedValue(null) + const outcome = start(runningPod('sim-sbx-gone'), async () => null) + + await vi.advanceTimersByTimeAsync(61_000) + + expect(outcome.settled).toBe(true) + expect(String(outcome.error)).toContain('was deleted while its agent was starting') + expect(String(outcome.error)).not.toContain('NetworkPolicy') + }) +}) + describe('waitUntilReady for a pod no node can schedule', () => { it('fails as capacity at the create deadline', async () => { const outcome = start(pendingPod('sim-sbx-unscheduled')) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts index e8d27c65d30..ec4dd0998cc 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/startup.ts @@ -201,8 +201,8 @@ export async function waitForAgent(client: SandboxAgentClient, signal: AbortSign * Why the sandbox container stopped, when it has: its current or last termination (reason and * exit code), or null while it has run without a restart. */ -function sandboxContainerCrash(pod: V1Pod | null): string | null { - const status = pod?.status?.containerStatuses?.find(({ name }) => name === SANDBOX_CONTAINER_NAME) +function sandboxContainerCrash(pod: V1Pod): string | null { + const status = pod.status?.containerStatuses?.find(({ name }) => name === SANDBOX_CONTAINER_NAME) if (!status) return null const stillRunning = Boolean(status.state?.running) if (stillRunning && !status.restartCount) return null @@ -233,12 +233,22 @@ async function waitForRunningAgent( await waitForAgent(client, AbortSignal.any([signal, unreachable.signal])) } catch (error) { if (signal.aborted || !unreachable.signal.aborted) throw error - const latest = await cluster.readPod(name, { signal }).catch(() => null) + const silent = `Sandbox pod ${name} is running but its agent at ${baseUrl} did not answer within ${AGENT_UNREACHABLE_MS / 1000}s` + let latest: V1Pod | null + try { + latest = await cluster.readPod(name, { signal }) + } catch (readError) { + throw new KubernetesSandboxConfigError( + `${silent}, and re-reading the pod to tell a crashed container from a blocked network path failed: ${getErrorMessage(readError)}`, + { cause: error } + ) + } + if (!latest) throw new Error(`Sandbox pod ${name} was deleted while its agent was starting`) const crash = sandboxContainerCrash(latest) throw new KubernetesSandboxConfigError( crash ? `Sandbox pod ${name}'s sandbox container stopped before its agent answered (${crash}). Check that the sandbox image runs the agent the init container installs.` - : `Sandbox pod ${name} is running but its agent at ${baseUrl} did not answer within ${AGENT_UNREACHABLE_MS / 1000}s. ${AGENT_PATH_HINT}`, + : `${silent}. ${AGENT_PATH_HINT}`, { cause: error } ) } finally { diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index ae5b15867c4..62f8e586b6a 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1244,14 +1244,22 @@ refuse or that would weaken isolation. {{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image. Published charts (oci://ghcr.io/simstudioai/charts/sim and the Helm repository) carry the one their appVersion runs; a chart installed from a git checkout does not" -}} {{- end -}} {{- end -}} -{{- $trigger := "" -}} -{{- if hasKey .Values.app.env "TRIGGER_DEV_ENABLED" -}} -{{- $trigger = toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}} -{{- else if hasKey (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED" -}} -{{- $trigger = toString (default "" (index .Values.app.envDefaults "TRIGGER_DEV_ENABLED")) -}} +{{- /* + The app's effective TRIGGER_DEV_ENABLED: a literal extraEnvVars entry (the last + one, as Kubernetes keeps the last duplicate), else a non-empty app.env value + (an empty one reads as unset, so envDefaults still applies), else envDefaults. +*/ -}} +{{- $trigger := toString (default "" (index (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED")) -}} +{{- with toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}} +{{- $trigger = . -}} +{{- end -}} +{{- range .Values.extraEnvVars -}} +{{- if and (eq (toString .name) "TRIGGER_DEV_ENABLED") (hasKey . "value") -}} +{{- $trigger = toString (default "" .value) -}} +{{- end -}} {{- end -}} {{- if has (lower $trigger) (list "true" "1") -}} -{{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env and app.envDefaults so executions run on the database-backed job queue" -}} +{{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env, app.envDefaults, and extraEnvVars so executions run on the database-backed job queue" -}} {{- end -}} {{- if $sbx.quota.enabled -}} {{- range $field := list "cpu" "memory" "ephemeralStorage" -}} diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index 6bdf48c331a..abedb5fbb9a 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -1051,6 +1051,40 @@ tests: - failedTemplate: errorPattern: "TRIGGER_DEV_ENABLED set" + - it: refuses a TRIGGER_DEV_ENABLED default that an empty app.env entry leaves in force + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.envDefaults.TRIGGER_DEV_ENABLED: "true" + app.env.TRIGGER_DEV_ENABLED: "" + asserts: + - failedTemplate: + errorPattern: "TRIGGER_DEV_ENABLED set" + + - it: refuses TRIGGER_DEV_ENABLED set through extraEnvVars + template: sandbox-kubernetes.yaml + set: + <<: *enabled + extraEnvVars: + - name: TRIGGER_DEV_ENABLED + value: "true" + asserts: + - failedTemplate: + errorPattern: "TRIGGER_DEV_ENABLED set" + + - it: lets the last extraEnvVars entry turn off TRIGGER_DEV_ENABLED from app.env + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.env.TRIGGER_DEV_ENABLED: "true" + extraEnvVars: + - name: TRIGGER_DEV_ENABLED + value: "true" + - name: TRIGGER_DEV_ENABLED + value: "false" + asserts: + - notFailedTemplate: {} + - it: lets app.env turn off a TRIGGER_DEV_ENABLED default template: sandbox-kubernetes.yaml set: diff --git a/scripts/write-chart-sandbox-images.test.ts b/scripts/write-chart-sandbox-images.test.ts new file mode 100644 index 00000000000..2feda8f6129 --- /dev/null +++ b/scripts/write-chart-sandbox-images.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { releaseRevision } from './write-chart-sandbox-images' + +describe('releaseRevision', () => { + it('reads the release tag when it exists', () => { + expect(releaseRevision({ version: 'v1.2.3', tagPresent: true, headSubject: 'anything' })).toBe( + 'refs/tags/v1.2.3' + ) + }) + + it('reads HEAD on the untagged release commit', () => { + expect( + releaseRevision({ version: 'v1.2.3', tagPresent: false, headSubject: 'v1.2.3: release' }) + ).toBe('HEAD') + }) + + it.each([ + ['another release commit', 'v1.2.30: release'], + ['an ordinary commit', 'fix(sandbox): v1.2.3: something'], + ])('refuses %s when the tag is missing, naming the fetch failure', (_label, headSubject) => { + expect(() => + releaseRevision({ + version: 'v1.2.3', + tagPresent: false, + headSubject, + fetchError: "fatal: couldn't find remote ref\n", + }) + ).toThrow(/not present and HEAD .* is not its release commit; fetching the tag failed: fatal/) + }) +}) diff --git a/scripts/write-chart-sandbox-images.ts b/scripts/write-chart-sandbox-images.ts index 7eb7878aa6c..df95ed096ea 100644 --- a/scripts/write-chart-sandbox-images.ts +++ b/scripts/write-chart-sandbox-images.ts @@ -19,9 +19,12 @@ * installed, matching `sync-chart-appversion.ts`; for the same reason it reports * with `console` rather than `@sim/logger`. * - * The release tag must be present locally (a shallow checkout fetches it first). A release - * that predates the list (v0.9.72 and earlier) gets a notice and no file, so its chart - * behaves like a checkout: pre-pull needs an explicit function image. + * The release tag is fetched when the checkout lacks it (publish jobs check out shallow). On + * the release commit itself the tag may not exist yet, since publishing does not wait for the + * job that cuts it, so HEAD is read when its subject names the release (`v1.2.3: ...`, the rule + * helm.yml resolves the version by). A release that predates the list (v0.9.72 and earlier) + * gets a notice and no file, so its chart behaves like a checkout: pre-pull needs an explicit + * function image. * * @example * ``` @@ -63,17 +66,55 @@ function run(command: string, args: string[]): string { return result.stdout } -/** True when `path` exists at `revision`; throws when the revision itself is unknown. */ -function existsAt(revision: string, path: string): boolean { - const commit = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${revision}^{commit}`], { - cwd: ROOT, +function git(args: readonly string[]): { ok: boolean; stdout: string; stderr: string } { + const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' }) + return { ok: result.status === 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' } +} + +/** + * The git revision to read `version`'s image list from: its tag when present, else HEAD when + * HEAD is the release commit that will be tagged `version`. Throws otherwise, naming why. + */ +export function releaseRevision(input: { + version: string + tagPresent: boolean + headSubject: string + fetchError?: string +}): string { + if (input.tagPresent) return `refs/tags/${input.version}` + if (input.headSubject.startsWith(`${input.version}:`)) return 'HEAD' + throw new Error( + `Release tag ${input.version} is not present and HEAD ("${input.headSubject}") is not its release commit${input.fetchError ? `; fetching the tag failed: ${input.fetchError.trim()}` : ''}` + ) +} + +/** Resolves {@link releaseRevision} against the repository, fetching the tag when absent. */ +function resolveReleaseRevision(version: string): string { + const tagRef = `refs/tags/${version}` + const hasTag = () => git(['rev-parse', '--verify', '--quiet', `${tagRef}^{commit}`]).ok + let fetchError: string | undefined + if (!hasTag()) { + const fetched = git([ + 'fetch', + '--quiet', + '--no-tags', + '--depth', + '1', + 'origin', + `+${tagRef}:${tagRef}`, + ]) + if (!fetched.ok) fetchError = fetched.stderr + } + return releaseRevision({ + version, + tagPresent: hasTag(), + headSubject: git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim(), + fetchError, }) - if (commit.status !== 0) throw new Error(`Release tag ${revision} is not present locally`) - return spawnSync('git', ['cat-file', '-e', `${revision}:${path}`], { cwd: ROOT }).status === 0 } -function releaseFunctionImage(version: string): string { - const list: unknown = JSON.parse(run('git', ['show', `${version}:${IMAGE_LIST_PATH}`])) +function releaseFunctionImage(version: string, revision: string): string { + const list: unknown = JSON.parse(run('git', ['show', `${revision}:${IMAGE_LIST_PATH}`])) const image = typeof list === 'object' && list !== null && 'function' in list ? list.function : undefined if (typeof image !== 'string' || !FUNCTION_IMAGE.test(image)) { @@ -111,13 +152,14 @@ function renderedPrePullImage(): string { async function main() { const { version, verify } = parseArgs(process.argv.slice(2)) - if (!existsAt(version, IMAGE_LIST_PATH)) { + const revision = resolveReleaseRevision(version) + if (!git(['cat-file', '-e', `${revision}:${IMAGE_LIST_PATH}`]).ok) { console.log( `Notice: ${version} has no ${IMAGE_LIST_PATH}, so the chart carries no default sandbox Function image; sandbox.kubernetes.prePull needs images.function.tag or digest with it.` ) return } - const image = releaseFunctionImage(version) + const image = releaseFunctionImage(version, revision) await mkdir(dirname(OUTPUT_PATH), { recursive: true }) await writeFile(OUTPUT_PATH, `${JSON.stringify({ function: image }, null, 2)}\n`) console.log(`Wrote ${image} to helm/sim/files/sandbox-images.json.`) From b1ad9f48be0652aa76f755031651963c030f11fb Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 11:15:49 -0600 Subject: [PATCH 3/5] improvement(sandbox): drop overheadPerPod, concise chart messages and docs --- .github/workflows/helm.yml | 8 +++- .gitignore | 4 +- .../docs/platform/enterprise/self-hosted.mdx | 2 +- .../docs/platform/self-hosting/sandboxes.mdx | 10 ++-- .../core/config/env-capabilities.server.ts | 7 ++- .../remote-sandbox/kubernetes/errors.test.ts | 2 +- .../remote-sandbox/kubernetes/errors.ts | 2 +- .../remote-sandbox/kubernetes/pod.ts | 5 +- .../execute-request.test.ts | 14 ++++++ .../lib/function-execution/execute-request.ts | 17 +++++-- helm/sim/templates/NOTES.txt | 7 ++- helm/sim/templates/_helpers.tpl | 15 +++--- helm/sim/tests/sandbox-kubernetes_test.yaml | 46 ++++++++++++------- helm/sim/values.schema.json | 18 -------- helm/sim/values.yaml | 41 ++++++----------- scripts/write-chart-sandbox-images.ts | 14 ++---- 16 files changed, 103 insertions(+), 109 deletions(-) diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 4cff18c2592..d77d88103e9 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -549,12 +549,18 @@ jobs: APP_VERSION: ${{ needs.release-version.outputs.version }} run: bun run scripts/sync-chart-appversion.ts --version "${APP_VERSION}" + - name: Set up Helm + if: steps.pages.outputs.exists == 'true' + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5.1.0 + with: + version: v3.16.4 + # Same bundled sandbox image as the OCI publish, so both repos ship the same chart. - name: Bundle the release's sandbox Function image if: steps.pages.outputs.exists == 'true' env: APP_VERSION: ${{ needs.release-version.outputs.version }} - run: bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" + run: bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify - name: Configure Git if: steps.pages.outputs.exists == 'true' diff --git a/.gitignore b/.gitignore index 758bc2b3cf0..677ce68dd54 100644 --- a/.gitignore +++ b/.gitignore @@ -111,7 +111,5 @@ __pycache__/ # anything added there later. /uploads -# Written by scripts/write-chart-sandbox-images.ts in the chart publish jobs from the -# release's sandbox image list, so a published chart pre-pulls the function image its -# appVersion runs. Never committed: from a checkout it would not match appVersion. +# Written at chart publish by scripts/write-chart-sandbox-images.ts; never committed. /helm/sim/files/sandbox-images.json diff --git a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx index 60dc5eb22cb..27fdcdd4517 100644 --- a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx +++ b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx @@ -259,7 +259,7 @@ Each feature is one server variable. Permission groups also turn on organization ### Sandbox readiness -A Sandbox entitlement also requires a remote execution provider with credentials and an immutable Function base image. Until the server verifies readiness, the Function block offers no **Shell** language, and **Settings → Sandboxes** shows an upgrade notice instead of a sandbox list. +Shell needs only a ready remote execution provider (credentials and an immutable Function base image), not the Sandbox entitlement: the Function block offers it once the server verifies that provider. Custom sandboxes need both the entitlement and the ready provider; until then **Settings → Sandboxes** shows an upgrade notice instead of a sandbox list. JavaScript without `import`, `require`, a selected sandbox, or a sandbox file-path reference runs in local Node child workers in the app container when Sandbox flags are off. Python, Shell, JavaScript with external imports, and selected custom Sandboxes require the remote Function base and fail with a configuration error until it is ready. See [Sandboxes](/platform/self-hosting/sandboxes). diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index 9333ff493cb..ab275611474 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -116,7 +116,7 @@ DAYTONA_FUNCTION_SNAPSHOT_ID= |---|---| | `SANDBOXES_ENABLED=true` | Grants the server-side sandbox entitlement on a billing-disabled self-hosted deployment | -Shell needs no entitlement: it appears in the Function block's language list once the server has verified the provider credentials and the immutable Function base. The custom sandboxes (the Function block's **Sandbox** selector and the sandbox list in **Settings → Sandboxes**) also need the entitlement, an enterprise feature: `SANDBOXES_ENABLED=true` on a billing-disabled deployment, or `ENTERPRISE_ENABLED=true` when `SANDBOXES_ENABLED` is unset. Until both hold, **Settings → Sandboxes** stays in the sidebar with an upgrade notice. Python remains selectable; execution still requires the remote configuration, and a run without it fails with an error linking to this page. When a provider is configured but incomplete or invalid, the app logs why at startup. +Shell appears in the Function block's language list once the server has verified the provider credentials and Function base; it needs no entitlement. The **Sandbox** selector and **Settings → Sandboxes** also need the sandbox entitlement: `SANDBOXES_ENABLED=true` on a billing-disabled deployment, or `ENTERPRISE_ENABLED=true` when `SANDBOXES_ENABLED` is unset; until then **Settings → Sandboxes** shows an upgrade notice. Python is always selectable but fails without a provider, with an error linking here. An incomplete or invalid provider is logged at startup. ## Promote or roll back a build @@ -258,7 +258,7 @@ sandbox: effect: NoSchedule ``` -Leave `SANDBOX_PROVIDER` and the `E2B_*` and `DAYTONA_*` variables unset in `app.env`: the chart sets `SANDBOX_PROVIDER=kubernetes` itself. Leave `TRIGGER_DEV_ENABLED` unset too. Sandboxes are created by the app, which reaches each pod's agent directly, and Trigger.dev workers cannot; the chart refuses to render with it set. Keep `cronjobs.enabled` and `cronjobs.jobs.cleanupSessionSandboxes.enabled` on: without them idle session pods run until their 24-hour limit, and the install notes warn about it. Python and Shell work without an entitlement; for custom sandboxes on a billing-disabled deployment, also set `SANDBOXES_ENABLED=true` ([Enable sandbox access and controls](#enable-sandbox-access-and-controls)). +Leave `SANDBOX_PROVIDER`, `E2B_*`, `DAYTONA_*`, and `TRIGGER_DEV_ENABLED` unset in `app.env`: the chart sets `SANDBOX_PROVIDER=kubernetes`, and refuses `TRIGGER_DEV_ENABLED` because Trigger.dev workers cannot reach sandbox pods. Keep `cronjobs.enabled` and `cronjobs.jobs.cleanupSessionSandboxes.enabled` on, or idle session pods run until their 24-hour limit. For custom sandboxes on a billing-disabled deployment, also set `SANDBOXES_ENABLED=true` ([Enable sandbox access and controls](#enable-sandbox-access-and-controls)). Installing needs cluster-scoped rights as well as rights in the release namespace: the chart creates a ClusterRole and ClusterRoleBinding, the sandbox Namespace (with `namespace.create: true`) and a RuntimeClass (with `runtimeClass.create: true`), the ValidatingAdmissionPolicy and its binding, and, with `warmCapacity.sandboxes` above 0, a PriorityClass. @@ -269,7 +269,7 @@ With the provider enabled, the chart renders: - **A ClusterRole** allowing `get` on the configured RuntimeClass only, so the app can check its handler. - **A NetworkPolicy** that selects every pod in the sandbox namespace (see [Network access](#network-access)). - **A ResourceQuota and LimitRange** (see [Capacity and cost](#capacity-and-cost)). -- **A ValidatingAdmissionPolicy and its binding**, scoped to the sandbox namespace. It admits only pods shaped like the app's own: under the configured RuntimeClass, with `automountServiceAccountToken: false`, only `emptyDir` volumes, no host network, PID, or IPC namespace, and no sysctls; and in every init, regular, and ephemeral container, no privilege or privilege escalation, no capabilities beyond the six listed below, no `hostPort`, the `Default` procMount, and the `RuntimeDefault` seccomp profile (set on the container or the pod; an unset profile runs `Unconfined` on most clusters, so it is refused). GKE Sandbox does not apply seccomp profiles, so there the seccomp rule is admission hygiene and gVisor is the boundary. It does not rely on Pod Security, so it holds in a namespace nobody labeled. When the app and chart come from different releases, the policy can refuse the app's pods; the error then names the policy, and upgrading both together fixes it. It needs Kubernetes 1.30 or later. On an older cluster, set `sandbox.kubernetes.admissionPolicy.enabled: false` (which needs `namespace.create: true`), or the install fails on the unknown kind. +- **A ValidatingAdmissionPolicy and its binding**, scoped to the sandbox namespace. It admits only pods shaped like the app's own: under the configured RuntimeClass, with `automountServiceAccountToken: false`, only `emptyDir` volumes, no host network, PID, or IPC namespace, and no sysctls; and in every init, regular, and ephemeral container, no privilege or privilege escalation, no capabilities beyond the six listed below, no `hostPort`, the `Default` procMount, and the `RuntimeDefault` seccomp profile (set on the container or the pod; an unset profile runs `Unconfined` on most clusters, so it is refused). GKE Sandbox does not apply seccomp profiles, so there the seccomp rule is admission hygiene and gVisor is the boundary. It does not rely on Pod Security, so it holds in a namespace nobody labeled. Upgrade the chart and app image together: a policy from another release can refuse the app's pods. It needs Kubernetes 1.30 or later. On an older cluster, set `sandbox.kubernetes.admissionPolicy.enabled: false` (which needs `namespace.create: true`), or the install fails on the unknown kind. - **With `runtimeClass.create: true`, or a `runtimeClass.handler` named for an existing class, that handler** is passed to the app as `SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS`, so a VM runtime whose handler Sim does not recognise is accepted. The app still compares it with the RuntimeClass's real handler, and the chart refuses `runc` and `crun`. The app pod mounts its ServiceAccount token only when the provider is enabled; every other chart pod keeps it unmounted. With `networkPolicy.enabled: true`, the app's own policy also allows egress to the sandbox namespace on port 49983, and to the Kubernetes API on ports 443 and 6443. Narrow that to your API server addresses with `sandbox.kubernetes.apiServerEgress.cidrs`. @@ -363,7 +363,7 @@ A kind with no image fails closed with a configuration error. The Chat code-tool 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. -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 plus its RuntimeClass `overhead` (VM runtimes have one), not its requests. Left empty, as by default, each of the three is derived as `quota.pods` × (the matching `resources` value + overhead), so the quota admits `quota.pods` sandboxes whatever their size. The chart takes the overhead from `runtimeClass.overhead.podFixed` when it creates the RuntimeClass; for one your platform provides, set `quota.overheadPerPod` from `kubectl get runtimeclass -o jsonpath='{.overhead.podFixed}'`, or the derived quota admits fewer sandboxes than `quota.pods`. An explicit quota wins, and the chart refuses one below that derived floor. 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. +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 plus its RuntimeClass `overhead` (VM runtimes have one), not its requests. Left empty, as by default, each of the three is derived as `quota.pods` × (the matching `resources` value + overhead), so the quota admits `quota.pods` sandboxes whatever their size. The chart takes the overhead from `runtimeClass.overhead.podFixed` when it creates the RuntimeClass. For a RuntimeClass your platform provides, it cannot see the overhead: if `kubectl get runtimeclass -o jsonpath='{.overhead.podFixed}'` shows one, set `quota.cpu`, `quota.memory`, and `quota.ephemeralStorage` explicitly to `quota.pods` × (resources + that overhead), or the derived quota admits fewer sandboxes than `quota.pods`. An explicit quota wins, and the chart refuses one below that derived floor. 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. 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: @@ -373,7 +373,7 @@ Sim records no sandbox cost for this provider: you pay for the nodes. Set the ku ### Cold start and pre-pull -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's app runs by default, and moves with it on upgrade. A chart installed from a git checkout carries no default, so set `images.function.tag` or `digest` there, and also when `app.image.tag` or `digest` points the app at another release; the chart refuses to guess. 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. +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. 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. diff --git a/apps/sim/lib/core/config/env-capabilities.server.ts b/apps/sim/lib/core/config/env-capabilities.server.ts index d7bc018ccf3..d3968d84256 100644 --- a/apps/sim/lib/core/config/env-capabilities.server.ts +++ b/apps/sim/lib/core/config/env-capabilities.server.ts @@ -42,10 +42,9 @@ export function getSelectedSandboxProviderId() { } /** - * Logs why the remote sandbox cannot run when it is configured but incomplete or invalid (a - * provider half set up, a bad image ref, Kubernetes sandboxes with `TRIGGER_DEV_ENABLED`). Python, - * Shell, and JavaScript with imports are refused on such a deployment, so the operator needs the - * reason at boot rather than from a failing run. Silent when no sandbox is configured at all. + * Logs why a configured remote sandbox cannot run (a half-set-up provider, a bad image ref, + * Kubernetes with `TRIGGER_DEV_ENABLED`), so the operator sees it at boot. Silent when no sandbox + * is configured. */ export function reportSandboxConfiguration(): void { const { error } = inspectCapability(SANDBOX_CAPABILITY, env) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts index 6d23e5cdd4a..08e566fc18a 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.test.ts @@ -24,7 +24,7 @@ describe('toPodCreateError for an admission policy denial', () => { expect(error).toBeInstanceOf(KubernetesSandboxConfigError) expect(error.message).toContain(`ValidatingAdmissionPolicy "${POLICY}"`) - expect(error.message).toContain('upgrade the Helm chart and the app image together') + expect(error.message).toContain('upgrade the Helm chart and app image together') expect(error.message).not.toContain('SANDBOX_K8S_NODE_SELECTOR') expect(error.message).not.toContain('sandbox Role') }) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts index 52d797fac08..59cccd4044f 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts @@ -122,7 +122,7 @@ export function toPodCreateError(failure: KubernetesApiFailure, namespace: strin const policy = ADMISSION_POLICY_DENIAL.exec(failure.message)?.[1] if (policy !== undefined && (failure.status === 403 || failure.status === 422)) { return new KubernetesSandboxConfigError( - `The ValidatingAdmissionPolicy "${policy}" refused the sandbox pod. When that is the chart's sandbox admission policy (sandbox.kubernetes.admissionPolicy), the policy and the app that builds the pod are from different releases: upgrade the Helm chart and the app image together. Cluster detail: ${failure.message}` + `ValidatingAdmissionPolicy "${policy}" refused the sandbox pod. If it is the chart's sandbox admission policy, upgrade the Helm chart and app image together. Cluster detail: ${failure.message}` ) } if (failure.status === 403 && /violates PodSecurity/i.test(failure.message)) { diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts index 58236a29c15..c538f98974d 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -128,10 +128,7 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod { privileged: false, runAsUser: 0, runAsGroup: 0, - // Kept under every runtime: admission never sees the runtime, and the sandbox admission - // policy requires it. A self-managed gVisor runsc enforces the OCI seccomp filter inside its - // sandbox (its `oci-seccomp` flag); GKE Sandbox does not apply seccomp, so there it is - // admission hygiene only. Under runc it is the usual host-kernel filter. + // Required by the sandbox admission policy under every runtime; GKE Sandbox does not apply it. seccompProfile: { type: 'RuntimeDefault' }, } return { diff --git a/apps/sim/lib/function-execution/execute-request.test.ts b/apps/sim/lib/function-execution/execute-request.test.ts index d5c296a044f..1da342d2ac7 100644 --- a/apps/sim/lib/function-execution/execute-request.test.ts +++ b/apps/sim/lib/function-execution/execute-request.test.ts @@ -422,6 +422,20 @@ describe('Function execution request', () => { } ) + it('keeps the self-hosting guide out of the error on Sim Cloud', async () => { + envFlagsMock.isHosted = true + try { + const response = await POST(createMockRequest('POST', { language: 'python', code: 'x' })) + const data = await response.json() + + expect(data.success).toBe(false) + expect(data.error).toContain('requires a remote code sandbox') + expect(data.error).not.toContain('self-hosting') + } finally { + envFlagsMock.isHosted = false + } + }) + it.each([ { language: 'python', code: 'return 42', kind: 'code' }, { language: 'shell', code: 'echo ready', kind: 'shell' }, diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 8fe162c3f4a..f1957093a71 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -11,7 +11,11 @@ import { generateShortId } from '@sim/utils/id' import { toRecord } from '@sim/utils/object' import { NextResponse } from 'next/server' import type { ParsedFunctionExecuteBody } from '@/lib/api/contracts' -import { isMothershipSandboxEnabled, isRemoteSandboxEnabled } from '@/lib/core/config/env-flags' +import { + isHosted, + isMothershipSandboxEnabled, + isRemoteSandboxEnabled, +} from '@/lib/core/config/env-flags' import { createTimeoutAbortController, isTimeoutAbortReason, @@ -1009,6 +1013,11 @@ function cleanStdout(stdout: string): string { * representation instead of `[object Object]`. `null`/`undefined` become an empty * string to match POSIX env semantics. */ +/** Where a self-hosted operator sets up the sandbox a refused run needs; nothing on Sim Cloud. */ +function sandboxSetupHint(): string { + return isHosted ? '' : ` See ${SELF_HOSTED_SANDBOX_DOCS_URL}` +} + function serializeForShellEnv(value: unknown, nullValue = ''): string { if (value === null || value === undefined) return nullValue if (typeof value === 'string') return value @@ -2649,19 +2658,19 @@ export async function executeFunctionRequest( if (lang === CodeLanguage.Shell && !remoteSandboxEnabled) { throw new Error( - `Shell execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` + `Shell execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it.${sandboxSetupHint()}` ) } if (lang === CodeLanguage.Python && !remoteSandboxEnabled) { throw new Error( - `Python execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it, or use JavaScript instead. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` + `Python execution requires a remote code sandbox to be enabled. Please contact your administrator to enable it, or use JavaScript instead.${sandboxSetupHint()}` ) } if (lang === CodeLanguage.JavaScript && hasImports && !remoteSandboxEnabled) { throw new Error( - `JavaScript code with import statements requires a remote code sandbox to be enabled. Please remove the import statements, or contact your administrator to enable it. See ${SELF_HOSTED_SANDBOX_DOCS_URL}` + `JavaScript code with import statements requires a remote code sandbox to be enabled. Please remove the import statements, or contact your administrator to enable it.${sandboxSetupHint()}` ) } diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index 5b7f0d9b7d4..ff615667119 100644 --- a/helm/sim/templates/NOTES.txt +++ b/helm/sim/templates/NOTES.txt @@ -109,9 +109,8 @@ STORAGE_PROVIDER in values.yaml). {{- $cleanup := .Values.cronjobs.jobs.cleanupSessionSandboxes | default dict }} {{- if not (and .Values.cronjobs.enabled $cleanup.enabled) }} -WARNING: Kubernetes sandboxes are enabled but the cleanup-session-sandboxes -cron job is off (cronjobs.enabled or cronjobs.jobs.cleanupSessionSandboxes.enabled). -Idle chat-session sandbox pods then run until their 24-hour lifetime cap and -hold sandbox quota. Turn the job back on. +WARNING: the cleanup-session-sandboxes cron job is off, so idle session sandbox +pods run to their 24-hour cap and hold quota. Turn on cronjobs.enabled and +cronjobs.jobs.cleanupSessionSandboxes.enabled. {{- end }} {{- end }} diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index 62f8e586b6a..e41e3b7545c 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1238,10 +1238,10 @@ refuse or that would weaken isolation. {{- if and $sbx.prePull.enabled (not (include "sim.sandbox.image" (dict "root" . "kind" "function"))) -}} {{- $appImage := .Values.app.image -}} {{- if or $appImage.digest (and $appImage.tag (ne (toString $appImage.tag) (toString .Chart.AppVersion))) -}} -{{- fail (printf "sandbox.kubernetes.prePull.enabled=true with app.image.tag or .digest overridden needs sandbox.kubernetes.images.function.tag or .digest: the function image the chart bundles is the one chart appVersion %s runs, so with a different app it would pre-pull an image the app never uses" (toString .Chart.AppVersion)) -}} +{{- fail (printf "sandbox.kubernetes.prePull needs images.function.tag or .digest when app.image.tag or .digest is overridden: the bundled function image is the one appVersion %s runs." (toString .Chart.AppVersion)) -}} {{- end -}} {{- if not (include "sim.sandbox.bundledFunctionImage" .) -}} -{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image. Published charts (oci://ghcr.io/simstudioai/charts/sim and the Helm repository) carry the one their appVersion runs; a chart installed from a git checkout does not" -}} +{{- fail "sandbox.kubernetes.prePull needs images.function.tag or .digest: a chart from a git checkout carries no default function image." -}} {{- end -}} {{- end -}} {{- /* @@ -1267,7 +1267,7 @@ refuse or that would weaken isolation. {{- if $explicit -}} {{- $needed := include "sim.sandbox.quotaFloor" (dict "root" $ "field" $field) -}} {{- if lt (float64 (include "sim.quantity" $explicit)) (float64 (include "sim.quantity" $needed)) -}} -{{- fail (printf "sandbox.kubernetes.quota.%s %q is below %s, what quota.pods (%d) sandboxes of resources.%s plus their RuntimeClass overhead need: the quota would refuse sandboxes before quota.pods run. Raise it, or leave it empty to derive it" $field $explicit $needed (int $sbx.quota.pods) $field) -}} +{{- fail (printf "sandbox.kubernetes.quota.%s %q is below %s, what quota.pods (%d) sandboxes need (resources.%s plus RuntimeClass overhead). Raise it, or leave it empty to derive it." $field $explicit $needed (int $sbx.quota.pods) $field) -}} {{- end -}} {{- end -}} {{- end -}} @@ -1280,9 +1280,9 @@ refuse or that would weaken isolation. {{/* Kubernetes sandbox provider: the overhead one sandbox pod carries for a resource, -as a quantity ("0" when none): the chart-created RuntimeClass's -overhead.podFixed, or quota.overheadPerPod for a RuntimeClass the chart does -not create. ResourceQuota counts a pod's overhead on top of its containers. +as a quantity ("0" when none): overhead.podFixed of a RuntimeClass the chart +creates. The overhead of one the platform provides is unknown here, so explicit +quotas cover it. ResourceQuota counts a pod's overhead on top of its containers. Usage: {{ include "sim.sandbox.podOverhead" (dict "root" . "field" "memory") }} */}} {{- define "sim.sandbox.podOverhead" -}} @@ -1293,9 +1293,6 @@ Usage: {{ include "sim.sandbox.podOverhead" (dict "root" . "field" "memory") }} {{- $podFixed := (($sbx.runtimeClass.overhead | default dict).podFixed) | default dict -}} {{- $value = index $podFixed (get $podFixedKeys .field) | default "" -}} {{- end -}} -{{- if not $value -}} -{{- $value = index ($sbx.quota.overheadPerPod | default dict) .field | default "" -}} -{{- end -}} {{- toString (default "0" $value) -}} {{- end }} diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index abedb5fbb9a..813dec21484 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -860,30 +860,39 @@ tests: limits.memory: 50Gi limits.ephemeral-storage: 80Gi - - it: adds overheadPerPod for a RuntimeClass the cloud provider manages + - it: counts no overhead for a RuntimeClass the chart does not create, whose overhead it cannot see template: sandbox-kubernetes.yaml set: <<: *enabled - sandbox.kubernetes.quota.overheadPerPod.cpu: 100m - sandbox.kubernetes.quota.overheadPerPod.ephemeralStorage: 1Gi + sandbox.kubernetes.runtimeClass.overhead: + podFixed: + cpu: 250m documentSelector: path: kind value: ResourceQuota asserts: - equal: - path: spec.hard - value: - pods: "20" - limits.cpu: "22" - limits.memory: 40Gi - limits.ephemeral-storage: 100Gi + path: spec.hard["limits.cpu"] + value: "20" + + - it: rejects the removed quota.overheadPerPod, whose overhead an explicit quota now carries + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.quota.overheadPerPod.cpu: 100m + asserts: + - failedTemplate: + errorPattern: "overheadPerPod" - it: rounds each sandbox's sub-millicore and fractional-byte share up, as Kubernetes does template: sandbox-kubernetes.yaml set: <<: *enabled - sandbox.kubernetes.quota.overheadPerPod.cpu: "0.0004" - sandbox.kubernetes.quota.overheadPerPod.memory: "0.4" + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.overhead: + podFixed: + cpu: "0.0004" + memory: "0.4" documentSelector: path: kind value: ResourceQuota @@ -929,7 +938,10 @@ tests: set: <<: *enabled sandbox.kubernetes.quota.cpu: "20" - sandbox.kubernetes.quota.overheadPerPod.cpu: 250m + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.overhead: + podFixed: + cpu: 250m asserts: - failedTemplate: errorPattern: "quota.cpu \"20\" is below 25" @@ -999,7 +1011,7 @@ tests: sandbox.kubernetes.prePull.enabled: true asserts: - failedTemplate: - errorPattern: "needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image" + errorPattern: "prePull needs images.function.tag or .digest: a chart from a git checkout carries no default function image" - it: refuses the bundled pre-pull image when the app image is pinned to another release template: sandbox-kubernetes.yaml @@ -1009,7 +1021,7 @@ tests: app.image.tag: v0.0.1-other asserts: - failedTemplate: - errorPattern: "app.image.tag or .digest overridden needs sandbox.kubernetes.images.function.tag or .digest" + errorPattern: "prePull needs images.function.tag or .digest when app.image.tag or .digest is overridden" - it: refuses the bundled pre-pull image when the app image is pinned by digest template: sandbox-kubernetes.yaml @@ -1019,7 +1031,7 @@ tests: app.image.digest: sha256:0000000000000000000000000000000000000000000000000000000000000000 asserts: - failedTemplate: - errorPattern: "app.image.tag or .digest overridden" + errorPattern: "when app.image.tag or .digest is overridden" - it: pre-pulls a pinned function image for an app pinned to another release template: daemonset-sandbox-prepull.yaml @@ -1101,7 +1113,7 @@ tests: cronjobs.enabled: false asserts: - matchRegexRaw: - pattern: "WARNING: Kubernetes sandboxes are enabled but the cleanup-session-sandboxes" + pattern: "WARNING: the cleanup-session-sandboxes cron job is off" - it: warns when the session sandbox cleanup job alone is off template: NOTES.txt @@ -1110,7 +1122,7 @@ tests: cronjobs.jobs.cleanupSessionSandboxes.enabled: false asserts: - matchRegexRaw: - pattern: "cleanup-session-sandboxes\\s+cron job is off" + pattern: "cronjobs.jobs.cleanupSessionSandboxes.enabled" - it: renders the sandbox objects with the cleanup job off template: sandbox-kubernetes.yaml diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index 64402a9413d..751703efc3c 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -1520,24 +1520,6 @@ "ephemeralStorage": { "type": "string", "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" - }, - "overheadPerPod": { - "type": "object", - "additionalProperties": false, - "properties": { - "cpu": { - "type": "string", - "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" - }, - "memory": { - "type": "string", - "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" - }, - "ephemeralStorage": { - "type": "string", - "pattern": "^(([0-9]*[1-9][0-9]*(\\.[0-9]+)?|[0-9]+\\.[0-9]*[1-9][0-9]*)(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?)?$" - } - } } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 9797c466517..343649d0c50 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1221,11 +1221,9 @@ sandbox: # runtimeClass.preset for your platform; everything else has a safe default. # Enabling sets SANDBOX_PROVIDER=kubernetes on the app, so do not also set it # in app.env. - # The app creates and reaches the pods itself, so leave TRIGGER_DEV_ENABLED - # unset: Trigger.dev workers cannot reach them, and the chart refuses to - # render with it set. Keep cronjobs.enabled and - # cronjobs.jobs.cleanupSessionSandboxes.enabled on: that job deletes idle - # session pods, and the install notes warn when it is off. + # Leave TRIGGER_DEV_ENABLED unset (Trigger.dev workers cannot reach sandbox + # pods; the chart refuses it), and keep cronjobs.jobs.cleanupSessionSandboxes + # on: it deletes idle session pods. enabled: false # Namespace that holds sandbox pods. It must differ from the release namespace: @@ -1314,26 +1312,17 @@ sandbox: nodeSelector: {} tolerations: [] - # Namespace-wide ceiling on concurrent sandboxes. Past it, new sandboxes fail - # with a quota error instead of queueing. cpu, memory, and ephemeralStorage - # cap the pods' summed limits, which include each pod's RuntimeClass - # overhead. Left empty, each is derived: pods x (resources + overhead), where - # overhead is runtimeClass.overhead.podFixed for a RuntimeClass the chart - # creates, or else overheadPerPod. A value set here wins, and the chart - # refuses one below that derived floor. + # Namespace-wide ceiling on concurrent sandboxes; past it, new sandboxes fail + # with a quota error. Empty cpu/memory/ephemeralStorage derive + # pods x (resources + RuntimeClass overhead); a lower explicit value fails + # the render. With a RuntimeClass the chart does not create, add its + # overhead.podFixed to these when you set them. quota: enabled: true pods: 20 cpu: "" memory: "" ephemeralStorage: "" - # Overhead of a RuntimeClass the chart does not create (EKS, GKE, AKS), - # as `kubectl get runtimeclass -o jsonpath='{.overhead.podFixed}'` - # shows it, e.g. cpu: 250m, memory: 256Mi. Empty counts as none. - overheadPerPod: - cpu: "" - memory: "" - ephemeralStorage: "" limitRange: enabled: true @@ -1425,15 +1414,11 @@ sandbox: digest: "" # Keeps the function image on every sandbox node so a sandbox does not pull it - # on first use. With images.function tag and digest empty, a published chart - # holds the image its appVersion's app runs by default (files/sandbox-images.json, - # written at publish), on global.imageRegistry, and moves with every upgrade. - # A chart from a git checkout carries no default and needs images.function.tag - # or digest. If app.image.tag or digest points the app at another release, - # set images.function.tag or digest too: the chart refuses to guess. It runs in the release namespace, - # so it pulls with global.imagePullSecrets, not imagePullSecret. Each node - # runs one idle pod under the sandbox RuntimeClass, so it schedules where - # sandboxes do and pulls the way they do. + # on first use. A published chart defaults to the image its appVersion runs; + # from a git checkout, or with app.image.tag/digest overridden, set + # images.function.tag or digest. Runs in the release namespace (pulls with + # global.imagePullSecrets) under the sandbox RuntimeClass, so it schedules and + # pulls where sandboxes do. prePull: enabled: false priorityClassName: "" diff --git a/scripts/write-chart-sandbox-images.ts b/scripts/write-chart-sandbox-images.ts index df95ed096ea..2e2c9f5e9b2 100644 --- a/scripts/write-chart-sandbox-images.ts +++ b/scripts/write-chart-sandbox-images.ts @@ -6,24 +6,20 @@ * release tag. The pre-pull DaemonSet then holds exactly that image without the * operator pinning `sandbox.kubernetes.images.function`, which would also pin the app. * - * The file is gitignored and written only here, next to `sync-chart-appversion.ts` in - * the publish jobs. Committing it would tie every sandbox image change to a chart - * version bump, and from a checkout it would not match appVersion anyway; a chart - * rendered from a checkout has no file, and pre-pull then needs an explicit tag. + * Gitignored: a checkout's copy would not match appVersion, so a chart rendered from a + * checkout needs an explicit pre-pull tag. * * `--verify` then renders the chart with pre-pull on and fails unless the DaemonSet * holds the written image, so a template regression cannot publish a chart whose * default pre-pull silently pulls something else. It needs `helm` on PATH. * - * Only node builtins are imported so this runs on a CI job with no dependencies - * installed, matching `sync-chart-appversion.ts`; for the same reason it reports - * with `console` rather than `@sim/logger`. + * Imports only node builtins and logs with console, so it runs on a CI job with no install. * * The release tag is fetched when the checkout lacks it (publish jobs check out shallow). On * the release commit itself the tag may not exist yet, since publishing does not wait for the * job that cuts it, so HEAD is read when its subject names the release (`v1.2.3: ...`, the rule - * helm.yml resolves the version by). A release that predates the list (v0.9.72 and earlier) - * gets a notice and no file, so its chart behaves like a checkout: pre-pull needs an explicit + * helm.yml resolves the version by). A release that predates the list gets a notice and + * no file, so its chart behaves like a checkout: pre-pull needs an explicit * function image. * * @example From 9e88fa72a8311375a5e407a920773948d1fe5780 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 16:03:12 -0800 Subject: [PATCH 4/5] improvement(sandbox): use the shared env resolver and fold upgrade notes --- helm/sim/README.md | 10 +++++++--- helm/sim/templates/_helpers.tpl | 16 ++-------------- helm/sim/tests/sandbox-kubernetes_test.yaml | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/helm/sim/README.md b/helm/sim/README.md index 7d7cfdd3385..6289c27847c 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -643,9 +643,9 @@ kubectl --namespace sim logs deploy/sim-app -c migrations --- -## Upgrading to 1.20.0 +## Upgrading to 1.21.0 -Covers 1.19.0–1.20.0; 1.18.0 is the previous published chart. This release refuses some values earlier charts accepted; run `helm template` with your values before upgrading. +Covers 1.19.0–1.21.0; 1.18.0 is the previous published chart. This release refuses some values earlier charts accepted; run `helm template` with your values before upgrading. * **Argo CD or `helm template | kubectl apply`: recreate the bundled Postgres StatefulSets once.** Their volume claim labels no longer carry the chart version (Kubernetes forbids changing them, which broke every upgrade). `helm upgrade` and Flux reuse the existing labels and need nothing; tools that render without `lookup` must orphan-delete first, which keeps the pods and PVCs: @@ -658,7 +658,11 @@ Covers 1.19.0–1.20.0; 1.18.0 is the previous published chart. This release ref * **`BETTER_AUTH_URL` defaults to `NEXT_PUBLIC_APP_URL`.** Delete a copied `app.envDefaults.BETTER_AUTH_URL: http://localhost:3000`. In `app.secrets.existingSecret` mode, keep `BETTER_AUTH_URL` in the Secret. * **External Secrets: synced keys win over `envDefaults`.** A key mapped in `externalSecrets.remoteRefs.app` is no longer masked by the chart default. No action. * **existingSecret mode applies no `envDefaults`.** Put overrides in `app.env`, which is inlined in that mode. -* **New render checks.** An enabled `existingSecret` with an empty `name` (`app.secrets`, `postgresql.auth`, `externalDatabase`) fails, as does enabling both `postgresql` and `externalDatabase`. +* **New render checks.** An enabled `existingSecret` with an empty `name` (`app.secrets`, `postgresql.auth`, `externalDatabase`) fails, as does enabling both `postgresql` and `externalDatabase`, and `TRIGGER_DEV_ENABLED=true` with `sandbox.kubernetes.enabled` (unset it; Trigger.dev workers cannot reach sandbox pods). +* **Kubernetes sandboxes only:** + * **The quota is derived.** Empty `sandbox.kubernetes.quota.cpu`/`memory`/`ephemeralStorage` (the new default) become `quota.pods` x (resources + RuntimeClass overhead); an explicit value below that floor fails. With a RuntimeClass the chart does not create, add its `overhead.podFixed` when you set quotas. + * **`prePull` no longer needs `images.function.tag` on a published chart.** It defaults to the image the chart's appVersion runs; unset `images.function.tag` if you set it only for `prePull`. + * **The restricted egress profile's default DNS allows the node-local caches** (169.254.20.10 on GKE, 169.254.10.10 and .11 on AKS). No action. ## Upgrading to 1.16.0 diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index e41e3b7545c..0e0175c9862 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1244,20 +1244,8 @@ refuse or that would weaken isolation. {{- fail "sandbox.kubernetes.prePull needs images.function.tag or .digest: a chart from a git checkout carries no default function image." -}} {{- end -}} {{- end -}} -{{- /* - The app's effective TRIGGER_DEV_ENABLED: a literal extraEnvVars entry (the last - one, as Kubernetes keeps the last duplicate), else a non-empty app.env value - (an empty one reads as unset, so envDefaults still applies), else envDefaults. -*/ -}} -{{- $trigger := toString (default "" (index (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED")) -}} -{{- with toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}} -{{- $trigger = . -}} -{{- end -}} -{{- range .Values.extraEnvVars -}} -{{- if and (eq (toString .name) "TRIGGER_DEV_ENABLED") (hasKey . "value") -}} -{{- $trigger = toString (default "" .value) -}} -{{- end -}} -{{- end -}} +{{- /* "?" is a secret reference the chart cannot read, so it does not fail. */ -}} +{{- $trigger := include "sim.envValue" (dict "root" . "key" "TRIGGER_DEV_ENABLED" "component" "app") -}} {{- if has (lower $trigger) (list "true" "1") -}} {{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env, app.envDefaults, and extraEnvVars so executions run on the database-backed job queue" -}} {{- end -}} diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index 813dec21484..5f8b42b6d26 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -1097,6 +1097,20 @@ tests: asserts: - notFailedTemplate: {} + - it: does not guess at a TRIGGER_DEV_ENABLED it cannot read from a secret reference + template: sandbox-kubernetes.yaml + set: + <<: *enabled + app.envDefaults.TRIGGER_DEV_ENABLED: "true" + extraEnvVars: + - name: TRIGGER_DEV_ENABLED + valueFrom: + secretKeyRef: + name: trigger + key: enabled + asserts: + - notFailedTemplate: {} + - it: lets app.env turn off a TRIGGER_DEV_ENABLED default template: sandbox-kubernetes.yaml set: From a71b630970c7a12b80477d43571895e66d244716 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 16:22:09 -0800 Subject: [PATCH 5/5] fix(sandbox): count the agent init container in the derived quota --- .../scripts/fixtures/content-baseline.json | 6 +++-- .../config/env-capabilities.server.test.ts | 1 + .../core/config/env-capabilities.server.ts | 14 +++++++---- helm/sim/templates/_helpers.tpl | 25 ++++++++++++++----- helm/sim/tests/sandbox-kubernetes_test.yaml | 20 +++++++++++++++ 5 files changed, 53 insertions(+), 13 deletions(-) diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index dc39fd0f631..cefa7727e4a 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -175502,7 +175502,7 @@ "lang": "yaml", "meta": null, "sha256": "367c0b8cc996a8dc240d3285d9bb77f38ad15eee8380c1477bcd84957dc25ec1", - "bytes": 77, + "bytes": 174, "line": 182 }, { @@ -175557,7 +175557,9 @@ { "lang": "yaml", "meta": null, - "sha256": "eecfe88b395d0c94f2b4b11d6c58d51fed7914a1bc13cca199dae94c55c9ae56" + "sha256": "eecfe88b395d0c94f2b4b11d6c58d51fed7914a1bc13cca199dae94c55c9ae56", + "bytes": 299, + "line": 429 } ], "links": [ diff --git a/apps/sim/lib/core/config/env-capabilities.server.test.ts b/apps/sim/lib/core/config/env-capabilities.server.test.ts index 76bd5004967..ace38337624 100644 --- a/apps/sim/lib/core/config/env-capabilities.server.test.ts +++ b/apps/sim/lib/core/config/env-capabilities.server.test.ts @@ -112,6 +112,7 @@ describe('server environment capabilities', () => { reportSandboxConfiguration() expect(capabilityLogger.warn).toHaveBeenCalledTimes(1) + expect(capabilityLogger.warn.mock.calls[0]?.[0]).toContain('provider is misconfigured') expect(capabilityLogger.warn.mock.calls[0]?.[1]).toMatchObject({ error: expect.stringContaining('TRIGGER_DEV_ENABLED'), }) diff --git a/apps/sim/lib/core/config/env-capabilities.server.ts b/apps/sim/lib/core/config/env-capabilities.server.ts index d3968d84256..e5830467d52 100644 --- a/apps/sim/lib/core/config/env-capabilities.server.ts +++ b/apps/sim/lib/core/config/env-capabilities.server.ts @@ -47,12 +47,16 @@ export function getSelectedSandboxProviderId() { * is configured. */ export function reportSandboxConfiguration(): void { - const { error } = inspectCapability(SANDBOX_CAPABILITY, env) + const { error, providerId } = inspectCapability(SANDBOX_CAPABILITY, env) if (!error) return - logger.warn('Remote sandbox is configured but cannot run; remote code execution is disabled', { - error: error.message, - docs: SELF_HOSTED_SANDBOX_DOCS_URL, - }) + logger.warn( + 'Selected sandbox provider is misconfigured; the sandbox kinds it cannot serve will fail', + { + provider: providerId, + error: error.message, + docs: SELF_HOSTED_SANDBOX_DOCS_URL, + } + ) } export function getConfiguredAsyncJobsProvider() { diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index 0e0175c9862..4c4db091765 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1221,8 +1221,9 @@ refuse or that would weaken isolation. {{- end -}} {{- end -}} {{- if $sbx.limitRange.enabled -}} -{{- /* The agent init container's limits (pod.ts agentInstallerContainer); the LimitRange max applies to it too. */ -}} -{{- range $field, $floor := dict "cpu" "100m" "memory" "128Mi" "ephemeralStorage" "32Mi" -}} +{{- /* The LimitRange max applies to the agent init container too. */ -}} +{{- range $field := list "cpu" "memory" "ephemeralStorage" -}} +{{- $floor := include "sim.sandbox.agentInitLimit" $field -}} {{- $value := toString (index $sbx.resources $field) -}} {{- if lt (float64 (include "sim.quantity" $value)) (float64 (include "sim.quantity" $floor)) -}} {{- fail (printf "sandbox.kubernetes.resources.%s %q is below %s, the agent init container's limit: the sandbox LimitRange would refuse every sandbox pod" $field $value $floor) -}} @@ -1284,17 +1285,29 @@ Usage: {{ include "sim.sandbox.podOverhead" (dict "root" . "field" "memory") }} {{- toString (default "0" $value) -}} {{- end }} +{{/* +Kubernetes sandbox provider: the agent init container's limit for a resource +(agentInstallerContainer in kubernetes/pod.ts), as a quantity. +Usage: {{ include "sim.sandbox.agentInitLimit" "memory" }} +*/}} +{{- define "sim.sandbox.agentInitLimit" -}} +{{- get (dict "cpu" "100m" "memory" "128Mi" "ephemeralStorage" "32Mi") . -}} +{{- end }} + {{/* Kubernetes sandbox provider: the least quota for a resource that admits -quota.pods sandboxes, as a quantity: pods x (resources. + pod overhead). -Every sandbox container's request is at most its limit, which the quota caps -(limits.*), and the agent init container is smaller than the sandbox container. +quota.pods sandboxes, as a quantity: pods x (pod limit + pod overhead). The +quota caps limits (limits.*), and a pod's limit is the larger of its one +sandbox container's (resources.) and its agent init container's. CPU renders in whole cores or millicores, memory and storage in Gi, Mi, or bytes. Usage: {{ include "sim.sandbox.quotaFloor" (dict "root" . "field" "memory") }} */}} {{- define "sim.sandbox.quotaFloor" -}} {{- $sbx := .root.Values.sandbox.kubernetes -}} -{{- $perPod := addf (include "sim.quantity" (toString (index $sbx.resources .field))) (include "sim.quantity" (include "sim.sandbox.podOverhead" .)) -}} +{{- $podLimit := float64 (include "sim.quantity" (toString (index $sbx.resources .field))) -}} +{{- $initLimit := float64 (include "sim.quantity" (include "sim.sandbox.agentInitLimit" .field)) -}} +{{- if lt $podLimit $initLimit -}}{{- $podLimit = $initLimit -}}{{- end -}} +{{- $perPod := addf $podLimit (include "sim.quantity" (include "sim.sandbox.podOverhead" .)) -}} {{- if eq .field "cpu" -}} {{- /* Rounded up per pod, as Kubernetes rounds a sub-millicore or fractional-byte quantity; the small tolerance keeps float error from bumping an exact value. */ -}} {{- $millis := mul (int64 $sbx.quota.pods) (int64 (ceil (subf (mulf $perPod 1000) 0.000001))) -}} diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index 5f8b42b6d26..64c85b8d16f 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -904,6 +904,26 @@ tests: path: spec.hard["limits.memory"] value: "42949672980" + - it: sizes each sandbox's share by its agent init container when that is larger, without a LimitRange + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.limitRange.enabled: false + sandbox.kubernetes.resources.cpu: 50m + sandbox.kubernetes.resources.memory: 64Mi + sandbox.kubernetes.resources.ephemeralStorage: 16Mi + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard + value: + pods: "20" + limits.cpu: "2" + limits.memory: 2560Mi + limits.ephemeral-storage: 640Mi + - it: keeps an explicit quota at or above what the sandboxes need template: sandbox-kubernetes.yaml set: