Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔨 chore(agent-signal,app): added tracing to agent signal, ensure traceparent propagate to handler (#14212)

Neko729fbc72d5f9
diff --git a/packages/observability-otel/src/modules/agent-signal/index.ts b/packages/observability-otel/src/modules/agent-signal/index.ts
index 583c5834bca..ed949099508 100644
--- a/packages/observability-otel/src/modules/agent-signal/index.ts
+++ b/packages/observability-otel/src/modules/agent-signal/index.ts
@@ -82,3 +82,65 @@ export const actionDurationHistogram = meter.createHistogram('agent_signal_actio
description: 'Observed duration for one AgentSignal action attempt.',
unit: 'ms',
});
+
+/**
+ * Count of source-event generation attempts grouped by source type and outcome.
+ */
+export const sourceEventCounter = meter.createCounter('agent_signal_source_events_total', {
+ description: 'Count of AgentSignal source-event generation attempts grouped by outcome.',
+ unit: '{event}',
+});
+
+/**
+ * Duration histogram for one source-event generation attempt.
+ */
+export const sourceEventDurationHistogram = meter.createHistogram(
+ 'agent_signal_source_event_duration_ms',
+ {
+ description: 'Observed duration for one AgentSignal source-event generation attempt.',
+ unit: 'ms',
+ },
+);
+
+/**
+ * Count of workflow runs grouped by source type and outcome.
+ */
+export const workflowRunCounter = meter.createCounter('agent_signal_workflow_runs_total', {
+ description: 'Count of AgentSignal workflow runs grouped by outcome.',
+ unit: '{workflow-run}',
+});
+
+/**
+ * Duration histogram for one workflow run.
+ */
+export const workflowRunDurationHistogram = meter.createHistogram(
+ 'agent_signal_workflow_duration_ms',
+ {
+ description: 'Observed duration for one AgentSignal workflow run.',
+ unit: 'ms',
+ },
+);
+
+/**
+ * Count of scheduler handler invocations grouped by handler identity and outcome.
+ */
+export const handlerCounter = meter.createCounter('agent_signal_handler_runs_total', {
+ description: 'Count of AgentSignal scheduler handler invocations grouped by outcome.',
+ unit: '{handler-run}',
+});
+
+/**
+ * Duration histogram for one scheduler handler invocation.
+ */
+export const handlerDurationHistogram = meter.createHistogram('agent_signal_handler_duration_ms', {
+ description: 'Observed duration for one AgentSignal scheduler handler invocation.',
+ unit: 'ms',
+});
+
+/**
+ * Count of terminal runtime results such as wait, schedule, or conclude.
+ */
+export const terminalResultCounter = meter.createCounter('agent_signal_terminal_results_total', {
+ description: 'Count of AgentSignal terminal runtime results grouped by status and reason.',
+ unit: '{terminal-result}',
+});
diff --git a/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts b/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts
index d0051af2aa7..19987134e54 100644
--- a/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts
+++ b/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts
@@ -10,6 +10,14 @@ import type {
RuntimeWaitProcessorResult,
} from '@lobechat/agent-signal';
import { AGENT_SIGNAL_TYPES, createSource } from '@lobechat/agent-signal';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import {
+ handlerCounter,
+ handlerDurationHistogram,
+ terminalResultCounter,
+ tracer,
+} from '@lobechat/observability-otel/modules/agent-signal';
+import { attributesCommon } from '@lobechat/observability-otel/node';
import {
createRuntimeProcessorContext,
@@ -98,6 +106,8 @@ const isExecutorResult = (value: unknown): value is ExecutorResult => {
return value.status === 'applied' || value.status === 'failed' || value.status === 'skipped';
};
+type HandlerKind = 'action' | 'signal' | 'source';
+
const buildExecutionSignal = (action: BaseAction, result: ExecutorResult): BaseSignal => {
const baseSignal = {
chain: {
@@ -140,6 +150,53 @@ const buildExecutionSignal = (action: BaseAction, result: ExecutorResult): BaseS
};
};
+const resolveRuntimeNodeKind = (node: RuntimeNode): HandlerKind => {
+ if (isSourceNode(node)) return 'source';
+ if (isSignalNode(node)) return 'signal';
+
+ return 'action';
+};
+
+const resolveRuntimeNodeType = (node: RuntimeNode) => {
+ if (isSourceNode(node)) return node.sourceType;
+ if (isSignalNode(node)) return node.signalType;
+
+ return node.actionType;
+};
+
+const resolveTerminalReason = (
+ result:
+ | RuntimeConcludeProcessorResult
+ | RuntimeScheduleProcessorResult
+ | RuntimeWaitProcessorResult,
+) => {
+ if (result.status === 'wait') {
+ return typeof result.pending?.reason === 'string' ? result.pending.reason : 'wait';
+ }
+
+ if (result.status === 'conclude') {
+ return typeof result.concluded?.reason === 'string' ? result.concluded.reason : 'conclude';
+ }
+
+ return 'schedule';
+};
+
+const recordTerminalResultMetric = (
+ node: RuntimeNode,
+ result:
+ | RuntimeConcludeProcessorResult
+ | RuntimeScheduleProcessorResult
+ | RuntimeWaitProcessorResult,
+) => {
+ terminalResultCounter.add(1, {
+ 'agent.signal.node_kind': resolveRuntimeNodeKind(node),
+ 'agent.signal.node_type': resolveRuntimeNodeType(node),
+ 'agent.signal.terminal_reason': resolveTerminalReason(result),
+ 'agent.signal.terminal_status': result.status,
+ ...attributesCommon(),
+ });
+};
+
/** Queue-driven scheduler for one already-assembled AgentSignal runtime. */
export class AgentSignalScheduler {
constructor(private readonly deps: AgentSignalSchedulerDeps) {}
@@ -214,6 +271,7 @@ export class AgentSignalScheduler {
case 'conclude':
case 'schedule':
case 'wait': {
+ recordTerminalResultMetric(node, result);
return result;
}
case 'dispatch': {
@@ -244,6 +302,39 @@ export class AgentSignalScheduler {
return 'timestamp' in node && typeof node.timestamp === 'number' ? node.timestamp : Date.now();
}
+ /**
+ * Dispatches one runtime node to every matching handler and records per-handler observability.
+ *
+ * Search spans:
+ * - `agent_signal.handler.run`
+ *
+ * Expected attributes:
+ * - `agent.signal.handler_id`
+ * - `agent.signal.handler_kind`
+ * - `agent.signal.node_type`
+ * - `agent.signal.scope_key`
+ * - `agent.signal.handler_result_status` after the handler returns
+ *
+ * Expected events:
+ * - none; handler runs are modeled as one span per invocation
+ *
+ * Expected metrics:
+ * - `agent_signal_handler_runs_total`
+ * - `agent_signal_handler_duration_ms`
+ * - `agent_signal_terminal_results_total` when a handler returns `wait`, `schedule`, or `conclude`
+ *
+ * Metric attributes:
+ * - `agent.signal.handler_id`
+ * - `agent.signal.handler_kind`: `source | signal | action`
+ * - `agent.signal.node_type`
+ * - `agent.signal.handler_status`: `ok | error`
+ * - `agent.signal.terminal_status` / `agent.signal.terminal_reason` for terminal runtime results
+ *
+ * Failure modes:
+ * - Marks the handler span as `ERROR` and rethrows when the handler throws
+ * - Records terminal-result metrics before returning `wait`, `schedule`, or `conclude`
+ * - Leaves `terminalResult` undefined when the handler only dispatches more work or returns void
+ */
private async dispatchHandlers<TNode extends RuntimeNode>(
handlers: Array<AgentSignalSchedulerHandler<TNode>>,
node: TNode,
@@ -253,21 +344,79 @@ export class AgentSignalScheduler {
) {
let terminalResult: AgentSignalSchedulerEmitResult | undefined;
const now = this.resolveNodeTime(node);
+ const handlerKind = resolveRuntimeNodeKind(node);
+ const nodeType = resolveRuntimeNodeType(node);
for (const handler of handlers) {
- const result = await handler.handle(
- node,
- createRuntimeProcessorContext({
- backend: this.deps.backend,
- now: () => now,
- scopeKey,
- }),
+ const startedAt = Date.now();
+ const metricAttributes = {
+ 'agent.signal.handler_id': handler.id,
+ 'agent.signal.handler_kind': handlerKind,
+ 'agent.signal.node_type': nodeType,
+ ...attributesCommon(),
+ };
+
+ await tracer.startActiveSpan(
+ 'agent_signal.handler.run',
+ {
+ attributes: {
+ 'agent.signal.handler_id': handler.id,
+ 'agent.signal.handler_kind': handlerKind,
+ 'agent.signal.node_type': nodeType,
+ 'agent.signal.scope_key': scopeKey,
+ },
+ },
+ async (span) => {
+ let outcome: 'error' | 'ok' = 'ok';
+
+ try {
+ const result = await handler.handle(
+ node,
+ createRuntimeProcessorContext({
+ backend: this.deps.backend,
+ now: () => now,
+ scopeKey,
+ }),
+ );
+ const runtimeResult = await this.applyResult(node, result, queue, trace);
+
+ if (isExecutorResult(result)) {
+ span.setAttribute('agent.signal.handler_result_status', result.status);
+ } else if (result) {
+ span.setAttribute('agent.signal.handler_result_status', result.status);
+ } else {
+ span.setAttribute('agent.signal.handler_result_status', 'void');
+ }
+
+ if (runtimeResult && !terminalResult) {
+ terminalResult = runtimeResult;
+ }
+
+ span.setStatus({ code: SpanStatusCode.OK });
+ } catch (error) {
+ outcome = 'error';
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'AgentSignal handler failed',
+ });
+ span.recordException(error as Error);
+
+ throw error;
+ } finally {
+ const durationMs = Date.now() - startedAt;
+
+ handlerCounter.add(1, {
+ ...metricAttributes,
+ 'agent.signal.handler_status': outcome,
+ });
+ handlerDurationHistogram.record(durationMs, {
+ ...metricAttributes,
+ 'agent.signal.handler_status': outcome,
+ });
+ span.end();
+ }
+ },
);
- const runtimeResult = await this.applyResult(node, result, queue, trace);
-
- if (runtimeResult && !terminalResult) {
- terminalResult = runtimeResult;
- }
}
return terminalResult;
diff --git a/src/server/services/agentSignal/sources/index.ts b/src/server/services/agentSignal/sources/index.ts
index f68370d4f22..d99a75a1967 100644
--- a/src/server/services/agentSignal/sources/index.ts
+++ b/src/server/services/agentSignal/sources/index.ts
@@ -1,4 +1,11 @@
import type { EmitSourceEventResult, SignalTriggerMetadata } from '@lobechat/agent-signal';
+import { SpanStatusCode } from '@lobechat/observability-otel/api';
+import {
+ sourceEventCounter,
+ sourceEventDurationHistogram,
+ tracer,
+} from '@lobechat/observability-otel/modules/agent-signal';
+import { attributesCommon } from '@lobechat/observability-otel/node';
import { AGENT_SIGNAL_DEFAULTS } from '../constants';
import { redisSourceEventStore } from '../store/adapters/redis/sourceEventStore';
@@ -29,51 +36,139 @@ const buildTrigger = (
};
};
+const buildSourceEventMetricAttributes = (
+ input: EmitSourceEventInput,
+ status: 'accepted' | 'duplicate' | 'error' | 'scope_locked',
+) => ({
+ 'agent.signal.source_event_status': status,
+ 'agent.signal.source_type': input.sourceType,
+ ...attributesCommon(),
+});
+
export { buildSource } from './buildSource';
export type { EmitSourceEventInput } from './types';
+/**
+ * Generates one normalized AgentSignal source event and records ingress observability.
+ *
+ * Search spans:
+ * - `agent_signal.source_event.generate`
+ *
+ * Expected attributes:
+ * - `agent.signal.scope_key`
+ * - `agent.signal.source_id`
+ * - `agent.signal.source_type`
+ * - `agent.signal.window_event_count` when the source event is accepted
+ *
+ * Expected events:
+ * - none; this boundary currently uses span status plus metrics instead of span events
+ *
+ * Expected metrics:
+ * - `agent_signal_source_events_total`
+ * - `agent_signal_source_event_duration_ms`
+ *
+ * Metric attributes:
+ * - `agent.signal.source_event_status`: `accepted | duplicate | scope_locked | error`
+ * - `agent.signal.source_type`
+ *
+ * Failure modes:
+ * - Returns deduped `duplicate` when the event id was already seen
+ * - Returns deduped `scope_locked` when another producer owns the scope lock
+ * - Marks the span as `ERROR` and rethrows when storage operations fail
+ */
export const emitSourceEvent = async (
input: EmitSourceEventInput,
options: EmitSourceEventOptions = {},
): Promise<EmitSourceEventResult> => {
- const store = options.store ?? defaultSourceEventStore;
- const eventId = buildEventId(input);
- const deduped = await store.tryDedupe(eventId, AGENT_SIGNAL_DEFAULTS.signalDedupeTtlSeconds);
+ const startedAt = Date.now();
- if (!deduped) {
- return { deduped: true, reason: 'duplicate' };
- }
+ return tracer.startActiveSpan(
+ 'agent_signal.source_event.generate',
+ {
+ attributes: {
+ 'agent.signal.scope_key': input.scopeKey,
+ 'agent.signal.source_id': input.sourceId,
+ 'agent.signal.source_type': input.sourceType,
+ },
+ },
+ async (span) => {
+ const store = options.store ?? defaultSourceEventStore;
+ const eventId = buildEventId(input);
+ let sourceEventStatus: 'accepted' | 'duplicate' | 'error' | 'scope_locked' = 'accepted';
- const locked = await store.acquireScopeLock(
- input.scopeKey,
- AGENT_SIGNAL_DEFAULTS.generationLockTtlSeconds,
- );
+ try {
+ const deduped = await store.tryDedupe(
+ eventId,
+ AGENT_SIGNAL_DEFAULTS.signalDedupeTtlSeconds,
+ );
- if (!locked) {
- return { deduped: true, reason: 'scope_locked' };
- }
-
- try {
- const currentWindow = await store.readWindow(input.scopeKey);
- const previousCount = Number(currentWindow?.eventCount ?? '0');
- const nextCount = previousCount + 1;
-
- await store.writeWindow(
- input.scopeKey,
- {
- eventCount: String(nextCount),
- lastEventAt: String(input.timestamp),
- lastEventId: eventId,
- },
- AGENT_SIGNAL_DEFAULTS.signalWindowTtlSeconds,
- );
-
- return {
- deduped: false,
- source: buildSource(input),
- trigger: buildTrigger(input.scopeKey, eventId, nextCount),
- };
- } finally {
- await store.releaseScopeLock(input.scopeKey);
- }
+ if (!deduped) {
+ sourceEventStatus = 'duplicate';
+ sourceEventCounter.add(1, buildSourceEventMetricAttributes(input, sourceEventStatus));
+ span.setStatus({ code: SpanStatusCode.OK, message: 'duplicate' });
+
+ return { deduped: true as const, reason: 'duplicate' as const };
+ }
+
+ const locked = await store.acquireScopeLock(
+ input.scopeKey,
+ AGENT_SIGNAL_DEFAULTS.generationLockTtlSeconds,
+ );
+
+ if (!locked) {
+ sourceEventStatus = 'scope_locked';
+ sourceEventCounter.add(1, buildSourceEventMetricAttributes(input, sourceEventStatus));
+ span.setStatus({ code: SpanStatusCode.OK, message: 'scope_locked' });
+
+ return { deduped: true as const, reason: 'scope_locked' as const };
+ }
+
+ try {
+ const currentWindow = await store.readWindow(input.scopeKey);
+ const previousCount = Number(currentWindow?.eventCount ?? '0');
+ const nextCount = previousCount + 1;
+
+ await store.writeWindow(
+ input.scopeKey,
+ {
+ eventCount: String(nextCount),
+ lastEventAt: String(input.timestamp),
+ lastEventId: eventId,
+ },
+ AGENT_SIGNAL_DEFAULTS.signalWindowTtlSeconds,
+ );
+
+ sourceEventStatus = 'accepted';
+ sourceEventCounter.add(1, buildSourceEventMetricAttributes(input, sourceEventStatus));
+ span.setAttribute('agent.signal.window_event_count', nextCount);
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ deduped: false as const,
+ source: buildSource(input),
+ trigger: buildTrigger(input.scopeKey, eventId, nextCount),
+ };
+ } finally {
+ await store.releaseScopeLock(input.scopeKey);
+ }
+ } catch (error) {
+ sourceEventStatus = 'error';
+ sourceEventCounter.add(1, buildSourceEventMetricAttributes(input, sourceEventStatus));
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message:
+ error instanceof Error ? error.message : 'AgentSignal source event generation failed',
+ });
+ span.recordException(error as Error);
+
+ throw error;
+ } finally {
+ sourceEventDurationHistogram.record(
+ Date.now() - startedAt,
+ buildSourceEventMetricAttributes(input, sourceEventStatus),
+ );
+ span.end();
+ }
+ },
+ );
};
diff --git a/src/server/workflows/agentSignal.test.ts b/src/server/workflows/agentSignal.test.ts
index 99e7e0c6b18..7332d97bca5 100644
--- a/src/server/workflows/agentSignal.test.ts
+++ b/src/server/workflows/agentSignal.test.ts
@@ -59,6 +59,7 @@ describe('AgentSignalWorkflow', () => {
key: 'agent-signal.run.scope.topic_topic-1',
parallelism: 1,
},
+ headers: {},
url: 'http://localhost:3011/api/workflows/agent-signal/run',
});
});
diff --git a/src/server/workflows/agentSignal/index.ts b/src/server/workflows/agentSignal/index.ts
index 580a3f016c4..839da2aae01 100644
--- a/src/server/workflows/agentSignal/index.ts
+++ b/src/server/workflows/agentSignal/index.ts
@@ -1,6 +1,7 @@
import debug from 'debug';
import { appEnv } from '@/envs/app';
+import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';
import { workflowClient } from '@/libs/qstash';
import type {
AgentSignalSourcePayloadMap,
@@ -66,9 +67,23 @@ const getWorkflowUrl = (path: string): string => {
export class AgentSignalWorkflow {
static triggerRun(payload: AgentSignalWorkflowRunPayload) {
const url = getWorkflowUrl(WORKFLOW_PATHS.run);
+ const traceHeaders = new Headers();
+
+ // NOTICE:
+ // Upstash Workflow/QStash only forwards user headers to the workflow destination when they
+ // are sent through the SDK's `headers` option, which the SDK rewrites into
+ // `Upstash-Forward-*` headers under the hood.
+ // Source/context:
+ // - Upstash docs: workflow trigger + QStash receiving docs describe `Upstash-Forward-*`
+ // - Local SDK source (`@upstash/workflow`) rewrites `headers` to `Upstash-Forward-*`
+ // Removal condition:
+ // - Safe to simplify only if Upstash adds native trace-context propagation for workflow
+ // triggers or we stop relying on Workflow/QStash as the async hop.
+ injectActiveTraceHeaders(traceHeaders);
log('Triggering run workflow payload=%O', {
agentId: payload.agentId,
+ headers: Object.fromEntries(traceHeaders.entries()),
sourceEvent: payload.sourceEvent,
url,
userId: payload.userId,
@@ -90,6 +105,7 @@ export class AgentSignalWorkflow {
key: `agent-signal.run.scope.${normalizeFlowControlKeySegment(payload.sourceEvent.scopeKey)}`,
parallelism: 1,
},
+ headers: Object.fromEntries(traceHeaders.entries()),
url,
});
}
diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.ts
index 4229ee190a2..45d78b7e9c1 100644
--- a/src/server/workflows/agentSignal/run.ts
+++ b/src/server/workflows/agentSignal/run.ts
@@ -1,10 +1,18 @@
import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';
import { messages } from '@lobechat/database/schemas';
+import { context as otContext, SpanStatusCode } from '@lobechat/observability-otel/api';
+import {
+ tracer,
+ workflowRunCounter,
+ workflowRunDurationHistogram,
+} from '@lobechat/observability-otel/modules/agent-signal';
+import { attributesCommon } from '@lobechat/observability-otel/node';
import debug from 'debug';
import { and, desc, eq, isNull, lte } from 'drizzle-orm';
import { MessageModel } from '@/database/models/message';
import { getServerDB } from '@/database/server';
+import { extractTraceContext } from '@/libs/observability/traceparent';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentSignal/orchestrator';
import { executeAgentSignalSourceEvent } from '@/server/services/agentSignal/orchestrator';
@@ -34,6 +42,7 @@ const isGeneratedEmission = (
* @param TPayload - Workflow request payload type.
*/
export interface AgentSignalWorkflowContext<TPayload = AgentSignalWorkflowRunPayload> {
+ headers?: Headers;
requestPayload?: TPayload;
run: <TResult>(stepId: string, handler: () => Promise<TResult>) => Promise<TResult>;
}
@@ -61,6 +70,15 @@ interface NormalizedWorkflowSourceEventInput<
timestamp: number;
}
+const buildWorkflowMetricAttributes = (
+ sourceType: string,
+ status: 'error' | 'generated' | 'invalid_payload' | 'no_emission',
+) => ({
+ 'agent.signal.source_type': sourceType,
+ 'agent.signal.workflow_status': status,
+ ...attributesCommon(),
+});
+
const createDefaultSnapshotStore = (): ISnapshotStore | null => {
if (process.env.NODE_ENV !== 'development') return null;
@@ -342,77 +360,220 @@ const normalizeWorkflowSourceEvent = async (
*
* Returns:
* - A small execution summary mirroring the workflow route response
+ *
+ * Search spans:
+ * - `agent_signal.workflow.run`
+ * - `agent_signal.workflow.normalize`
+ * - `agent_signal.workflow.execute`
+ *
+ * Expected attributes:
+ * - `agent.signal.scope_key`
+ * - `agent.signal.source_id`
+ * - `agent.signal.source_type`
+ * - `agent.signal.emitted_signal_count` after execution
+ * - `agent.signal.workflow_deduped` after execution
+ *
+ * Expected events:
+ * - none; this boundary currently models phases as nested spans instead of events
+ *
+ * Expected metrics:
+ * - `agent_signal_workflow_runs_total`
+ * - `agent_signal_workflow_duration_ms`
+ *
+ * Metric attributes:
+ * - `agent.signal.source_type`
+ * - `agent.signal.workflow_status`: `generated | no_emission | invalid_payload | error`
+ *
+ * Failure modes:
+ * - Marks the top-level span as `ERROR` for invalid payloads
+ * - Marks nested spans as `ERROR` when normalize or execute fails
+ * - Re-throws execution failures after recording workflow metrics
*/
export const runAgentSignalWorkflow = async (
context: AgentSignalWorkflowContext,
deps: RunAgentSignalWorkflowDeps = {},
) => {
const payload = context.requestPayload;
-
- if (!payload?.userId || !payload.sourceEvent) {
- return { error: 'Missing userId or sourceEvent', success: false } as const;
- }
-
- log('Worker received payload=%O', payload);
-
- const getDb = deps.getDb ?? getServerDB;
- const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;
- const createGuardBackend = deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;
- const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();
-
- const db = await getDb();
- const normalizedSourceEvent = await normalizeWorkflowSourceEvent(payload.sourceEvent, {
- db,
- userId: payload.userId,
- });
- const result = await context.run(
- `agent-signal:execute:${normalizedSourceEvent.sourceType}:${normalizedSourceEvent.sourceId}`,
- () =>
- executeSourceEvent(
- normalizedSourceEvent,
- {
- agentId: payload.agentId,
- db,
- userId: payload.userId,
- },
- {
- runtimeGuardBackend: createGuardBackend(),
+ const sourceType = payload?.sourceEvent?.sourceType ?? 'unknown';
+ const startedAt = Date.now();
+ // NOTICE:
+ // Upstash Workflow Hono handlers do not flow through our regular backend auth middleware, so
+ // the usual request-level trace-context extraction does not happen automatically here.
+ // We must extract `traceparent` / `tracestate` from the workflow request headers manually before
+ // opening the top-level workflow span, otherwise each workflow run starts a fresh trace.
+ // Source/context:
+ // - `src/app/(backend)/middleware/auth/index.ts` performs extract/inject for normal backend APIs
+ // - `src/server/workflows-hono/agent-signal/index.ts` wires `serve(...)` directly to
+ // `runAgentSignalWorkflow(...)`
+ // Removal condition:
+ // - Safe to remove only if the workflow entry stack gains a shared request middleware that
+ // guarantees OTEL context extraction before invoking workflow handlers.
+ const traceContext = context.headers ? extractTraceContext(context.headers) : otContext.active();
+
+ return otContext.with(traceContext, () =>
+ tracer.startActiveSpan(
+ 'agent_signal.workflow.run',
+ {
+ attributes: {
+ 'agent.signal.scope_key': payload?.sourceEvent?.scopeKey,
+ 'agent.signal.source_id': payload?.sourceEvent?.sourceId,
+ 'agent.signal.source_type': sourceType,
},
- ),
- );
+ },
+ async (span) => {
+ let workflowStatus: 'error' | 'generated' | 'invalid_payload' | 'no_emission' | undefined;
+
+ try {
+ if (!payload?.userId || !payload.sourceEvent) {
+ workflowStatus = 'invalid_payload';
+ workflowRunCounter.add(1, buildWorkflowMetricAttributes(sourceType, workflowStatus));
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: 'Missing userId or sourceEvent',
+ });
+
+ return { error: 'Missing userId or sourceEvent', success: false } as const;
+ }
- log('Processed source event result=%O', {
- deduped: result?.deduped ?? true,
- orchestration:
- result && !result.deduped
- ? {
- actionTypes: result.orchestration.actions.map((action) => action.actionType),
- resultStatuses: result.orchestration.results.map((item) => item.status),
- runtimeStatus:
- 'runtimeResult' in result.orchestration
- ? result.orchestration.runtimeResult.status
+ log('Worker received payload=%O', payload);
+
+ const getDb = deps.getDb ?? getServerDB;
+ const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;
+ const createGuardBackend =
+ deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;
+ const snapshotStore = (deps.createSnapshotStore ?? createDefaultSnapshotStore)();
+
+ const db = await getDb();
+ const normalizedSourceEvent = await tracer.startActiveSpan(
+ 'agent_signal.workflow.normalize',
+ async (normalizeSpan) => {
+ try {
+ const result = await normalizeWorkflowSourceEvent(payload.sourceEvent, {
+ db,
+ userId: payload.userId,
+ });
+ normalizeSpan.setStatus({ code: SpanStatusCode.OK });
+
+ return result;
+ } catch (error) {
+ normalizeSpan.setStatus({
+ code: SpanStatusCode.ERROR,
+ message:
+ error instanceof Error
+ ? error.message
+ : 'AgentSignal workflow normalize failed',
+ });
+ normalizeSpan.recordException(error as Error);
+ throw error;
+ } finally {
+ normalizeSpan.end();
+ }
+ },
+ );
+ const result = await tracer.startActiveSpan(
+ 'agent_signal.workflow.execute',
+ async (executeSpan) => {
+ try {
+ const executionResult = await context.run(
+ `agent-signal:execute:${normalizedSourceEvent.sourceType}:${normalizedSourceEvent.sourceId}`,
+ () =>
+ executeSourceEvent(
+ normalizedSourceEvent,
+ {
+ agentId: payload.agentId,
+ db,
+ userId: payload.userId,
+ },
+ {
+ runtimeGuardBackend: createGuardBackend(),
+ },
+ ),
+ );
+ executeSpan.setStatus({ code: SpanStatusCode.OK });
+
+ return executionResult;
+ } catch (error) {
+ executeSpan.setStatus({
+ code: SpanStatusCode.ERROR,
+ message:
+ error instanceof Error ? error.message : 'AgentSignal workflow execute failed',
+ });
+ executeSpan.recordException(error as Error);
+ throw error;
+ } finally {
+ executeSpan.end();
+ }
+ },
+ );
+
+ workflowStatus = isGeneratedEmission(result) ? 'generated' : 'no_emission';
+
+ log('Processed source event result=%O', {
+ deduped: result?.deduped ?? true,
+ orchestration:
+ result && !result.deduped
+ ? {
+ actionTypes: result.orchestration.actions.map((action) => action.actionType),
+ resultStatuses: result.orchestration.results.map((item) => item.status),
+ runtimeStatus:
+ 'runtimeResult' in result.orchestration
+ ? result.orchestration.runtimeResult.status
+ : undefined,
+ signalTypes: result.orchestration.emittedSignals.map(
+ (signal) => signal.signalType,
+ ),
+ }
: undefined,
- signalTypes: result.orchestration.emittedSignals.map((signal) => signal.signalType),
+ scopeKey: payload.sourceEvent.scopeKey,
+ sourceId: normalizedSourceEvent.sourceId,
+ sourceType: normalizedSourceEvent.sourceType,
+ });
+
+ if (snapshotStore && isGeneratedEmission(result)) {
+ try {
+ await persistWorkflowSnapshot(result, snapshotStore, payload.userId);
+ } catch (error) {
+ log('Persist workflow snapshot failed error=%O', error);
+ }
}
- : undefined,
- scopeKey: payload.sourceEvent.scopeKey,
- sourceId: normalizedSourceEvent.sourceId,
- sourceType: normalizedSourceEvent.sourceType,
- });
- if (snapshotStore && isGeneratedEmission(result)) {
- try {
- await persistWorkflowSnapshot(result, snapshotStore, payload.userId);
- } catch (error) {
- log('Persist workflow snapshot failed error=%O', error);
- }
- }
-
- return {
- deduped: result?.deduped ?? true,
- emittedSignals: isGeneratedEmission(result) ? result.orchestration.emittedSignals.length : 0,
- scopeKey: normalizedSourceEvent.scopeKey,
- sourceId: normalizedSourceEvent.sourceId,
- success: true,
- } as const;
+ workflowRunCounter.add(
+ 1,
+ buildWorkflowMetricAttributes(normalizedSourceEvent.sourceType, workflowStatus),
+ );
+ span.setAttribute(
+ 'agent.signal.emitted_signal_count',
+ isGeneratedEmission(result) ? result.orchestration.emittedSignals.length : 0,
+ );
+ span.setAttribute('agent.signal.workflow_deduped', result?.deduped ?? true);
+ span.setStatus({ code: SpanStatusCode.OK });
+
+ return {
+ deduped: result?.deduped ?? true,
+ emittedSignals: isGeneratedEmission(result)
+ ? result.orchestration.emittedSignals.length
+ : 0,
+ scopeKey: normalizedSourceEvent.scopeKey,
+ sourceId: normalizedSourceEvent.sourceId,
+ success: true,
+ } as const;
+ } catch (error) {
+ workflowStatus = 'error';
+ workflowRunCounter.add(1, buildWorkflowMetricAttributes(sourceType, workflowStatus));
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'AgentSignal workflow run failed',
+ });
+ span.recordException(error as Error);
+ throw error;
+ } finally {
+ workflowRunDurationHistogram.record(
+ Date.now() - startedAt,
+ buildWorkflowMetricAttributes(sourceType, workflowStatus ?? 'no_emission'),
+ );
+ span.end();
+ }
+ },
+ ),
+ );
};