import { context, trace as otelTrace, propagation, type Span, SpanKind, } from '@opentelemetry/api'; import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'; import { W3CTraceContextPropagator } from '@opentelemetry/core'; import { BasicTracerProvider, InMemorySpanExporter, type ReadableSpan, SimpleSpanProcessor, } from '@opentelemetry/sdk-trace-base'; import { RUN_ERROR_CODES } from '@workflow/errors'; import { setWorkflowBasePath } from '@workflow/utils'; import { type Event, SPEC_VERSION_CURRENT, type WorkflowRun, } from '@workflow/world'; import { afterAll, afterEach, beforeAll, describe, expect, it, vi, } from 'vitest'; import { runtimeLogger } from './logger.js'; import { setWorld } from './runtime/world.js'; import { workflowEntrypoint } from './runtime.js'; import { dehydrateWorkflowArguments } from './serialization.js'; import { getNextTraceCarrier, getWorkflowTraceMode } from './telemetry.js'; import { acceptingFenceSnapshot } from './test-support/fence-snapshot.js'; vi.mock('@vercel/functions', () => ({ waitUntil: vi.fn((p: Promise) => { p.catch(() => {}); }), })); // Run-origin trace context, as carried in queue messages. Uses a fixed, // valid W3C traceparent so assertions are deterministic. const ORIGIN_TRACE_ID = '0af7651916cd43dd8448eb211c80319c'; const ORIGIN_SPAN_ID = 'b7ad6b7169203331'; const ORIGIN_CARRIER = { traceparent: `00-${ORIGIN_TRACE_ID}-${ORIGIN_SPAN_ID}-01`, }; const exporter = new InMemorySpanExporter(); const provider = new BasicTracerProvider(); const contextManager = new AsyncLocalStorageContextManager(); beforeAll(() => { provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); contextManager.enable(); context.setGlobalContextManager(contextManager); propagation.setGlobalPropagator(new W3CTraceContextPropagator()); otelTrace.setGlobalTracerProvider(provider); }); afterAll(async () => { await provider.shutdown(); context.disable(); propagation.disable(); otelTrace.disable(); }); afterEach(() => { exporter.reset(); setWorld(undefined); vi.unstubAllEnvs(); vi.clearAllMocks(); }); const getWorkflowTransformCode = (workflowName: string) => `;globalThis.__private_workflows = new Map(); globalThis.__private_workflows.set(${JSON.stringify(workflowName)}, ${workflowName});`; const simpleWorkflow = `async function workflow() { return 'done'; }${getWorkflowTransformCode('workflow')}`; async function makeRunningRun( runId: string, executionContext?: WorkflowRun['executionContext'], workflowName = 'workflow' ): Promise { return { runId, workflowName, status: 'running', input: await dehydrateWorkflowArguments([], runId, undefined, []), createdAt: new Date('2024-01-01T00:00:00.000Z'), updatedAt: new Date('2024-01-01T00:00:00.000Z'), startedAt: new Date('2024-01-01T00:00:00.000Z'), deploymentId: 'test-deployment', attributes: {}, executionContext, }; } /** * Drives the workflow queue handler once with the given trace carrier, * inside an active "delivery" span (simulating the span the platform/queue * consumer creates around the delivery request). Returns the finished * route and WORKFLOW_V2 spans, the delivery span, and all queued messages. */ async function driveHandler(opts: { runId: string; workflowCode: string; traceCarrier?: Record; routeModuleBodyStartedAt?: number; basePath?: string; executionContext?: WorkflowRun['executionContext']; persistedWorkflowName?: string; includeRunInput?: boolean; streamRunCreatedBeforeResponse?: boolean; onRunStartedRequest?: () => void; whileRunStartedPending?: (state: { getEncryptionKeyForRun: ReturnType; }) => Promise; }) { const workflowRun = await makeRunningRun( opts.runId, opts.executionContext, opts.persistedWorkflowName ); const queuedMessages: any[] = []; const getEncryptionKeyForRun = vi.fn(async () => undefined); const eventsCreate = vi.fn(async (_runId: string, data: any, params: any) => { if (data.eventType === 'run_started') { opts.onRunStartedRequest?.(); let streamedRunCreated: Event | undefined; if (opts.streamRunCreatedBeforeResponse) { streamedRunCreated = { eventId: 'evnt_00000000000000000000000001', runId: workflowRun.runId, eventType: 'run_created', specVersion: SPEC_VERSION_CURRENT, createdAt: workflowRun.createdAt, eventData: { deploymentId: workflowRun.deploymentId, workflowName: workflowRun.workflowName, input: workflowRun.input, executionContext: workflowRun.executionContext, }, }; params?.replayEventObserver?.(streamedRunCreated); } await opts.whileRunStartedPending?.({ getEncryptionKeyForRun }); return { run: workflowRun, events: streamedRunCreated ? [streamedRunCreated] : ([] as Event[]), }; } return { event: { eventId: `event-${Math.random()}`, runId: workflowRun.runId, createdAt: new Date(), ...data, }, }; }); setWorld({ capabilities: { inBandFence: true }, specVersion: SPEC_VERSION_CURRENT, createQueueHandler: vi.fn( ( _prefix: string, handler: (message: unknown, metadata: unknown) => Promise ) => { return async () => { await handler( { runId: workflowRun.runId, requestedAt: new Date('2024-01-01T00:00:00.000Z'), traceCarrier: opts.traceCarrier, ...(opts.includeRunInput ? { runInput: { input: workflowRun.input, deploymentId: workflowRun.deploymentId, workflowName: 'workflow', specVersion: SPEC_VERSION_CURRENT, executionContext: opts.executionContext, }, } : {}), }, { requestId: 'req_test', attempt: 1, queueName: '__wkf_workflow_workflow', messageId: 'msg_test', } ); return new Response(null, { status: 204 }); }; } ), events: { create: eventsCreate, list: vi.fn(async () => ({ data: [] as Event[], hasMore: false, cursor: 'cursor_test', snapshot: acceptingFenceSnapshot([]), })), }, runs: { get: vi.fn(async () => workflowRun), }, queue: vi.fn(async (_queueName: string, message: unknown) => { queuedMessages.push(message); return { messageId: null }; }), getEncryptionKeyForRun, } as any); const handler = workflowEntrypoint( opts.workflowCode, opts.routeModuleBodyStartedAt === undefined && opts.basePath === undefined ? undefined : { routeModuleBodyStartedAt: opts.routeModuleBodyStartedAt, basePath: opts.basePath, } ); // Invoke inside an active "delivery" span so linkToCurrentContext() // observes a live delivery context, as it would in production. const tracer = otelTrace.getTracer('test'); let deliverySpan!: Span; await tracer.startActiveSpan('queue delivery', async (span) => { deliverySpan = span; try { await handler(new Request('https://example.test')); } finally { span.end(); } }); const workflowSpan = exporter .getFinishedSpans() .find((s) => s.name === 'workflow.execute workflow'); const routeSpan = exporter .getFinishedSpans() .find((s) => s.name === 'workflow.route.flow'); const routeInitSpan = exporter .getFinishedSpans() .find((s) => s.name === 'workflow.route.init'); const getWorldHandlersSpan = exporter .getFinishedSpans() .find((s) => s.name === 'workflow.route.get_world_handlers'); const getWorldSpan = exporter .getFinishedSpans() .find((s) => s.name === 'workflow.route.get_world'); return { workflowSpan, routeSpan, routeInitSpan, getWorldHandlersSpan, getWorldSpan, deliverySpan, queuedMessages, eventsCreate, getEncryptionKeyForRun, }; } function linkTraceIds(span: ReadableSpan | undefined): string[] { return (span?.links ?? []).map((l) => l.context.traceId); } describe('getWorkflowTraceMode', () => { it('defaults to linked when WORKFLOW_TRACE_MODE is unset', () => { vi.stubEnv('WORKFLOW_TRACE_MODE', ''); expect(getWorkflowTraceMode()).toBe('linked'); }); it('returns continuous when WORKFLOW_TRACE_MODE=continuous', () => { vi.stubEnv('WORKFLOW_TRACE_MODE', 'continuous'); expect(getWorkflowTraceMode()).toBe('continuous'); }); it('warns once for unrecognized values and falls back to linked', () => { const warnSpy = vi .spyOn(runtimeLogger, 'warn') .mockImplementation(() => {}); vi.stubEnv('WORKFLOW_TRACE_MODE', 'continous'); expect(getWorkflowTraceMode()).toBe('linked'); expect(getWorkflowTraceMode()).toBe('linked'); expect(warnSpy).toHaveBeenCalledTimes(1); const message = warnSpy.mock.calls[0][0] as string; expect(message).toContain('"continous"'); expect(message).toContain('"linked"'); expect(message).toContain('"continuous"'); warnSpy.mockRestore(); }); }); describe('workflowEntrypoint trace modes', () => { it('starts Node replay work while run_started is pending', async () => { // The run's persisted workflow name differs from the message's, which // only the authoritative run (not turbo's synthesized one) carries. vi.stubEnv('WORKFLOW_TURBO', '0'); const persistedWorkflowCode = `async function persistedWorkflow() { return 'done'; }${getWorkflowTransformCode('persistedWorkflow')}`; const { eventsCreate, workflowSpan } = await driveHandler({ runId: 'wrun_trace_persisted_workflow', workflowCode: persistedWorkflowCode, persistedWorkflowName: 'persistedWorkflow', includeRunInput: true, onRunStartedRequest: () => { expect( exporter .getFinishedSpans() .find((span) => span.name === 'workflow.bundle.evaluate') ).toBeUndefined(); }, whileRunStartedPending: async () => { // The bundle compiles from the message's run input while the // run_started write is still in flight; evaluation waits for it. await vi.waitFor(() => { expect( exporter .getFinishedSpans() .find((span) => span.name === 'workflow.bundle.compile') ).toBeDefined(); }); expect( exporter .getFinishedSpans() .find((span) => span.name === 'workflow.bundle.evaluate') ).toBeUndefined(); }, }); expect( eventsCreate.mock.calls.some( ([, event]) => event.eventType === 'run_completed' ) ).toBe(true); expect( eventsCreate.mock.calls.some( ([, event]) => event.eventType === 'run_failed' ) ).toBe(false); const compileSpans = exporter .getFinishedSpans() .filter((span) => span.name === 'workflow.bundle.compile'); expect(compileSpans.length).toBeGreaterThan(0); expect( compileSpans.every( (span) => span.parentSpanId === workflowSpan?.spanContext().spanId ) ).toBe(true); expect( exporter .getFinishedSpans() .find((span) => span.name === 'workflow.bundle.evaluate') ).toBeDefined(); }); it.each([ '0', '1', ])('records invalid VM configuration as setup failure with turbo=%s', async (turbo) => { vi.stubEnv('WORKFLOW_TURBO', turbo); const { eventsCreate } = await driveHandler({ runId: `wrun_trace_invalid_vm_${turbo}`, workflowCode: simpleWorkflow, includeRunInput: true, executionContext: { workflowVm: 'bogus' }, }); expect(eventsCreate).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ eventType: 'run_failed', eventData: expect.objectContaining({ errorCode: RUN_ERROR_CODES.RUNTIME_ERROR, }), }), expect.anything() ); }); it('does not leak a streamed replay-load rejection after synchronous setup failure', async () => { vi.stubEnv('WORKFLOW_TURBO', '0'); const unhandledRejection = vi.fn(); process.on('unhandledRejection', unhandledRejection); try { const { eventsCreate } = await driveHandler({ runId: 'wrun_trace_streamed_invalid_vm', workflowCode: simpleWorkflow, includeRunInput: true, streamRunCreatedBeforeResponse: true, executionContext: { workflowVm: 'bogus' }, }); expect(eventsCreate).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ eventType: 'run_failed', eventData: expect.objectContaining({ errorCode: RUN_ERROR_CODES.RUNTIME_ERROR, }), }), expect.anything() ); await new Promise((resolve) => setImmediate(resolve)); expect(unhandledRejection).not.toHaveBeenCalled(); } finally { process.off('unhandledRejection', unhandledRejection); } }); it('does not compile a Node bundle for a known QuickJS run', async () => { const { getEncryptionKeyForRun } = await driveHandler({ runId: 'wrun_trace_quickjs_compile', workflowCode: simpleWorkflow, includeRunInput: true, streamRunCreatedBeforeResponse: true, executionContext: { workflowVm: 'quickjs' }, }); expect( exporter .getFinishedSpans() .find((span) => span.name === 'workflow.bundle.compile') ).toBeUndefined(); expect(getEncryptionKeyForRun).toHaveBeenCalledTimes(1); expect(getEncryptionKeyForRun).not.toHaveBeenCalledWith( 'wrun_trace_quickjs_compile', undefined ); }); it('includes the base path in the flow route span http.route', async () => { try { const { routeSpan } = await driveHandler({ runId: 'wrun_trace_base_path', workflowCode: simpleWorkflow, basePath: '/v2/dashboard', }); expect(routeSpan?.attributes['http.route']).toBe( '/v2/dashboard/.well-known/workflow/v1/flow' ); } finally { // The base path is process-global; later tests expect none. setWorkflowBasePath(undefined); } }); it('linked (default): nests under the flow route context with a link to the run-origin context', async () => { const { workflowSpan, routeSpan, routeInitSpan, getWorldHandlersSpan, getWorldSpan, deliverySpan, } = await driveHandler({ runId: 'wrun_trace_linked', workflowCode: simpleWorkflow, traceCarrier: ORIGIN_CARRIER, routeModuleBodyStartedAt: Date.now(), }); expect(routeSpan).toBeDefined(); expect(routeSpan?.parentSpanId).toBe(deliverySpan.spanContext().spanId); expect(routeSpan?.attributes['workflow.route.type']).toBe('flow'); expect(routeSpan?.attributes['workflow.route.handler_cached']).toBe(false); expect(routeSpan?.attributes['workflow.route.invocation_count']).toBe(1); expect(routeSpan?.attributes['faas.instance']).toMatch( /^cinst_[0-9A-HJKMNP-TV-Z]{26}$/ ); const moduleBodyInitMs = routeSpan?.attributes['workflow.route.module_body_init_ms']; expect(typeof moduleBodyInitMs).toBe('number'); expect(moduleBodyInitMs as number).toBeGreaterThanOrEqual(0); expect(routeSpan?.attributes['http.route']).toBe( '/.well-known/workflow/v1/flow' ); expect(routeSpan?.attributes['http.response.status_code']).toBe(204); expect(routeInitSpan).toBeDefined(); expect(routeInitSpan?.parentSpanId).toBe(routeSpan?.spanContext().spanId); expect(getWorldHandlersSpan).toBeDefined(); expect(getWorldHandlersSpan?.parentSpanId).toBe( routeInitSpan?.spanContext().spanId ); expect(getWorldSpan).toBeDefined(); expect(getWorldSpan?.parentSpanId).toBe(routeSpan?.spanContext().spanId); expect(workflowSpan).toBeDefined(); // Child of the local /flow route span — same trace, so one // invocation is a single bounded trace rather than a new root. expect(workflowSpan?.parentSpanId).toBe(routeSpan?.spanContext().spanId); expect(workflowSpan?.spanContext().traceId).toBe( deliverySpan.spanContext().traceId ); // Single link to the run-origin context (NOT a parent) — connecting this // bounded invocation trace back to where the run was started. expect(workflowSpan?.links).toHaveLength(1); expect(linkTraceIds(workflowSpan)).toContain(ORIGIN_TRACE_ID); // The delivery context is the parent now, so it is not also a link. expect(linkTraceIds(workflowSpan)).not.toContain( deliverySpan.spanContext().traceId ); expect(workflowSpan?.attributes['workflow.trace.mode']).toBe('linked'); expect(workflowSpan?.attributes['workflow.trace.propagated']).toBe(true); expect(workflowSpan?.attributes['workflow.turbo']).toBe(false); const runStartedCreateEvent = workflowSpan?.events.find( (e) => e.name === 'workflow.run_started.create.start' ); expect(runStartedCreateEvent).toBeDefined(); expect( runStartedCreateEvent?.attributes['workflow.run_started.skip_preload'] ).toBe(false); const replayLoadSpan = exporter .getFinishedSpans() .find((finished) => finished.name === 'workflow.replay.load'); expect(replayLoadSpan?.parentSpanId).toBe( workflowSpan?.spanContext().spanId ); // Queue-delivered invocation spans use the CONSUMER kind, matching // queue-delivered step.execute spans. expect(workflowSpan?.kind).toBe(SpanKind.CONSUMER); }); it('linked: treats an empty trace carrier ({}) like an absent one', async () => { const { workflowSpan, routeSpan } = await driveHandler({ runId: 'wrun_trace_linked_empty_carrier', workflowCode: simpleWorkflow, traceCarrier: {}, }); expect(workflowSpan).toBeDefined(); // Still nested under the local /flow route context... expect(workflowSpan?.parentSpanId).toBe(routeSpan?.spanContext().spanId); // ...but no run-origin link is derived from `{}`. expect(workflowSpan?.links ?? []).toHaveLength(0); // An empty carrier does not count as propagated trace context. expect(workflowSpan?.attributes['workflow.trace.propagated']).toBe(false); }); it('linked: without an incoming carrier, nests under the flow route context with no links', async () => { const { workflowSpan, routeSpan } = await driveHandler({ runId: 'wrun_trace_linked_no_carrier', workflowCode: simpleWorkflow, traceCarrier: undefined, }); expect(workflowSpan).toBeDefined(); expect(workflowSpan?.parentSpanId).toBe(routeSpan?.spanContext().spanId); expect(workflowSpan?.links ?? []).toHaveLength(0); expect(workflowSpan?.attributes['workflow.trace.propagated']).toBe(false); }); it('traces route initialization only on the first flow request', async () => { const workflowRun = await makeRunningRun('wrun_trace_route_cache'); setWorld({ capabilities: { inBandFence: true }, specVersion: SPEC_VERSION_CURRENT, createQueueHandler: vi.fn( ( _prefix: string, handler: (message: unknown, metadata: unknown) => Promise ) => { return async () => { await handler( { runId: workflowRun.runId, requestedAt: new Date('2024-01-01T00:00:00.000Z'), }, { requestId: 'req_test', attempt: 1, queueName: '__wkf_workflow_workflow', messageId: 'msg_test', } ); return new Response(null, { status: 204 }); }; } ), events: { create: vi.fn(async (_runId: string, data: any) => { if (data.eventType === 'run_started') { return { run: workflowRun, events: [] as Event[] }; } return { event: { eventId: `event-${Math.random()}`, runId: workflowRun.runId, createdAt: new Date(), ...data, }, }; }), list: vi.fn(async () => ({ data: [] as Event[], hasMore: false, cursor: 'cursor_test', snapshot: acceptingFenceSnapshot([]), })), }, runs: { get: vi.fn(async () => workflowRun), }, queue: vi.fn(async () => ({ messageId: null })), getEncryptionKeyForRun: vi.fn(async () => undefined), } as any); const handler = workflowEntrypoint(simpleWorkflow); const tracer = otelTrace.getTracer('test'); await tracer.startActiveSpan('queue delivery', async (span) => { try { await handler(new Request('https://example.test')); await handler(new Request('https://example.test')); } finally { span.end(); } }); const spans = exporter.getFinishedSpans(); const routeSpans = spans.filter((s) => s.name === 'workflow.route.flow'); const routeInitSpans = spans.filter( (s) => s.name === 'workflow.route.init' ); expect(routeSpans).toHaveLength(2); expect(routeInitSpans).toHaveLength(1); expect(routeSpans[0]?.attributes['workflow.route.handler_cached']).toBe( false ); expect(routeSpans[0]?.attributes['workflow.route.invocation_count']).toBe( 1 ); expect(routeSpans[1]?.attributes['workflow.route.handler_cached']).toBe( true ); expect(routeSpans[1]?.attributes['workflow.route.invocation_count']).toBe( 2 ); // Minted once at module load, so it identifies the compute instance rather // than the invocation: both invocations report the same id. const instanceId = routeSpans[0]?.attributes['faas.instance']; expect(instanceId).toMatch(/^cinst_[0-9A-HJKMNP-TV-Z]{26}$/); expect(routeSpans[1]?.attributes['faas.instance']).toBe(instanceId); }); it('continuous: preserves the legacy shape — parented to the run-origin context with a delivery link', async () => { vi.stubEnv('WORKFLOW_TRACE_MODE', 'continuous'); const { workflowSpan, deliverySpan } = await driveHandler({ runId: 'wrun_trace_continuous', workflowCode: simpleWorkflow, traceCarrier: ORIGIN_CARRIER, }); expect(workflowSpan).toBeDefined(); // Same trace as the run origin, parented to the carrier's span. expect(workflowSpan?.spanContext().traceId).toBe(ORIGIN_TRACE_ID); expect(workflowSpan?.parentSpanId).toBe(ORIGIN_SPAN_ID); // Only the delivery link (no self-link to the origin). expect(workflowSpan?.links).toHaveLength(1); expect(linkTraceIds(workflowSpan)).toContain( deliverySpan.spanContext().traceId ); expect(workflowSpan?.attributes['workflow.trace.mode']).toBe('continuous'); }); }); // The carrier put on re-enqueued messages is produced by getNextTraceCarrier. // (The combined V2 handler now executes a single owned step inline rather // than queueing it, so this invariant is exercised directly on the helper // instead of by inspecting a queued step message.) describe('getNextTraceCarrier (re-enqueue carrier semantics)', () => { it('linked: forwards a usable run-origin carrier unchanged', async () => { // The original carrier flows forward unchanged so the run-origin // identity is preserved for future links. const next = await getNextTraceCarrier('linked', ORIGIN_CARRIER); expect(next).toEqual(ORIGIN_CARRIER); }); it('linked: replaces an empty carrier with the current invocation context', async () => { const tracer = otelTrace.getTracer('test'); let activeTraceId = ''; const next = await tracer.startActiveSpan('inv', async (span) => { activeTraceId = span.spanContext().traceId; try { return await getNextTraceCarrier('linked', {}); } finally { span.end(); } }); // The useless `{}` is not forwarded — this invocation serializes its // own context, becoming the de-facto run origin for future links. expect(next.traceparent).toContain(activeTraceId); expect(next.traceparent).not.toBe(ORIGIN_CARRIER.traceparent); }); it('continuous: serializes the current invocation context, not the origin carrier', async () => { const tracer = otelTrace.getTracer('test'); let activeTraceId = ''; const next = await tracer.startActiveSpan('inv', async (span) => { activeTraceId = span.spanContext().traceId; try { return await getNextTraceCarrier('continuous', ORIGIN_CARRIER); } finally { span.end(); } }); // Continuous mode always serializes the current context rather than // forwarding the incoming carrier. expect(next.traceparent).toContain(activeTraceId); expect(next.traceparent).not.toBe(ORIGIN_CARRIER.traceparent); expect(activeTraceId).not.toBe(ORIGIN_TRACE_ID); }); });