11import { 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'
37import { storageServiceMockFns } from '@sim/testing/mocks/storage-service.mock'
48import { uploadsMock } from '@sim/testing/mocks/uploads.mock'
59import { beforeEach , describe , expect , it , vi } from 'vitest'
10+ import { classifyFailure , logFailureOnce } from '@/lib/core/errors/failure-log'
611import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache'
712import { EDGE } from '@/executor/constants'
813import type { DAG , DAGNode } from '@/executor/dag/builder'
914import type { EdgeManager } from '@/executor/execution/edge-manager'
15+ import { loopWorkflow , runLoopWorkflow } from '@/executor/execution/loop-workflow.test-helpers'
1016import type { BlockStateController } from '@/executor/execution/types'
1117import { LoopOrchestrator } from '@/executor/orchestrators/loop'
12- import type { ExecutionContext } from '@/executor/types'
18+ import type { ExecutionContext , ExecutionResult } from '@/executor/types'
1319import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
1420
1521const mockUploadFile = storageServiceMockFns . mockUploadFile
@@ -24,6 +30,20 @@ vi.mock('@/lib/execution/isolated-vm', () => isolatedVmMock)
2430
2531vi . 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+
2747function 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 , / a t c a p a c i t y / ] ,
437+ [ 'rejects' , sandboxRejects , / R E D I S _ U R L i s r e q u i r e d / ] ,
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 ( / ^ 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 : / )
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 ( / ^ 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 / )
511+ expect (
512+ JSON . stringify ( [ ( error as Error ) . message , ctx . blockLogs , scope . validationError ] )
513+ ) . not . toContain ( secret )
514+ } )
515+ } )
0 commit comments