From 3feb69dffc15e6c54165f3f8d9ef04a27c8efc36 Mon Sep 17 00:00:00 2001 From: "mastra-platform[bot]" Date: Tue, 17 Nov 2026 08:31:45 +0000 Subject: [PATCH] fix(observability): stop deep-copying span metadata twice per context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `getLoggerContext()` and `getMetricsContext()` deep-copied `span.metadata` before handing it to `LoggerContextImpl` / `MetricsContextImpl`, whose constructors deep-copy it again. Every logger and metrics context therefore ran two structured clones of the same object, four per pair, on the ordinary agent execution path — hundreds per turn for apps that put metadata in `tracingOptions`. The factories now pass span metadata straight through. The constructors stay the single defensive-copy boundary, so emitted log and metric metadata is still a snapshot that later mutations of the span's metadata cannot change. The two comments in `spans/base.ts` that attributed the clone to the factory methods are corrected, so the invariant is documented where it is read. ## Test plan - [x] `vitest run src/instances/base.test.ts` — 4/4 pass; the two clone-count tests report 2 clones with the fix reverted - [x] `vitest run src/context/logger.test.ts src/context/metrics.test.ts src/tracing.test.ts` — 139/139 pass - [x] `vitest run` (full `@mastra/observability` suite) — 1883 pass, 0 fail - [x] `tsc --noEmit -p tsconfig.json` — clean - [x] `oxlint --type-aware observability/mastra` — 0 warnings, 0 errors - [x] core callers: `context-factory.test.ts`, `dual-logger.test.ts`, `observe.test.ts`, `observe-execute.test.ts`, `processor-stream-observability-context.test.ts` — 67/67 pass Fixes #30665 Co-authored-by: mastra-platform[bot] <284800079+mastra-platform[bot]@users.noreply.github.com> --- .changeset/quiet-spans-snapshot.md | 5 + .../mastra/src/instances/base.test.ts | 108 ++++++++++++++++++ observability/mastra/src/instances/base.ts | 8 +- observability/mastra/src/spans/base.ts | 6 +- 4 files changed, 122 insertions(+), 5 deletions(-) create mode 100644 .changeset/quiet-spans-snapshot.md create mode 100644 observability/mastra/src/instances/base.test.ts 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