Skip to content

Commit 754a28e

Browse files
authored
fix(executor): a loop whose condition cannot be evaluated fails instead of ending early as success (#10282)
Counted loops (for, forEach, count-driven doWhile) decide continuation natively instead of evaluating <loop.index> < N in the isolated VM, so a sandbox failure can no longer truncate them. A while/doWhile condition that cannot be evaluated (user error, VM error result, VM rejection, unresolved reference) now fails the loop with a visible, secret-projected error and loop error log instead of returning false and reporting success. User errors are attributed to the user, and the failure is marked logged so the engine does not log it twice.
1 parent dfff8c3 commit 754a28e

8 files changed

Lines changed: 358 additions & 185 deletions

File tree

‎apps/sim/executor/constants.ts‎

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -184,13 +184,6 @@ export const SPECIAL_REFERENCE_PREFIXES = [
184184
*/
185185
export const RESERVED_BLOCK_NAMES = RESERVED_WORKFLOW_BLOCK_NAMES
186186

187-
export const LOOP_REFERENCE = {
188-
ITERATION: 'iteration',
189-
INDEX: 'index',
190-
ITEM: 'item',
191-
INDEX_PATH: 'loop.index',
192-
} as const
193-
194187
export const DEFAULTS = {
195188
BLOCK_TYPE: 'unknown',
196189
BLOCK_TITLE: 'Untitled Block',
@@ -389,18 +382,6 @@ export function isAnnotationOnlyBlock(blockType: string | undefined): boolean {
389382
return blockType === BlockType.NOTE
390383
}
391384

392-
export function buildReference(path: string): string {
393-
return `${REFERENCE.START}${path}${REFERENCE.END}`
394-
}
395-
396-
export function buildLoopReference(property: string): string {
397-
return buildReference(`${REFERENCE.PREFIX.LOOP}${REFERENCE.PATH_DELIMITER}${property}`)
398-
}
399-
400-
export function buildLoopIndexCondition(maxIterations: number): string {
401-
return `${buildLoopReference(LOOP_REFERENCE.INDEX)} < ${maxIterations}`
402-
}
403-
404385
export function isReference(value: string): boolean {
405386
return value.startsWith(REFERENCE.START) && value.endsWith(REFERENCE.END)
406387
}

‎apps/sim/executor/execution/condition-loop-ceiling.test.ts‎

Lines changed: 10 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,8 @@
1-
import type { SessionPrincipal } from '@sim/auth/principal'
2-
import {
3-
createSerializedBlock,
4-
createSerializedWorkflow,
5-
} from '@sim/testing/factories/serialized-block.factory'
6-
import {
7-
evaluateLoopIndexCheck,
8-
isolatedVmMock,
9-
isolatedVmMockFns,
10-
} from '@sim/testing/mocks/isolated-vm.mock'
1+
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
112
import { beforeEach, describe, expect, it, vi } from 'vitest'
12-
import { BlockType, DEFAULTS } from '@/executor/constants'
13-
import { DAGExecutor } from '@/executor/execution/executor'
14-
import type { ExecutionResult } from '@/executor/types'
15-
import { hasExecutionResult } from '@/executor/utils/errors'
16-
import type { SerializedLoop, SerializedWorkflow } from '@/serializer/types'
3+
import { DEFAULTS } from '@/executor/constants'
4+
import { loopWorkflow, runLoopWorkflow } from '@/executor/execution/loop-workflow.test-helpers'
5+
import type { SerializedWorkflow } from '@/serializer/types'
176

187
const { bodyRuns, conditionResult, runaway } = vi.hoisted(() => ({
198
bodyRuns: { count: 0 },
@@ -37,50 +26,20 @@ vi.mock('@/executor/handlers/registry', () => ({
3726
],
3827
}))
3928

40-
const PRINCIPAL: SessionPrincipal = { kind: 'session', userId: 'user-1', sessionId: 'session-1' }
4129
const CEILING = DEFAULTS.MAX_CONDITION_LOOP_ITERATIONS
4230

43-
function loopWorkflow(loop: Partial<Omit<SerializedLoop, 'id' | 'nodes'>>): SerializedWorkflow {
44-
const blocks = [
45-
createSerializedBlock({ id: 'start', name: 'start', type: BlockType.STARTER }),
46-
createSerializedBlock({ id: 'loop', name: 'loop', type: BlockType.LOOP }),
47-
createSerializedBlock({ id: 'tick', name: 'tick', type: BlockType.FUNCTION }),
48-
]
49-
return {
50-
...createSerializedWorkflow(blocks, [
51-
{ source: 'start', target: 'loop' },
52-
{ source: 'loop', target: 'tick', sourceHandle: 'loop-start-source' },
53-
]),
54-
loops: { loop: { id: 'loop', nodes: ['tick'], iterations: 0, ...loop } },
55-
}
56-
}
57-
58-
/** Runs the workflow and returns its result, including the one a failed run attaches to its throw. */
59-
async function run(workflow: SerializedWorkflow): Promise<ExecutionResult> {
60-
try {
61-
return await new DAGExecutor({
62-
workflow,
63-
contextExtensions: {
64-
workspaceId: 'ws',
65-
executionId: 'exec-1',
66-
principal: PRINCIPAL,
67-
abortSignal: runaway.controller.signal,
68-
},
69-
}).execute('wf')
70-
} catch (error) {
71-
if (hasExecutionResult(error)) return error.executionResult
72-
throw error
73-
}
74-
}
31+
/** Runs under the runaway guard, so a loop the ceiling fails to stop is cancelled instead of hanging. */
32+
const run = (workflow: SerializedWorkflow) =>
33+
runLoopWorkflow(workflow, { abortSignal: runaway.controller.signal })
7534

7635
describe('condition-driven loop iteration ceiling', () => {
7736
beforeEach(() => {
7837
bodyRuns.count = 0
7938
conditionResult.stopAfter = Number.POSITIVE_INFINITY
8039
runaway.controller = new AbortController()
81-
/** Count conditions evaluate; user conditions stay opaque and hold until `stopAfter`. */
82-
isolatedVmMockFns.mockExecuteInIsolatedVM.mockImplementation(async ({ code }) => ({
83-
result: evaluateLoopIndexCheck(code) ?? bodyRuns.count < conditionResult.stopAfter,
40+
/** Only user conditions reach the sandbox; they stay opaque and hold until `stopAfter`. */
41+
isolatedVmMockFns.mockExecuteInIsolatedVM.mockImplementation(async () => ({
42+
result: bodyRuns.count < conditionResult.stopAfter,
8443
}))
8544
})
8645

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import type { SessionPrincipal } from '@sim/auth/principal'
2+
import {
3+
createSerializedBlock,
4+
createSerializedWorkflow,
5+
} from '@sim/testing/factories/serialized-block.factory'
6+
import { BlockType } from '@/executor/constants'
7+
import { DAGExecutor } from '@/executor/execution/executor'
8+
import type { ExecutionResult } from '@/executor/types'
9+
import { hasExecutionResult } from '@/executor/utils/errors'
10+
import type { SerializedLoop, SerializedWorkflow } from '@/serializer/types'
11+
12+
const PRINCIPAL: SessionPrincipal = { kind: 'session', userId: 'user-1', sessionId: 'session-1' }
13+
14+
/** A Start block feeding a loop named `loop` whose body is one block, `tick`. */
15+
export function loopWorkflow(
16+
loop: Partial<Omit<SerializedLoop, 'id' | 'nodes'>>
17+
): SerializedWorkflow {
18+
const blocks = [
19+
createSerializedBlock({ id: 'start', name: 'start', type: BlockType.STARTER }),
20+
createSerializedBlock({ id: 'loop', name: 'loop', type: BlockType.LOOP }),
21+
createSerializedBlock({ id: 'tick', name: 'tick', type: BlockType.FUNCTION }),
22+
]
23+
return {
24+
...createSerializedWorkflow(blocks, [
25+
{ source: 'start', target: 'loop' },
26+
{ source: 'loop', target: 'tick', sourceHandle: 'loop-start-source' },
27+
]),
28+
loops: { loop: { id: 'loop', nodes: ['tick'], iterations: 0, ...loop } },
29+
}
30+
}
31+
32+
/** Runs the workflow and returns its result, including the one a failed run attaches to its throw. */
33+
export async function runLoopWorkflow(
34+
workflow: SerializedWorkflow,
35+
options: { abortSignal?: AbortSignal } = {}
36+
): Promise<ExecutionResult> {
37+
try {
38+
return await new DAGExecutor({
39+
workflow,
40+
contextExtensions: {
41+
workspaceId: 'ws',
42+
executionId: 'exec-1',
43+
principal: PRINCIPAL,
44+
abortSignal: options.abortSignal,
45+
},
46+
}).execute('wf')
47+
} catch (error) {
48+
if (hasExecutionResult(error)) return error.executionResult
49+
throw error
50+
}
51+
}

‎apps/sim/executor/orchestrators/loop.test.ts‎

Lines changed: 182 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
import { createLogger } from '@sim/logger'
2-
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
2+
import {
3+
isolatedVmMock,
4+
isolatedVmMockFns,
5+
resetIsolatedVmMock,
6+
} from '@sim/testing/mocks/isolated-vm.mock'
37
import { storageServiceMockFns } from '@sim/testing/mocks/storage-service.mock'
48
import { uploadsMock } from '@sim/testing/mocks/uploads.mock'
59
import { beforeEach, describe, expect, it, vi } from 'vitest'
10+
import { classifyFailure, logFailureOnce } from '@/lib/core/errors/failure-log'
611
import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
712
import { EDGE } from '@/executor/constants'
813
import type { DAG, DAGNode } from '@/executor/dag/builder'
914
import type { EdgeManager } from '@/executor/execution/edge-manager'
15+
import { loopWorkflow, runLoopWorkflow } from '@/executor/execution/loop-workflow.test-helpers'
1016
import type { BlockStateController } from '@/executor/execution/types'
1117
import { LoopOrchestrator } from '@/executor/orchestrators/loop'
12-
import type { ExecutionContext } from '@/executor/types'
18+
import type { ExecutionContext, ExecutionResult } from '@/executor/types'
1319
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
1420

1521
const mockUploadFile = storageServiceMockFns.mockUploadFile
@@ -24,6 +30,20 @@ vi.mock('@/lib/execution/isolated-vm', () => isolatedVmMock)
2430

2531
vi.mock('@/lib/uploads', () => uploadsMock)
2632

33+
const { bodyRuns } = vi.hoisted(() => ({ bodyRuns: { count: 0 } }))
34+
35+
vi.mock('@/executor/handlers/registry', () => ({
36+
createBlockHandlers: () => [
37+
{
38+
canHandle: () => true,
39+
execute: async (_ctx: unknown, block: { id: string }) => {
40+
if (block.id === 'tick') bodyRuns.count++
41+
return { ok: true }
42+
},
43+
},
44+
],
45+
}))
46+
2747
function createNode(id: string): DAGNode {
2848
return {
2949
id,
@@ -333,3 +353,163 @@ describe('LoopOrchestrator', () => {
333353
expect(scope.condition).toBe('true')
334354
})
335355
})
356+
357+
const SANDBOX_AT_CAPACITY = {
358+
result: null,
359+
stdout: '',
360+
error: {
361+
message: 'Code execution is at capacity. Please try again in a moment.',
362+
name: 'Error',
363+
isSystemError: true,
364+
},
365+
}
366+
367+
const CONDITION_SYNTAX_ERROR = {
368+
result: null,
369+
stdout: '',
370+
error: { message: "Unexpected token ')'", name: 'SyntaxError' },
371+
}
372+
373+
function loopLog(result: ExecutionResult) {
374+
return result.logs?.find((log) => log.blockId === 'loop')
375+
}
376+
377+
const sandboxAtCapacity = () => mockExecuteInIsolatedVM.mockResolvedValue(SANDBOX_AT_CAPACITY)
378+
const sandboxRejects = () =>
379+
mockExecuteInIsolatedVM.mockRejectedValue(new Error('REDIS_URL is required'))
380+
381+
describe('loop continuation when the sandbox cannot evaluate', () => {
382+
beforeEach(() => {
383+
bodyRuns.count = 0
384+
resetIsolatedVmMock()
385+
clearLargeValueCacheForTests()
386+
mockUploadFile.mockImplementation(async ({ customKey }) => ({ key: customKey }))
387+
})
388+
389+
it.each([
390+
['For', 'is at capacity', { loopType: 'for', iterations: 5 }, sandboxAtCapacity],
391+
['For', 'rejects', { loopType: 'for', iterations: 5 }, sandboxRejects],
392+
[
393+
'ForEach',
394+
'is at capacity',
395+
{ loopType: 'forEach', forEachItems: ['a', 'b', 'c', 'd', 'e'] },
396+
sandboxAtCapacity,
397+
],
398+
[
399+
'count-driven Do While',
400+
'is at capacity',
401+
{ loopType: 'doWhile', iterations: 5 },
402+
sandboxAtCapacity,
403+
],
404+
] as const)(
405+
'runs every iteration of a %s loop when the sandbox %s',
406+
async (_label, _mode, loop, failSandbox) => {
407+
failSandbox()
408+
409+
const result = await runLoopWorkflow(loopWorkflow(loop))
410+
411+
expect(result.success).toBe(true)
412+
expect(bodyRuns.count).toBe(5)
413+
expect(loopLog(result)?.output?.results).toHaveLength(5)
414+
}
415+
)
416+
417+
it('fails a While loop whose condition has a syntax error instead of skipping its body', async () => {
418+
mockExecuteInIsolatedVM.mockResolvedValue(CONDITION_SYNTAX_ERROR)
419+
420+
const result = await runLoopWorkflow(
421+
loopWorkflow({ loopType: 'while', whileCondition: '<loop.index> < 3)' })
422+
)
423+
424+
expect(result.success).toBe(false)
425+
expect(bodyRuns.count).toBe(0)
426+
expect(result.error).toContain(
427+
"While loop condition could not be evaluated: Unexpected token ')'"
428+
)
429+
expect(loopLog(result)).toMatchObject({
430+
success: false,
431+
error: expect.stringContaining('condition could not be evaluated'),
432+
})
433+
})
434+
435+
it.each([
436+
['answers with a system error', sandboxAtCapacity, /at capacity/],
437+
['rejects', sandboxRejects, /REDIS_URL is required/],
438+
] as const)(
439+
'fails a Do While loop mid-run when the sandbox %s instead of ending it early',
440+
async (_label, failSandbox, message) => {
441+
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
442+
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
443+
failSandbox()
444+
445+
const result = await runLoopWorkflow(
446+
loopWorkflow({ loopType: 'doWhile', doWhileCondition: '<loop.index> < 10' })
447+
)
448+
449+
expect(result.success).toBe(false)
450+
expect(bodyRuns.count).toBe(3)
451+
expect(result.error).toMatch(/^Do While loop condition could not be evaluated: /)
452+
expect(result.error).toMatch(message)
453+
expect(loopLog(result)).toMatchObject({ success: false })
454+
}
455+
)
456+
457+
it('attributes a broken condition to the author and a sandbox failure to Sim', async () => {
458+
const { orchestrator } = createOrchestrator()
459+
const whileScope = () => ({
460+
iteration: 0,
461+
currentIterationOutputs: new Map(),
462+
allIterationOutputs: [],
463+
loopType: 'while',
464+
condition: 'x <',
465+
})
466+
467+
mockExecuteInIsolatedVM.mockResolvedValueOnce(CONDITION_SYNTAX_ERROR)
468+
const userError = await orchestrator
469+
.evaluateInitialCondition(createContext(whileScope()), 'loop-1')
470+
.catch((error: unknown) => error)
471+
472+
mockExecuteInIsolatedVM.mockResolvedValueOnce(SANDBOX_AT_CAPACITY)
473+
const systemError = await orchestrator
474+
.evaluateInitialCondition(createContext(whileScope()), 'loop-1')
475+
.catch((error: unknown) => error)
476+
477+
expect(classifyFailure(userError)).toBe('user')
478+
expect(classifyFailure(systemError)).toBe('internal')
479+
expect(logFailureOnce(createLogger('probe'), 'probe', userError)).toBeUndefined()
480+
expect(logFailureOnce(createLogger('probe'), 'probe', systemError)).toBeUndefined()
481+
})
482+
483+
it('keeps a resolved secret out of the persisted condition error', async () => {
484+
const secret = 'resolved-condition-secret-value'
485+
const { orchestrator } = createOrchestrator()
486+
const scope = {
487+
iteration: 0,
488+
currentIterationOutputs: new Map(),
489+
allIterationOutputs: [],
490+
loopType: 'while',
491+
condition: '<condition.output>',
492+
} as Record<string, unknown>
493+
const ctx = createContext(scope)
494+
const registry = new ResolvedSecretTraceRegistry([
495+
{ name: 'CONDITION_SECRET', plaintext: secret, encryptedValue: 'encrypted-condition-secret' },
496+
])
497+
registry.recordResolved('CONDITION_SECRET', secret)
498+
ctx.resolvedSecretTraceRegistry = registry
499+
mockExecuteInIsolatedVM.mockResolvedValueOnce({
500+
result: null,
501+
stdout: '',
502+
error: { message: `ReferenceError: ${secret} is not defined`, name: 'ReferenceError' },
503+
})
504+
505+
const error = await orchestrator
506+
.evaluateInitialCondition(ctx, 'loop-1')
507+
.catch((thrown: unknown) => thrown)
508+
509+
expect(error).toBeInstanceOf(Error)
510+
expect((error as Error).message).toMatch(/^While loop condition could not be evaluated/)
511+
expect(
512+
JSON.stringify([(error as Error).message, ctx.blockLogs, scope.validationError])
513+
).not.toContain(secret)
514+
})
515+
})

0 commit comments

Comments
 (0)