Skip to content

Commit 2317d9a

Browse files
committed
fix(executor): a loop whose condition cannot be evaluated fails instead of ending early as success
For, ForEach, and count-driven Do While loops decide continuation from their count instead of evaluating '<loop.index> < N' in the isolated VM, so a sandbox failure can no longer truncate them. A While or Do While condition that fails to evaluate (syntax or runtime error, unresolvable reference, sandbox failure) now fails the loop with a loop error log and a secret-projected message instead of being read as false. Author errors are attributed to the user; sandbox failures stay internal.
1 parent 188d06f commit 2317d9a

7 files changed

Lines changed: 311 additions & 117 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: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,7 @@ import {
33
createSerializedBlock,
44
createSerializedWorkflow,
55
} from '@sim/testing/factories/serialized-block.factory'
6-
import {
7-
evaluateLoopIndexCheck,
8-
isolatedVmMock,
9-
isolatedVmMockFns,
10-
} from '@sim/testing/mocks/isolated-vm.mock'
6+
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
117
import { beforeEach, describe, expect, it, vi } from 'vitest'
128
import { BlockType, DEFAULTS } from '@/executor/constants'
139
import { DAGExecutor } from '@/executor/execution/executor'
@@ -78,9 +74,9 @@ describe('condition-driven loop iteration ceiling', () => {
7874
bodyRuns.count = 0
7975
conditionResult.stopAfter = Number.POSITIVE_INFINITY
8076
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,
77+
/** Only user conditions reach the sandbox; they stay opaque and hold until `stopAfter`. */
78+
isolatedVmMockFns.mockExecuteInIsolatedVM.mockImplementation(async () => ({
79+
result: bodyRuns.count < conditionResult.stopAfter,
8480
}))
8581
})
8682

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

Lines changed: 214 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
1+
import type { SessionPrincipal } from '@sim/auth/principal'
12
import { createLogger } from '@sim/logger'
3+
import {
4+
createSerializedBlock,
5+
createSerializedWorkflow,
6+
} from '@sim/testing/factories/serialized-block.factory'
27
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
38
import { storageServiceMockFns } from '@sim/testing/mocks/storage-service.mock'
49
import { uploadsMock } from '@sim/testing/mocks/uploads.mock'
510
import { beforeEach, describe, expect, it, vi } from 'vitest'
11+
import { classifyFailure } from '@/lib/core/errors/failure-log'
612
import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
7-
import { EDGE } from '@/executor/constants'
13+
import { BlockType, EDGE } from '@/executor/constants'
814
import type { DAG, DAGNode } from '@/executor/dag/builder'
915
import type { EdgeManager } from '@/executor/execution/edge-manager'
16+
import { DAGExecutor } from '@/executor/execution/executor'
1017
import type { BlockStateController } from '@/executor/execution/types'
1118
import { LoopOrchestrator } from '@/executor/orchestrators/loop'
12-
import type { ExecutionContext } from '@/executor/types'
19+
import type { ExecutionContext, ExecutionResult } from '@/executor/types'
20+
import { hasExecutionResult } from '@/executor/utils/errors'
1321
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
22+
import type { SerializedLoop, SerializedWorkflow } from '@/serializer/types'
1423

1524
const mockUploadFile = storageServiceMockFns.mockUploadFile
1625

@@ -24,6 +33,20 @@ vi.mock('@/lib/execution/isolated-vm', () => isolatedVmMock)
2433

2534
vi.mock('@/lib/uploads', () => uploadsMock)
2635

36+
const { bodyRuns } = vi.hoisted(() => ({ bodyRuns: { count: 0 } }))
37+
38+
vi.mock('@/executor/handlers/registry', () => ({
39+
createBlockHandlers: () => [
40+
{
41+
canHandle: () => true,
42+
execute: async (_ctx: unknown, block: { id: string }) => {
43+
if (block.id === 'tick') bodyRuns.count++
44+
return { ok: true }
45+
},
46+
},
47+
],
48+
}))
49+
2750
function createNode(id: string): DAGNode {
2851
return {
2952
id,
@@ -333,3 +356,192 @@ describe('LoopOrchestrator', () => {
333356
expect(scope.condition).toBe('true')
334357
})
335358
})
359+
360+
const PRINCIPAL: SessionPrincipal = { kind: 'session', userId: 'user-1', sessionId: 'session-1' }
361+
362+
const SANDBOX_AT_CAPACITY = {
363+
result: null,
364+
stdout: '',
365+
error: {
366+
message: 'Code execution is at capacity. Please try again in a moment.',
367+
name: 'Error',
368+
isSystemError: true,
369+
},
370+
}
371+
372+
const CONDITION_SYNTAX_ERROR = {
373+
result: null,
374+
stdout: '',
375+
error: { message: "Unexpected token ')'", name: 'SyntaxError' },
376+
}
377+
378+
function loopWorkflow(loop: Partial<Omit<SerializedLoop, 'id' | 'nodes'>>): SerializedWorkflow {
379+
const blocks = [
380+
createSerializedBlock({ id: 'start', name: 'start', type: BlockType.STARTER }),
381+
createSerializedBlock({ id: 'loop', name: 'loop', type: BlockType.LOOP }),
382+
createSerializedBlock({ id: 'tick', name: 'tick', type: BlockType.FUNCTION }),
383+
]
384+
return {
385+
...createSerializedWorkflow(blocks, [
386+
{ source: 'start', target: 'loop' },
387+
{ source: 'loop', target: 'tick', sourceHandle: 'loop-start-source' },
388+
]),
389+
loops: { loop: { id: 'loop', nodes: ['tick'], iterations: 0, ...loop } },
390+
}
391+
}
392+
393+
/** Runs the workflow and returns its result, including the one a failed run attaches to its throw. */
394+
async function runWorkflow(workflow: SerializedWorkflow): Promise<ExecutionResult> {
395+
try {
396+
return await new DAGExecutor({
397+
workflow,
398+
contextExtensions: { workspaceId: 'ws', executionId: 'exec-1', principal: PRINCIPAL },
399+
}).execute('wf')
400+
} catch (error) {
401+
if (hasExecutionResult(error)) return error.executionResult
402+
throw error
403+
}
404+
}
405+
406+
function loopLog(result: ExecutionResult) {
407+
return result.logs?.find((log) => log.blockId === 'loop')
408+
}
409+
410+
describe('loop continuation when the sandbox cannot evaluate', () => {
411+
beforeEach(() => {
412+
bodyRuns.count = 0
413+
clearLargeValueCacheForTests()
414+
mockUploadFile.mockImplementation(async ({ customKey }) => ({ key: customKey }))
415+
})
416+
417+
it.each([
418+
['For', { loopType: 'for', iterations: 5 }],
419+
['ForEach', { loopType: 'forEach', forEachItems: ['a', 'b', 'c', 'd', 'e'] }],
420+
['count-driven Do While', { loopType: 'doWhile', iterations: 5 }],
421+
] as const)(
422+
'runs every iteration of a %s loop while the sandbox is at capacity',
423+
async (_label, loop) => {
424+
mockExecuteInIsolatedVM.mockResolvedValue(SANDBOX_AT_CAPACITY)
425+
426+
const result = await runWorkflow(loopWorkflow(loop))
427+
428+
expect(result.success).toBe(true)
429+
expect(bodyRuns.count).toBe(5)
430+
expect(loopLog(result)?.output?.results).toHaveLength(5)
431+
}
432+
)
433+
434+
it('runs every iteration of a For loop when the sandbox call rejects', async () => {
435+
mockExecuteInIsolatedVM.mockRejectedValue(new Error('REDIS_URL is required'))
436+
437+
const result = await runWorkflow(loopWorkflow({ loopType: 'for', iterations: 5 }))
438+
439+
expect(result.success).toBe(true)
440+
expect(bodyRuns.count).toBe(5)
441+
})
442+
443+
it('fails a While loop whose condition has a syntax error instead of skipping its body', async () => {
444+
mockExecuteInIsolatedVM.mockResolvedValue(CONDITION_SYNTAX_ERROR)
445+
446+
const result = await runWorkflow(
447+
loopWorkflow({ loopType: 'while', whileCondition: '<loop.index> < 3)' })
448+
)
449+
450+
expect(result.success).toBe(false)
451+
expect(bodyRuns.count).toBe(0)
452+
expect(result.error).toContain(
453+
"While loop condition could not be evaluated: Unexpected token ')'"
454+
)
455+
expect(loopLog(result)).toMatchObject({
456+
success: false,
457+
error: expect.stringContaining('condition could not be evaluated'),
458+
})
459+
})
460+
461+
it.each([
462+
[
463+
'answers with a system error',
464+
() => mockExecuteInIsolatedVM.mockResolvedValue(SANDBOX_AT_CAPACITY),
465+
/at capacity/,
466+
],
467+
[
468+
'rejects',
469+
() => mockExecuteInIsolatedVM.mockRejectedValue(new Error('REDIS_URL is required')),
470+
/REDIS_URL is required/,
471+
],
472+
] as const)(
473+
'fails a Do While loop mid-run when the sandbox %s instead of ending it early',
474+
async (_label, failSandbox, message) => {
475+
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
476+
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
477+
failSandbox()
478+
479+
const result = await runWorkflow(
480+
loopWorkflow({ loopType: 'doWhile', doWhileCondition: '<loop.index> < 10' })
481+
)
482+
483+
expect(result.success).toBe(false)
484+
expect(bodyRuns.count).toBe(3)
485+
expect(result.error).toMatch(/^Do While loop condition could not be evaluated: /)
486+
expect(result.error).toMatch(message)
487+
expect(loopLog(result)).toMatchObject({ success: false })
488+
}
489+
)
490+
491+
it('attributes a broken condition to the author and a sandbox failure to Sim', async () => {
492+
const { orchestrator } = createOrchestrator()
493+
const whileScope = () => ({
494+
iteration: 0,
495+
currentIterationOutputs: new Map(),
496+
allIterationOutputs: [],
497+
loopType: 'while',
498+
condition: 'x <',
499+
})
500+
501+
mockExecuteInIsolatedVM.mockResolvedValueOnce(CONDITION_SYNTAX_ERROR)
502+
const userError = await orchestrator
503+
.evaluateInitialCondition(createContext(whileScope()), 'loop-1')
504+
.catch((error: unknown) => error)
505+
506+
mockExecuteInIsolatedVM.mockResolvedValueOnce(SANDBOX_AT_CAPACITY)
507+
const systemError = await orchestrator
508+
.evaluateInitialCondition(createContext(whileScope()), 'loop-1')
509+
.catch((error: unknown) => error)
510+
511+
expect(classifyFailure(userError)).toBe('user')
512+
expect(classifyFailure(systemError)).toBe('internal')
513+
})
514+
515+
it('keeps a resolved secret out of the persisted condition error', async () => {
516+
const secret = 'resolved-condition-secret-value'
517+
const { orchestrator } = createOrchestrator()
518+
const scope = {
519+
iteration: 0,
520+
currentIterationOutputs: new Map(),
521+
allIterationOutputs: [],
522+
loopType: 'while',
523+
condition: '<condition.output>',
524+
} as Record<string, unknown>
525+
const ctx = createContext(scope)
526+
const registry = new ResolvedSecretTraceRegistry([
527+
{ name: 'CONDITION_SECRET', plaintext: secret, encryptedValue: 'encrypted-condition-secret' },
528+
])
529+
registry.recordResolved('CONDITION_SECRET', secret)
530+
ctx.resolvedSecretTraceRegistry = registry
531+
mockExecuteInIsolatedVM.mockResolvedValueOnce({
532+
result: null,
533+
stdout: '',
534+
error: { message: `ReferenceError: ${secret} is not defined`, name: 'ReferenceError' },
535+
})
536+
537+
const error = await orchestrator
538+
.evaluateInitialCondition(ctx, 'loop-1')
539+
.catch((thrown: unknown) => thrown)
540+
541+
expect(error).toBeInstanceOf(Error)
542+
expect((error as Error).message).toMatch(/^While loop condition could not be evaluated/)
543+
expect(
544+
JSON.stringify([(error as Error).message, ctx.blockLogs, scope.validationError])
545+
).not.toContain(secret)
546+
})
547+
})

0 commit comments

Comments
 (0)