Skip to content

Commit d424f34

Browse files
committed
refactor(executor): share loop error projection and loop-workflow test helpers
Extract projectLoopErrorMessage for the ForEach-resolution and condition-evaluation failure paths, drop the count check that the native continuation now covers, and move loopWorkflow/runLoopWorkflow into a shared test helper.
1 parent 2317d9a commit d424f34

4 files changed

Lines changed: 123 additions & 150 deletions

File tree

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

Lines changed: 6 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,8 @@
1-
import type { SessionPrincipal } from '@sim/auth/principal'
2-
import {
3-
createSerializedBlock,
4-
createSerializedWorkflow,
5-
} from '@sim/testing/factories/serialized-block.factory'
61
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
72
import { beforeEach, describe, expect, it, vi } from 'vitest'
8-
import { BlockType, DEFAULTS } from '@/executor/constants'
9-
import { DAGExecutor } from '@/executor/execution/executor'
10-
import type { ExecutionResult } from '@/executor/types'
11-
import { hasExecutionResult } from '@/executor/utils/errors'
12-
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'
136

147
const { bodyRuns, conditionResult, runaway } = vi.hoisted(() => ({
158
bodyRuns: { count: 0 },
@@ -33,41 +26,11 @@ vi.mock('@/executor/handlers/registry', () => ({
3326
],
3427
}))
3528

36-
const PRINCIPAL: SessionPrincipal = { kind: 'session', userId: 'user-1', sessionId: 'session-1' }
3729
const CEILING = DEFAULTS.MAX_CONDITION_LOOP_ITERATIONS
3830

39-
function loopWorkflow(loop: Partial<Omit<SerializedLoop, 'id' | 'nodes'>>): SerializedWorkflow {
40-
const blocks = [
41-
createSerializedBlock({ id: 'start', name: 'start', type: BlockType.STARTER }),
42-
createSerializedBlock({ id: 'loop', name: 'loop', type: BlockType.LOOP }),
43-
createSerializedBlock({ id: 'tick', name: 'tick', type: BlockType.FUNCTION }),
44-
]
45-
return {
46-
...createSerializedWorkflow(blocks, [
47-
{ source: 'start', target: 'loop' },
48-
{ source: 'loop', target: 'tick', sourceHandle: 'loop-start-source' },
49-
]),
50-
loops: { loop: { id: 'loop', nodes: ['tick'], iterations: 0, ...loop } },
51-
}
52-
}
53-
54-
/** Runs the workflow and returns its result, including the one a failed run attaches to its throw. */
55-
async function run(workflow: SerializedWorkflow): Promise<ExecutionResult> {
56-
try {
57-
return await new DAGExecutor({
58-
workflow,
59-
contextExtensions: {
60-
workspaceId: 'ws',
61-
executionId: 'exec-1',
62-
principal: PRINCIPAL,
63-
abortSignal: runaway.controller.signal,
64-
},
65-
}).execute('wf')
66-
} catch (error) {
67-
if (hasExecutionResult(error)) return error.executionResult
68-
throw error
69-
}
70-
}
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 })
7134

7235
describe('condition-driven loop iteration ceiling', () => {
7336
beforeEach(() => {
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: 33 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
1-
import type { SessionPrincipal } from '@sim/auth/principal'
21
import { createLogger } from '@sim/logger'
32
import {
4-
createSerializedBlock,
5-
createSerializedWorkflow,
6-
} from '@sim/testing/factories/serialized-block.factory'
7-
import { isolatedVmMock, isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
3+
isolatedVmMock,
4+
isolatedVmMockFns,
5+
resetIsolatedVmMock,
6+
} from '@sim/testing/mocks/isolated-vm.mock'
87
import { storageServiceMockFns } from '@sim/testing/mocks/storage-service.mock'
98
import { uploadsMock } from '@sim/testing/mocks/uploads.mock'
109
import { beforeEach, describe, expect, it, vi } from 'vitest'
1110
import { classifyFailure } from '@/lib/core/errors/failure-log'
1211
import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
13-
import { BlockType, EDGE } from '@/executor/constants'
12+
import { EDGE } from '@/executor/constants'
1413
import type { DAG, DAGNode } from '@/executor/dag/builder'
1514
import type { EdgeManager } from '@/executor/execution/edge-manager'
16-
import { DAGExecutor } from '@/executor/execution/executor'
15+
import { loopWorkflow, runLoopWorkflow } from '@/executor/execution/loop-workflow.test-helpers'
1716
import type { BlockStateController } from '@/executor/execution/types'
1817
import { LoopOrchestrator } from '@/executor/orchestrators/loop'
1918
import type { ExecutionContext, ExecutionResult } from '@/executor/types'
20-
import { hasExecutionResult } from '@/executor/utils/errors'
2119
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
22-
import type { SerializedLoop, SerializedWorkflow } from '@/serializer/types'
2320

2421
const mockUploadFile = storageServiceMockFns.mockUploadFile
2522

@@ -357,8 +354,6 @@ describe('LoopOrchestrator', () => {
357354
})
358355
})
359356

360-
const PRINCIPAL: SessionPrincipal = { kind: 'session', userId: 'user-1', sessionId: 'session-1' }
361-
362357
const SANDBOX_AT_CAPACITY = {
363358
result: null,
364359
stdout: '',
@@ -375,75 +370,54 @@ const CONDITION_SYNTAX_ERROR = {
375370
error: { message: "Unexpected token ')'", name: 'SyntaxError' },
376371
}
377372

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-
406373
function loopLog(result: ExecutionResult) {
407374
return result.logs?.find((log) => log.blockId === 'loop')
408375
}
409376

377+
const sandboxAtCapacity = () => mockExecuteInIsolatedVM.mockResolvedValue(SANDBOX_AT_CAPACITY)
378+
const sandboxRejects = () =>
379+
mockExecuteInIsolatedVM.mockRejectedValue(new Error('REDIS_URL is required'))
380+
410381
describe('loop continuation when the sandbox cannot evaluate', () => {
411382
beforeEach(() => {
412383
bodyRuns.count = 0
384+
resetIsolatedVmMock()
413385
clearLargeValueCacheForTests()
414386
mockUploadFile.mockImplementation(async ({ customKey }) => ({ key: customKey }))
415387
})
416388

417389
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 }],
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+
],
421404
] 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)
405+
'runs every iteration of a %s loop when the sandbox %s',
406+
async (_label, _mode, loop, failSandbox) => {
407+
failSandbox()
425408

426-
const result = await runWorkflow(loopWorkflow(loop))
409+
const result = await runLoopWorkflow(loopWorkflow(loop))
427410

428411
expect(result.success).toBe(true)
429412
expect(bodyRuns.count).toBe(5)
430413
expect(loopLog(result)?.output?.results).toHaveLength(5)
431414
}
432415
)
433416

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-
443417
it('fails a While loop whose condition has a syntax error instead of skipping its body', async () => {
444418
mockExecuteInIsolatedVM.mockResolvedValue(CONDITION_SYNTAX_ERROR)
445419

446-
const result = await runWorkflow(
420+
const result = await runLoopWorkflow(
447421
loopWorkflow({ loopType: 'while', whileCondition: '<loop.index> < 3)' })
448422
)
449423

@@ -459,24 +433,16 @@ describe('loop continuation when the sandbox cannot evaluate', () => {
459433
})
460434

461435
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-
],
436+
['answers with a system error', sandboxAtCapacity, /at capacity/],
437+
['rejects', sandboxRejects, /REDIS_URL is required/],
472438
] as const)(
473439
'fails a Do While loop mid-run when the sandbox %s instead of ending it early',
474440
async (_label, failSandbox, message) => {
475441
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
476442
mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: true })
477443
failSandbox()
478444

479-
const result = await runWorkflow(
445+
const result = await runLoopWorkflow(
480446
loopWorkflow({ loopType: 'doWhile', doWhileCondition: '<loop.index> < 10' })
481447
)
482448

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

Lines changed: 33 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,25 @@ async function replaceLoopConditionReferences(
5252
return result + condition.slice(cursor)
5353
}
5454

55+
/**
56+
* Projects a loop failure message through the run's resolved-secret registry. `persistedMessage`
57+
* is safe for block logs and the thrown error: it falls back to `fallback` whenever projection
58+
* cannot prove the message free of resolved secrets.
59+
*/
60+
function projectLoopErrorMessage(
61+
message: string,
62+
fallback: string,
63+
registry: ExecutionContext['resolvedSecretTraceRegistry'],
64+
loopId: string
65+
): { diagnostic: Record<string, unknown>; persistedMessage: string } {
66+
const diagnostic = projectResolvedSecretDiagnosticError(new Error(message), registry, { loopId })
67+
if (!registry) return { diagnostic, persistedMessage: message }
68+
return {
69+
diagnostic,
70+
persistedMessage: typeof diagnostic.error === 'string' ? diagnostic.error : fallback,
71+
}
72+
}
73+
5574
/** While loops, and Do While loops given a condition, stop only when their condition does. */
5675
function isConditionDriven(scope: LoopScope): boolean {
5776
return (
@@ -155,17 +174,13 @@ export class LoopOrchestrator {
155174
buildLoopSentinelStartId(loopId)
156175
)
157176
} catch (error) {
158-
const errorMessage = `ForEach loop resolution failed: ${toError(error).message}`
159-
const errorDiagnostic = projectResolvedSecretDiagnosticError(
160-
new Error(errorMessage),
161-
resolutionCtx.resolvedSecretTraceRegistry,
162-
{ loopId }
163-
)
164-
const persistedErrorMessage = resolutionCtx.resolvedSecretTraceRegistry
165-
? typeof errorDiagnostic.error === 'string'
166-
? errorDiagnostic.error
167-
: 'ForEach loop resolution failed'
168-
: errorMessage
177+
const { diagnostic: errorDiagnostic, persistedMessage: persistedErrorMessage } =
178+
projectLoopErrorMessage(
179+
`ForEach loop resolution failed: ${toError(error).message}`,
180+
'ForEach loop resolution failed',
181+
resolutionCtx.resolvedSecretTraceRegistry,
182+
loopId
183+
)
169184
logger.error('ForEach loop resolution failed', errorDiagnostic)
170185
await this.addLoopErrorLog(resolutionCtx, loopId, loopType, persistedErrorMessage, {
171186
inputType: Array.isArray(loopConfig.forEachItems)
@@ -305,10 +320,6 @@ export class LoopOrchestrator {
305320

306321
scope.currentIterationOutputs.clear()
307322

308-
if (this.hasReachedConfiguredIterationLimit(scope, scope.iteration + 1)) {
309-
return await this.createExitResult(ctx, loopId, scope)
310-
}
311-
312323
if (!(await this.evaluateCondition(ctx, loopId, scope, scope.iteration + 1))) {
313324
return await this.createExitResult(ctx, loopId, scope)
314325
}
@@ -330,13 +341,6 @@ export class LoopOrchestrator {
330341
}
331342
}
332343

333-
private hasReachedConfiguredIterationLimit(scope: LoopScope, nextIteration: number): boolean {
334-
if (scope.loopType !== 'doWhile' || scope.maxIterations === undefined) {
335-
return false
336-
}
337-
return nextIteration >= scope.maxIterations
338-
}
339-
340344
/**
341345
* Fails the run once a condition-driven loop has used its iteration ceiling with the condition
342346
* still true. Exiting quietly instead would hand downstream blocks a truncated result as if
@@ -770,10 +774,6 @@ export class LoopOrchestrator {
770774
condition: string,
771775
scope: LoopScope
772776
): Promise<boolean> {
773-
if (!condition) {
774-
return false
775-
}
776-
777777
logger.info('Evaluating loop condition', {
778778
conditionLength: condition.length,
779779
iteration: scope.iteration,
@@ -849,20 +849,13 @@ export class LoopOrchestrator {
849849
): Promise<never> {
850850
const loopType = scope.loopType === 'doWhile' ? 'doWhile' : 'while'
851851
const label = loopType === 'doWhile' ? 'Do While' : 'While'
852-
const errorMessage = `${label} loop condition could not be evaluated: ${toError(cause).message}`
853-
const registry = ctx.resolvedSecretTraceRegistry
854-
const errorDiagnostic = projectResolvedSecretDiagnosticError(
855-
new Error(errorMessage),
856-
registry,
857-
{
858-
loopId,
859-
}
860-
)
861-
const persistedErrorMessage = registry
862-
? typeof errorDiagnostic.error === 'string'
863-
? errorDiagnostic.error
864-
: `${label} loop condition could not be evaluated`
865-
: errorMessage
852+
const { diagnostic: errorDiagnostic, persistedMessage: persistedErrorMessage } =
853+
projectLoopErrorMessage(
854+
`${label} loop condition could not be evaluated: ${toError(cause).message}`,
855+
`${label} loop condition could not be evaluated`,
856+
ctx.resolvedSecretTraceRegistry,
857+
loopId
858+
)
866859
const isUserFailure = classifyFailure(cause) === 'user'
867860
const logFn = isUserFailure ? logger.warn.bind(logger) : logger.error.bind(logger)
868861
logFn('Failed to evaluate loop condition', { ...errorDiagnostic, isUserFailure })

0 commit comments

Comments
 (0)