Skip to content

Commit 8614dbb

Browse files
committed
fix(sandbox): tolerate an untagged release commit at publish, keep Kubernetes read errors honest, and resolve the effective TRIGGER_DEV_ENABLED
1 parent 7339feb commit 8614dbb

8 files changed

Lines changed: 194 additions & 35 deletions

File tree

‎.github/workflows/helm.yml‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -310,10 +310,9 @@ jobs:
310310
- name: Bundle the release's sandbox Function image
311311
env:
312312
APP_VERSION: ${{ needs.release-version.outputs.version }}
313-
run: |
314-
set -euo pipefail
315-
git fetch --no-tags --depth=1 origin "refs/tags/${APP_VERSION}:refs/tags/${APP_VERSION}"
316-
bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify
313+
# The script fetches the tag itself, and reads HEAD when this is the release commit
314+
# whose tag the release job has not cut yet.
315+
run: bun run scripts/write-chart-sandbox-images.ts --version "${APP_VERSION}" --verify
317316

318317
- name: Package chart
319318
id: package
@@ -512,7 +511,6 @@ jobs:
512511
run: bun run scripts/sync-chart-appversion.ts --version "${APP_VERSION}"
513512

514513
# Same bundled sandbox image as the OCI publish, so both repos ship the same chart.
515-
# The full-history checkout already has the release tag.
516514
- name: Bundle the release's sandbox Function image
517515
if: steps.pages.outputs.exists == 'true'
518516
env:

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175494,7 +175494,7 @@
175494175494
{
175495175495
"lang": "yaml",
175496175496
"meta": null,
175497-
"sha256": "7682823a0d915778f2433bbd40d57c0fb2abd8ffdc82774a2ad8e0716b51b5df",
175497+
"sha256": "367c0b8cc996a8dc240d3285d9bb77f38ad15eee8380c1477bcd84957dc25ec1",
175498175498
"bytes": 77,
175499175499
"line": 182
175500175500
},
@@ -175546,6 +175546,11 @@
175546175546
"sha256": "df790200d0bf869d634b8a6fb573356b2f2114cfada800837daf28aacac46198",
175547175547
"bytes": 208,
175548175548
"line": 401
175549+
},
175550+
{
175551+
"lang": "yaml",
175552+
"meta": null,
175553+
"sha256": "eecfe88b395d0c94f2b4b11d6c58d51fed7914a1bc13cca199dae94c55c9ae56"
175549175554
}
175550175555
],
175551175556
"links": [

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

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,18 @@ function crashLoopingPod(name: string): V1Pod {
9191
}
9292

9393
/**
94-
* A cluster whose pod never changes: every watch ends quietly and every read returns `latest`
94+
* A cluster whose pod never changes: every watch ends quietly and every read answers with `read`
9595
* (the created pod unless given).
9696
*/
97-
function staticCluster(pod: V1Pod, latest: V1Pod = pod): SandboxCluster {
97+
function staticCluster(
98+
pod: V1Pod,
99+
read: () => Promise<V1Pod | null> = async () => pod
100+
): SandboxCluster {
98101
return {
99102
namespace: SETTINGS.namespace,
100103
readRuntimeClassHandler: async () => 'runsc',
101104
createPod: async () => pod,
102-
readPod: async () => latest,
105+
readPod: read,
103106
listPods: async () => [],
104107
listPodEvents: async () => [],
105108
watchPod: (_name, _version, _onUpdate, signal) =>
@@ -117,13 +120,13 @@ function staticCluster(pod: V1Pod, latest: V1Pod = pod): SandboxCluster {
117120
}
118121

119122
/** Starts `waitUntilReady` under a create deadline and records how it settled. */
120-
function start(pod: V1Pod, latest: V1Pod = pod) {
123+
function start(pod: V1Pod, read: () => Promise<V1Pod | null> = async () => pod) {
121124
const deadline = new AbortController()
122125
setTimeout(() => deadline.abort(), CREATE_DEADLINE_MS)
123126
const name = pod.metadata?.name ?? ''
124127
const outcome: { error?: unknown; settled: boolean } = { settled: false }
125128
waitUntilReady(
126-
staticCluster(pod, latest),
129+
staticCluster(pod, read),
127130
{ pod, name, token: 'token' },
128131
'code',
129132
SETTINGS,
@@ -166,7 +169,9 @@ describe('waitUntilReady for a pod that runs but whose agent never answers', ()
166169
describe('waitUntilReady for a pod whose sandbox container crashes before its agent answers', () => {
167170
it('reports the crash and its exit, not the network path', async () => {
168171
checkHealth.mockResolvedValue(null)
169-
const outcome = start(runningPod('sim-sbx-crashing'), crashLoopingPod('sim-sbx-crashing'))
172+
const outcome = start(runningPod('sim-sbx-crashing'), async () =>
173+
crashLoopingPod('sim-sbx-crashing')
174+
)
170175

171176
await vi.advanceTimersByTimeAsync(61_000)
172177

@@ -177,6 +182,33 @@ describe('waitUntilReady for a pod whose sandbox container crashes before its ag
177182
})
178183
})
179184

185+
describe('waitUntilReady when the re-read after a silent agent does not show the container', () => {
186+
it('keeps a Kubernetes read failure in the error rather than blaming the network', async () => {
187+
checkHealth.mockResolvedValue(null)
188+
const outcome = start(runningPod('sim-sbx-unreadable'), async () => {
189+
throw new Error('Kubernetes readPod failed: etcdserver: request timed out')
190+
})
191+
192+
await vi.advanceTimersByTimeAsync(61_000)
193+
194+
expect(outcome.settled).toBe(true)
195+
expect(outcome.error).toBeInstanceOf(KubernetesSandboxConfigError)
196+
expect(String(outcome.error)).toContain('etcdserver: request timed out')
197+
expect(String(outcome.error)).not.toContain('NetworkPolicy')
198+
})
199+
200+
it('reports a pod deleted while its agent was starting', async () => {
201+
checkHealth.mockResolvedValue(null)
202+
const outcome = start(runningPod('sim-sbx-gone'), async () => null)
203+
204+
await vi.advanceTimersByTimeAsync(61_000)
205+
206+
expect(outcome.settled).toBe(true)
207+
expect(String(outcome.error)).toContain('was deleted while its agent was starting')
208+
expect(String(outcome.error)).not.toContain('NetworkPolicy')
209+
})
210+
})
211+
180212
describe('waitUntilReady for a pod no node can schedule', () => {
181213
it('fails as capacity at the create deadline', async () => {
182214
const outcome = start(pendingPod('sim-sbx-unscheduled'))

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

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,8 @@ export async function waitForAgent(client: SandboxAgentClient, signal: AbortSign
201201
* Why the sandbox container stopped, when it has: its current or last termination (reason and
202202
* exit code), or null while it has run without a restart.
203203
*/
204-
function sandboxContainerCrash(pod: V1Pod | null): string | null {
205-
const status = pod?.status?.containerStatuses?.find(({ name }) => name === SANDBOX_CONTAINER_NAME)
204+
function sandboxContainerCrash(pod: V1Pod): string | null {
205+
const status = pod.status?.containerStatuses?.find(({ name }) => name === SANDBOX_CONTAINER_NAME)
206206
if (!status) return null
207207
const stillRunning = Boolean(status.state?.running)
208208
if (stillRunning && !status.restartCount) return null
@@ -233,12 +233,22 @@ async function waitForRunningAgent(
233233
await waitForAgent(client, AbortSignal.any([signal, unreachable.signal]))
234234
} catch (error) {
235235
if (signal.aborted || !unreachable.signal.aborted) throw error
236-
const latest = await cluster.readPod(name, { signal }).catch(() => null)
236+
const silent = `Sandbox pod ${name} is running but its agent at ${baseUrl} did not answer within ${AGENT_UNREACHABLE_MS / 1000}s`
237+
let latest: V1Pod | null
238+
try {
239+
latest = await cluster.readPod(name, { signal })
240+
} catch (readError) {
241+
throw new KubernetesSandboxConfigError(
242+
`${silent}, and re-reading the pod to tell a crashed container from a blocked network path failed: ${getErrorMessage(readError)}`,
243+
{ cause: error }
244+
)
245+
}
246+
if (!latest) throw new Error(`Sandbox pod ${name} was deleted while its agent was starting`)
237247
const crash = sandboxContainerCrash(latest)
238248
throw new KubernetesSandboxConfigError(
239249
crash
240250
? `Sandbox pod ${name}'s sandbox container stopped before its agent answered (${crash}). Check that the sandbox image runs the agent the init container installs.`
241-
: `Sandbox pod ${name} is running but its agent at ${baseUrl} did not answer within ${AGENT_UNREACHABLE_MS / 1000}s. ${AGENT_PATH_HINT}`,
251+
: `${silent}. ${AGENT_PATH_HINT}`,
242252
{ cause: error }
243253
)
244254
} finally {

‎helm/sim/templates/_helpers.tpl‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -999,14 +999,22 @@ refuse or that would weaken isolation.
999999
{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest when the chart carries no default function image. Published charts (oci://ghcr.io/simstudioai/charts/sim and the Helm repository) carry the one their appVersion runs; a chart installed from a git checkout does not" -}}
10001000
{{- end -}}
10011001
{{- end -}}
1002-
{{- $trigger := "" -}}
1003-
{{- if hasKey .Values.app.env "TRIGGER_DEV_ENABLED" -}}
1004-
{{- $trigger = toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}}
1005-
{{- else if hasKey (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED" -}}
1006-
{{- $trigger = toString (default "" (index .Values.app.envDefaults "TRIGGER_DEV_ENABLED")) -}}
1002+
{{- /*
1003+
The app's effective TRIGGER_DEV_ENABLED: a literal extraEnvVars entry (the last
1004+
one, as Kubernetes keeps the last duplicate), else a non-empty app.env value
1005+
(an empty one reads as unset, so envDefaults still applies), else envDefaults.
1006+
*/ -}}
1007+
{{- $trigger := toString (default "" (index (.Values.app.envDefaults | default dict) "TRIGGER_DEV_ENABLED")) -}}
1008+
{{- with toString (default "" (index .Values.app.env "TRIGGER_DEV_ENABLED")) -}}
1009+
{{- $trigger = . -}}
1010+
{{- end -}}
1011+
{{- range .Values.extraEnvVars -}}
1012+
{{- if and (eq (toString .name) "TRIGGER_DEV_ENABLED") (hasKey . "value") -}}
1013+
{{- $trigger = toString (default "" .value) -}}
1014+
{{- end -}}
10071015
{{- end -}}
10081016
{{- if has (lower $trigger) (list "true" "1") -}}
1009-
{{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env and app.envDefaults so executions run on the database-backed job queue" -}}
1017+
{{- fail "sandbox.kubernetes.enabled=true with TRIGGER_DEV_ENABLED set: executions would run on Trigger.dev workers, which cannot reach sandbox pods in this cluster, and the app reports the Kubernetes provider misconfigured. Unset TRIGGER_DEV_ENABLED in app.env, app.envDefaults, and extraEnvVars so executions run on the database-backed job queue" -}}
10101018
{{- end -}}
10111019
{{- if $sbx.quota.enabled -}}
10121020
{{- range $field := list "cpu" "memory" "ephemeralStorage" -}}

‎helm/sim/tests/sandbox-kubernetes_test.yaml‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,40 @@ tests:
10491049
- failedTemplate:
10501050
errorPattern: "TRIGGER_DEV_ENABLED set"
10511051

1052+
- it: refuses a TRIGGER_DEV_ENABLED default that an empty app.env entry leaves in force
1053+
template: sandbox-kubernetes.yaml
1054+
set:
1055+
<<: *enabled
1056+
app.envDefaults.TRIGGER_DEV_ENABLED: "true"
1057+
app.env.TRIGGER_DEV_ENABLED: ""
1058+
asserts:
1059+
- failedTemplate:
1060+
errorPattern: "TRIGGER_DEV_ENABLED set"
1061+
1062+
- it: refuses TRIGGER_DEV_ENABLED set through extraEnvVars
1063+
template: sandbox-kubernetes.yaml
1064+
set:
1065+
<<: *enabled
1066+
extraEnvVars:
1067+
- name: TRIGGER_DEV_ENABLED
1068+
value: "true"
1069+
asserts:
1070+
- failedTemplate:
1071+
errorPattern: "TRIGGER_DEV_ENABLED set"
1072+
1073+
- it: lets the last extraEnvVars entry turn off TRIGGER_DEV_ENABLED from app.env
1074+
template: sandbox-kubernetes.yaml
1075+
set:
1076+
<<: *enabled
1077+
app.env.TRIGGER_DEV_ENABLED: "true"
1078+
extraEnvVars:
1079+
- name: TRIGGER_DEV_ENABLED
1080+
value: "true"
1081+
- name: TRIGGER_DEV_ENABLED
1082+
value: "false"
1083+
asserts:
1084+
- notFailedTemplate: {}
1085+
10521086
- it: lets app.env turn off a TRIGGER_DEV_ENABLED default
10531087
template: sandbox-kubernetes.yaml
10541088
set:
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { releaseRevision } from './write-chart-sandbox-images'
3+
4+
describe('releaseRevision', () => {
5+
it('reads the release tag when it exists', () => {
6+
expect(releaseRevision({ version: 'v1.2.3', tagPresent: true, headSubject: 'anything' })).toBe(
7+
'refs/tags/v1.2.3'
8+
)
9+
})
10+
11+
it('reads HEAD on the untagged release commit', () => {
12+
expect(
13+
releaseRevision({ version: 'v1.2.3', tagPresent: false, headSubject: 'v1.2.3: release' })
14+
).toBe('HEAD')
15+
})
16+
17+
it.each([
18+
['another release commit', 'v1.2.30: release'],
19+
['an ordinary commit', 'fix(sandbox): v1.2.3: something'],
20+
])('refuses %s when the tag is missing, naming the fetch failure', (_label, headSubject) => {
21+
expect(() =>
22+
releaseRevision({
23+
version: 'v1.2.3',
24+
tagPresent: false,
25+
headSubject,
26+
fetchError: "fatal: couldn't find remote ref\n",
27+
})
28+
).toThrow(/not present and HEAD .* is not its release commit; fetching the tag failed: fatal/)
29+
})
30+
})

‎scripts/write-chart-sandbox-images.ts‎

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@
1919
* installed, matching `sync-chart-appversion.ts`; for the same reason it reports
2020
* with `console` rather than `@sim/logger`.
2121
*
22-
* The release tag must be present locally (a shallow checkout fetches it first). A release
23-
* that predates the list (v0.9.72 and earlier) gets a notice and no file, so its chart
24-
* behaves like a checkout: pre-pull needs an explicit function image.
22+
* The release tag is fetched when the checkout lacks it (publish jobs check out shallow). On
23+
* the release commit itself the tag may not exist yet, since publishing does not wait for the
24+
* job that cuts it, so HEAD is read when its subject names the release (`v1.2.3: ...`, the rule
25+
* helm.yml resolves the version by). A release that predates the list (v0.9.72 and earlier)
26+
* gets a notice and no file, so its chart behaves like a checkout: pre-pull needs an explicit
27+
* function image.
2528
*
2629
* @example
2730
* ```
@@ -63,17 +66,55 @@ function run(command: string, args: string[]): string {
6366
return result.stdout
6467
}
6568

66-
/** True when `path` exists at `revision`; throws when the revision itself is unknown. */
67-
function existsAt(revision: string, path: string): boolean {
68-
const commit = spawnSync('git', ['rev-parse', '--verify', '--quiet', `${revision}^{commit}`], {
69-
cwd: ROOT,
69+
function git(args: readonly string[]): { ok: boolean; stdout: string; stderr: string } {
70+
const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' })
71+
return { ok: result.status === 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' }
72+
}
73+
74+
/**
75+
* The git revision to read `version`'s image list from: its tag when present, else HEAD when
76+
* HEAD is the release commit that will be tagged `version`. Throws otherwise, naming why.
77+
*/
78+
export function releaseRevision(input: {
79+
version: string
80+
tagPresent: boolean
81+
headSubject: string
82+
fetchError?: string
83+
}): string {
84+
if (input.tagPresent) return `refs/tags/${input.version}`
85+
if (input.headSubject.startsWith(`${input.version}:`)) return 'HEAD'
86+
throw new Error(
87+
`Release tag ${input.version} is not present and HEAD ("${input.headSubject}") is not its release commit${input.fetchError ? `; fetching the tag failed: ${input.fetchError.trim()}` : ''}`
88+
)
89+
}
90+
91+
/** Resolves {@link releaseRevision} against the repository, fetching the tag when absent. */
92+
function resolveReleaseRevision(version: string): string {
93+
const tagRef = `refs/tags/${version}`
94+
const hasTag = () => git(['rev-parse', '--verify', '--quiet', `${tagRef}^{commit}`]).ok
95+
let fetchError: string | undefined
96+
if (!hasTag()) {
97+
const fetched = git([
98+
'fetch',
99+
'--quiet',
100+
'--no-tags',
101+
'--depth',
102+
'1',
103+
'origin',
104+
`+${tagRef}:${tagRef}`,
105+
])
106+
if (!fetched.ok) fetchError = fetched.stderr
107+
}
108+
return releaseRevision({
109+
version,
110+
tagPresent: hasTag(),
111+
headSubject: git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim(),
112+
fetchError,
70113
})
71-
if (commit.status !== 0) throw new Error(`Release tag ${revision} is not present locally`)
72-
return spawnSync('git', ['cat-file', '-e', `${revision}:${path}`], { cwd: ROOT }).status === 0
73114
}
74115

75-
function releaseFunctionImage(version: string): string {
76-
const list: unknown = JSON.parse(run('git', ['show', `${version}:${IMAGE_LIST_PATH}`]))
116+
function releaseFunctionImage(version: string, revision: string): string {
117+
const list: unknown = JSON.parse(run('git', ['show', `${revision}:${IMAGE_LIST_PATH}`]))
77118
const image =
78119
typeof list === 'object' && list !== null && 'function' in list ? list.function : undefined
79120
if (typeof image !== 'string' || !FUNCTION_IMAGE.test(image)) {
@@ -111,13 +152,14 @@ function renderedPrePullImage(): string {
111152

112153
async function main() {
113154
const { version, verify } = parseArgs(process.argv.slice(2))
114-
if (!existsAt(version, IMAGE_LIST_PATH)) {
155+
const revision = resolveReleaseRevision(version)
156+
if (!git(['cat-file', '-e', `${revision}:${IMAGE_LIST_PATH}`]).ok) {
115157
console.log(
116158
`Notice: ${version} has no ${IMAGE_LIST_PATH}, so the chart carries no default sandbox Function image; sandbox.kubernetes.prePull needs images.function.tag or digest with it.`
117159
)
118160
return
119161
}
120-
const image = releaseFunctionImage(version)
162+
const image = releaseFunctionImage(version, revision)
121163
await mkdir(dirname(OUTPUT_PATH), { recursive: true })
122164
await writeFile(OUTPUT_PATH, `${JSON.stringify({ function: image }, null, 2)}\n`)
123165
console.log(`Wrote ${image} to helm/sim/files/sandbox-images.json.`)

0 commit comments

Comments
 (0)