import { beforeEach, describe, expect, it, vi } from 'vitest'; import { z } from 'zod/v4'; import { RequestContext } from '../di'; import { MastraError, MastraNonRetryableError, ErrorDomain, ErrorCategory } from '../error'; import type { PubSub } from '../events'; import { EventEmitterPubSub } from '../events/event-emitter'; import { createObservabilityContext, SpanType } from '../observability'; import { MASTRA_AUTH_TOKEN_KEY } from '../request-context'; import { WORKFLOW_CANCELLED_SYMBOL } from './constants'; import { createWorkflow } from './create'; import { DefaultExecutionEngine } from './default'; import type { Step } from './step'; import type { FormattedWorkflowResult, StepResult } from './types'; import { createStep } from './workflow'; class TestableExecutionEngine extends DefaultExecutionEngine { async fmtReturnValuePublic( pubsub: PubSub, stepResults: Record>, lastOutput: StepResult, error?: Error | unknown, stepExecutionPath?: string[], ) { return this.fmtReturnValue(pubsub, stepResults, lastOutput, error, stepExecutionPath); } deserializeRequestContextPublic(obj: Record): RequestContext { return this.deserializeRequestContext(obj); } } describe('DefaultExecutionEngine.serializeRequestContext', () => { it('should correctly serialize serializable values', () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const ctx = new RequestContext(); ctx.set('userId', 'user-123'); ctx.set('feature', 'dark-mode'); ctx.set('count', 42); const result = engine.serializeRequestContext(ctx); expect(result).toEqual({ userId: 'user-123', feature: 'dark-mode', count: 42, }); }); it('should skip non-serializable values (functions)', () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const ctx = new RequestContext(); ctx.set('userId', 'user-123'); ctx.set('callback', () => {}); const result = engine.serializeRequestContext(ctx); expect(result).toEqual({ userId: 'user-123', }); expect(result).not.toHaveProperty('callback'); }); it('should skip objects with circular references', () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const ctx = new RequestContext(); ctx.set('userId', 'user-123'); const circular: Record = { name: 'circular' }; circular.self = circular; ctx.set('circular', circular); const result = engine.serializeRequestContext(ctx); expect(result).toEqual({ userId: 'user-123', }); expect(result).not.toHaveProperty('circular'); }); it('should skip non-serializable objects like RPC proxies', () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const ctx = new RequestContext(); ctx.set('userId', 'user-123'); const rpcProxy = new Proxy( {}, { get(target, prop) { if (prop === 'toJSON') { throw new TypeError('The RPC receiver does not implement the method "toJSON".'); } return Reflect.get(target, prop); }, }, ); ctx.set('rpcProxy', rpcProxy); const result = engine.serializeRequestContext(ctx); expect(result).toEqual({ userId: 'user-123', }); expect(result).not.toHaveProperty('rpcProxy'); }); it('should exclude the framework-managed auth token from snapshots', () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const ctx = new RequestContext(); ctx.set('userId', 'user-123'); ctx.set(MASTRA_AUTH_TOKEN_KEY, 'super-secret-bearer-token'); const result = engine.serializeRequestContext(ctx); expect(result).toEqual({ userId: 'user-123' }); expect(result).not.toHaveProperty(MASTRA_AUTH_TOKEN_KEY); }); }); describe('DefaultExecutionEngine.executeConditional error handling', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); async function runConditional({ conditions, workflowId, runId, stepResults = {} as Record>, timeTravel, executionPath = [], steps, }: { conditions: any[]; workflowId: string; runId: string; stepResults?: Record>; timeTravel?: { executionPath: number[]; steps: string[]; stepResults: Record>; inputData?: any; }; executionPath?: number[]; steps?: any[]; }) { const entry = { type: 'conditional' as const, steps: steps ?? [ { type: 'step' as const, step: { id: 'step1', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ result: 'step1-output' }), }, }, { type: 'step' as const, step: { id: 'step2', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ result: 'step2-output' }), }, }, ], conditions, }; const result = await engine.executeConditional({ workflowId, runId, entry, prevOutput: null, serializedStepGraph: [], stepResults, timeTravel: timeTravel as any, executionContext: { workflowId, runId, executionPath, suspendedPaths: {} as Record, retryConfig: { attempts: 3, delay: 1000, }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); return { result, stepResults }; } it('should handle MastraError during condition evaluation and continue workflow', async () => { // Arrange: Set up conditions array with one throwing MastraError and one valid const mastraError = new MastraError({ id: 'TEST_ERROR', domain: ErrorDomain.MASTRA_WORKFLOW, category: ErrorCategory.USER, }); let truthyIndexes: number[] = []; const conditions = [ async () => { throw mastraError; }, async () => { truthyIndexes.push(1); return true; }, ]; // Act: Execute conditional with the conditions const { result } = await runConditional({ conditions, workflowId: 'test-workflow', runId: globalThis.crypto.randomUUID(), }); // Assert: Verify error handling, truthyIndexes, and workflow continuation expect(result.status).toBe('success'); expect(truthyIndexes).toEqual([1]); // Only second condition was truthy expect(Object.keys((result as any).output || {})).toHaveLength(1); }); it('should wrap non-MastraError and handle condition evaluation failure', async () => { // Arrange: Set up conditions array with one throwing regular Error and one valid const regularError = new Error('Test regular error'); const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); // Mock the logger to capture trackException calls const mockTrackException = vi.fn(); const mockError = vi.fn(); (engine as any).logger = { trackException: mockTrackException, error: mockError, }; let truthyIndexes: number[] = []; const conditions = [ async () => { throw regularError; // This will be caught and wrapped internally, returning null }, async () => { truthyIndexes.push(1); return true; }, ]; // Act: Execute conditional with the conditions const { result } = await runConditional({ conditions, workflowId, runId, }); // Assert: Verify error handling and workflow continuation expect(result.status).toBe('success'); expect(truthyIndexes).toEqual([1]); // Only second condition was truthy expect(Object.keys((result as any).output || {})).toHaveLength(1); // Verify that trackException was called with the wrapped error expect(mockTrackException).toHaveBeenCalledTimes(1); const wrappedError = mockTrackException.mock.calls[0][0]; // Verify the wrapped error properties expect(wrappedError).toBeInstanceOf(MastraError); expect(wrappedError.id).toBe('WORKFLOW_CONDITION_EVALUATION_FAILED'); expect(wrappedError.domain).toBe(ErrorDomain.MASTRA_WORKFLOW); expect(wrappedError.category).toBe(ErrorCategory.USER); expect(wrappedError.details).toEqual({ workflowId, runId }); // Verify that the original error is preserved as the cause expect(wrappedError.cause).toBe(regularError); }); // Regression coverage for the time-travel conditional reconciliation in // packages/core/src/workflows/handlers/control-flow.ts. When a paused run is rehydrated and // time-travelled into a conditional, createTimeTravelExecutionParams pre-marks the targeted arm // as 'running'. If the condition re-evaluates and selects a different arm, the targeted-but- // rejected arm must be rewritten to 'skipped' so the wrong branch is neither rendered as active // nor executed on the rehydrated run. describe('conditional time-travel reconciliation', () => { it("rewrites a targeted-but-non-truthy arm from 'running' to 'skipped' during time travel", async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); // arm step1 (index 0) is truthy, arm step2 (index 1) is NOT truthy. const conditions = [async () => true, async () => false]; // Mirror createTimeTravelExecutionParams: the targeted arm (step2) is pre-marked 'running'. const stepResults: Record> = { step2: { status: 'running', payload: { from: 'time-travel' }, startedAt: Date.now(), } as unknown as StepResult, }; const { result, stepResults: finalStepResults } = await runConditional({ conditions, workflowId, runId, stepResults, executionPath: [0], timeTravel: { executionPath: [0], steps: ['step2'], stepResults: {}, }, }); // The rejected arm is reconciled to 'skipped' with the expected bookkeeping fields. expect(finalStepResults.step2.status).toBe('skipped'); expect(finalStepResults.step2).toHaveProperty('payload'); expect(finalStepResults.step2).toHaveProperty('startedAt'); expect(finalStepResults.step2).toHaveProperty('endedAt'); // The truthy arm (step1) still runs and the conditional succeeds. expect(result.status).toBe('success'); expect(finalStepResults.step2.status).not.toBe('running'); }); it("rewrites a targeted-but-non-truthy declarative arm (agent / mapping) from 'running' to 'skipped'", async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); // arm step1 (index 0) is truthy; the declarative arms (indexes 1 and 2) are NOT truthy. const conditions = [async () => true, async () => false, async () => false]; // Declarative arms carry their own top-level `id` (no wrapped `step`). Reconciliation must // key off getSingleStepEntryId rather than assuming a `{ type: 'step' }` shape. const steps = [ { type: 'step' as const, step: { id: 'step1', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ result: 'step1-output' }), }, }, { type: 'agent' as const, id: 'agent-arm', agentId: 'some-agent' }, { type: 'mapping' as const, id: 'mapping-arm', mapConfig: {} }, ]; // Mirror createTimeTravelExecutionParams: the targeted declarative arm is pre-marked 'running'. const stepResults: Record> = { 'agent-arm': { status: 'running', payload: { from: 'time-travel' }, startedAt: Date.now(), } as unknown as StepResult, 'mapping-arm': { status: 'running', payload: { from: 'time-travel' }, startedAt: Date.now(), } as unknown as StepResult, }; const { result, stepResults: finalStepResults } = await runConditional({ conditions, workflowId, runId, stepResults, steps, executionPath: [0], timeTravel: { executionPath: [0], steps: ['agent-arm'], stepResults: {}, }, }); expect(finalStepResults['agent-arm'].status).toBe('skipped'); expect(finalStepResults['mapping-arm'].status).toBe('skipped'); expect(result.status).toBe('success'); }); it("leaves a 'running' arm untouched for normal start/resume (no time travel)", async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); const conditions = [async () => true, async () => false]; const stepResults: Record> = { step2: { status: 'running', payload: {}, startedAt: Date.now(), } as unknown as StepResult, }; const { stepResults: finalStepResults } = await runConditional({ conditions, workflowId, runId, stepResults, // no timeTravel param -> reconciliation must not fire }); expect(finalStepResults.step2.status).toBe('running'); }); }); }); describe('DefaultExecutionEngine.executeEntry resume payload handling', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); it.each([[], undefined])('uses the suspended step payload with resumePath=%j', async resumePath => { const workflowId = 'resume-payload-repro'; const runId = globalThis.crypto.randomUUID(); const resumedStep = { id: 'needs-approval', inputSchema: z.object({ id: z.string() }), outputSchema: z.object({ resumed: z.boolean(), receivedId: z.string() }), resumeSchema: z.object({ approved: z.boolean() }), execute: async ({ inputData, resumeData }: { inputData: { id: string }; resumeData?: { approved: boolean } }) => { return { resumed: resumeData?.approved ?? false, receivedId: inputData.id }; }, }; const producerStep = { id: 'producer', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stale: true }), }; const stepResults = { producer: { status: 'success', output: { stale: true }, payload: {}, startedAt: 0, endedAt: 0, }, 'needs-approval': { status: 'suspended', payload: { id: 'from-suspended-snapshot' }, suspendPayload: { reason: 'manual-review' }, startedAt: 0, suspendedAt: Date.now(), }, } as Record>; const result = await engine.executeEntry({ workflowId, runId, entry: { type: 'step', step: resumedStep as unknown as Step }, prevStep: { type: 'step', step: producerStep }, serializedStepGraph: [], stepResults, resume: { steps: ['needs-approval'], stepResults, resumePayload: { approved: true }, resumePath: resumePath as number[], }, executionContext: { workflowId, runId, executionPath: [1], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.result).toMatchObject({ status: 'success', output: { resumed: true, receivedId: 'from-suspended-snapshot' }, }); }); it('should use a null suspended step payload when resuming a step with stale previous output', async () => { const workflowId = 'resume-null-payload-repro'; const runId = globalThis.crypto.randomUUID(); const resumedStep = { id: 'needs-approval', inputSchema: z.null(), outputSchema: z.object({ resumed: z.boolean(), receivedNull: z.boolean() }), resumeSchema: z.object({ approved: z.boolean() }), execute: async ({ inputData, resumeData }: { inputData: null; resumeData?: { approved: boolean } }) => { return { resumed: resumeData?.approved ?? false, receivedNull: inputData === null }; }, }; const producerStep = { id: 'producer', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stale: true }), }; const stepResults = { producer: { status: 'success', output: { stale: true }, payload: {}, startedAt: 0, endedAt: 0, }, 'needs-approval': { status: 'suspended', payload: null, suspendPayload: { reason: 'manual-review' }, startedAt: 0, suspendedAt: Date.now(), }, } as Record>; const result = await engine.executeEntry({ workflowId, runId, entry: { type: 'step', step: resumedStep as unknown as Step }, prevStep: { type: 'step', step: producerStep }, serializedStepGraph: [], stepResults, resume: { steps: ['needs-approval'], stepResults, resumePayload: { approved: true }, resumePath: [], }, executionContext: { workflowId, runId, executionPath: [1], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.result).toMatchObject({ status: 'success', output: { resumed: true, receivedNull: true }, }); }); it('should use the suspended foreach payload when resuming with stale previous output', async () => { const workflowId = 'resume-foreach-payload-repro'; const runId = globalThis.crypto.randomUUID(); const foreachStep = { id: 'process-item', inputSchema: z.number(), outputSchema: z.number(), resumeSchema: z.object({ approved: z.boolean() }), execute: async ({ inputData }: { inputData: number }) => inputData + 1, }; const producerStep = { id: 'producer', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ stale: true }), }; const stepResults = { producer: { status: 'success', output: { stale: true }, payload: {}, startedAt: 0, endedAt: 0, }, 'process-item': { status: 'suspended', payload: [10, 20], suspendPayload: { __workflow_meta: { foreachIndex: 0, foreachOutput: [{ status: 'suspended', suspendPayload: {}, startedAt: 0, suspendedAt: Date.now() }], resumeLabels: {}, }, }, startedAt: 0, suspendedAt: Date.now(), }, } as Record>; const result = await engine.executeEntry({ workflowId, runId, entry: { type: 'foreach', step: { type: 'step', step: foreachStep as unknown as Step }, opts: { concurrency: 1 }, }, prevStep: { type: 'step', step: producerStep }, serializedStepGraph: [], stepResults, resume: { steps: ['process-item'], stepResults, resumePayload: { approved: true }, resumePath: [], forEachIndex: 0, }, executionContext: { workflowId, runId, executionPath: [1], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.result).toMatchObject({ status: 'success', output: [11, 21], }); }); }); describe('DefaultExecutionEngine.executeLoop resume payload handling', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); it('should use a null suspended loop payload when resuming with stale previous output', async () => { const workflowId = 'resume-loop-null-payload-repro'; const runId = globalThis.crypto.randomUUID(); const step = { id: 'loop-step', inputSchema: z.null(), outputSchema: z.object({ receivedNull: z.boolean() }), resumeSchema: z.object({ approved: z.boolean() }), execute: async ({ inputData }: { inputData: null }) => ({ receivedNull: inputData === null }), }; const stepResults = { 'loop-step': { status: 'suspended', payload: null, suspendPayload: { reason: 'manual-review' }, startedAt: 0, suspendedAt: Date.now(), }, } as Record>; const result = await engine.executeLoop({ workflowId, runId, entry: { type: 'loop', step: { type: 'step', step: step as unknown as Step }, condition: async () => true, loopType: 'dountil', }, prevStep: { type: 'step', step } as any, prevOutput: { stale: true }, stepResults, resume: { steps: ['loop-step'], stepResults, resumePayload: { approved: true }, resumePath: [], }, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result).toMatchObject({ status: 'success', output: { receivedNull: true }, }); }); }); describe('DefaultExecutionEngine.executeLoop cancellation', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); // Reproduces https://github.com/mastra-ai/mastra/issues/15990 // A long-running dountil loop should stop iterating once the run is // cancelled, even when the user's step does not observe abortSignal. it('should stop iterating a dountil loop when abortController is aborted between iterations', async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); let iterations = 0; const step = { id: 'fetch-user', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: { iteration: number } }) => { iterations++; // Simulate a step that does NOT observe the abort signal, // matching the user's repro (raw setTimeout/fetch). // Trigger cancel while the second iteration is in-flight. if (iterations === 2) { abortController.abort(); } return { iteration: (inputData?.iteration ?? 0) + 1 }; }, }; const entry = { type: 'loop' as const, step: { type: 'step' as const, step: step as unknown as Step }, // dountil: stop when iteration >= 1000 condition: async ({ inputData }: { inputData: { iteration: number } }) => inputData.iteration >= 1000, loopType: 'dountil' as const, }; const result = await engine.executeLoop({ workflowId, runId, entry, prevStep: { type: 'step', step } as any, prevOutput: { iteration: 0 }, stepResults: {} as Record>, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); // The loop must terminate quickly with 'canceled' rather than running 1000 times. expect(result.status).toBe('canceled'); // Should have stopped at the iteration that triggered cancel, // not run the full 1000 iterations. expect(iterations).toBeLessThan(10); }, 30_000); // The condition context exposes `abort()` and the run can also be cancelled // externally while the condition is awaiting. If the condition returns a // terminal value (e.g. dountil reaching its target) after that, the loop // must still surface 'canceled' rather than 'success'. it('should surface canceled when abortController is aborted during condition evaluation', async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); let stepCalls = 0; const step = { id: 'fetch-user', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: { iteration: number } }) => { stepCalls++; return { iteration: (inputData?.iteration ?? 0) + 1 }; }, }; const entry = { type: 'loop' as const, step: { type: 'step' as const, step: step as unknown as Step }, // Condition aborts the run mid-evaluation, then returns true (dountil // terminal value). Pre-fix, the loop exits as 'success'. condition: async ({ abort }: { abort: () => void }) => { abort(); return true; }, loopType: 'dountil' as const, }; const result = await engine.executeLoop({ workflowId, runId, entry, prevStep: { type: 'step', step } as any, prevOutput: { iteration: 0 }, stepResults: {} as Record>, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.status).toBe('canceled'); expect(stepCalls).toBe(1); }, 30_000); }); describe('DefaultExecutionEngine.executeForeach cancellation', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); // Cancellation that lands before the next concurrency chunk starts must // stop the foreach from dispatching more work. Steps that ignore abortSignal // would otherwise let the loop keep iterating. it('should return canceled before dispatching the next concurrency chunk', async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); let callCount = 0; const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { callCount++; // Trigger cancel from inside a step but ignore the abort signal, // matching user steps that don't observe abortSignal (e.g. raw fetch). if (inputData === 1) { abortController.abort(); } return inputData * 2; }, }; const entry = { type: 'foreach' as const, step: { type: 'step' as const, step: step as unknown as Step }, opts: { concurrency: 2 }, }; const result = await engine.executeForeach({ workflowId, runId, entry, prevStep: { type: 'step', step } as any, prevOutput: [0, 1, 2, 3], stepResults: {} as Record>, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.status).toBe('canceled'); // Items 2 and 3 (the next chunk) must not have been dispatched. expect(callCount).toBe(2); }, 30_000); // Cancellation can land during the final concurrency chunk. Without the // post-loop abort check, the foreach would emit a successful workflow-step // result and persist 'success' even though the run was cancelled. it('should return canceled when abortController is aborted during the final chunk', async () => { const workflowId = 'test-workflow'; const runId = globalThis.crypto.randomUUID(); const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { // Single-chunk run (concurrency >= length), so this is the final chunk. // Step ignores abortSignal — only the post-loop check can catch it. if (inputData === 1) { abortController.abort(); } return inputData * 2; }, }; const entry = { type: 'foreach' as const, step: { type: 'step' as const, step: step as unknown as Step }, opts: { concurrency: 4 }, }; const result = await engine.executeForeach({ workflowId, runId, entry, prevStep: { type: 'step', step } as any, prevOutput: [0, 1], stepResults: {} as Record>, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); expect(result.status).toBe('canceled'); }, 30_000); }); describe('DefaultExecutionEngine.executeForeach concurrency', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; const deferred = () => { let resolve!: () => void; const promise = new Promise(res => { resolve = res; }); return { promise, resolve }; }; const waitFor = async (predicate: () => boolean, timeout = 1000) => { const startedAt = Date.now(); while (!predicate()) { if (Date.now() - startedAt > timeout) { throw new Error('Timed out waiting for foreach test condition'); } await new Promise(resolve => setTimeout(resolve, 5)); } }; const runForeach = async ({ step, prevOutput, concurrency, workflowId = 'test-workflow', runId = globalThis.crypto.randomUUID(), }: { step: any; prevOutput: any[]; concurrency: number | ((ctx: { inputData: unknown; getInitData: () => unknown }) => number); workflowId?: string; runId?: string; }) => engine.executeForeach({ workflowId, runId, entry: { type: 'foreach' as const, step: { type: 'step' as const, step: step as unknown as Step }, opts: { concurrency }, }, prevStep: { type: 'step', step } as any, prevOutput, stepResults: {} as Record>, serializedStepGraph: [], executionContext: { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {}, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }, pubsub, abortController, requestContext, ...createObservabilityContext(), }); beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); }); it('keeps concurrency slots filled and preserves ordered results while progress follows completion order', async () => { const runId = globalThis.crypto.randomUUID(); const firstItemGate = deferred(); const starts: number[] = []; const completed: number[] = []; const progressEvents: any[] = []; let active = 0; let maxActive = 0; await pubsub.subscribe(`workflow.events.v2.${runId}`, event => { if (event.data.type === 'workflow-step-progress') { progressEvents.push(event.data.payload); } }); const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { starts.push(inputData); active++; maxActive = Math.max(maxActive, active); try { if (inputData === 0) { await firstItemGate.promise; } return inputData * 2; } finally { completed.push(inputData); active--; } }, }; const resultPromise = runForeach({ step, prevOutput: [0, 1, 2, 3], concurrency: 2, runId }); await waitFor(() => starts.includes(2)); expect(starts.slice(0, 3)).toEqual([0, 1, 2]); expect(completed).not.toContain(0); expect(maxActive).toBeLessThanOrEqual(2); firstItemGate.resolve(); const result = await resultPromise; expect(result.status).toBe('success'); if (result.status === 'success') { expect(result.output).toEqual([0, 2, 4, 6]); } expect(maxActive).toBe(2); expect(progressEvents.map(event => event.currentIndex)).toEqual([1, 2, 3, 0]); expect(progressEvents.map(event => event.iterationOutput)).toEqual([2, 4, 6, 0]); expect(progressEvents.map(event => event.iterationStatus)).toEqual(['success', 'success', 'success', 'success']); }); it('stops queued work and returns failed when an iteration fails', async () => { const firstItemGate = deferred(); const starts: number[] = []; const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { starts.push(inputData); if (inputData === 0) { await firstItemGate.promise; return inputData; } if (inputData === 1) { throw new Error('item failed'); } return inputData; }, }; const resultPromise = runForeach({ step, prevOutput: [0, 1, 2, 3], concurrency: 2 }); await waitFor(() => starts.includes(1)); await new Promise(resolve => setTimeout(resolve, 10)); expect(starts).toEqual([0, 1]); firstItemGate.resolve(); const result = await resultPromise; expect(result.status).toBe('failed'); if (result.status === 'failed') { expect(result.error).toBeInstanceOf(Error); expect(result.error.message).toBe('item failed'); } }); it('stops queued work and returns suspended when an iteration suspends', async () => { const firstItemGate = deferred(); const starts: number[] = []; const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), suspendSchema: z.object({ item: z.number() }), execute: async ({ inputData, suspend, }: { inputData: number; suspend: (payload: { item: number }) => Promise; }) => { starts.push(inputData); if (inputData === 0) { await firstItemGate.promise; return inputData; } if (inputData === 1) { await suspend({ item: inputData }); return inputData; } return inputData; }, }; const resultPromise = runForeach({ step, prevOutput: [0, 1, 2, 3], concurrency: 2 }); await waitFor(() => starts.includes(1)); await new Promise(resolve => setTimeout(resolve, 10)); expect(starts).toEqual([0, 1]); firstItemGate.resolve(); const result = await resultPromise; expect(result.status).toBe('suspended'); if (result.status === 'suspended') { expect(result.suspendPayload?.item).toBe(1); expect(result.suspendPayload?.__workflow_meta.foreachIndex).toBe(1); expect(result.suspendPayload?.__workflow_meta.foreachOutput[0]).toMatchObject({ status: 'success', output: 0 }); expect(result.suspendPayload?.__workflow_meta.foreachOutput[1]).toMatchObject({ status: 'suspended', suspendPayload: { item: 1 }, }); } }); // Concurrency may be a resolver function evaluated at execution time from the // run's input, instead of a static number (used by durable agents to derive // tool-call concurrency from serialized run state). it('resolves concurrency from a resolver function at execution time', async () => { const gate = deferred(); const starts: number[] = []; let active = 0; let maxActive = 0; const resolverContexts: { inputData: unknown }[] = []; const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { starts.push(inputData); active++; maxActive = Math.max(maxActive, active); try { if (inputData === 0) { await gate.promise; } return inputData * 2; } finally { active--; } }, }; const resultPromise = runForeach({ step, prevOutput: [0, 1, 2, 3], concurrency: ctx => { resolverContexts.push({ inputData: ctx.inputData }); return 2; }, }); await waitFor(() => starts.includes(2)); expect(maxActive).toBeLessThanOrEqual(2); gate.resolve(); const result = await resultPromise; expect(result.status).toBe('success'); if (result.status === 'success') { expect(result.output).toEqual([0, 2, 4, 6]); } expect(maxActive).toBe(2); // Resolver is called at execution time with the foreach input. expect(resolverContexts).toEqual([{ inputData: [0, 1, 2, 3] }]); }); it('falls back to sequential execution when the resolver returns an invalid value', async () => { let maxActive = 0; let active = 0; const step = { id: 'process-item', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => { active++; maxActive = Math.max(maxActive, active); await new Promise(resolve => setTimeout(resolve, 5)); active--; return inputData; }, }; const result = await runForeach({ step, prevOutput: [0, 1, 2], concurrency: () => Number.NaN, }); expect(result.status).toBe('success'); expect(maxActive).toBe(1); }); }); describe('DefaultExecutionEngine.fmtReturnValue stepExecutionPath and payload deduplication', () => { let engine: TestableExecutionEngine; let pubsub: PubSub; beforeEach(() => { engine = new TestableExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); }); it('preserves an already-classified nested tripwire result', async () => { // Nested workflow results include tripwire even though leaf StepResult does not. const lastOutput = { status: 'tripwire', tripwire: { reason: 'Guardrail fired', processorId: 'policy' }, } as unknown as StepResult; const result = await engine.fmtReturnValuePublic(pubsub, { step: lastOutput }, lastOutput); expect(result).toMatchObject({ status: 'tripwire', tripwire: { reason: 'Guardrail fired', processorId: 'policy' }, }); }); it.each(['suspended', 'canceled'] as const)('retains %s when step data also carries a tripwire', async status => { const lastOutput = { status, tripwire: { reason: 'Earlier guardrail', processorId: 'policy' }, suspendPayload: { question: 'Which order?' }, } as unknown as StepResult; const result = await engine.fmtReturnValuePublic(pubsub, { step: lastOutput }, lastOutput); expect(result.status).toBe(status); if (status === 'suspended') expect(result.suspendPayload).toEqual({ step: { question: 'Which order?' } }); }); it('should include stepExecutionPath in the result', async () => { const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: { value: 1 }, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.stepExecutionPath).toEqual(['step1']); }); it('should remove an identity-equal payload without serializing it', async () => { const sharedData = { value: 1 }; const toJSON = vi.fn(() => { throw new Error('workflow payload must not be serialized for comparison'); }); Object.defineProperty(sharedData, 'toJSON', { value: toJSON }); const stepResults: Record> = { input: sharedData as any, step1: { status: 'success', output: { value: 2 }, payload: sharedData, startedAt: 1, endedAt: 2 }, step2: { status: 'success', output: { value: 3 }, payload: { value: 2 }, startedAt: 3, endedAt: 4 }, }; const lastOutput: StepResult = stepResults.step2!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1', 'step2']); expect(result.steps.step1.payload).toBeUndefined(); expect(result.steps.step2.payload).toBeUndefined(); expect(toJSON).not.toHaveBeenCalled(); }); it('should preserve payload when it does not match the previous step output', async () => { const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: { different: true }, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toEqual({ different: true }); }); it('should preserve a circular payload when structural comparison cannot complete', async () => { const input: Record = { value: 1 }; input.self = input; const payload: Record = { value: 1 }; payload.self = payload; const stepResults: Record> = { input: input as any, step1: { status: 'success', output: { value: 2 }, payload, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBe(payload); }); it('should handle structural equality after deserialization', async () => { const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: JSON.parse(JSON.stringify({ value: 1 })), startedAt: 1, endedAt: 2, }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBeUndefined(); }); it('should ignore object key order when comparing deserialized payloads', async () => { const stepResults: Record> = { input: JSON.parse('{"first":1,"second":2}'), step1: { status: 'success', output: { value: 2 }, payload: JSON.parse('{"second":2,"first":1}'), startedAt: 1, endedAt: 2, }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBeUndefined(); }); it('should fully compare and remove a structurally equal 4 MiB payload without serializing it', async () => { const input = { data: 'x'.repeat(4 * 1024 * 1024) }; const payload = { data: 'x'.repeat(4 * 1024 * 1024) }; const inputToJSON = vi.fn(() => { throw new Error('workflow input must not be serialized for comparison'); }); const payloadToJSON = vi.fn(() => { throw new Error('workflow payload must not be serialized for comparison'); }); Object.defineProperty(input, 'toJSON', { value: inputToJSON }); Object.defineProperty(payload, 'toJSON', { value: payloadToJSON }); const stepResults: Record> = { input: input as any, step1: { status: 'success', output: { value: 2 }, payload, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBeUndefined(); expect(inputToJSON).not.toHaveBeenCalled(); expect(payloadToJSON).not.toHaveBeenCalled(); }); it('should fully compare and preserve a distinct 4 MiB payload without serializing it', async () => { const input = { data: `${'x'.repeat(4 * 1024 * 1024 - 1)}a` }; const payload = { data: `${'x'.repeat(4 * 1024 * 1024 - 1)}b` }; const inputToJSON = vi.fn(() => { throw new Error('workflow input must not be serialized for comparison'); }); const payloadToJSON = vi.fn(() => { throw new Error('workflow payload must not be serialized for comparison'); }); Object.defineProperty(input, 'toJSON', { value: inputToJSON }); Object.defineProperty(payload, 'toJSON', { value: payloadToJSON }); const stepResults: Record> = { input: input as any, step1: { status: 'success', output: { value: 2 }, payload, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBe(payload); expect(inputToJSON).not.toHaveBeenCalled(); expect(payloadToJSON).not.toHaveBeenCalled(); }); it('should not deduplicate when there is no input in stepResults', async () => { const stepResults: Record> = { step1: { status: 'success', output: { value: 2 }, payload: { value: 1 }, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toEqual({ value: 1 }); }); it('should not mutate original stepResults', async () => { const originalPayload = { value: 1 }; const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: originalPayload, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(stepResults.step1!.payload).toBe(originalPayload); }); it('should not apply deduplication when stepExecutionPath is not provided', async () => { const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: { value: 1 }, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput); expect(result.stepExecutionPath).toBeUndefined(); expect(result.steps.step1.payload).toEqual({ value: 1 }); }); it('should skip steps in path that are not in stepResults', async () => { const stepResults: Record> = { input: { value: 1 } as any, step2: { status: 'success', output: { value: 3 }, payload: { value: 1 }, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step2!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, [ 'missing_step', 'step2', ]); expect(result.steps.step2.payload).toBeUndefined(); }); it('should only track previous output from successful steps', async () => { const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'failed', error: new Error('fail'), output: { value: 999 }, payload: { value: 1 }, startedAt: 1, endedAt: 2, } as unknown as StepResult, step2: { status: 'success', output: { value: 3 }, payload: { value: 1 }, startedAt: 3, endedAt: 4 }, }; const lastOutput: StepResult = stepResults.step2!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1', 'step2']); // step1 payload matches input, should be removed expect(result.steps.step1.payload).toBeUndefined(); // step2 payload matches input (not step1.output since step1 failed), should be removed expect(result.steps.step2.payload).toBeUndefined(); }); it('should not throw when payload contains non-JSON-serializable values', async () => { const circular: any = { value: 1 }; circular.self = circular; const stepResults: Record> = { input: { value: 1 } as any, step1: { status: 'success', output: { value: 2 }, payload: circular, startedAt: 1, endedAt: 2 }, }; const lastOutput: StepResult = stepResults.step1!; const result = await engine.fmtReturnValuePublic(pubsub, stepResults, lastOutput, undefined, ['step1']); expect(result.steps.step1.payload).toBe(circular); }); }); describe('DefaultExecutionEngine.deserializeRequestContext', () => { it('should produce JSON-safe serialized request context values', () => { const engine = new TestableExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const requestContext = new RequestContext(); const circular: any = { name: 'service' }; circular.self = circular; requestContext.set('userId', 'user-123'); requestContext.set('progressEmitter', () => undefined); requestContext.set('service', circular); const serialized = engine.serializeRequestContext(requestContext); expect(() => JSON.stringify(requestContext.toJSON())).not.toThrow(); expect(() => JSON.stringify(serialized)).not.toThrow(); expect(serialized).toEqual({ userId: 'user-123' }); }); it('should return a RequestContext instance with all entries from the plain object', () => { const engine = new TestableExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const plainObj = { userId: 'user-123', tenantId: 'tenant-456', nested: { flag: true } }; const result = engine.deserializeRequestContextPublic(plainObj); expect(result).toBeInstanceOf(RequestContext); expect(result.get('userId')).toBe('user-123'); expect(result.get('tenantId')).toBe('tenant-456'); expect(result.get('nested')).toEqual({ flag: true }); expect(result.size()).toBe(3); }); it('should return an empty RequestContext for an empty object', () => { const engine = new TestableExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); const result = engine.deserializeRequestContextPublic({}); expect(result).toBeInstanceOf(RequestContext); expect(result.size()).toBe(0); }); }); describe('DefaultExecutionEngine.execute cancellation onFinish contract', () => { it('should format returned steps and onFinish steps identically for canceled runs', async () => { const pubsub = new EventEmitterPubSub(); const requestContext = new RequestContext(); const abortController = new AbortController(); let onFinishResult: any = null; const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false, onFinish: (result: any) => { onFinishResult = result; }, } as any, }); const persistSpy = vi.spyOn(engine as any, 'persistStepUpdate').mockResolvedValue(undefined); // Inject metadata during step execution start to test stripping vi.spyOn(engine, 'onStepExecutionStart').mockImplementation(async ({ stepInfo }) => { stepInfo.metadata = { nestedRunId: 'nested-123', customField: 'keep-me' }; return Date.now(); }); const step1 = { id: 'step1', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: any) => { // Trigger cancel during step 1 so step 2 is skipped and engine loop catches cancellation abortController.abort(WORKFLOW_CANCELLED_SYMBOL); // Return a payload matching input to test deduplication return { ...inputData, }; }, }; const step2 = { id: 'step2', inputSchema: z.any(), outputSchema: z.any(), execute: async () => { return { data: 'should-not-run' }; }, }; const graph = { id: 'test-graph', steps: [ { type: 'step' as const, step: step1 }, { type: 'step' as const, step: step2 }, ], }; const inputData = { data: 'test-input' }; const result = await engine.execute({ workflowId: 'test-workflow', runId: 'test-run', graph, input: inputData, serializedStepGraph: [], pubsub, requestContext, abortController, outputOptions: { includeState: true }, }); expect(result.status).toBe('canceled'); expect(result.runId).toBe('test-run'); expect(result.state).toBeDefined(); // Ensure state exists in output // Top-level input is preserved expect((result as any).input).toEqual(inputData); expect(onFinishResult).toBeDefined(); expect(onFinishResult?.status).toBe('canceled'); // The returned steps and onFinish steps should be identically normalized expect(result.steps).toEqual(onFinishResult?.steps); // Payload deduplication: step1 output matches input, so payload should be removed const step1Result = result.steps?.step1 as any; expect(step1Result?.payload).toBeUndefined(); // Ensure raw nestedRunId is omitted from formatted steps, but other metadata is preserved expect(step1Result?.metadata?.nestedRunId).toBeUndefined(); expect(step1Result?.metadata?.customField).toBe('keep-me'); // Verify raw persistence: persistStepUpdate receives the un-deduplicated payload and raw metadata expect(persistSpy).toHaveBeenCalled(); const persistArgs = persistSpy.mock.calls[0][0] as any; expect(persistArgs.stepResults.step1.payload).toEqual(inputData); expect(persistArgs.stepResults.step1.metadata?.nestedRunId).toBe('nested-123'); }); }); describe('DefaultExecutionEngine retryCount isolation', () => { it.each([ { concurrency: 1, retryItems: [] }, { concurrency: 2, retryItems: [] }, { concurrency: 2, retryItems: ['a', 'b'] }, { concurrency: 2, retryItems: ['a'] }, ])( 'isolates nested children with $concurrency concurrent items and retries for $retryItems', async ({ concurrency, retryItems }) => { const calls: { item: string; runId: string; retryCount: number }[] = []; const inspect = createStep({ id: 'inspect', inputSchema: z.string(), outputSchema: z.string(), retries: 1, execute: async ({ inputData, runId, retryCount }) => { const firstAttempt = !calls.some(call => call.runId === runId); calls.push({ item: inputData, runId, retryCount }); if (firstAttempt && retryItems.includes(inputData)) throw new Error('transient'); return inputData; }, }); const child = createWorkflow({ id: 'child', inputSchema: z.string(), outputSchema: z.string() }) .then(inspect) .commit(); const parent = createWorkflow({ id: 'parent', inputSchema: z.array(z.string()), outputSchema: z.array(z.string()), }) .foreach(child, { id: 'items', concurrency }) .commit(); for (let execution = 0; execution < 2; execution++) { calls.length = 0; const run = await parent.createRun(); const result = await run.start({ inputData: ['a', 'b'] }); expect(result.status).toBe('success'); if (result.status === 'success') expect(result.result).toEqual(['a', 'b']); expect(new Set(calls.map(call => call.runId)).size).toBe(2); for (const item of ['a', 'b']) { expect(calls.filter(call => call.item === item).map(call => call.retryCount)).toEqual( retryItems.includes(item) ? [0, 1] : [0], ); } } }, ); it('isolates overlapping runs when another run starts between retries', async () => { let signalStarted!: () => void; let release!: () => void; const started = new Promise(resolve => { signalStarted = resolve; }); const blocked = new Promise(resolve => { release = resolve; }); const calls: Record = { a: [], b: [] }; const step = createStep({ id: 'inspect', inputSchema: z.string(), outputSchema: z.string(), retries: 1, execute: async ({ inputData, retryCount }) => { calls[inputData]!.push(retryCount); if (inputData === 'a' && calls.a!.length === 1) { signalStarted(); await blocked; throw new Error('transient'); } return inputData; }, }); const workflow = createWorkflow({ id: 'overlap', inputSchema: z.string(), outputSchema: z.string() }) .then(step) .commit(); const first = await workflow.createRun(); const second = await workflow.createRun(); const pending = first.start({ inputData: 'a' }); try { await Promise.race([ started, pending.then(() => { throw new Error('First run never reached barrier'); }), ]); expect((await second.start({ inputData: 'b' })).status).toBe('success'); } finally { release(); await pending; } expect((await pending).status).toBe('success'); expect(calls).toEqual({ a: [0, 1], b: [0] }); }); it('starts each plain foreach invocation at zero', async () => { const step = createStep({ id: 'inspect', inputSchema: z.string(), outputSchema: z.number(), execute: async ({ retryCount }) => retryCount, }); const workflow = createWorkflow({ id: 'plain-foreach', inputSchema: z.array(z.string()), outputSchema: z.array(z.number()), }) .foreach(step, { concurrency: 2 }) .commit(); const run = await workflow.createRun(); const result = await run.start({ inputData: ['a', 'b'] }); expect(result.status).toBe('success'); if (result.status === 'success') expect(result.result).toEqual([0, 0]); }); }); describe('DefaultExecutionEngine.executeStepWithRetry', () => { it('keeps reads stable across awaits and restores nested attempt contexts', async () => { const engine = new DefaultExecutionEngine({ mastra: undefined }); const params = { retries: 1, delay: 0, workflowId: 'test', runId: 'run' }; const outerCounts: number[] = []; const innerCounts: number[] = []; const result = await engine.executeStepWithRetry( 'outer', async () => { const attempt = outerCounts.length; outerCounts.push(engine.getOrGenerateRetryCount('outer')); await Promise.resolve(); expect(engine.getOrGenerateRetryCount('outer')).toBe(attempt); let innerCalls = 0; const innerResult = await engine.executeStepWithRetry( 'inner', async () => { innerCounts.push(engine.getOrGenerateRetryCount('inner')); if (innerCalls++ === 0) throw new Error('inner transient'); return 'inner'; }, params, ); expect(innerResult).toEqual({ ok: true, result: 'inner' }); expect(engine.getOrGenerateRetryCount('outer')).toBe(attempt); if (attempt === 0) throw new Error('outer transient'); return 'outer'; }, params, ); expect(result).toEqual({ ok: true, result: 'outer' }); expect(outerCounts).toEqual([0, 1]); expect(innerCounts).toEqual([0, 1, 0, 1]); expect(engine.getOrGenerateRetryCount('outer')).toBe(0); }); it('preserves the delay between retry attempts', async () => { vi.useFakeTimers(); try { const engine = new DefaultExecutionEngine({ mastra: undefined }); const counts: number[] = []; const pending = engine.executeStepWithRetry( 'delayed', async () => { counts.push(engine.getOrGenerateRetryCount('delayed')); if (counts.length === 1) throw new Error('transient'); return 'done'; }, { retries: 1, delay: 100, workflowId: 'test', runId: 'run' }, ); await vi.advanceTimersByTimeAsync(99); expect(counts).toEqual([0]); await vi.advanceTimersByTimeAsync(1); expect(await pending).toEqual({ ok: true, result: 'done' }); expect(counts).toEqual([0, 1]); } finally { vi.useRealTimers(); } }); it('does not retry when the step throws MastraNonRetryableError', async () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); let calls = 0; const result = await engine.executeStepWithRetry( 'workflow.test.step.fatal', async () => { calls++; throw new MastraNonRetryableError('permanent failure'); }, { retries: 3, delay: 0, workflowId: 'test-workflow', runId: 'test-run' }, ); expect(calls).toBe(1); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error.nonRetryable).toBe(true); expect(result.error.error.message).toBe('permanent failure'); } }); it('retries transient errors until retry attempts are exhausted', async () => { const engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); let calls = 0; const result = await engine.executeStepWithRetry( 'workflow.test.step.transient', async () => { calls++; throw new Error('transient failure'); }, { retries: 3, delay: 0, workflowId: 'test-workflow', runId: 'test-run' }, ); expect(calls).toBe(4); expect(result.ok).toBe(false); if (!result.ok) { expect(result.error.nonRetryable).toBeUndefined(); } }); }); describe('DefaultExecutionEngine — requestContext serialization gating', () => { const ioSchema = z.object({ n: z.number() }); const buildStep = (id: string) => createStep({ id, inputSchema: ioSchema, outputSchema: ioSchema, execute: async ({ inputData }) => ({ n: inputData.n + 1 }), }); it('does not serialize the requestContext during execution on the default engine', async () => { const spy = vi.spyOn(DefaultExecutionEngine.prototype, 'serializeRequestContext'); try { const workflow = createWorkflow({ id: 'no-context-serialize-wf', inputSchema: ioSchema, outputSchema: ioSchema, // Keep snapshot persistence (which legitimately serializes the // context) out of the count — this test pins the execution path only. options: { shouldPersistSnapshot: () => false }, }) .then(buildStep('step-1')) .then(buildStep('step-2')) .commit(); const requestContext = new RequestContext(); requestContext.set('userId', 'user-123'); const run = await workflow.createRun(); const result = await run.start({ inputData: { n: 0 }, requestContext }); expect(result.status).toBe('success'); expect(spy).not.toHaveBeenCalled(); } finally { spy.mockRestore(); } }); it('serializes the requestContext for engines that require durable context serialization', async () => { class DurableContextEngine extends DefaultExecutionEngine { requiresDurableContextSerialization(): boolean { return true; } } const engine = new DurableContextEngine({ mastra: undefined, options: { validateInputs: false, shouldPersistSnapshot: () => false }, }); const spy = vi.spyOn(engine, 'serializeRequestContext'); const workflow = createWorkflow({ id: 'durable-context-serialize-wf', inputSchema: ioSchema, outputSchema: ioSchema, executionEngine: engine, options: { shouldPersistSnapshot: () => false }, }) .then(buildStep('step-1')) .then(buildStep('step-2')) .commit(); const requestContext = new RequestContext(); requestContext.set('userId', 'user-123'); const run = await workflow.createRun(); const result = await run.start({ inputData: { n: 0 }, requestContext }); expect(result.status).toBe('success'); expect(spy).toHaveBeenCalled(); for (const call of spy.mock.results) { expect(call.value).toMatchObject({ userId: 'user-123' }); } }); }); describe('DefaultExecutionEngine control-flow span identity', () => { let engine: DefaultExecutionEngine; let pubsub: PubSub; let requestContext: RequestContext; let abortController: AbortController; let childSpanSpy: ReturnType; beforeEach(() => { engine = new DefaultExecutionEngine({ mastra: undefined, options: { validateInputs: true, shouldPersistSnapshot: () => false }, }); pubsub = new EventEmitterPubSub(); requestContext = new RequestContext(); abortController = new AbortController(); childSpanSpy = vi.spyOn(engine, 'createChildSpan'); }); function baseExecutionContext(workflowId: string, runId: string) { return { workflowId, runId, executionPath: [0], stepExecutionPath: [], suspendedPaths: {} as Record, retryConfig: { attempts: 0, delay: 0 }, activeStepsPath: {}, resumeLabels: {}, state: {}, }; } function containerSpanOptions(type: SpanType) { const call = childSpanSpy.mock.calls.find(([params]: any[]) => params?.options?.type === type); return call?.[0]?.options as { name: string; attributes?: Record } | undefined; } const passthroughStep = { id: 'branch-step', inputSchema: z.any(), outputSchema: z.any(), execute: async () => ({ ok: true }), }; it('names the parallel container span from the entry id and attaches identity attributes', async () => { const workflowId = 'span-parallel'; const runId = globalThis.crypto.randomUUID(); await engine.executeParallel({ workflowId, runId, entry: { type: 'parallel', id: 'check-document', description: 'run checks in parallel', metadata: { team: 'docs' }, steps: [{ type: 'step', step: passthroughStep as unknown as Step }], } as any, prevStep: { type: 'step', step: passthroughStep } as any, stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_PARALLEL); expect(options?.name).toBe("parallel: 'check-document'"); expect(options?.attributes).toMatchObject({ entryId: 'check-document', entryDescription: 'run checks in parallel', entryMetadata: { team: 'docs' }, }); }); it('falls back to the structural parallel name when no entry id is present', async () => { const workflowId = 'span-parallel-fallback'; const runId = globalThis.crypto.randomUUID(); await engine.executeParallel({ workflowId, runId, entry: { type: 'parallel', steps: [{ type: 'step', step: passthroughStep as unknown as Step }], } as any, prevStep: { type: 'step', step: passthroughStep } as any, stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_PARALLEL); expect(options?.name).toBe("parallel: '1 branches'"); expect(options?.attributes).not.toHaveProperty('entryId'); }); it('uses one canonical trimmed id for both the parallel span name and the entryId attribute', async () => { const workflowId = 'span-parallel-trim'; const runId = globalThis.crypto.randomUUID(); await engine.executeParallel({ workflowId, runId, entry: { type: 'parallel', id: ' check-document ', steps: [{ type: 'step', step: passthroughStep as unknown as Step }], } as any, prevStep: { type: 'step', step: passthroughStep } as any, stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_PARALLEL); expect(options?.name).toBe("parallel: 'check-document'"); expect(options?.attributes).toMatchObject({ entryId: 'check-document' }); }); it('falls back to the structural parallel name when the entry id is whitespace-only', async () => { const workflowId = 'span-parallel-whitespace'; const runId = globalThis.crypto.randomUUID(); await engine.executeParallel({ workflowId, runId, entry: { type: 'parallel', id: ' ', steps: [{ type: 'step', step: passthroughStep as unknown as Step }], } as any, prevStep: { type: 'step', step: passthroughStep } as any, stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_PARALLEL); expect(options?.name).toBe("parallel: '1 branches'"); expect(options?.attributes).not.toHaveProperty('entryId'); }); it('names the conditional container span from the entry id and attaches identity attributes', async () => { const workflowId = 'span-conditional'; const runId = globalThis.crypto.randomUUID(); await engine.executeConditional({ workflowId, runId, entry: { type: 'conditional', id: 'route-request', metadata: { kind: 'router' }, steps: [{ type: 'step', step: passthroughStep as unknown as Step }], conditions: [async () => true], } as any, prevOutput: null, serializedStepGraph: [], stepResults: {} as Record>, executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_CONDITIONAL); expect(options?.name).toBe("conditional: 'route-request'"); expect(options?.attributes).toMatchObject({ entryId: 'route-request', entryMetadata: { kind: 'router' }, }); }); it('names the loop container span from the entry id and attaches identity attributes', async () => { const workflowId = 'span-loop'; const runId = globalThis.crypto.randomUUID(); const step = { id: 'loop-step', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: { iteration: number } }) => ({ iteration: (inputData?.iteration ?? 0) + 1, }), }; await engine.executeLoop({ workflowId, runId, entry: { type: 'loop', id: 'retry-until-ready', description: 'poll until ready', step: { type: 'step', step: step as unknown as Step }, condition: async ({ inputData }: { inputData: { iteration: number } }) => inputData.iteration >= 1, loopType: 'dountil', } as any, prevStep: { type: 'step', step } as any, prevOutput: { iteration: 0 }, stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_LOOP); expect(options?.name).toBe("loop: 'retry-until-ready'"); expect(options?.attributes).toMatchObject({ entryId: 'retry-until-ready', entryDescription: 'poll until ready', }); }); it('names the foreach container span from the entry id and attaches identity attributes', async () => { const workflowId = 'span-foreach'; const runId = globalThis.crypto.randomUUID(); const step = { id: 'foreach-step', inputSchema: z.any(), outputSchema: z.any(), execute: async ({ inputData }: { inputData: number }) => inputData * 2, }; await engine.executeForeach({ workflowId, runId, entry: { type: 'foreach', id: 'process-items', metadata: { batch: true }, step: { type: 'step', step: step as unknown as Step }, opts: { concurrency: 2 }, } as any, prevStep: { type: 'step', step } as any, prevOutput: [1, 2], stepResults: {} as Record>, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_LOOP); expect(options?.name).toBe("loop: 'process-items'"); expect(options?.attributes).toMatchObject({ entryId: 'process-items', entryMetadata: { batch: true }, }); }); it.each(['sleep', 'sleepUntil'] as const)('preserves the exact error from a dynamic %s function', async kind => { const error = new Error('Dynamic wait failed', { cause: new Error('Original cause') }); const before = Object.getOwnPropertyDescriptors(error); const params = { workflowId: 'dynamic-wait-error', runId: 'dynamic-wait-run', serializedStepGraph: [], entry: { type: kind, id: 'dynamic', fn: async () => { throw error; }, }, prevStep: { type: 'step', step: passthroughStep }, prevOutput: null, stepResults: {}, executionContext: baseExecutionContext('dynamic-wait-error', 'dynamic-wait-run'), pubsub, abortController, requestContext, ...createObservabilityContext(), }; const invoke = kind === 'sleep' ? engine.executeSleep.bind(engine) : engine.executeSleepUntil.bind(engine); await expect(invoke(params as any)).rejects.toBe(error); expect(Object.getOwnPropertyDescriptors(error)).toEqual(before); }); it('attaches entry identity to the sleep span while keeping the duration name', async () => { const workflowId = 'span-sleep'; const runId = globalThis.crypto.randomUUID(); await engine.executeSleep({ workflowId, runId, serializedStepGraph: [], entry: { type: 'sleep', id: 'cool-off', description: 'wait before retrying', metadata: { reason: 'rate-limit' }, duration: 5, } as any, prevStep: { type: 'step', step: passthroughStep } as any, prevOutput: null, stepResults: {} as Record>, executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_SLEEP); expect(options?.name).toBe('sleep: 5ms'); expect(options?.attributes).toMatchObject({ entryId: 'cool-off', entryDescription: 'wait before retrying', entryMetadata: { reason: 'rate-limit' }, }); }); it('attaches entry identity to the sleepUntil span while keeping the date name', async () => { const workflowId = 'span-sleep-until'; const runId = globalThis.crypto.randomUUID(); const date = new Date(Date.now() - 1000); await engine.executeSleepUntil({ workflowId, runId, serializedStepGraph: [], entry: { type: 'sleepUntil', id: 'wait-for-window', metadata: { window: 'business-hours' }, date, } as any, prevStep: { type: 'step', step: passthroughStep } as any, prevOutput: null, stepResults: {} as Record>, executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const options = containerSpanOptions(SpanType.WORKFLOW_SLEEP); expect(options?.name).toBe(`sleepUntil: ${date.toISOString()}`); expect(options?.attributes).toMatchObject({ entryId: 'wait-for-window', entryMetadata: { window: 'business-hours' }, }); }); it('forwards mapping entry metadata to the step span', async () => { const workflowId = 'span-mapping'; const runId = globalThis.crypto.randomUUID(); const stepSpanSpy = vi.spyOn(engine, 'createStepSpan'); await engine.executeMapping({ workflowId, runId, entry: { type: 'mapping', id: 'collect-results', description: 'gather branch outputs', metadata: { title: 'Collect results' }, mapConfig: async ({ inputData }: { inputData: any }) => inputData, } as any, stepResults: { input: {} } as Record>, prevOutput: { a: 1 }, serializedStepGraph: [], executionContext: baseExecutionContext(workflowId, runId), pubsub, abortController, requestContext, ...createObservabilityContext(), }); const stepCall = stepSpanSpy.mock.calls.find(([params]: any[]) => params?.options?.type === SpanType.WORKFLOW_STEP); const options = stepCall?.[0]?.options as { attributes?: Record } | undefined; expect(options?.attributes).toMatchObject({ entryDescription: 'gather branch outputs', entryMetadata: { title: 'Collect results' }, }); }); });