From fbc170866db76c10de76ab39405d7eb7ad82580e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 03:24:48 -0600 Subject: [PATCH 1/6] fix(self-hosting): let sim-setup update adopt a manually installed compose file, and correct the last doc gaps --- .../docs/platform/self-hosting/docker.mdx | 20 +++-- .../docs/platform/self-hosting/kubernetes.mdx | 7 +- .../docs/platform/self-hosting/sandboxes.mdx | 12 ++- .../docs/platform/self-hosting/upgrades.mdx | 30 ++++++- .../docs/platform/self-hosting/verify.mdx | 2 +- .../scripts/fixtures/content-baseline.json | 32 ++++++- helm/sim/Chart.yaml | 2 +- helm/sim/README.md | 9 +- helm/sim/templates/NOTES.txt | 2 +- helm/sim/tests/notes_test.yaml | 13 +-- packages/sim-setup/README.md | 20 +++-- packages/sim-setup/src/compose-asset.test.ts | 4 +- packages/sim-setup/src/compose-asset.ts | 86 ++++++++++++++++--- packages/sim-setup/src/lifecycle.test.ts | 86 ++++++++++++++++++- packages/sim-setup/src/lifecycle.ts | 53 ++++++++++-- packages/sim-setup/src/modes/k8s.ts | 35 ++++++-- 16 files changed, 342 insertions(+), 71 deletions(-) diff --git a/apps/docs/content/docs/platform/self-hosting/docker.mdx b/apps/docs/content/docs/platform/self-hosting/docker.mdx index dfaf1a26465..8c747ff4f70 100644 --- a/apps/docs/content/docs/platform/self-hosting/docker.mdx +++ b/apps/docs/content/docs/platform/self-hosting/docker.mdx @@ -24,7 +24,7 @@ The wizard writes `docker-compose.prod.yml` and a generated `.env` to `./sim`, a ## Manual install [#production-setup] -Fetch the Compose file from the [release](https://github.com/simstudioai/sim/releases) you want to run: +Fetch the Compose file from the [release](https://github.com/simstudioai/sim/releases) you want to run. Use a `vX.Y.Z` release tag (e.g. the release marked Latest), not a `helm-chart-*` tag: ```bash mkdir sim && cd sim @@ -78,11 +78,11 @@ curl -fsS http://localhost:3000/api/health Then run [Verify your install](/platform/self-hosting/verify). -Without object storage, uploads go to the `sim_uploads` volume on this host. Back it up, or configure [object storage](/platform/self-hosting/object-storage). +Without object storage, uploads go to the `sim_uploads` volume on this host (Docker names it `_sim_uploads`, after the Compose project name). Back it up with the commands in [Upgrades](/platform/self-hosting/upgrades#upgrade-procedure), or configure [object storage](/platform/self-hosting/object-storage). ## Serve your domain over TLS -Put a TLS proxy in front of the stack. Route `/socket.io` to realtime on port 3002 and everything else to the app on port 3000, with WebSocket upgrades and response streaming enabled. [Networking](/platform/self-hosting/networking#reverse-proxy-configuration) has Caddy, Nginx, and Traefik configurations. +Put a TLS proxy in front of the stack. Route `/socket.io` to realtime on port 3002 and everything else to the app on port 3000, with WebSocket upgrades and response streaming enabled. [Networking](/platform/self-hosting/networking#reverse-proxy-configuration) has Caddy and Nginx configurations. When the proxy runs on the same host, publish the app and realtime on loopback only. Keep the ports, which `sim-setup` checks: @@ -142,17 +142,17 @@ To run Ollama, LM Studio, or vLLM with this stack, see [Local models](/platform/ ## The `sim-setup` CLI -Run `npx sim-setup `. Run the wizard, `doctor`, and `config` from the configuration directory. Lifecycle commands find running Compose stacks, source checkouts, and Helm releases, and apply every Compose file a stack was started with. A stopped stack uses `COMPOSE_FILE` from its `.env`. Compose does not record profiles, so set `COMPOSE_PROFILES` in `.env` for a stack that uses them. +Run `npx sim-setup `. Run the wizard, `doctor`, and `config` from the configuration directory. Lifecycle commands find running Compose stacks, source checkouts, and the `sim-dev` Helm release that `--mode k8s` creates (not other Helm releases), and apply every Compose file a stack was started with. A stopped stack uses `COMPOSE_FILE` from its `.env`. Compose does not record profiles, so set `COMPOSE_PROFILES` in `.env` for a stack that uses them. | Command | Behavior | | --- | --- | | `sim-setup` | Wizard. `--quick` uses defaults; `--mode compose\|dev\|k8s` picks the target (dev and k8s need a source checkout: run `bun run sim-setup` from the repo root); `--url ` sets a Compose install's public URL. | | `status` | Reports detected installations and their health. | -| `logs` | Follows Compose logs or the Kubernetes app Deployment. | +| `logs` | Follows Compose logs or the `sim-dev` release's app Deployment. | | `start` / `stop` / `restart` | Manages Compose services. For Kubernetes, prints the commands instead of running them. `restart` does not apply changed environment; recreate the containers. | -| `update` | Pulls the images for `SIM_VERSION` (or rebuilds a source stack) and recreates the services. `--yes` skips the prompt about uploads still inside an old app container. Refuses dev and Kubernetes installs. | -| `down` | Removes managed containers, or uninstalls the Helm release, after confirming. Data volumes remain. | -| `reset` | Archives env files and removes managed Compose data after confirming. On Helm it uninstalls the release; PostgreSQL PVCs remain. | +| `update` | Refreshes the Compose file, pulls the images for `SIM_VERSION` (or rebuilds a source stack), and recreates the services. Works for `sim-setup` and manual installs; a manually downloaded Compose file is backed up beside itself before it is replaced. `--yes` skips the prompts for that and for uploads still inside an old app container. Refuses dev and Kubernetes installs. | +| `down` | Removes managed containers, or uninstalls the `sim-dev` Helm release, after confirming. Data volumes remain. | +| `reset` | Archives env files and removes managed Compose data after confirming. On Kubernetes it uninstalls the `sim-dev` release; PostgreSQL PVCs remain. | | `config` | Reports configured capabilities and integrations. | | `doctor` | Checks env files and reachable services. `--fix` writes supported repairs; `--json` prints structured findings. | | `add ` | Configures `email`, `storage`, `sandbox`, `jobs`, `knowledge`, `knowledge-embeddings`, `chat`, `llm`, or `integration ` in a writable `.env`. Refuses Helm releases. | @@ -166,4 +166,6 @@ Run `npx sim-setup `. Run the wizard, `doctor`, and `config` from the c ## Back up and upgrade [#commands] -Back up the database, the `sim_uploads` volume, and `.env`. [Upgrades](/platform/self-hosting/upgrades) has the backup, update, and rollback commands. +Back up the database, the `_sim_uploads` volume, and `.env`. [Upgrades](/platform/self-hosting/upgrades) has the backup, update, and rollback commands. + +To upgrade, set `SIM_VERSION` in `.env` and run `npx sim-setup update`, for a `sim-setup` or a manual install; it backs up a manually downloaded Compose file first, and `--yes` runs it without prompting. Without `sim-setup`, download `docker-compose.prod.yml` from the new `vX.Y.Z` tag as in [Manual install](#production-setup), set `SIM_VERSION` to that tag, and run `docker compose pull && docker compose up -d` (with `-f docker-compose.prod.yml` unless `COMPOSE_FILE` is set). diff --git a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx index 097850024cc..8827c0ba4e2 100644 --- a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx @@ -95,6 +95,7 @@ postgresql: size: 50Gi ``` +- With External Secrets, move `NEXT_PUBLIC_APP_URL` from `app.env` to `app.envDefaults` and `realtime.envDefaults`: the chart refuses an `app.env` key that `externalSecrets.remoteRefs.app` does not map. See the [External Secrets example](#secret-store-examples). - `BETTER_AUTH_URL` follows `NEXT_PUBLIC_APP_URL`, and realtime always admits that origin. In existing-Secret mode the chart derives neither: set `NEXT_PUBLIC_APP_URL` and `BETTER_AUTH_URL` in the Secret or `app.env`. - Realtime is served on the app host under `/socket.io`. For a separate realtime host, set `ingress.realtime.host`; the chart points the app at it with `NEXT_PUBLIC_SOCKET_URL` (in existing-Secret mode, set that yourself). Cover both hosts with the certificate. - The `null` removes the chart's default ingress-nginx annotation. Configure your controller's own HTTPS redirect, body size, WebSocket, timeout, and streaming settings; see [Networking](/platform/self-hosting/networking). @@ -122,7 +123,7 @@ helm install sim oci://ghcr.io/simstudioai/charts/sim \ --set postgresql.auth.password="$POSTGRES_PASSWORD" ``` -With an existing Secret or External Secrets, drop the `--set` lines. Render first with `helm template` and the same arguments to review what will be applied. +With an existing Secret or External Secrets, drop the `--set` lines; with External Secrets, `NEXT_PUBLIC_APP_URL` must be in `app.envDefaults` and `realtime.envDefaults`, not `app.env` (step 5). Render first with `helm template` and the same arguments to review what will be applied. For a trial without ingress, install with `app.env.NEXT_PUBLIC_APP_URL=http://localhost:3000` and `ingress.enabled=false` in place of the public values, then forward both services and open [http://localhost:3000](http://localhost:3000): @@ -140,7 +141,7 @@ kubectl get cronjobs -n simstudio curl -fsS https://sim.yourdomain.com/api/health ``` -Run `helm test sim -n simstudio --logs`, then [Verify your install](/platform/self-hosting/verify). +Run `helm test sim -n simstudio --logs --timeout 10m`, then [Verify your install](/platform/self-hosting/verify). ## Secret store examples [#secret-store-examples] @@ -159,7 +160,7 @@ postgresql: name: sim-postgresql-secret ``` -**External Secrets Operator.** Create the store and remote keys first. Non-secret values go in `envDefaults`: +**External Secrets Operator.** Create the store and remote keys first. Non-secret values go in `envDefaults`, including `NEXT_PUBLIC_APP_URL` from step 5: the chart refuses any `app.env` key not mapped in `remoteRefs.app`: ```yaml app: diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index 49b05f882a5..e654408d44c 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -208,7 +208,7 @@ sandbox: -Then [verify your install](#verify-your-install). Without a preset, the chart refuses to render and names the preset for each platform. The sections below cover what the chart creates and every knob past these defaults. +Then run `helm test --logs --timeout 10m`: it starts a real sandbox and checks it is confined (see [Verify your install](#verify-your-install)). Without a preset, the chart refuses to render and names the preset for each platform. The sections below cover what the chart creates and every knob past these defaults. ### How it works @@ -415,7 +415,15 @@ What Sim's sandboxes need on EKS Auto Mode with Nitro Sandboxes (`runtimeClass.p ### Verify your install -Run the live suite against your cluster from a checkout with dependencies installed (`bun install`). It starts real sandboxes through the provider, as the app's ServiceAccount, and checks isolation, network policy, and cleanup. It makes no cloud calls; it uses whatever your kubectl context grants and writes a JSON report: +Run the chart's test after every install or upgrade: + +```bash +helm test -n --logs --timeout 10m +``` + +Its self-check starts a real sandbox through the provider and passes only when user code runs as the sandbox user, with no cloud metadata credentials or Kubernetes API, and cannot reach the app, its data stores, or another sandbox. The reach checks fail where the network plugin does not enforce NetworkPolicy. `--logs` prints each check's result. + +For a deeper, optional check, run the live suite against your cluster from a checkout with dependencies installed (`bun install`). It starts real sandboxes through the provider, as the app's ServiceAccount, and checks isolation, network policy, and cleanup. It makes no cloud calls; it uses whatever your kubectl context grants and writes a JSON report: ```bash kubectl config use-context diff --git a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx index 7102cda04a2..bc359fe6cf1 100644 --- a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx +++ b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx @@ -15,13 +15,13 @@ The app, realtime, and migrations images must run the same release; they share t -Set `SIM_VERSION` in `.env` to a tag from the [releases page](https://github.com/simstudioai/sim/releases). One variable drives all three images; without it they track `latest`. +Set `SIM_VERSION` in `.env` to a `vX.Y.Z` release tag from the [releases page](https://github.com/simstudioai/sim/releases) (e.g. the release marked Latest), not a `helm-chart-*` tag. One variable drives all three images; without it they track `latest`. ```bash SIM_VERSION= ``` -The `cron` image shares no schema and follows `SIM_CRON_VERSION`, or `latest`. +The `cron` image shares no schema and follows `latest` unless `SIM_CRON_VERSION` is set. When you pin an older `SIM_VERSION`, pin `SIM_CRON_VERSION` to the same release so the scheduler calls only job endpoints that release has. @@ -46,7 +46,7 @@ Read every entry between your current release and the target. Chart-only value c ```bash docker compose -f docker-compose.prod.yml cp simstudio:/app/apps/sim/uploads ./uploads-backup -# switch to the new docker-compose.prod.yml, or run npx sim-setup update, then: +# run npx sim-setup update, or switch to the new docker-compose.prod.yml, then: docker compose -f docker-compose.prod.yml cp ./uploads-backup/. simstudio:/app/apps/sim/uploads docker compose -f docker-compose.prod.yml exec -u 0 simstudio chown -R nextjs:nodejs /app/apps/sim/uploads ``` @@ -103,7 +103,29 @@ npx sim-setup update docker compose -f docker-compose.prod.yml logs migrations ``` -`update` refreshes its managed copy of the Compose file, pulls the images for `SIM_VERSION`, and recreates the stack, keeping the data volumes. It applies every Compose file the stack uses, as recorded in `COMPOSE_FILE`. It refuses to overwrite a Compose file you edited; keep customizations in an overlay. Compose has no rolling updates, so plan a short maintenance window. +`update` works for installs made with `sim-setup` and for manual installs. It refreshes the Compose file, pulls the images for `SIM_VERSION`, and recreates the stack, keeping the data volumes. It applies every Compose file the stack uses, as recorded in `COMPOSE_FILE`. A manually downloaded Compose file is first moved to a timestamped backup beside it (`docker-compose.prod.yml.bak- diff --git a/apps/docs/content/docs/platform/self-hosting/verify.mdx b/apps/docs/content/docs/platform/self-hosting/verify.mdx index b1794eac2a8..34d98dcf528 100644 --- a/apps/docs/content/docs/platform/self-hosting/verify.mdx +++ b/apps/docs/content/docs/platform/self-hosting/verify.mdx @@ -69,7 +69,7 @@ kubectl get cronjobs -n simstudio The migrations init container must complete before the app starts. Inspect failed CronJob pods and their logs; the presence of a schedule alone does not prove the endpoint call succeeded. -Then run `helm test sim -n simstudio --logs`. One test pod checks the app and realtime Services answer; the other calls the app's authenticated self-check, which passes only when the database answers and is migrated, Redis answers, realtime is healthy, and, with the Kubernetes sandbox provider, a sandbox runs user code confined (sandbox user, no cloud metadata credentials or Kubernetes API, no reach into the app, its data stores, or another sandbox). `--logs` prints each check's result. It skips, passing, when `CRON_SECRET` is not in the app Secret. +Then run `helm test sim -n simstudio --logs --timeout 10m`. One test pod checks the app and realtime Services answer; the other calls the app's authenticated self-check, which passes only when the database answers and is migrated, Redis answers, realtime is healthy, and, with the Kubernetes sandbox provider, a sandbox runs user code confined (sandbox user, no cloud metadata credentials or Kubernetes API, no reach into the app, its data stores, or another sandbox). `--logs` prints each check's result. It skips, passing, when `CRON_SECRET` is not in the app Secret. For Compose: diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 2dc56e3d155..d2928e33a65 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -174948,6 +174948,13 @@ "bytes": 137, "line": 380 }, + { + "lang": "bash", + "meta": null, + "sha256": "ff167fa2e294ffcc39ee7cbc155f7dfe5cc879fdf5c8d519cafdafe407d7ac4e", + "bytes": 55, + "line": 420 + }, { "lang": "bash", "meta": null, @@ -175637,9 +175644,9 @@ { "lang": "bash", "meta": null, - "sha256": "b50d71970c84ee49664e12825a44282aa99b2bf5518e22802993072f6ca0a9d6", + "sha256": "3303961098245a66cb9e784f3c477a0694cca631e5f21ca73c22e11d9fedce55", "bytes": 376, - "line": 43 + "line": 47 }, { "lang": "bash", @@ -175655,6 +175662,27 @@ "bytes": 320, "line": 93 }, + { + "lang": "bash", + "meta": null, + "sha256": "c5a65043e9f6e56cc008680976a8f175be94e52290ad74f51dbd3a837425c544", + "bytes": 272, + "line": 110 + }, + { + "lang": "bash", + "meta": null, + "sha256": "62b5bbf5c8dfa8f5e9fa0a8deadd465ba2329845914ab9a6f482ed8c5a50fb04", + "bytes": 114, + "line": 120 + }, + { + "lang": "bash", + "meta": null, + "sha256": "16eedc8fd9f8c687ea53d7bb41cdf432d360f8af5aacc79bb1d68c5a5b4c8ed6", + "bytes": 112, + "line": 126 + }, { "lang": "bash", "meta": null, diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 7441336a4d4..2f5f9ac4a57 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.22.1 +version: 1.22.2 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/README.md b/helm/sim/README.md index 2de4d77fead..5fbd0d06e2a 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -136,7 +136,8 @@ confined: as the sandbox user, with no cloud metadata credentials or Kubernetes API, and no reach into the app, its data stores, or another sandbox. The reach checks fail where the network plugin does not enforce NetworkPolicy. `--logs` prints the JSON report (each check with pass, fail, warn, or skip); the pods stay -until the next `helm test`. +until the next `helm test`. Keep `--timeout 10m`: the self-check retries for up +to a minute and its request can take four, past helm's 5-minute default. The self-check skips, and passes, when `CRON_SECRET` is not in the app Secret or the app image has no self-check endpoint. Disable it with @@ -335,11 +336,11 @@ When `autoscaling.enabled=true`, the chart omits `spec.replicas` from the Deploy --- -## Upgrading to 1.22.1 +## Upgrading to 1.22.2 -Covers 1.22.0–1.22.1; 1.21.0 is the previous published chart. +Covers 1.22.0–1.22.2; 1.21.0 is the previous published chart. -* **`helm test` runs the authenticated self-check, and `tests.image` is now `curlimages/curl:8.5.0`.** Drop a `busybox` override of `tests.image`; with Kubernetes sandboxes run `helm test` with `--timeout 10m`. See [Test the install](#test-the-install). +* **`helm test` runs the authenticated self-check, and `tests.image` is now `curlimages/curl:8.5.0`.** Drop a `busybox` override of `tests.image`, and always run `helm test` with `--timeout 10m`: the self-check can outlast helm's 5-minute default. See [Test the install](#test-the-install). * **Air-gapped mirrors: `images.yaml` adds `pause` and the `copilot-sandbox-*` images, and `busybox` is gone.** Mirror from the published chart's copy, which also lists the sandbox images its appVersion runs. * **Each scheduled job has a `description` in `values.yaml`.** No action. diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index e6fa671fbd2..d5e0ad1e852 100644 --- a/helm/sim/templates/NOTES.txt +++ b/helm/sim/templates/NOTES.txt @@ -91,7 +91,7 @@ STORAGE_PROVIDER in values.yaml). kubectl --namespace {{ .Release.Namespace }} logs -f deployment/{{ include "sim.fullname" . }}-app # Prove the install works (connectivity, database, migrations, Redis, sandboxes) - helm test {{ .Release.Name }} --namespace {{ .Release.Namespace }} --logs{{ if .Values.sandbox.kubernetes.enabled }} --timeout 10m{{ end }} + helm test {{ .Release.Name }} --namespace {{ .Release.Namespace }} --logs --timeout 10m # Show the rendered values helm get values {{ .Release.Name }} --namespace {{ .Release.Namespace }} diff --git a/helm/sim/tests/notes_test.yaml b/helm/sim/tests/notes_test.yaml index 549f88d79b0..c1cd8de9b4f 100644 --- a/helm/sim/tests/notes_test.yaml +++ b/helm/sim/tests/notes_test.yaml @@ -27,18 +27,9 @@ tests: - notMatchRegexRaw: pattern: "\\./helm/sim" - - it: gives helm test room for the sandbox check's two sandbox pods when Kubernetes sandboxes are on + - it: gives helm test room beyond helm's 5m default, since the self-check can take over 5 minutes set: <<: *defaults - sandbox.kubernetes.enabled: true - sandbox.kubernetes.runtimeClass.preset: gvisor asserts: - matchRegexRaw: - pattern: "helm test t --namespace sim --logs --timeout 10m" - - - it: prints the plain helm test command without Kubernetes sandboxes - set: - <<: *defaults - asserts: - - matchRegexRaw: - pattern: "helm test t --namespace sim --logs\\n" + pattern: "helm test t --namespace sim --logs --timeout 10m\\n" diff --git a/packages/sim-setup/README.md b/packages/sim-setup/README.md index e9a7192d629..590c6a59208 100644 --- a/packages/sim-setup/README.md +++ b/packages/sim-setup/README.md @@ -199,7 +199,11 @@ npx sim-setup status The update command keeps Docker volumes, applies the current managed Compose file, pulls the version selected by `SIM_VERSION`, and runs migrations. If -`SIM_VERSION` is unset, the deployment tracks `latest`. +`SIM_VERSION` is unset, the deployment tracks `latest`. It also updates a +manually installed `docker-compose.prod.yml`: after you confirm (or with +`--yes`), it moves that file to a timestamped backup beside it and installs the +current one. It refuses to overwrite a file you edited after `sim-setup` +installed it; keep customizations in a Compose overlay. For production, pin an explicit version, back up the database first, and read the [upgrade guide](https://docs.sim.ai/platform/self-hosting/upgrades). Docker @@ -216,7 +220,8 @@ data. In particular, `ENCRYPTION_KEY` and `API_ENCRYPTION_KEY` protect stored credentials and API keys. A database backup restored without the matching keys contains data that Sim cannot decrypt. -PostgreSQL data lives in a Docker volume. These commands preserve it: +PostgreSQL data and, without object storage, uploaded files live in Docker +volumes. These commands preserve them: - `start` - `stop` @@ -228,10 +233,13 @@ PostgreSQL data lives in a Docker volume. These commands preserve it: installation. If Docker is not running, `reset` stops without changing anything. The local archive is not a substitute for an off-machine backup. -The default local file-storage fallback is different: uploaded files live inside -the application container, not in a managed volume. They can be lost when the -container is removed or recreated, including during `down` or `update`. -Configure object storage before keeping files you care about. +Without object storage, uploaded files live in the `_sim_uploads` +volume, where `` is the installation's Compose project name. Back it +up with the database (the +[upgrade guide](https://docs.sim.ai/platform/self-hosting/upgrades) has the +commands), or configure object storage. Installations from before that volume +kept uploads inside the application container; `update` warns and asks before +recreating such a container. ## Production deployments diff --git a/packages/sim-setup/src/compose-asset.test.ts b/packages/sim-setup/src/compose-asset.test.ts index 6587cda4c07..b5860af218d 100644 --- a/packages/sim-setup/src/compose-asset.test.ts +++ b/packages/sim-setup/src/compose-asset.test.ts @@ -21,13 +21,13 @@ afterEach(() => { }) describe('ensureProductionComposeFile', () => { - it('fails instead of overwriting local Compose changes', () => { + it('refuses to overwrite a managed file edited since sim-setup wrote it', () => { const root = tempRoot() const composeFile = ensureProductionComposeFile(standaloneContext(root)) writeFileSync(composeFile, `${readFileSync(composeFile, 'utf8')}\n# local change\n`) expect(() => ensureProductionComposeFile({ kind: 'standalone', root, existing: true })).toThrow( - 'has local changes' + 'was edited after sim-setup installed it' ) }) }) diff --git a/packages/sim-setup/src/compose-asset.ts b/packages/sim-setup/src/compose-asset.ts index 7b115371975..55374ab64da 100644 --- a/packages/sim-setup/src/compose-asset.ts +++ b/packages/sim-setup/src/compose-asset.ts @@ -3,11 +3,16 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from import path from 'node:path' import { fileURLToPath } from 'node:url' import { SETUP_CONTEXT, type SetupContext } from './context' +import { archiveFile } from './env-files' const COMPOSE_FILE = 'docker-compose.prod.yml' const SIM_COMPOSE_MARKER = 'ghcr.io/simstudioai/simstudio' const MANAGED_STATE_FILE = '.sim-setup.json' +/** Where the docs show keeping Compose customizations in an overlay file. */ +export const OVERLAY_DOCS = + 'https://docs.sim.ai/platform/self-hosting/docker#external-postgresql-and-redis' + interface ManagedState { schemaVersion: 1 composeSha256: string @@ -46,6 +51,66 @@ function packagedComposeFile(): string { : path.join(moduleDirectory, COMPOSE_FILE) } +type ComposeFileState = 'current' | 'managed' | 'unmanaged' | 'edited' + +/** + * Classifies an existing Compose file against the packaged copy: `current` matches it, + * `managed` is an unedited copy sim-setup wrote earlier, `unmanaged` is a Sim file sim-setup + * never recorded (fetched by hand per the manual-install docs), and `edited` is a managed + * file changed since sim-setup wrote it. + */ +function classifyComposeFile( + root: string, + destination: string, + packaged: string +): ComposeFileState { + const current = readFileSync(destination, 'utf8') + if (current === packaged) return 'current' + if (!current.includes(SIM_COMPOSE_MARKER)) { + throw new Error(`${destination} exists but is not a recognized Sim Compose file`) + } + const managed = readManagedState(root) + if (!managed) return 'unmanaged' + return managed.composeSha256 === sha256(current) ? 'managed' : 'edited' +} + +function readPackagedComposeFile(): { bundled: string; packaged: string } { + const bundled = packagedComposeFile() + if (!existsSync(bundled)) { + throw new Error(`The sim-setup package is missing its bundled ${COMPOSE_FILE}`) + } + return { bundled, packaged: readFileSync(bundled, 'utf8') } +} + +/** + * Whether a published install holds a Sim Compose file that sim-setup never recorded and that + * differs from the packaged copy, as after a manual install. Updating it needs adoption. + */ +export function hasUnmanagedComposeFile(context: SetupContext = SETUP_CONTEXT): boolean { + if (context.kind === 'source') return false + const destination = path.join(context.root, COMPOSE_FILE) + if (!existsSync(destination)) return false + const { packaged } = readPackagedComposeFile() + return classifyComposeFile(context.root, destination, packaged) === 'unmanaged' +} + +/** + * Takes over a manually installed Compose file: moves it to a timestamped backup beside itself, + * writes the packaged copy, and records it as managed. Returns the backup path. + */ +export function adoptUnmanagedComposeFile(context: SetupContext = SETUP_CONTEXT): string { + if (!hasUnmanagedComposeFile(context)) { + throw new Error(`${COMPOSE_FILE} in ${context.root} is not an unmanaged Sim Compose file`) + } + const destination = path.join(context.root, COMPOSE_FILE) + const backup = archiveFile(destination) + if (!backup) throw new Error(`${destination} disappeared before it could be backed up`) + const { bundled, packaged } = readPackagedComposeFile() + copyFileSync(bundled, destination) + writeManagedState(context.root, packaged) + return backup +} + /** Materializes the published Compose asset without overwriting user-customized files. */ export function ensureProductionComposeFile(context: SetupContext = SETUP_CONTEXT): string { const destination = path.join(context.root, COMPOSE_FILE) @@ -56,25 +121,22 @@ export function ensureProductionComposeFile(context: SetupContext = SETUP_CONTEX return destination } - const bundled = packagedComposeFile() - if (!existsSync(bundled)) { - throw new Error(`The sim-setup package is missing its bundled ${COMPOSE_FILE}`) - } + const { bundled, packaged } = readPackagedComposeFile() mkdirSync(context.root, { recursive: true }) - const packaged = readFileSync(bundled, 'utf8') if (existsSync(destination)) { - const current = readFileSync(destination, 'utf8') - if (current === packaged) { + const existing = classifyComposeFile(context.root, destination, packaged) + if (existing === 'current') { writeManagedState(context.root, packaged) return destination } - if (!current.includes(SIM_COMPOSE_MARKER)) { - throw new Error(`${destination} exists but is not a recognized Sim Compose file`) + if (existing === 'unmanaged') { + throw new Error( + `${destination} was not installed by sim-setup and differs from this version; run \`npx sim-setup update\` to back it up and replace it.` + ) } - const managed = readManagedState(context.root) - if (!managed || managed.composeSha256 !== sha256(current)) { + if (existing === 'edited') { throw new Error( - `${destination} has local changes; preserve or remove your customizations before updating it.` + `${destination} was edited after sim-setup installed it; move your changes to a Compose overlay (${OVERLAY_DOCS}) and restore the file, or delete it and ${MANAGED_STATE_FILE}, before updating.` ) } } diff --git a/packages/sim-setup/src/lifecycle.test.ts b/packages/sim-setup/src/lifecycle.test.ts index 59a70602922..76b3a9ab4c6 100644 --- a/packages/sim-setup/src/lifecycle.test.ts +++ b/packages/sim-setup/src/lifecycle.test.ts @@ -1,7 +1,15 @@ -import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' -import { afterAll, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, describe, expect, it, vi } from 'vitest' const { fakeRoot, mockSpawnSync, mockConfirm } = vi.hoisted(() => { const { mkdtempSync } = require('node:fs') as typeof import('node:fs') @@ -36,6 +44,7 @@ import { composeServiceQuery, composeServiceState, type Install, + refreshComposeFileForUpdate, runLifecycle, serviceStatusRows, uploadsLostOnRecreate, @@ -243,3 +252,76 @@ describe('uploads an update would discard', () => { expect(uploadsLostOnRecreate(mounts, changes)).toBe(atRisk) }) }) + +describe('update of a manually installed Compose file', () => { + const roots: string[] = [] + const stdinIsTTY = process.stdin.isTTY + + afterEach(() => { + process.stdin.isTTY = stdinIsTTY + mockConfirm.mockReset() + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) + }) + + /** A directory holding an older Compose file fetched by hand, with no sim-setup state. */ + function manualInstall(): { root: string; file: string; manual: string; packaged: string } { + const root = mkdtempSync(path.join(tmpdir(), 'sim-setup-manual-')) + roots.push(root) + const file = ensureProductionComposeFile({ kind: 'standalone', root, existing: false }) + const packaged = readFileSync(file, 'utf8') + rmSync(path.join(root, '.sim-setup.json')) + const manual = packaged.replace(/\n {2}uploads-init:[\s\S]*$/, '\n') + writeFileSync(file, manual) + return { root, file, manual, packaged } + } + + it('backs up and replaces the file with --yes, then treats it as managed', async () => { + const { root, file, manual, packaged } = manualInstall() + + await expect(refreshComposeFileForUpdate(file, root, true)).resolves.toBe(file) + + expect(readFileSync(file, 'utf8')).toBe(packaged) + const backups = readdirSync(root).filter((name) => + name.startsWith('docker-compose.prod.yml.bak-') + ) + expect(backups).toHaveLength(1) + expect(readFileSync(path.join(root, backups[0]), 'utf8')).toBe(manual) + expect(mockConfirm).not.toHaveBeenCalled() + await expect(refreshComposeFileForUpdate(file, root, false)).resolves.toBe(file) + }) + + it('refuses without --yes when no one can confirm, leaving the file alone', async () => { + const { root, file, manual } = manualInstall() + process.stdin.isTTY = false + + await expect(refreshComposeFileForUpdate(file, root, false)).rejects.toThrow( + 'was not installed by sim-setup' + ) + + expect(readFileSync(file, 'utf8')).toBe(manual) + expect(readdirSync(root).some((name) => name.includes('.bak-'))).toBe(false) + }) + + it('leaves the file alone when the operator declines', async () => { + const { root, file, manual } = manualInstall() + process.stdin.isTTY = true + mockConfirm.mockResolvedValue(false) + + await expect(refreshComposeFileForUpdate(file, root, false)).resolves.toBeNull() + + expect(readFileSync(file, 'utf8')).toBe(manual) + expect(readdirSync(root).some((name) => name.includes('.bak-'))).toBe(false) + }) + + it('updates a file identical to the packaged copy without a backup or prompt', async () => { + const { root, file, packaged } = manualInstall() + writeFileSync(file, packaged) + process.stdin.isTTY = false + + await expect(refreshComposeFileForUpdate(file, root, false)).resolves.toBe(file) + + expect(readFileSync(file, 'utf8')).toBe(packaged) + expect(readdirSync(root).some((name) => name.includes('.bak-'))).toBe(false) + expect(mockConfirm).not.toHaveBeenCalled() + }) +}) diff --git a/packages/sim-setup/src/lifecycle.ts b/packages/sim-setup/src/lifecycle.ts index 48558848869..9187f0f4941 100644 --- a/packages/sim-setup/src/lifecycle.ts +++ b/packages/sim-setup/src/lifecycle.ts @@ -2,7 +2,12 @@ import { spawnSync } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' import { toRecordOrNull } from '@sim/utils/object' -import { ensureProductionComposeFile } from './compose-asset' +import { + adoptUnmanagedComposeFile, + ensureProductionComposeFile, + hasUnmanagedComposeFile, + OVERLAY_DOCS, +} from './compose-asset' import { choosePostgresPassword, composeFileRequiresPostgresPassword, @@ -535,10 +540,43 @@ export function getComposeUpdateMode(file: string): ComposeUpdateMode { throw new Error(`Unsupported Sim Compose file: ${file}`) } -/** Refreshes a published install's managed Compose file before applying an update. */ -export function refreshComposeFileForUpdate(file: string, dir: string): string { +/** + * Refreshes a published install's managed Compose file before applying an update. A manually + * installed file is backed up and replaced, after confirmation (`yes` confirms up front); returns + * null when the operator declines. + */ +export async function refreshComposeFileForUpdate( + file: string, + dir: string, + yes: boolean +): Promise { if (getComposeUpdateMode(file) === 'build') return file - return ensureProductionComposeFile(resolveSetupContextAtRoot(dir)) + const context = resolveSetupContextAtRoot(dir) + if (hasUnmanagedComposeFile(context)) { + p.note( + [ + `${file} was not installed by sim-setup and differs from this version.`, + 'Updating moves it to a timestamped backup beside it and installs the current file.', + `Re-apply any edits of your own as a Compose overlay: ${OVERLAY_DOCS}`, + ].join('\n'), + 'Manually installed Compose file' + ) + if (!yes) { + if (!process.stdin.isTTY) { + throw new SetupError(`${file} was not installed by sim-setup.`, [ + `re-run ${theme.command('npx sim-setup update --yes')} to back it up and replace it`, + ]) + } + const confirmed = await p.confirm({ + message: 'Back up and replace this Compose file?', + initialValue: false, + }) + if (!confirmed) return null + } + const backup = adoptUnmanagedComposeFile(context) + p.log.step(`Backed up your Compose file to ${backup}`) + } + return ensureProductionComposeFile(context) } /** Where the app keeps local uploads inside its container. */ @@ -639,7 +677,12 @@ async function update(install: Install, yes: boolean): Promise { const mode = getComposeUpdateMode(install.file) if (mode === 'pull') { const previous = path.resolve(install.file) - install.file = refreshComposeFileForUpdate(install.file, install.dir) + const refreshed = await refreshComposeFileForUpdate(install.file, install.dir, yes) + if (!refreshed) { + p.log.info('Update cancelled.') + return + } + install.file = refreshed install.recordedFiles = install.recordedFiles?.map((file) => path.resolve(file) === previous ? install.file : file ) diff --git a/packages/sim-setup/src/modes/k8s.ts b/packages/sim-setup/src/modes/k8s.ts index b13a2d6a8b9..6df252955c9 100644 --- a/packages/sim-setup/src/modes/k8s.ts +++ b/packages/sim-setup/src/modes/k8s.ts @@ -284,11 +284,29 @@ async function helmInstall( } } +interface ImageValues { + image?: { tag?: string } +} + interface ReleaseValues { - app?: { env?: Record } + app?: ImageValues & { env?: Record } + realtime?: ImageValues + migrations?: ImageValues postgresql?: { auth?: { password?: string } } } +/** + * `--set` flags pinning the app, realtime, and migrations images. A checkout's chart carries a + * deliberately stale appVersion, so without them the release would run old images; a tag + * the existing release already pins is kept. + */ +function imageTagArgs(values: ReleaseValues | null): string[] { + return (['app', 'realtime', 'migrations'] as const).flatMap((component) => [ + '--set', + `${component}.image.tag=${values?.[component]?.image?.tag || 'latest'}`, + ]) +} + function existingReleaseValues(context: string): ReleaseValues | null { const scope = ['--kube-context', context, '-n', NAMESPACE] const status = spawnSync('helm', ['status', RELEASE, ...scope], { stdio: 'ignore' }) @@ -399,6 +417,7 @@ export async function runK8sMode(detection: Detection): Promise { './helm/sim/examples/values-development.yaml', '--values', '-', + ...imageTagArgs(releaseValues), '--wait', '--timeout', '15m', @@ -412,17 +431,21 @@ export async function runK8sMode(detection: Detection): Promise { throw new SetupError(getErrorMessage(error), [ `pod status: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} get pods`)}`, `stuck pods: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} describe pod | tail -20`)}`, - 'ImagePullBackOff on ghcr.io/simstudioai/* usually means the chart appVersion tag was never published — check Chart.yaml against ghcr', + 'ImagePullBackOff on ghcr.io/simstudioai/* usually means the image tag was never published — check app.image.tag against ghcr', ]) } spin.stop('Release deployed, all pods ready') const testSpin = p.spinner() testSpin.start('Running helm test…') - const test = spawnSync('helm', ['test', RELEASE, '--kube-context', context, '-n', NAMESPACE], { - encoding: 'utf8', - cwd: ROOT, - }) + const test = spawnSync( + 'helm', + ['test', RELEASE, '--kube-context', context, '-n', NAMESPACE, '--timeout', '10m'], + { + encoding: 'utf8', + cwd: ROOT, + } + ) if (test.status !== 0) { testSpin.stop(`${glyph.fail} helm test failed`) throw new SetupError(`helm test failed:\n${test.stdout}${test.stderr}`, [ From 8d4c1e74d084e0b86256c7344cdaa89f771d4ff3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 03:27:02 -0600 Subject: [PATCH 2/6] fix(docs): escape backslashes before pipes in generated self-hosting tables --- scripts/sync-self-hosting-docs.test.ts | 5 +++++ scripts/sync-self-hosting-docs.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/sync-self-hosting-docs.test.ts b/scripts/sync-self-hosting-docs.test.ts index a86e2d24bab..c69a821f806 100644 --- a/scripts/sync-self-hosting-docs.test.ts +++ b/scripts/sync-self-hosting-docs.test.ts @@ -64,6 +64,11 @@ describe('cron values', () => { expect(job.description).toBe("Retries the outbox | it's idempotent") expect(renderCronTable([job])).toContain("Retries the outbox \\| it's idempotent |") }) + + it('keeps a pipe escaped when the text already holds a backslash before it', () => { + const job = { ...parseCronJobs(VALUES)[1], description: 'Splits on a\\|b' } + expect(renderCronTable([job])).toContain('Splits on a\\\\\\|b |') + }) }) describe('replaceBetweenMarkers', () => { diff --git a/scripts/sync-self-hosting-docs.ts b/scripts/sync-self-hosting-docs.ts index bd5660d02ba..4d71d451c2f 100644 --- a/scripts/sync-self-hosting-docs.ts +++ b/scripts/sync-self-hosting-docs.ts @@ -286,7 +286,7 @@ export function unquoteYamlScalar(raw: string): string { /** Text safe inside a Markdown table cell. */ export function escapeTableCell(text: string): string { - return text.replace(/\|/g, '\\|') + return text.replace(/\\/g, '\\\\').replace(/\|/g, '\\|') } export function renderCronTable(jobs: readonly CronJob[]): string { From 226fc5cadfc5938186553131c631c92a23fae92b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 03:39:20 -0600 Subject: [PATCH 3/6] fix(sim-setup): pull latest images on every k8s start, and drop a now-used export from the baseline --- packages/sim-setup/src/modes/k8s.ts | 13 ++++++++----- scripts/check-unused-exports.baseline.json | 1 - 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/sim-setup/src/modes/k8s.ts b/packages/sim-setup/src/modes/k8s.ts index 6df252955c9..5ff2d35f38b 100644 --- a/packages/sim-setup/src/modes/k8s.ts +++ b/packages/sim-setup/src/modes/k8s.ts @@ -298,13 +298,16 @@ interface ReleaseValues { /** * `--set` flags pinning the app, realtime, and migrations images. A checkout's chart carries a * deliberately stale appVersion, so without them the release would run old images; a tag - * the existing release already pins is kept. + * the existing release already pins is kept. `latest` is pulled on every start, or nodes would + * keep the image they cached and never see a newer build. */ function imageTagArgs(values: ReleaseValues | null): string[] { - return (['app', 'realtime', 'migrations'] as const).flatMap((component) => [ - '--set', - `${component}.image.tag=${values?.[component]?.image?.tag || 'latest'}`, - ]) + return (['app', 'realtime', 'migrations'] as const).flatMap((component) => { + const pinned = values?.[component]?.image?.tag + const tag = pinned && pinned !== 'latest' ? pinned : 'latest' + const args = ['--set', `${component}.image.tag=${tag}`] + return tag === 'latest' ? [...args, '--set', `${component}.image.pullPolicy=Always`] : args + }) } function existingReleaseValues(context: string): ReleaseValues | null { diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index d29f67a8581..88ffc8e26b6 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -5738,7 +5738,6 @@ "packages/sim-setup/src/lifecycle.ts#LIFECYCLE_COMMANDS", "packages/sim-setup/src/lifecycle.ts#getComposeUpdateMode", "packages/sim-setup/src/lifecycle.ts#isLifecycleCommand", - "packages/sim-setup/src/lifecycle.ts#refreshComposeFileForUpdate", "packages/sim-setup/src/setup-status.ts#SetupStatusSource", "packages/sim-setup/src/twins.ts#getConfiguredMailProvider", "packages/sim-setup/src/wizard.ts#WizardMode", From b85a84c3391cb754fd8644814a3e039a2809a979 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 04:56:50 -0600 Subject: [PATCH 4/6] fix(self-hosting): fit the self-check to cold EKS Nitro starts, schedule pre-pull where sandboxes run, and keep sandboxes from consolidation --- .../docs/platform/self-hosting/kubernetes.mdx | 16 +++ .../self-hosting/reference-architectures.mdx | 4 +- .../docs/platform/self-hosting/sandboxes.mdx | 13 +- .../scripts/fixtures/content-baseline.json | 11 +- apps/sim/app/api/cron/self-check/route.ts | 2 +- .../remote-sandbox/kubernetes/pod.test.ts | 4 + .../remote-sandbox/kubernetes/pod.ts | 10 +- apps/sim/lib/self-check/outcome.ts | 2 +- apps/sim/lib/self-check/run.ts | 8 +- apps/sim/lib/self-check/sandbox.test.ts | 110 +++++++++++++++++ apps/sim/lib/self-check/sandbox.ts | 111 ++++++++++-------- helm/sim/Chart.yaml | 2 +- helm/sim/README.md | 11 +- helm/sim/templates/_helpers.tpl | 44 +++++++ .../templates/daemonset-sandbox-prepull.yaml | 10 +- helm/sim/templates/tests/test-connection.yaml | 1 + helm/sim/templates/tests/test-self-check.yaml | 1 + helm/sim/tests/helm-test-hook_test.yaml | 11 ++ helm/sim/tests/sandbox-kubernetes_test.yaml | 76 +++++++++++- helm/sim/tests/self-check_test.yaml | 9 ++ helm/sim/values.schema.json | 2 +- helm/sim/values.yaml | 10 +- 22 files changed, 394 insertions(+), 74 deletions(-) create mode 100644 apps/sim/lib/self-check/sandbox.test.ts diff --git a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx index 8827c0ba4e2..f921bf748cd 100644 --- a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx @@ -14,6 +14,22 @@ The Helm chart deploys the app, realtime, migrations (as an init container on th - An ingress controller and a TLS certificate for public access. - `metrics-server` for autoscaling, and the External Secrets Operator if you use it. +EKS Auto Mode has no default StorageClass, so the bundled PostgreSQL's volume stays Pending. Create one with Auto Mode's EBS provisioner (the name `gp3` is the one `values-aws.yaml` selects), or set `postgresql.persistence.storageClass` to a class you have: + +```yaml +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: gp3 + annotations: + storageclass.kubernetes.io/is-default-class: "true" +provisioner: ebs.csi.eks.amazonaws.com +volumeBindingMode: WaitForFirstConsumer +parameters: + type: gp3 + encrypted: "true" +``` + ## 1. Pin the chart Each chart version installs one Sim release, its `appVersion`. Resolve the newest chart once and reuse the version for every later command: diff --git a/apps/docs/content/docs/platform/self-hosting/reference-architectures.mdx b/apps/docs/content/docs/platform/self-hosting/reference-architectures.mdx index e165570133f..39d163c5f0a 100644 --- a/apps/docs/content/docs/platform/self-hosting/reference-architectures.mdx +++ b/apps/docs/content/docs/platform/self-hosting/reference-architectures.mdx @@ -35,14 +35,14 @@ Each tab names the chart's example values file. Fetch it at your chart's `helm-c | You provision | Notes | | --- | --- | | EKS cluster | Kubernetes 1.25 or later | -| EBS CSI driver and a `gp3` StorageClass | The example selects `gp3`; confirm it exists with the installed provisioner | +| EBS CSI driver and a `gp3` StorageClass | The example selects `gp3`; confirm it exists with the installed provisioner. EKS Auto Mode has no default StorageClass; create one as in [Kubernetes prerequisites](/platform/self-hosting/kubernetes#prerequisites) | | AWS Load Balancer Controller | ALB ingress | | ACM certificate | ALB discovers it from the ingress hosts, or pin it with `alb.ingress.kubernetes.io/certificate-arn`. ALB cannot use a Kubernetes TLS Secret | | RDS or Aurora PostgreSQL | Reachable from the cluster subnets | | S3 buckets | One per file purpose | | ElastiCache | Optional; the bundled Redis also works | -**Identity.** Bind an IAM role to the ServiceAccount with IRSA. Grant it access to your buckets and to anything else you enable, such as Bedrock or SES. **Timeouts.** Raise the ALB idle timeout; see [Networking](/platform/self-hosting/networking#aws-alb-ingress). **Sandboxes.** EKS sandboxes run under Nitro Sandboxes; see [Kubernetes sandboxes](/platform/self-hosting/sandboxes#kubernetes-no-third-party). +**Identity.** Bind an IAM role to the ServiceAccount with IRSA. Grant it access to your buckets and to anything else you enable, such as Bedrock or SES. **Timeouts.** Raise the ALB idle timeout; see [Networking](/platform/self-hosting/networking#aws-alb-ingress). **Sandboxes.** EKS sandboxes run under Nitro Sandboxes; see [Kubernetes sandboxes](/platform/self-hosting/sandboxes#kubernetes-no-third-party). On Auto Mode they also need the `amazon-vpc-cni` ConfigMap that turns on NetworkPolicy enforcement ([Amazon EKS Auto Mode](/platform/self-hosting/sandboxes#amazon-eks-auto-mode)). #### AWS GovCloud (US) diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index e654408d44c..eb50aa5d625 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -151,7 +151,7 @@ Two values turn it on: `sandbox.kubernetes.enabled` and the `runtimeClass.preset -Kubernetes 1.36 or later. Turn on NetworkPolicy enforcement first ([Amazon EKS Auto Mode](#amazon-eks-auto-mode)). +Kubernetes 1.36 or later. Turn on NetworkPolicy enforcement first, and create a default StorageClass for the bundled PostgreSQL ([Amazon EKS Auto Mode](#amazon-eks-auto-mode)). A cold sandbox takes about 2 minutes (a new node, the image pull, the microVM load), so keep one or two warm: ```yaml sandbox: @@ -159,8 +159,12 @@ sandbox: enabled: true runtimeClass: preset: isolated-sandbox + warmCapacity: + sandboxes: 1 ``` +On a cold cluster `helm test` can take several minutes, since each of its two sandboxes may wait for a node. + @@ -373,7 +377,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 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. +A sandbox's start time is dominated by the first image pull on its node. `sandbox.kubernetes.prePull.enabled: true` renders a DaemonSet that keeps the Function image on every node a sandbox can land on, under the same RuntimeClass, so the holder pulls the image the way a sandbox does. A DaemonSet places a pod on every node it selects before the RuntimeClass's scheduling applies, so the chart selects the RuntimeClass's nodes itself: a chart-created class's `runtimeClass.scheduling`, or the platform's node label for the `isolated-sandbox` (EKS), `gvisor` (GKE Sandbox, with its taint tolerated), and `kata` (AKS) presets, merged with `nodeSelector` and `tolerations` (yours win). A `custom` class the chart does not create needs `nodeSelector`. With `images.function` tag and digest empty, a published chart holds the image its appVersion runs. From a git checkout, or with `app.image.tag` or `digest` overridden, set `images.function.tag` or `digest`. Each node then runs one idle pod; under a VM runtime that pod is a small VM that occupies one sandbox slot on the node (EKS Nitro Sandboxes cap sandboxes per node). 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. @@ -406,10 +410,13 @@ What Sim's sandboxes need on EKS Auto Mode with Nitro Sandboxes (`runtimeClass.p ``` Then confirm enforcement before running untrusted code, as above. +- **Storage.** Auto Mode has no default StorageClass, so the bundled PostgreSQL's volume stays Pending until you create one; see [Kubernetes prerequisites](/platform/self-hosting/kubernetes#prerequisites). +- **Warm capacity.** Set `warmCapacity.sandboxes` to 1 or 2. A sandbox that needs a new node takes about 2 minutes (the node, the image pull, and the microVM load), which is close to its 3-minute start deadline; a warm slot starts it in seconds. `helm test` on a cold cluster can take several minutes for the same reason. +- **Consolidation.** Sandbox pods and the `helm test` pods carry `karpenter.sh/do-not-disrupt: "true"`, so Auto Mode does not consolidate a node away under a running sandbox. - **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. +- **Instance metadata.** A Nitro Sandbox serves its own IMDSv2-only metadata at `169.254.169.254` from inside the guest, where NetworkPolicy does not apply. It answers only region, Availability Zone, and partition paths; instance ID, user data, and IAM credentials return 404 ([AWS: Pod Identity and credentials](https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-metadata-credentials.html)). EKS Pod Identity's endpoint is also served in the guest; sandbox pods mount no service account token, so it gives them no credentials as long as you do not inject one (for example with a Pod Identity association on the sandbox namespace). AWS lets a pod turn the metadata surrogate off with a Cedar policy generated with `eks-nitro-sandbox-genpolicy --deny-imds` and attached as the `sandbox.amazonaws.com/policy` annotation; Sim does not set that annotation, so sandboxes keep the surrogate. - **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. - **Start times.** Measured on Kubernetes 1.37 with `c8a.large` nodes: about 6 seconds from create to first command on a node that already has the image, and about 2 minutes when Auto Mode must launch a node first. Pre-pulling helps less than on gVisor: after a 31-second pull, loading the 840 MB Function image into the microVM took another 53 seconds. diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index d2928e33a65..b4c74930784 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -173480,6 +173480,13 @@ ], "expressions": [], "codeFences": [ + { + "lang": "yaml", + "meta": null, + "sha256": "5332014ec1087e70604503756fcd9554d2974bf71fe0da7bc59be3013dd9c6ab", + "bytes": 264, + "line": 19 + }, { "lang": "bash", "meta": null, @@ -174888,8 +174895,8 @@ { "lang": "yaml", "meta": null, - "sha256": "bdac8bd2b3fd1b79fff8cfc0d0eae5b903d64cd870472fcb924dd8363edb2b69", - "bytes": 89, + "sha256": "7e0b03f45c173041b7369dce7ee04146a198c1e851b3797f43310f5f2f70e403", + "bytes": 126, "line": 156 }, { diff --git a/apps/sim/app/api/cron/self-check/route.ts b/apps/sim/app/api/cron/self-check/route.ts index 6d7a2e0c598..559920d0b41 100644 --- a/apps/sim/app/api/cron/self-check/route.ts +++ b/apps/sim/app/api/cron/self-check/route.ts @@ -7,7 +7,7 @@ import { runSelfCheck } from '@/lib/self-check/run' export const dynamic = 'force-dynamic' /** Above the sandbox check's own budget, so a slow sandbox start still reports. */ -export const maxDuration = 180 +export const maxDuration = 300 /** * Post-install self-check for self-hosted deployments, called by the Helm chart's `helm test` diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts index 37397b242c6..dd37b586806 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts @@ -123,6 +123,10 @@ describe('sandbox pod isolation', () => { expect(build().spec?.shareProcessNamespace).toBe(true) }) + it('asks Karpenter not to consolidate its node away while it runs', () => { + expect(build().metadata?.annotations?.['karpenter.sh/do-not-disrupt']).toBe('true') + }) + it('never restarts and is ended by Kubernetes at the 24-hour cap', () => { const spec = build().spec expect(spec?.restartPolicy).toBe('Never') diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts index c538f98974d..6e6fc4d82a8 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -26,6 +26,11 @@ export const EXPIRES_AT_ANNOTATION = 'sim.ai/expires-at' * lease. Session lookups skip it; its deadline and the reaper treat it like any other pod. */ export const RETIRED_ANNOTATION = 'sim.ai/retired' +/** + * Keeps Karpenter (and EKS Auto Mode) from consolidating a node out from under a running sandbox, + * which would end the user's code mid-run. The pod's own deadline still bounds how long it holds a node. + */ +const DO_NOT_DISRUPT_ANNOTATION = 'karpenter.sh/do-not-disrupt' /** Pod label selector for every sandbox pod Sim manages. */ export const MANAGED_SELECTOR = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}` @@ -142,7 +147,10 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod { [SANDBOX_KIND_LABEL]: input.kind, ...(input.sessionLabel ? { [SESSION_LABEL]: input.sessionLabel } : {}), }, - annotations: { [EXPIRES_AT_ANNOTATION]: String(input.expiresAtMs) }, + annotations: { + [EXPIRES_AT_ANNOTATION]: String(input.expiresAtMs), + [DO_NOT_DISRUPT_ANNOTATION]: 'true', + }, }, spec: { ...(settings.runtimeClassName ? { runtimeClassName: settings.runtimeClassName } : {}), diff --git a/apps/sim/lib/self-check/outcome.ts b/apps/sim/lib/self-check/outcome.ts index d02d38e0063..63d92f6f8ad 100644 --- a/apps/sim/lib/self-check/outcome.ts +++ b/apps/sim/lib/self-check/outcome.ts @@ -27,7 +27,7 @@ export interface CheckOutcome { * HTTP, so it names the error's code and points there. */ export function failedWith(check: SelfCheckName, error: unknown): CheckOutcome { - logger.warn('Self-check failed', { check, error: getErrorMessage(error) }) + logger.error('Self-check failed', { check, error: getErrorMessage(error) }) return { status: 'fail', detail: `error: ${errorCode(error)}; see app logs` } } diff --git a/apps/sim/lib/self-check/run.ts b/apps/sim/lib/self-check/run.ts index a241873057f..e083cac5bb6 100644 --- a/apps/sim/lib/self-check/run.ts +++ b/apps/sim/lib/self-check/run.ts @@ -57,9 +57,9 @@ export async function runSelfCheck(options: SelfCheckOptions): Promise check.status !== 'fail'), checks } - logger.info('Self-check completed', { - ok: report.ok, - failed: checks.filter((check) => check.status === 'fail').map((check) => check.name), - }) + // At error, so a failure reaches the app log under production's default LOG_LEVEL. + const failed = checks.filter((check) => check.status === 'fail').map((check) => check.name) + if (report.ok) logger.info('Self-check completed', { ok: true }) + else logger.error('Self-check found failures', { failed }) return report } diff --git a/apps/sim/lib/self-check/sandbox.test.ts b/apps/sim/lib/self-check/sandbox.test.ts new file mode 100644 index 00000000000..943dad9533a --- /dev/null +++ b/apps/sim/lib/self-check/sandbox.test.ts @@ -0,0 +1,110 @@ +import { remoteSandboxMock } from '@sim/testing/mocks/remote-sandbox.mock' +import { + remoteSandboxProviderMock, + remoteSandboxProviderMockFns, +} from '@sim/testing/mocks/remote-sandbox-provider.mock' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/execution/remote-sandbox', () => remoteSandboxMock) +vi.mock('@/lib/execution/remote-sandbox/provider', () => remoteSandboxProviderMock) +vi.mock('@/lib/core/config/env-capabilities.server', () => ({ + getSelectedSandboxProviderId: () => 'kubernetes', +})) +vi.mock('@/lib/execution/remote-sandbox/kubernetes/settings', () => ({ + readKubernetesSandboxSettings: () => ({ namespace: 'sim-sandboxes' }), +})) + +import { checkSandbox } from '@/lib/self-check/sandbox' + +interface FakeSandbox { + podAddress: string + kill: ReturnType + runCode: ReturnType +} + +function fakeSandbox(address: string): FakeSandbox { + return { + podAddress: address, + kill: vi.fn(async () => {}), + runCode: vi.fn(async () => ({ + text: '', + stdout: '', + stderr: '', + error: { name: 'RuntimeError', value: 'probe crashed', traceback: '' }, + })), + } +} + +/** A provider whose creates settle only when the test says so, in call order. */ +function controlledProvider() { + const pending: Array<{ + resolve: (sandbox: FakeSandbox) => void + reject: (error: Error) => void + }> = [] + const create = vi.fn( + () => + new Promise((resolve, reject) => { + pending.push({ resolve, reject }) + }) + ) + remoteSandboxProviderMockFns.mockResolveProvider.mockReturnValue({ id: 'kubernetes', create }) + return { create, pending } +} + +async function flush(): Promise { + for (let i = 0; i < 20; i++) await Promise.resolve() +} + +afterEach(() => { + remoteSandboxProviderMockFns.mockResolveProvider.mockReset() +}) + +describe('checkSandbox', () => { + it('starts the neighbor and the probe sandbox together, so two cold starts share the budget', async () => { + const { create, pending } = controlledProvider() + const running = checkSandbox() + await flush() + + expect(create).toHaveBeenCalledTimes(2) + + const neighbor = fakeSandbox('10.0.0.11') + const prober = fakeSandbox('10.0.0.12') + pending[0].resolve(neighbor) + pending[1].resolve(prober) + const results = await running + + expect(prober.runCode).toHaveBeenCalledTimes(1) + expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail') + expect(neighbor.kill).toHaveBeenCalled() + expect(prober.kill).toHaveBeenCalled() + }) + + it('kills the neighbor when the probe sandbox fails to start', async () => { + const { pending } = controlledProvider() + const running = checkSandbox() + await flush() + + const neighbor = fakeSandbox('10.0.0.11') + pending[0].resolve(neighbor) + pending[1].reject(new Error('no capacity')) + const results = await running + + expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail') + expect(neighbor.kill).toHaveBeenCalled() + }) + + it('kills the probe sandbox when the neighbor fails to start', async () => { + const { pending } = controlledProvider() + const running = checkSandbox() + await flush() + + const prober = fakeSandbox('10.0.0.12') + pending[0].reject(new Error('no capacity')) + pending[1].resolve(prober) + const results = await running + + expect(results.find((check) => check.name === 'sandbox.execution')?.status).toBe('fail') + expect(prober.runCode).not.toHaveBeenCalled() + expect(prober.kill).toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/self-check/sandbox.ts b/apps/sim/lib/self-check/sandbox.ts index bfcb7f518d7..4f488abe88b 100644 --- a/apps/sim/lib/self-check/sandbox.ts +++ b/apps/sim/lib/self-check/sandbox.ts @@ -1,14 +1,16 @@ import { lookup } from 'node:dns/promises' import { isIP } from 'node:net' import { networkInterfaces } from 'node:os' +import { createLogger } from '@sim/logger' import { SANDBOX_AGENT_PORT } from '@sim/sandbox-agent-protocol' import { env, envNumber } from '@/lib/core/config/env' import { getSelectedSandboxProviderId } from '@/lib/core/config/env-capabilities.server' import { CodeLanguage } from '@/lib/execution/languages' -import { executeInSandbox } from '@/lib/execution/remote-sandbox' +import { SIM_RESULT_PREFIX } from '@/lib/execution/remote-sandbox' import { findSandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error' import { confinementProbe } from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' import { readKubernetesSandboxSettings } from '@/lib/execution/remote-sandbox/kubernetes/settings' +import { MAX_SANDBOX_PROCESS_OUTPUT_BYTES } from '@/lib/execution/remote-sandbox/output-limits' import { resolveProvider } from '@/lib/execution/remote-sandbox/provider' import type { SandboxHandle } from '@/lib/execution/remote-sandbox/types' import { @@ -21,10 +23,15 @@ import { type CheckOutcome, failedWith, untilAborted } from '@/lib/self-check/ou import { dataStoreEndpoints } from '@/lib/self-check/targets' import type { SelfCheckName, SelfCheckResult } from '@/lib/self-check/types' -/** Two sandbox starts and one probe, inside the route's `maxDuration`. */ -const SANDBOX_BUDGET_MS = 150_000 -/** Outlives the budget, so the pod deadline reaps the neighbor even if its delete is lost. */ -const NEIGHBOR_LIFETIME_MS = 4 * 60_000 +const logger = createLogger('SelfCheck') + +/** + * Two concurrent sandbox starts and one probe, inside the route's `maxDuration`. A cold start on a + * microVM runtime can take about two minutes (a new node, the image pull, the VM load). + */ +const SANDBOX_BUDGET_MS = 270_000 +/** Outlives the budget, so the pod deadline reaps both sandboxes even if a delete is lost. */ +const SANDBOX_LIFETIME_MS = 6 * 60_000 const DEFAULT_APP_PORT = 3000 /** The cluster's API Service name, probed as an API target and resolved as the positive control. */ const CLUSTER_API_NAME = 'kubernetes.default.svc' @@ -88,37 +95,30 @@ async function dataStoreTargets(): Promise<{ return { targets, unresolved } } -/** - * Starts a sibling sandbox and takes its pod address. Its create returns only once the app has - * reached its agent, which is the positive control: the agent listens and an allowed peer gets - * through, so a probe that cannot connect was refused by policy. - */ -async function startNeighbor( - signal: AbortSignal -): Promise<{ handle: SandboxHandle; address: string }> { +/** Starts a code sandbox; one whose create lands after the deadline is killed when it does. */ +async function startSandbox(signal: AbortSignal): Promise { const creating = resolveProvider().create('code', { language: CodeLanguage.Python, - lifetimeMs: NEIGHBOR_LIFETIME_MS, + lifetimeMs: SANDBOX_LIFETIME_MS, }) - let handle: SandboxHandle try { - handle = await untilAborted(creating, signal) + return await untilAborted(creating, signal) } catch (error) { - // A create still running at the deadline leaves a pod behind once it lands. creating.then( (late) => late.kill().catch(() => {}), () => {} ) throw error } - const address = handle.podAddress - if (!address || isIP(address) === 0) { - await handle.kill().catch(() => {}) - throw Object.assign(new Error('Neighbor sandbox has no pod address'), { - name: 'NeighborAddressError', - }) - } - return { handle, address } +} + +/** The JSON the probe prints after the result marker, or null when it printed none. */ +function probeFacts(output: string): unknown { + const marker = output + .split('\n') + .reverse() + .find((line) => line.startsWith(SIM_RESULT_PREFIX)) + return marker ? JSON.parse(marker.slice(SIM_RESULT_PREFIX.length)) : null } function result(name: SelfCheckName, outcome: CheckOutcome, durationMs = 0): SelfCheckResult { @@ -162,25 +162,35 @@ export async function checkSandbox(): Promise { } const signal = AbortSignal.timeout(SANDBOX_BUDGET_MS) - let neighbor: { handle: SandboxHandle; address: string } - try { - neighbor = await startNeighbor(signal) - } catch (error) { - return failedToRun(failure(error), elapsed()) - } - + // Started together: on a cold cluster each start can wait minutes for a node. The neighbor's + // create returns only once the app has reached its agent, which is the positive control: the + // agent listens and an allowed peer gets through, so a probe that cannot connect was refused. + const [neighbor, prober] = await Promise.allSettled([startSandbox(signal), startSandbox(signal)]) + const started = [neighbor, prober].flatMap((start) => + start.status === 'fulfilled' ? [start.value] : [] + ) try { - return await probe(namespace, neighbor.address, signal, elapsed) + if (neighbor.status === 'rejected') return failedToRun(failure(neighbor.reason), elapsed()) + if (prober.status === 'rejected') return failedToRun(failure(prober.reason), elapsed()) + const address = neighbor.value.podAddress + if (!address || isIP(address) === 0) { + const error = Object.assign(new Error('Neighbor sandbox has no pod address'), { + name: 'NeighborAddressError', + }) + return failedToRun(failure(error), elapsed()) + } + return await probe(namespace, address, prober.value, signal, elapsed) } catch (error) { return failedToRun(failure(error), elapsed()) } finally { - await neighbor.handle.kill().catch(() => {}) + await Promise.all(started.map((handle) => handle.kill().catch(() => {}))) } } async function probe( namespace: string, neighborAddress: string, + sandbox: SandboxHandle, signal: AbortSignal, elapsed: () => number ): Promise { @@ -196,19 +206,26 @@ async function probe( const servicePort = Number(process.env.KUBERNETES_SERVICE_PORT) || 443 if (serviceHost && isIP(serviceHost)) apiTargets.push([serviceHost, servicePort]) - const execution = await executeInSandbox({ - code: confinementProbe({ - apiTargets, - deniedTargets: [...lateral.map(({ target }) => target), neighborTarget], - allowedTargets: [], - resolveNames: [...RESOLVE_NAMES], - namespace, - }), - language: CodeLanguage.Python, - timeoutMs: Math.max(1, SANDBOX_BUDGET_MS - elapsed()), - signal, + const code = confinementProbe({ + apiTargets, + deniedTargets: [...lateral.map(({ target }) => target), neighborTarget], + allowedTargets: [], + resolveNames: [...RESOLVE_NAMES], + namespace, }) - if (execution.error) { + const execution = await untilAborted( + sandbox.runCode(code, { + timeoutMs: Math.max(1, SANDBOX_BUDGET_MS - elapsed()), + maxOutputBytes: MAX_SANDBOX_PROCESS_OUTPUT_BYTES, + signal, + }), + signal + ) + if (execution.error || execution.timedOut) { + logger.error('Self-check probe did not finish', { + error: execution.error?.name, + timedOut: Boolean(execution.timedOut), + }) return failedToRun({ status: 'fail', detail: 'the probe exited with an error' }, elapsed()) } @@ -219,7 +236,7 @@ async function probe( unresolved: dataStores.unresolved, resolveNames: RESOLVE_NAMES, } - const judged = judgeProbeResult(execution.result, plan) + const judged = judgeProbeResult(probeFacts([execution.text, execution.stdout].join('\n')), plan) if (!judged.outcomes) return failedToRun(judged.execution, elapsed()) const { outcomes } = judged return [ diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 2f5f9ac4a57..22c6c44a158 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.22.2 +version: 1.22.3 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/README.md b/helm/sim/README.md index 5fbd0d06e2a..414f352aed6 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -137,7 +137,9 @@ API, and no reach into the app, its data stores, or another sandbox. The reach checks fail where the network plugin does not enforce NetworkPolicy. `--logs` prints the JSON report (each check with pass, fail, warn, or skip); the pods stay until the next `helm test`. Keep `--timeout 10m`: the self-check retries for up -to a minute and its request can take four, past helm's 5-minute default. +to a minute and its request can take five and a half (`tests.selfCheck.timeoutSeconds`, +330), past helm's 5-minute default. On a cold cluster where each sandbox needs a +new node, such as EKS Auto Mode with Nitro Sandboxes, expect several minutes. The self-check skips, and passes, when `CRON_SECRET` is not in the app Secret or the app image has no self-check endpoint. Disable it with @@ -336,13 +338,16 @@ When `autoscaling.enabled=true`, the chart omits `spec.replicas` from the Deploy --- -## Upgrading to 1.22.2 +## Upgrading to 1.22.3 -Covers 1.22.0–1.22.2; 1.21.0 is the previous published chart. +Covers 1.22.0–1.22.3; 1.21.0 is the previous published chart. * **`helm test` runs the authenticated self-check, and `tests.image` is now `curlimages/curl:8.5.0`.** Drop a `busybox` override of `tests.image`, and always run `helm test` with `--timeout 10m`: the self-check can outlast helm's 5-minute default. See [Test the install](#test-the-install). * **Air-gapped mirrors: `images.yaml` adds `pause` and the `copilot-sandbox-*` images, and `busybox` is gone.** Mirror from the published chart's copy, which also lists the sandbox images its appVersion runs. * **Each scheduled job has a `description` in `values.yaml`.** No action. +* **`tests.selfCheck.timeoutSeconds` defaults to 330 (was 240)**, to cover two cold sandbox starts. Raise a lower override; keep `helm test --timeout 10m`. +* **The `prePull` DaemonSet now selects the nodes its RuntimeClass schedules onto** (a chart-created class's `runtimeClass.scheduling`, or the platform label for the `isolated-sandbox`, `gvisor`, and `kata` presets), so its pods no longer sit Pending on other nodes and block `helm --wait`. A `custom` class the chart does not create needs `sandbox.kubernetes.nodeSelector`. On VM runtimes each pre-pull pod occupies one sandbox slot per node. +* **Both `helm test` pods carry `karpenter.sh/do-not-disrupt: "true"`**, as sandbox pods now do, so Karpenter and EKS Auto Mode consolidation does not evict them mid-run. No action. ## Upgrading to 1.21.0 diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index 4c4db091765..e955a031d31 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1139,6 +1139,50 @@ Kubernetes sandbox provider: the handler of a chart-created RuntimeClass. {{- default (get $presetHandlers (toString $rc.preset)) $rc.handler -}} {{- end }} +{{/* +Kubernetes sandbox provider: node selection for the pre-pull DaemonSet. A RuntimeClass's +scheduling is merged into each pod at admission, after the DaemonSet controller has already +placed one pod per node it selects, so a pod on a node the class excludes stays Pending (and +blocks helm --wait). The DaemonSet therefore selects the class's nodes itself: a chart-created +class's runtimeClass.scheduling, or the label the platform's class selects (AKS documents +kubernetes.azure.com/kata-vm-isolation, GKE Sandbox labels and taints its nodes +sandbox.gke.io/runtime=gvisor, and EKS Auto Mode labels Nitro Sandbox nodes +eks.amazonaws.com/nitro-sandbox). sandbox.kubernetes.nodeSelector wins on a shared key, and its +tolerations are added. A custom class the chart does not create has no known selector, so +nodeSelector is required. +*/}} +{{- define "sim.sandbox.prePullScheduling" -}} +{{- $sbx := .Values.sandbox.kubernetes -}} +{{- $rc := $sbx.runtimeClass -}} +{{- $preset := toString $rc.preset -}} +{{- $selector := dict -}} +{{- $tolerations := list -}} +{{- if $rc.create -}} +{{- $scheduling := default (dict) $rc.scheduling -}} +{{- $selector = deepCopy (default (dict) $scheduling.nodeSelector) -}} +{{- $tolerations = default (list) $scheduling.tolerations -}} +{{- else if eq $preset "isolated-sandbox" -}} +{{- $selector = dict "eks.amazonaws.com/nitro-sandbox" "true" -}} +{{- else if eq $preset "gvisor" -}} +{{- $selector = dict "sandbox.gke.io/runtime" "gvisor" -}} +{{- $tolerations = list (dict "key" "sandbox.gke.io/runtime" "operator" "Equal" "value" "gvisor" "effect" "NoSchedule") -}} +{{- else if eq $preset "kata" -}} +{{- $selector = dict "kubernetes.azure.com/kata-vm-isolation" "true" -}} +{{- else if and (include "sim.sandbox.runtimeClassName" .) (not $sbx.nodeSelector) -}} +{{- fail "sandbox.kubernetes.prePull needs sandbox.kubernetes.nodeSelector with a RuntimeClass the chart neither creates nor knows: set it to the nodes the RuntimeClass schedules onto (kubectl get runtimeclass -o jsonpath='{.scheduling}'), or the pre-pull pods on other nodes stay Pending" -}} +{{- end -}} +{{- $selector = mergeOverwrite $selector (default (dict) $sbx.nodeSelector) -}} +{{- $tolerations = concat $tolerations (default (list) $sbx.tolerations) -}} +{{- with $selector }} +nodeSelector: + {{- toYaml . | nindent 2 }} +{{- end }} +{{- with $tolerations }} +tolerations: + {{- toYaml . | nindent 2 }} +{{- end }} +{{- end }} + {{/* Kubernetes sandbox provider: one sandbox image reference, or empty when neither tag nor digest is set (the app then uses the image built for its release, from diff --git a/helm/sim/templates/daemonset-sandbox-prepull.yaml b/helm/sim/templates/daemonset-sandbox-prepull.yaml index 0625448db4a..04e92f9963c 100644 --- a/helm/sim/templates/daemonset-sandbox-prepull.yaml +++ b/helm/sim/templates/daemonset-sandbox-prepull.yaml @@ -2,9 +2,8 @@ Holds the sandbox function image on every node sandbox pods can land on, so a sandbox start does not wait for the pull. The idle container keeps the image in use, which also keeps kubelet image garbage collection from removing it. It runs - under the sandbox RuntimeClass, not the default runtime: the RuntimeClass carries - the scheduling that puts pods on sandbox nodes (GKE Sandbox's, or runtimeClass.scheduling), - and the pull then takes the same path a sandbox's does, whether the runtime reads + under the sandbox RuntimeClass, not the default runtime, on the nodes that class + schedules onto (sim.sandbox.prePullScheduling), and the pull then takes the same path a sandbox's does, whether the runtime reads the node's containerd store (gVisor) or hands layers to a guest that runs its own containerd (EKS Nitro Sandboxes). Lives in the release namespace so it never counts against the sandbox quota. @@ -46,8 +45,9 @@ spec: priorityClassName: {{ . }} {{- end }} {{- include "sim.podSecurityContext" (dict) | nindent 6 }} - {{- include "sim.nodeSelector" $sbx | nindent 6 }} - {{- include "sim.tolerations" $sbx | nindent 6 }} + {{- with include "sim.sandbox.prePullScheduling" . | trim }} + {{- . | nindent 6 }} + {{- end }} terminationGracePeriodSeconds: 0 containers: - name: hold-function-image diff --git a/helm/sim/templates/tests/test-connection.yaml b/helm/sim/templates/tests/test-connection.yaml index bcccc6e5863..2d6bf477663 100644 --- a/helm/sim/templates/tests/test-connection.yaml +++ b/helm/sim/templates/tests/test-connection.yaml @@ -11,6 +11,7 @@ metadata: annotations: "helm.sh/hook": test "helm.sh/hook-delete-policy": before-hook-creation + karpenter.sh/do-not-disrupt: "true" spec: {{- include "sim.tests.podSpec" . | nindent 2 }} containers: diff --git a/helm/sim/templates/tests/test-self-check.yaml b/helm/sim/templates/tests/test-self-check.yaml index 9207f864f17..bea7704c0ac 100644 --- a/helm/sim/templates/tests/test-self-check.yaml +++ b/helm/sim/templates/tests/test-self-check.yaml @@ -18,6 +18,7 @@ metadata: "helm.sh/hook": test "helm.sh/hook-weight": "1" "helm.sh/hook-delete-policy": before-hook-creation + karpenter.sh/do-not-disrupt: "true" spec: {{- include "sim.tests.podSpec" . | nindent 2 }} containers: diff --git a/helm/sim/tests/helm-test-hook_test.yaml b/helm/sim/tests/helm-test-hook_test.yaml index 36062e8a548..bcfbeac85ad 100644 --- a/helm/sim/tests/helm-test-hook_test.yaml +++ b/helm/sim/tests/helm-test-hook_test.yaml @@ -52,3 +52,14 @@ tests: asserts: - hasDocuments: count: 0 + + - it: keeps Karpenter and EKS Auto Mode from consolidating either test pod away mid-run + templates: + - tests/test-connection.yaml + - tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - equal: + path: 'metadata.annotations["karpenter.sh/do-not-disrupt"]' + value: "true" diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index 64c85b8d16f..1d649d76f9f 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -1193,7 +1193,7 @@ tests: value: gvisor - equal: path: spec.template.spec.nodeSelector - value: { pool: sandboxes } + value: { pool: sandboxes, sandbox.gke.io/runtime: gvisor } - equal: path: spec.template.spec.containers[0].image value: ghcr.io/simstudioai/sandbox-function:abc123 @@ -1201,6 +1201,80 @@ tests: path: spec.template.spec.automountServiceAccountToken value: false + - it: schedules pre-pull pods only where a chart-created RuntimeClass schedules, with the operator's selector winning + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.scheduling: + nodeSelector: { runtime: gvisor, pool: default } + tolerations: + - { key: runtime, operator: Exists, effect: NoSchedule } + sandbox.kubernetes.nodeSelector: + pool: sandboxes + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: { runtime: gvisor, pool: sandboxes } + - equal: + path: spec.template.spec.tolerations + value: + - { key: runtime, operator: Exists, effect: NoSchedule } + + - it: schedules pre-pull pods only on EKS Nitro Sandbox nodes for the isolated-sandbox preset + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: isolated-sandbox + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: { eks.amazonaws.com/nitro-sandbox: "true" } + + - it: schedules pre-pull pods only on AKS Kata nodes for the kata preset + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: kata + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: { kubernetes.azure.com/kata-vm-isolation: "true" } + + - it: schedules pre-pull pods onto GKE Sandbox nodes, tolerating their taint, for the gvisor preset + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: { sandbox.gke.io/runtime: gvisor } + - equal: + path: spec.template.spec.tolerations + value: + - { key: sandbox.gke.io/runtime, operator: Equal, value: gvisor, effect: NoSchedule } + + - it: refuses pre-pull on a custom RuntimeClass it does not create without a node selector + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: custom + sandbox.kubernetes.runtimeClass.name: my-runtime + sandbox.kubernetes.runtimeClass.handler: kata + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - failedTemplate: + errorPattern: "prePull needs sandbox.kubernetes.nodeSelector with a RuntimeClass the chart neither creates nor knows" + - it: renders no admission policy when the provider is disabled template: sandbox-admission-policy.yaml set: diff --git a/helm/sim/tests/self-check_test.yaml b/helm/sim/tests/self-check_test.yaml index 9d61413f7da..17fe3dcc242 100644 --- a/helm/sim/tests/self-check_test.yaml +++ b/helm/sim/tests/self-check_test.yaml @@ -214,3 +214,12 @@ tests: asserts: - hasDocuments: count: 0 + + - it: waits longer for the self-check than the app's 270s sandbox budget + template: tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - matchRegex: + path: spec.containers[0].command[2] + pattern: "--max-time 330 " diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index 37942339c8c..c63fcb92e62 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -922,7 +922,7 @@ "timeoutSeconds": { "type": "integer", "minimum": 30, - "description": "Self-check request timeout; the sandbox check starts two sandbox pods" + "description": "Self-check request timeout; keep it above the app's 270s sandbox budget (the check starts two sandbox pods)" } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 053ff7de23d..8e84bc5fb67 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1419,6 +1419,10 @@ sandbox: # 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. + # Pre-pull: a DaemonSet holding the Function image on every node the sandbox RuntimeClass + # schedules onto (its chart-created scheduling, or the platform's label for a preset; a custom + # class needs nodeSelector). On a VM runtime each holder pod is a small VM that occupies one + # sandbox slot on its node (EKS Nitro Sandboxes cap sandboxes per node). prePull: enabled: false priorityClassName: "" @@ -2361,8 +2365,10 @@ tests: # Calls /api/cron/self-check with CRON_SECRET (see "Test the install" in README.md). Skips, passing, without CRON_SECRET or on an app image without the endpoint. selfCheck: enabled: true - # The sandbox check starts two sandbox pods; a cold image pull can take minutes. - timeoutSeconds: 240 + # Above the app's 270s sandbox budget: the check starts two sandbox pods, and a cold start on a + # microVM runtime (a new node, the image pull, the VM load) takes about two minutes. Run helm + # test with --timeout 10m, which covers this plus the 60s connection retry. + timeoutSeconds: 330 resources: limits: cpu: 100m From 6f876ab5ba64ed4f9f0e07bcb2c0fd287f034490 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 05:17:46 -0600 Subject: [PATCH 5/6] fix(self-hosting): honor renamed runtime classes, digest pins, and selector conflicts --- .../docs/platform/self-hosting/sandboxes.mdx | 2 +- helm/sim/README.md | 2 +- helm/sim/templates/_helpers.tpl | 22 ++++++--- helm/sim/tests/sandbox-kubernetes_test.yaml | 45 ++++++++++++++++++- helm/sim/values.schema.json | 2 +- helm/sim/values.yaml | 3 +- packages/sim-setup/src/modes/k8s.test.ts | 21 +++++++++ packages/sim-setup/src/modes/k8s.ts | 18 +++++--- 8 files changed, 96 insertions(+), 19 deletions(-) create mode 100644 packages/sim-setup/src/modes/k8s.test.ts diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index eb50aa5d625..e97d4c0893d 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -377,7 +377,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, so the holder pulls the image the way a sandbox does. A DaemonSet places a pod on every node it selects before the RuntimeClass's scheduling applies, so the chart selects the RuntimeClass's nodes itself: a chart-created class's `runtimeClass.scheduling`, or the platform's node label for the `isolated-sandbox` (EKS), `gvisor` (GKE Sandbox, with its taint tolerated), and `kata` (AKS) presets, merged with `nodeSelector` and `tolerations` (yours win). A `custom` class the chart does not create needs `nodeSelector`. With `images.function` tag and digest empty, a published chart holds the image its appVersion runs. From a git checkout, or with `app.image.tag` or `digest` overridden, set `images.function.tag` or `digest`. Each node then runs one idle pod; under a VM runtime that pod is a small VM that occupies one sandbox slot on the node (EKS Nitro Sandboxes cap sandboxes per node). +A sandbox's start time is dominated by the first image pull on its node. `sandbox.kubernetes.prePull.enabled: true` renders a DaemonSet that keeps the Function image on every node a sandbox can land on, under the same RuntimeClass, so the holder pulls the image the way a sandbox does. A DaemonSet places a pod on every node it selects before the RuntimeClass's scheduling applies, so the chart selects the RuntimeClass's nodes itself: a chart-created class's `runtimeClass.scheduling`, or the platform's node label for the `isolated-sandbox` (EKS), `gvisor` (GKE Sandbox, with its taint tolerated), and `kata` (AKS) presets, merged with your `nodeSelector` and `tolerations`. Your `nodeSelector` may add keys but not change one the RuntimeClass sets, which Kubernetes would reject; the chart refuses that. A `custom` class the chart does not create, or a preset whose `runtimeClass.name` you override, needs `nodeSelector`. With `images.function` tag and digest empty, a published chart holds the image its appVersion runs. From a git checkout, or with `app.image.tag` or `digest` overridden, set `images.function.tag` or `digest`. Each node then runs one idle pod; under a VM runtime that pod is a small VM that occupies one sandbox slot on the node (EKS Nitro Sandboxes cap sandboxes per node). 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/helm/sim/README.md b/helm/sim/README.md index 414f352aed6..383f2cf9e16 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -346,7 +346,7 @@ Covers 1.22.0–1.22.3; 1.21.0 is the previous published chart. * **Air-gapped mirrors: `images.yaml` adds `pause` and the `copilot-sandbox-*` images, and `busybox` is gone.** Mirror from the published chart's copy, which also lists the sandbox images its appVersion runs. * **Each scheduled job has a `description` in `values.yaml`.** No action. * **`tests.selfCheck.timeoutSeconds` defaults to 330 (was 240)**, to cover two cold sandbox starts. Raise a lower override; keep `helm test --timeout 10m`. -* **The `prePull` DaemonSet now selects the nodes its RuntimeClass schedules onto** (a chart-created class's `runtimeClass.scheduling`, or the platform label for the `isolated-sandbox`, `gvisor`, and `kata` presets), so its pods no longer sit Pending on other nodes and block `helm --wait`. A `custom` class the chart does not create needs `sandbox.kubernetes.nodeSelector`. On VM runtimes each pre-pull pod occupies one sandbox slot per node. +* **The `prePull` DaemonSet now selects the nodes its RuntimeClass schedules onto** (a chart-created class's `runtimeClass.scheduling`, or the platform label for the `isolated-sandbox`, `gvisor`, and `kata` presets), so its pods no longer sit Pending on other nodes and block `helm --wait`. A `custom` class the chart does not create, or a preset with an overridden `runtimeClass.name`, needs `sandbox.kubernetes.nodeSelector`, and a `nodeSelector` key that conflicts with the RuntimeClass's is refused. On VM runtimes each pre-pull pod occupies one sandbox slot per node. * **Both `helm test` pods carry `karpenter.sh/do-not-disrupt: "true"`**, as sandbox pods now do, so Karpenter and EKS Auto Mode consolidation does not evict them mid-run. No action. ## Upgrading to 1.21.0 diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index e955a031d31..1491fac7563 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -1147,9 +1147,10 @@ blocks helm --wait). The DaemonSet therefore selects the class's nodes itself: a class's runtimeClass.scheduling, or the label the platform's class selects (AKS documents kubernetes.azure.com/kata-vm-isolation, GKE Sandbox labels and taints its nodes sandbox.gke.io/runtime=gvisor, and EKS Auto Mode labels Nitro Sandbox nodes -eks.amazonaws.com/nitro-sandbox). sandbox.kubernetes.nodeSelector wins on a shared key, and its -tolerations are added. A custom class the chart does not create has no known selector, so -nodeSelector is required. +eks.amazonaws.com/nitro-sandbox). sandbox.kubernetes.nodeSelector adds keys, but may not give a +shared key another value, since Kubernetes rejects a pod whose nodeSelector conflicts with its +RuntimeClass's; its tolerations are added. A custom class the chart does not create, or a preset +whose class name is overridden, has no known selector, so nodeSelector is required. */}} {{- define "sim.sandbox.prePullScheduling" -}} {{- $sbx := .Values.sandbox.kubernetes -}} @@ -1157,21 +1158,28 @@ nodeSelector is required. {{- $preset := toString $rc.preset -}} {{- $selector := dict -}} {{- $tolerations := list -}} +{{- $presetNames := dict "isolated-sandbox" "isolated-sandbox" "gvisor" "gvisor" "kata" "kata-vm-isolation" -}} +{{- $knownPreset := and (hasKey $presetNames $preset) (or (not $rc.name) (eq (toString $rc.name) (get $presetNames $preset))) -}} {{- if $rc.create -}} {{- $scheduling := default (dict) $rc.scheduling -}} {{- $selector = deepCopy (default (dict) $scheduling.nodeSelector) -}} {{- $tolerations = default (list) $scheduling.tolerations -}} -{{- else if eq $preset "isolated-sandbox" -}} +{{- else if and $knownPreset (eq $preset "isolated-sandbox") -}} {{- $selector = dict "eks.amazonaws.com/nitro-sandbox" "true" -}} -{{- else if eq $preset "gvisor" -}} +{{- else if and $knownPreset (eq $preset "gvisor") -}} {{- $selector = dict "sandbox.gke.io/runtime" "gvisor" -}} {{- $tolerations = list (dict "key" "sandbox.gke.io/runtime" "operator" "Equal" "value" "gvisor" "effect" "NoSchedule") -}} -{{- else if eq $preset "kata" -}} +{{- else if and $knownPreset (eq $preset "kata") -}} {{- $selector = dict "kubernetes.azure.com/kata-vm-isolation" "true" -}} {{- else if and (include "sim.sandbox.runtimeClassName" .) (not $sbx.nodeSelector) -}} {{- fail "sandbox.kubernetes.prePull needs sandbox.kubernetes.nodeSelector with a RuntimeClass the chart neither creates nor knows: set it to the nodes the RuntimeClass schedules onto (kubectl get runtimeclass -o jsonpath='{.scheduling}'), or the pre-pull pods on other nodes stay Pending" -}} {{- end -}} -{{- $selector = mergeOverwrite $selector (default (dict) $sbx.nodeSelector) -}} +{{- range $key, $value := default (dict) $sbx.nodeSelector -}} +{{- if and (hasKey $selector $key) (ne (toString (get $selector $key)) (toString $value)) -}} +{{- fail (printf "sandbox.kubernetes.nodeSelector sets %s=%s, but the sandbox RuntimeClass schedules onto %s=%s: Kubernetes rejects a pod whose nodeSelector conflicts with its RuntimeClass's. Drop the key or use the RuntimeClass's value." $key (toString $value) $key (toString (get $selector $key))) -}} +{{- end -}} +{{- $_ := set $selector $key $value -}} +{{- end -}} {{- $tolerations = concat $tolerations (default (list) $sbx.tolerations) -}} {{- with $selector }} nodeSelector: diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml index 1d649d76f9f..eb4a1071895 100644 --- a/helm/sim/tests/sandbox-kubernetes_test.yaml +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -1201,7 +1201,7 @@ tests: path: spec.template.spec.automountServiceAccountToken value: false - - it: schedules pre-pull pods only where a chart-created RuntimeClass schedules, with the operator's selector winning + - it: schedules pre-pull pods only where a chart-created RuntimeClass schedules, adding the operator's keys template: daemonset-sandbox-prepull.yaml set: <<: *enabled @@ -1209,10 +1209,11 @@ tests: sandbox.kubernetes.images.function.tag: abc123 sandbox.kubernetes.runtimeClass.create: true sandbox.kubernetes.runtimeClass.scheduling: - nodeSelector: { runtime: gvisor, pool: default } + nodeSelector: { runtime: gvisor } tolerations: - { key: runtime, operator: Exists, effect: NoSchedule } sandbox.kubernetes.nodeSelector: + runtime: gvisor pool: sandboxes asserts: - equal: @@ -1262,6 +1263,46 @@ tests: value: - { key: sandbox.gke.io/runtime, operator: Equal, value: gvisor, effect: NoSchedule } + - it: refuses a node selector that contradicts the RuntimeClass's, which Kubernetes would reject + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.scheduling: + nodeSelector: { pool: gvisor-nodes } + sandbox.kubernetes.nodeSelector: + pool: sandboxes + asserts: + - failedTemplate: + errorPattern: "nodeSelector sets pool=sandboxes, but the sandbox RuntimeClass schedules onto pool=gvisor-nodes" + + - it: refuses pre-pull on a preset whose RuntimeClass name is overridden without a node selector + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: kata + sandbox.kubernetes.runtimeClass.name: my-kata + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - failedTemplate: + errorPattern: "prePull needs sandbox.kubernetes.nodeSelector with a RuntimeClass the chart neither creates nor knows" + + - it: keeps the preset's node label when runtimeClass.name repeats the preset's own class name + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: kata + sandbox.kubernetes.runtimeClass.name: kata-vm-isolation + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: { kubernetes.azure.com/kata-vm-isolation: "true" } + - it: refuses pre-pull on a custom RuntimeClass it does not create without a node selector template: daemonset-sandbox-prepull.yaml set: diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index c63fcb92e62..bfd58ef99f8 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -922,7 +922,7 @@ "timeoutSeconds": { "type": "integer", "minimum": 30, - "description": "Self-check request timeout; keep it above the app's 270s sandbox budget (the check starts two sandbox pods)" + "description": "Self-check request timeout; should exceed the app's 270 s sandbox budget when sandbox.kubernetes.enabled" } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 8e84bc5fb67..bbceeabd053 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1421,7 +1421,8 @@ sandbox: # pulls where sandboxes do. # Pre-pull: a DaemonSet holding the Function image on every node the sandbox RuntimeClass # schedules onto (its chart-created scheduling, or the platform's label for a preset; a custom - # class needs nodeSelector). On a VM runtime each holder pod is a small VM that occupies one + # or renamed class needs nodeSelector, which may add keys but not contradict the class's). + # On a VM runtime each holder pod is a small VM that occupies one # sandbox slot on its node (EKS Nitro Sandboxes cap sandboxes per node). prePull: enabled: false diff --git a/packages/sim-setup/src/modes/k8s.test.ts b/packages/sim-setup/src/modes/k8s.test.ts new file mode 100644 index 00000000000..67828ce23d0 --- /dev/null +++ b/packages/sim-setup/src/modes/k8s.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { imageTagArgs } from './k8s' + +const DIGEST = 'sha256:0000000000000000000000000000000000000000000000000000000000000000' + +describe('k8s image pins', () => { + it('keeps a digest the existing release pins, without forcing latest or Always', () => { + const args = imageTagArgs({ app: { image: { digest: DIGEST } } }) + + expect(args).toContain(`app.image.digest=${DIGEST}`) + expect(args).not.toContain('app.image.tag=latest') + expect(args).not.toContain('app.image.pullPolicy=Always') + }) + + it('tracks latest, pulled on every start, for a component with no pin', () => { + const args = imageTagArgs({ app: { image: { digest: DIGEST } } }) + + expect(args).toContain('realtime.image.tag=latest') + expect(args).toContain('realtime.image.pullPolicy=Always') + }) +}) diff --git a/packages/sim-setup/src/modes/k8s.ts b/packages/sim-setup/src/modes/k8s.ts index 5ff2d35f38b..6fa65a74670 100644 --- a/packages/sim-setup/src/modes/k8s.ts +++ b/packages/sim-setup/src/modes/k8s.ts @@ -285,7 +285,7 @@ async function helmInstall( } interface ImageValues { - image?: { tag?: string } + image?: { tag?: string; digest?: string } } interface ReleaseValues { @@ -297,13 +297,19 @@ interface ReleaseValues { /** * `--set` flags pinning the app, realtime, and migrations images. A checkout's chart carries a - * deliberately stale appVersion, so without them the release would run old images; a tag - * the existing release already pins is kept. `latest` is pulled on every start, or nodes would - * keep the image they cached and never see a newer build. + * deliberately stale appVersion, so without them the release would run old images. A digest or + * tag the existing release already pins is kept (a digest overrides any tag in the chart). + * `latest` is pulled on every start, or nodes would keep the image they cached and never see a + * newer build. */ -function imageTagArgs(values: ReleaseValues | null): string[] { +export function imageTagArgs(values: ReleaseValues | null): string[] { return (['app', 'realtime', 'migrations'] as const).flatMap((component) => { - const pinned = values?.[component]?.image?.tag + const image = values?.[component]?.image + if (image?.digest) { + const args = ['--set', `${component}.image.digest=${image.digest}`] + return image.tag ? [...args, '--set', `${component}.image.tag=${image.tag}`] : args + } + const pinned = image?.tag const tag = pinned && pinned !== 'latest' ? pinned : 'latest' const args = ['--set', `${component}.image.tag=${tag}`] return tag === 'latest' ? [...args, '--set', `${component}.image.pullPolicy=Always`] : args From 3068b57ac431ca55eda7cb89211b2d9906aa2f31 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 5 Dec 2026 05:27:55 -0600 Subject: [PATCH 6/6] fix(sim-setup): keep realtime and migrations on the app's pinned release, and pass image tags as strings --- packages/sim-setup/src/modes/k8s.test.ts | 14 ++++++++++++++ packages/sim-setup/src/modes/k8s.ts | 15 +++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/sim-setup/src/modes/k8s.test.ts b/packages/sim-setup/src/modes/k8s.test.ts index 67828ce23d0..6a265ba60df 100644 --- a/packages/sim-setup/src/modes/k8s.test.ts +++ b/packages/sim-setup/src/modes/k8s.test.ts @@ -18,4 +18,18 @@ describe('k8s image pins', () => { expect(args).toContain('realtime.image.tag=latest') expect(args).toContain('realtime.image.pullPolicy=Always') }) + + it('keeps unpinned realtime and migrations on the release the app is pinned to', () => { + const args = imageTagArgs({ app: { image: { tag: 'v0.9.74' } } }) + + expect(args).toContain('realtime.image.tag=v0.9.74') + expect(args).toContain('migrations.image.tag=v0.9.74') + expect(args).not.toContain('realtime.image.pullPolicy=Always') + }) + + it('passes tags as strings so a numeric-looking tag is not coerced', () => { + const args = imageTagArgs({ app: { image: { tag: '20260101' } } }) + + expect(args[args.indexOf('app.image.tag=20260101') - 1]).toBe('--set-string') + }) }) diff --git a/packages/sim-setup/src/modes/k8s.ts b/packages/sim-setup/src/modes/k8s.ts index 6fa65a74670..615d05e7522 100644 --- a/packages/sim-setup/src/modes/k8s.ts +++ b/packages/sim-setup/src/modes/k8s.ts @@ -299,19 +299,22 @@ interface ReleaseValues { * `--set` flags pinning the app, realtime, and migrations images. A checkout's chart carries a * deliberately stale appVersion, so without them the release would run old images. A digest or * tag the existing release already pins is kept (a digest overrides any tag in the chart). - * `latest` is pulled on every start, or nodes would keep the image they cached and never see a - * newer build. + * An unpinned realtime or migrations image follows the app's pinned tag, so the three stay on one + * release. `latest` is pulled on every start, or nodes would keep the image they cached and never + * see a newer build. Tags go through `--set-string` so a numeric-looking tag stays a string. */ export function imageTagArgs(values: ReleaseValues | null): string[] { + const appTag = values?.app?.image?.tag + const releaseTag = appTag && appTag !== 'latest' ? appTag : 'latest' return (['app', 'realtime', 'migrations'] as const).flatMap((component) => { const image = values?.[component]?.image if (image?.digest) { - const args = ['--set', `${component}.image.digest=${image.digest}`] - return image.tag ? [...args, '--set', `${component}.image.tag=${image.tag}`] : args + const args = ['--set-string', `${component}.image.digest=${image.digest}`] + return image.tag ? [...args, '--set-string', `${component}.image.tag=${image.tag}`] : args } const pinned = image?.tag - const tag = pinned && pinned !== 'latest' ? pinned : 'latest' - const args = ['--set', `${component}.image.tag=${tag}`] + const tag = pinned && pinned !== 'latest' ? pinned : releaseTag + const args = ['--set-string', `${component}.image.tag=${tag}`] return tag === 'latest' ? [...args, '--set', `${component}.image.pullPolicy=Always`] : args }) }