1+ import type { SessionPrincipal } from '@sim/auth/principal'
12import { createLogger } from '@sim/logger'
3+ import {
4+ createSerializedBlock ,
5+ createSerializedWorkflow ,
6+ } from '@sim/testing/factories/serialized-block.factory'
27import { isolatedVmMock , isolatedVmMockFns } from '@sim/testing/mocks/isolated-vm.mock'
38import { storageServiceMockFns } from '@sim/testing/mocks/storage-service.mock'
49import { uploadsMock } from '@sim/testing/mocks/uploads.mock'
510import { beforeEach , describe , expect , it , vi } from 'vitest'
11+ import { classifyFailure } from '@/lib/core/errors/failure-log'
612import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
7- import { EDGE } from '@/executor/constants'
13+ import { BlockType , EDGE } from '@/executor/constants'
814import type { DAG , DAGNode } from '@/executor/dag/builder'
915import type { EdgeManager } from '@/executor/execution/edge-manager'
16+ import { DAGExecutor } from '@/executor/execution/executor'
1017import type { BlockStateController } from '@/executor/execution/types'
1118import { 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'
1321import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
22+ import type { SerializedLoop , SerializedWorkflow } from '@/serializer/types'
1423
1524const mockUploadFile = storageServiceMockFns . mockUploadFile
1625
@@ -24,6 +33,20 @@ vi.mock('@/lib/execution/isolated-vm', () => isolatedVmMock)
2433
2534vi . 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+
2750function 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+ / a t c a p a c i t y / ,
466+ ] ,
467+ [
468+ 'rejects' ,
469+ ( ) => mockExecuteInIsolatedVM . mockRejectedValue ( new Error ( 'REDIS_URL is required' ) ) ,
470+ / R E D I S _ U R L i s r e q u i r e d / ,
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 ( / ^ D o W h i l e l o o p c o n d i t i o n c o u l d n o t b e e v a l u a t e d : / )
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 ( / ^ W h i l e l o o p c o n d i t i o n c o u l d n o t b e e v a l u a t e d / )
543+ expect (
544+ JSON . stringify ( [ ( error as Error ) . message , ctx . blockLogs , scope . validationError ] )
545+ ) . not . toContain ( secret )
546+ } )
547+ } )
0 commit comments