diff --git a/.changeset/quiet-spans-snapshot.md b/.changeset/quiet-spans-snapshot.md new file mode 100644 index 00000000000..01fd3cefa65 --- /dev/null +++ b/.changeset/quiet-spans-snapshot.md @@ -0,0 +1,5 @@ +--- +'@mastra/observability': patch +--- + +Stop deep-copying span metadata twice for every logger and metrics context. `getLoggerContext` and `getMetricsContext` now pass span metadata straight to the context implementation, which snapshots it once, halving the deep copies taken on the agent execution path when observability is enabled. diff --git a/observability/mastra/src/instances/base.test.ts b/observability/mastra/src/instances/base.test.ts new file mode 100644 index 00000000000..f182fc1496f --- /dev/null +++ b/observability/mastra/src/instances/base.test.ts @@ -0,0 +1,108 @@ +/** + * Regression tests for the span -> context factory methods on + * BaseObservabilityInstance. + * + * Creating a logger or metrics context must deep-copy the span's metadata + * exactly once: the context implementations snapshot what they are given, so + * the factories must not copy it again on the way in. + */ + +import type { AnySpan, LogEvent, MetricEvent, ObservabilityExporter, TracingEvent } from '@mastra/core/observability'; +import { SamplingStrategyType } from '@mastra/core/observability'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { DefaultObservabilityInstance } from './default'; + +class CapturingExporter implements ObservabilityExporter { + name = 'capturing-exporter'; + logEvents: LogEvent[] = []; + metricEvents: MetricEvent[] = []; + + async exportTracingEvent(_event: TracingEvent): Promise {} + + async onLogEvent(event: LogEvent): Promise { + this.logEvents.push(event); + } + + async onMetricEvent(event: MetricEvent): Promise { + this.metricEvents.push(event); + } + + async flush(): Promise {} + + async shutdown(): Promise {} +} + +function createInstance(exporter: CapturingExporter) { + return new DefaultObservabilityInstance({ + serviceName: 'test-service', + name: 'test-instance', + sampling: { type: SamplingStrategyType.ALWAYS }, + exporters: [exporter], + logging: { level: 'info' }, + }); +} + +/** + * A plain object cast to AnySpan: the factories only read metadata, traceId and + * the optional getExportedSpanId() (the same fixture style as the legacy-span + * case in tracing.test.ts). + */ +function createSpan(metadata: Record): AnySpan { + return { id: 'span-1', traceId: 'trace-1', metadata } as unknown as AnySpan; +} + +describe('context factories', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('deep-copies span metadata once when creating a logger context', () => { + const exporter = new CapturingExporter(); + const instance = createInstance(exporter); + const cloneSpy = vi.spyOn(globalThis, 'structuredClone'); + + instance.getLoggerContext(createSpan({ runId: 'run-1', nested: { depth: 1 } })); + + expect(cloneSpy).toHaveBeenCalledTimes(1); + }); + + it('deep-copies span metadata once when creating a metrics context', () => { + const exporter = new CapturingExporter(); + const instance = createInstance(exporter); + const cloneSpy = vi.spyOn(globalThis, 'structuredClone'); + + instance.getMetricsContext(createSpan({ runId: 'run-1', nested: { depth: 1 } })); + + expect(cloneSpy).toHaveBeenCalledTimes(1); + }); + + it('keeps logger metadata a snapshot when the span metadata is mutated later', async () => { + const exporter = new CapturingExporter(); + const instance = createInstance(exporter); + const metadata = { runId: 'run-1', nested: { depth: 1 } }; + + const logger = instance.getLoggerContext(createSpan(metadata)); + metadata.nested.depth = 2; + + logger.warn('after mutation'); + await instance.flush(); + + expect(exporter.logEvents).toHaveLength(1); + expect(exporter.logEvents[0]!.log.metadata).toEqual({ runId: 'run-1', nested: { depth: 1 } }); + }); + + it('keeps metrics metadata a snapshot when the span metadata is mutated later', async () => { + const exporter = new CapturingExporter(); + const instance = createInstance(exporter); + const metadata = { runId: 'run-1', nested: { depth: 1 } }; + + const metrics = instance.getMetricsContext(createSpan(metadata)); + metadata.nested.depth = 2; + + metrics.emit('mastra_agent_runs', 1); + await instance.flush(); + + expect(exporter.metricEvents).toHaveLength(1); + expect(exporter.metricEvents[0]!.metric.metadata).toEqual({ runId: 'run-1', nested: { depth: 1 } }); + }); +}); diff --git a/observability/mastra/src/instances/base.ts b/observability/mastra/src/instances/base.ts index dc696d59243..1d87a2f05cf 100644 --- a/observability/mastra/src/instances/base.ts +++ b/observability/mastra/src/instances/base.ts @@ -573,7 +573,9 @@ export abstract class BaseObservabilityInstance extends MastraBase implements Ob } const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext(); - const metadata: Record | undefined = span?.metadata ? structuredClone(span.metadata) : undefined; + // Pass metadata through untouched: LoggerContextImpl snapshots it in its + // constructor, so cloning here would deep-copy span metadata twice. + const metadata: Record | undefined = span?.metadata; return new LoggerContextImpl({ traceId: span?.traceId, @@ -595,7 +597,9 @@ export abstract class BaseObservabilityInstance extends MastraBase implements Ob */ getMetricsContext(span?: AnySpan): MetricsContext { const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext(); - const metadata: Record | undefined = span?.metadata ? structuredClone(span.metadata) : undefined; + // Pass metadata through untouched: MetricsContextImpl snapshots it in its + // constructor, so cloning here would deep-copy span metadata twice. + const metadata: Record | undefined = span?.metadata; return new MetricsContextImpl({ traceId: span?.traceId, diff --git a/observability/mastra/src/spans/base.ts b/observability/mastra/src/spans/base.ts index 36ef9255eb9..2ac133bcabc 100644 --- a/observability/mastra/src/spans/base.ts +++ b/observability/mastra/src/spans/base.ts @@ -315,7 +315,7 @@ export abstract class BaseSpan implements Span implements Span