@mastra/observability 1.24.0-alpha.3 → 1.24.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/bus/observability-bus.d.ts +2 -1
  2. package/dist/bus/observability-bus.d.ts.map +1 -1
  3. package/dist/bus/route-event.d.ts.map +1 -1
  4. package/dist/default.d.ts +4 -1
  5. package/dist/default.d.ts.map +1 -1
  6. package/dist/docs/SKILL.md +1 -1
  7. package/dist/docs/assets/SOURCE_MAP.json +53 -53
  8. package/dist/docs/references/docs-observability-feedback.md +5 -7
  9. package/dist/docs/references/reference-observability-feedback.md +43 -14
  10. package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +19 -16
  11. package/dist/exporters/default.d.ts +4 -7
  12. package/dist/exporters/default.d.ts.map +1 -1
  13. package/dist/exporters/event-buffer.d.ts +5 -2
  14. package/dist/exporters/event-buffer.d.ts.map +1 -1
  15. package/dist/exporters/mastra-platform.d.ts +5 -1
  16. package/dist/exporters/mastra-platform.d.ts.map +1 -1
  17. package/dist/exporters/mastra-storage.d.ts +4 -7
  18. package/dist/exporters/mastra-storage.d.ts.map +1 -1
  19. package/dist/exporters/platform-resolved-record.d.ts +3 -0
  20. package/dist/exporters/platform-resolved-record.d.ts.map +1 -0
  21. package/dist/exporters/storage-annotation.d.ts +9 -0
  22. package/dist/exporters/storage-annotation.d.ts.map +1 -0
  23. package/dist/exporters/storage-byte-tracker.d.ts +2 -3
  24. package/dist/exporters/storage-byte-tracker.d.ts.map +1 -1
  25. package/dist/index.cjs +911 -730
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +911 -730
  28. package/dist/index.js.map +1 -1
  29. package/dist/instances/base.d.ts +2 -1
  30. package/dist/instances/base.d.ts.map +1 -1
  31. package/dist/metrics/pricing-data.json +279 -101
  32. package/dist/model-tracing.d.ts.map +1 -1
  33. package/dist/recorded.d.ts +4 -12
  34. package/dist/recorded.d.ts.map +1 -1
  35. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -77,6 +77,9 @@ function routeToHandler(handler, event, logger) {
77
77
  }), handler.name, "score", logger);
78
78
  }
79
79
  break;
80
+ case "feedback_replacement":
81
+ if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
82
+ break;
80
83
  case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
81
84
  }
82
85
  } catch (err) {
@@ -577,6 +580,10 @@ function cleanEvent(event, options) {
577
580
  type: "score",
578
581
  score: deepClean(event.score, options)
579
582
  };
583
+ case "feedback_replacement": return {
584
+ type: event.type,
585
+ feedback: deepClean(event.feedback, options)
586
+ };
580
587
  case "feedback": return {
581
588
  type: "feedback",
582
589
  feedback: deepClean(event.feedback, options)
@@ -669,10 +676,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
669
676
  * emit() is synchronous — async handler promises are tracked internally
670
677
  * and can be drained via flush().
671
678
  */
672
- emit(event) {
679
+ emit(event, shouldHandle) {
673
680
  const cleaned = cleanEvent(event, this.deepCleanOptions);
674
- for (const exporter of this.exporters) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
675
- if (this.bridge) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
681
+ for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
682
+ if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
676
683
  super.emit(cleaned);
677
684
  }
678
685
  /**
@@ -3252,11 +3259,22 @@ var ModelSpanTracker = class {
3252
3259
  * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
3253
3260
  */
3254
3261
  wrapStream(stream, inferenceOnly = false) {
3262
+ let servedModelId;
3255
3263
  return stream.pipeThrough(new stream_web.TransformStream({ transform: (chunk, controller) => {
3256
3264
  if (inferenceOnly) {
3257
3265
  try {
3266
+ if (chunk.type === "response-metadata" && typeof chunk.payload?.modelId === "string") servedModelId = chunk.payload.modelId;
3258
3267
  if (MODEL_RESPONSE_CHUNK_TYPES.has(chunk.type)) this.#captureCompletionStartTime();
3259
- if (chunk.type === "finish") this.#endInferenceSpan(chunk.payload, false);
3268
+ if (chunk.type === "finish") {
3269
+ const payload = servedModelId && !chunk.payload?.metadata?.modelId ? {
3270
+ ...chunk.payload,
3271
+ metadata: {
3272
+ ...chunk.payload?.metadata,
3273
+ modelId: servedModelId
3274
+ }
3275
+ } : chunk.payload;
3276
+ this.#endInferenceSpan(payload, false);
3277
+ }
3260
3278
  } catch {}
3261
3279
  controller.enqueue(chunk);
3262
3280
  return;
@@ -4613,193 +4631,548 @@ var EventBuffer = class {
4613
4631
  });
4614
4632
  }
4615
4633
  };
4616
- // src/exporters/default.ts
4617
- /**
4618
- * Resolves the final tracing storage strategy based on config and observability store hints
4619
- */
4620
- function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4621
- const observabilityStrategy = observabilityStorage.observabilityStrategy;
4622
- if (config.strategy && config.strategy !== "auto") {
4623
- if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4624
- logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4625
- userStrategy: config.strategy,
4626
- storageAdapter: storageName,
4627
- supportedStrategies: observabilityStrategy.supported,
4628
- fallbackStrategy: observabilityStrategy.preferred
4629
- });
4630
- }
4631
- return observabilityStrategy.preferred;
4634
+ // src/recorded.ts
4635
+ function nullToUndefined(value) {
4636
+ return value ?? void 0;
4632
4637
  }
4633
- const FLUSH_SUCCEEDED$1 = { failed: false };
4634
- /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
4635
- const MAX_FLUSH_ROUNDS$1 = 3;
4636
- /**
4637
- * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
4638
- * This class is preserved unchanged so existing integrations (including code
4639
- * that matches on the `mastra-default-observability-exporter` exporter name)
4640
- * keep working. It will be removed in a future major version.
4641
- *
4642
- * Default storage-backed exporter. Buffers observability events and flushes them
4643
- * in batches to the configured ObservabilityStorage backend with retry support.
4644
- */
4645
- var DefaultExporter = class extends BaseExporter {
4646
- name = "mastra-default-observability-exporter";
4647
- #config;
4648
- #isInitializing = false;
4649
- #initPromises = /* @__PURE__ */ new Set();
4650
- #eventBuffer;
4651
- #storage;
4652
- #observabilityStorage;
4653
- #resolvedStrategy;
4654
- #flushTimer;
4655
- /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
4656
- #inFlightFlushes = /* @__PURE__ */ new Set();
4657
- #emitDropEvent;
4658
- #unsupportedSignals = /* @__PURE__ */ new Set();
4659
- constructor(config = {}) {
4660
- super(config);
4661
- this.#config = {
4662
- ...config,
4663
- maxBatchSize: config.maxBatchSize ?? 1e3,
4664
- maxBufferSize: config.maxBufferSize ?? 1e4,
4665
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
4666
- maxRetries: config.maxRetries ?? 4,
4667
- retryDelayMs: config.retryDelayMs ?? 500,
4668
- strategy: config.strategy ?? "auto"
4669
- };
4670
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
4671
- }
4672
- /**
4673
- * Initialize the exporter (called after all dependencies are ready)
4674
- */
4675
- async init(options) {
4676
- try {
4677
- this.#isInitializing = true;
4678
- this.#emitDropEvent = options.emitDropEvent;
4679
- this.#storage = options.mastra?.getStorage();
4680
- if (!this.#storage) {
4681
- this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
4682
- return;
4683
- }
4684
- this.#observabilityStorage = await this.#storage.getStore("observability");
4685
- if (!this.#observabilityStorage) {
4686
- this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
4687
- return;
4688
- }
4689
- if (!this.#resolvedStrategy) {
4690
- this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
4691
- this.logger.debug("tracing storage exporter initialized", {
4692
- strategy: this.#resolvedStrategy,
4693
- source: this.#config.strategy !== "auto" ? "user" : "auto",
4694
- storageAdapter: this.#storage.constructor.name,
4695
- maxBatchSize: this.#config.maxBatchSize,
4696
- maxBatchWaitMs: this.#config.maxBatchWaitMs
4697
- });
4698
- }
4699
- if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4700
- } finally {
4701
- this.#isInitializing = false;
4702
- /**
4703
- * Assumes caller waits until export of a parent span is completed before calling
4704
- * export for child spans , order is not relevant for resolve
4705
- */
4706
- this.#initPromises.forEach((resolve) => {
4707
- resolve();
4708
- });
4709
- this.#initPromises.clear();
4710
- }
4711
- }
4712
- /**
4713
- * Checks if buffer should be flushed based on size or time triggers
4714
- */
4715
- shouldFlush() {
4716
- if (this.#resolvedStrategy === "realtime") return true;
4717
- if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
4718
- if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
4719
- if (this.#eventBuffer.totalSize > 0) {
4720
- if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
4721
- }
4722
- return false;
4723
- }
4724
- /**
4725
- * Schedules a flush using setTimeout
4726
- */
4727
- scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
4728
- if (this.#flushTimer) clearTimeout(this.#flushTimer);
4729
- this.#flushTimer = setTimeout(() => {
4730
- this.#flushTimer = void 0;
4731
- this.trackFlushBuffer().catch((error) => {
4732
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
4733
- });
4734
- }, delayMs);
4735
- }
4736
- retryDelay(retryAttempt) {
4737
- return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
4738
- }
4739
- retryAttempt(events) {
4740
- return events.reduce((earliestAttempt, event) => {
4741
- if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
4742
- return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
4743
- }, void 0);
4744
- }
4745
- logStorageFailure(signal, events, retryAttempt, error) {
4746
- this.logger.warn("Failed to persist observability events", {
4747
- signal,
4748
- eventCount: events.length,
4749
- retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
4750
- maxRetries: this.#config.maxRetries,
4751
- ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
4752
- error: error instanceof Error ? error.message : String(error)
4753
- });
4754
- }
4755
- /**
4756
- * Checks flush triggers and schedules/triggers flush as needed.
4757
- * Called after adding any event to the buffer.
4758
- * Returns the flush promise when flushing so callers can await it.
4759
- */
4760
- async handleBatchedFlush() {
4761
- if (this.shouldFlush()) await this.trackFlushBuffer();
4762
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
4763
- }
4764
- sanitizeDropError(error) {
4765
- if (error instanceof _mastra_core_error.MastraError) return {
4766
- id: error.id,
4767
- domain: String(error.domain),
4768
- message: error.message
4769
- };
4770
- if (error instanceof Error) return { message: error.message };
4771
- return { message: String(error) };
4772
- }
4773
- emitDrop(signal, reason, count, error) {
4774
- if (count === 0) return;
4775
- const dropEvent = {
4776
- type: "drop",
4777
- signal,
4778
- reason,
4779
- count,
4638
+ function mergeMetadata(base, extra) {
4639
+ if (!base && !extra) return void 0;
4640
+ return {
4641
+ ...base ?? {},
4642
+ ...extra ?? {}
4643
+ };
4644
+ }
4645
+ function normalizeErrorInfo(error) {
4646
+ if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
4647
+ return {
4648
+ message: error.message,
4649
+ id: "id" in error && typeof error.id === "string" ? error.id : void 0,
4650
+ name: "name" in error && typeof error.name === "string" ? error.name : void 0,
4651
+ stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
4652
+ domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
4653
+ category: "category" in error && typeof error.category === "string" ? error.category : void 0,
4654
+ details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
4655
+ };
4656
+ }
4657
+ function buildCorrelationContext(span, rootSpan, parent) {
4658
+ return {
4659
+ tags: rootSpan.tags ?? void 0,
4660
+ entityType: nullToUndefined(span.entityType),
4661
+ entityId: nullToUndefined(span.entityId),
4662
+ entityName: nullToUndefined(span.entityName),
4663
+ parentEntityType: parent?.entityType ?? void 0,
4664
+ parentEntityId: parent?.entityId ?? void 0,
4665
+ parentEntityName: parent?.entityName ?? void 0,
4666
+ rootEntityType: nullToUndefined(rootSpan.entityType),
4667
+ rootEntityId: nullToUndefined(rootSpan.entityId),
4668
+ rootEntityName: nullToUndefined(rootSpan.entityName),
4669
+ userId: nullToUndefined(span.userId),
4670
+ organizationId: nullToUndefined(span.organizationId),
4671
+ resourceId: nullToUndefined(span.resourceId),
4672
+ runId: nullToUndefined(span.runId),
4673
+ sessionId: nullToUndefined(span.sessionId),
4674
+ threadId: nullToUndefined(span.threadId),
4675
+ requestId: nullToUndefined(span.requestId),
4676
+ environment: nullToUndefined(span.environment),
4677
+ source: nullToUndefined(span.source),
4678
+ serviceName: nullToUndefined(span.serviceName),
4679
+ experimentId: nullToUndefined(span.experimentId)
4680
+ };
4681
+ }
4682
+ function buildScoreEvent(args) {
4683
+ const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
4684
+ return {
4685
+ type: "score",
4686
+ score: {
4687
+ scoreId: generateSignalId(),
4780
4688
  timestamp: /* @__PURE__ */ new Date(),
4781
- exporterName: this.name,
4782
- ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
4783
- ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
4784
- };
4785
- this.#emitDropEvent?.(dropEvent);
4786
- }
4787
- /**
4788
- * Flush a batch of create events for a single signal type.
4789
- * On "not implemented" errors, disables the signal for future flushes.
4790
- * On other errors, re-adds events to the buffer for retry.
4791
- */
4792
- async flushCreates(signal, events, storageCall) {
4793
- if (events.length === 0) return FLUSH_SUCCEEDED$1;
4794
- if (this.#unsupportedSignals.has(signal)) {
4795
- this.emitDrop(signal, "unsupported-storage", events.length);
4796
- return { failed: true };
4689
+ traceId,
4690
+ spanId,
4691
+ scorerId: score.scorerId,
4692
+ scorerName: score.scorerName,
4693
+ scorerVersion: score.scorerVersion,
4694
+ source: score.source,
4695
+ scoreSource: score.scoreSource,
4696
+ score: score.score,
4697
+ reason: score.reason,
4698
+ experimentId: score.experimentId,
4699
+ scoreTraceId: score.scoreTraceId,
4700
+ targetEntityType: score.targetEntityType,
4701
+ correlationContext,
4702
+ metadata: mergeMetadata(inheritedMetadata, score.metadata)
4797
4703
  }
4798
- try {
4799
- await storageCall(events);
4800
- return FLUSH_SUCCEEDED$1;
4801
- } catch (error) {
4802
- if (error instanceof _mastra_core_error.MastraError && error.domain === _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
4704
+ };
4705
+ }
4706
+ function buildFeedbackEvent(args) {
4707
+ const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
4708
+ return {
4709
+ type: "feedback",
4710
+ feedback: {
4711
+ feedbackId: generateSignalId(),
4712
+ timestamp: /* @__PURE__ */ new Date(),
4713
+ traceId,
4714
+ spanId,
4715
+ source: feedback.source,
4716
+ feedbackSource: feedback.feedbackSource,
4717
+ feedbackType: feedback.feedbackType,
4718
+ value: feedback.value,
4719
+ userId: feedback.userId,
4720
+ feedbackUserId: feedback.feedbackUserId,
4721
+ comment: feedback.comment,
4722
+ sourceId: feedback.sourceId,
4723
+ experimentId: feedback.experimentId,
4724
+ correlationContext,
4725
+ metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
4726
+ }
4727
+ };
4728
+ }
4729
+ function findSpanById(spans, spanId) {
4730
+ if (!spanId) return void 0;
4731
+ return spans.find((span) => span.spanId === spanId);
4732
+ }
4733
+ /** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
4734
+ function resolveRecordedEventFromTrace(trace, event) {
4735
+ const record = event.type === "score" ? event.score : event.feedback;
4736
+ const spans = trace.spans.filter((span) => span.traceId === record.traceId);
4737
+ const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
4738
+ if (!span) return null;
4739
+ const byId = new Map(spans.map((span) => [span.spanId, span]));
4740
+ let root = span;
4741
+ const visited = /* @__PURE__ */ new Set();
4742
+ while (root.parentSpanId) {
4743
+ if (visited.has(root.spanId)) return null;
4744
+ visited.add(root.spanId);
4745
+ const parent = byId.get(root.parentSpanId);
4746
+ if (!parent) return null;
4747
+ root = parent;
4748
+ }
4749
+ const context = {
4750
+ correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
4751
+ metadata: mergeMetadata(span.metadata, record.metadata)
4752
+ };
4753
+ return event.type === "score" ? {
4754
+ type: "score",
4755
+ score: {
4756
+ ...event.score,
4757
+ ...context
4758
+ }
4759
+ } : event.type === "feedback_replacement" ? {
4760
+ type: "feedback_replacement",
4761
+ feedback: {
4762
+ ...event.feedback,
4763
+ ...context
4764
+ }
4765
+ } : {
4766
+ type: "feedback",
4767
+ feedback: {
4768
+ ...event.feedback,
4769
+ ...context
4770
+ }
4771
+ };
4772
+ }
4773
+ var RecordedSpanImpl = class {
4774
+ id;
4775
+ traceId;
4776
+ name;
4777
+ type;
4778
+ entityType;
4779
+ entityId;
4780
+ entityName;
4781
+ startTime;
4782
+ endTime;
4783
+ attributes;
4784
+ metadata;
4785
+ tags;
4786
+ input;
4787
+ output;
4788
+ errorInfo;
4789
+ requestContext;
4790
+ isEvent;
4791
+ isRootSpan;
4792
+ parentSpanId;
4793
+ parent;
4794
+ children = [];
4795
+ #raw;
4796
+ #rootSpan;
4797
+ #emitRecordedEvent;
4798
+ #canEmitRecordedEvent;
4799
+ #debugRecordedAnnotationUnavailable;
4800
+ constructor(args) {
4801
+ const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
4802
+ this.#raw = raw;
4803
+ this.#rootSpan = rootSpan;
4804
+ this.#emitRecordedEvent = emitRecordedEvent;
4805
+ this.#canEmitRecordedEvent = canEmitRecordedEvent;
4806
+ this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
4807
+ this.id = raw.spanId;
4808
+ this.traceId = raw.traceId;
4809
+ this.name = raw.name;
4810
+ this.type = raw.spanType;
4811
+ this.entityType = raw.entityType ?? void 0;
4812
+ this.entityId = raw.entityId ?? void 0;
4813
+ this.entityName = raw.entityName ?? void 0;
4814
+ this.startTime = raw.startedAt;
4815
+ this.endTime = raw.endedAt ?? void 0;
4816
+ this.attributes = raw.attributes ?? void 0;
4817
+ this.metadata = raw.metadata ?? void 0;
4818
+ this.tags = raw.tags ?? void 0;
4819
+ this.input = raw.input ?? void 0;
4820
+ this.output = raw.output ?? void 0;
4821
+ this.errorInfo = normalizeErrorInfo(raw.error);
4822
+ this.requestContext = raw.requestContext ?? void 0;
4823
+ this.isEvent = raw.isEvent;
4824
+ this.isRootSpan = !raw.parentSpanId;
4825
+ this.parentSpanId = raw.parentSpanId ?? void 0;
4826
+ }
4827
+ async addScore(score) {
4828
+ if (!this.#canEmitRecordedEvent()) {
4829
+ this.#debugRecordedAnnotationUnavailable({
4830
+ kind: "score",
4831
+ traceId: this.traceId,
4832
+ spanId: this.id
4833
+ });
4834
+ return;
4835
+ }
4836
+ await this.#emitRecordedEvent(buildScoreEvent({
4837
+ traceId: this.#raw.traceId,
4838
+ spanId: this.id,
4839
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4840
+ score,
4841
+ inheritedMetadata: this.#raw.metadata
4842
+ }));
4843
+ }
4844
+ async addFeedback(feedback) {
4845
+ if (!this.#canEmitRecordedEvent()) {
4846
+ this.#debugRecordedAnnotationUnavailable({
4847
+ kind: "feedback",
4848
+ traceId: this.traceId,
4849
+ spanId: this.id
4850
+ });
4851
+ return;
4852
+ }
4853
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4854
+ traceId: this.#raw.traceId,
4855
+ spanId: this.id,
4856
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4857
+ feedback,
4858
+ inheritedMetadata: this.#raw.metadata
4859
+ }));
4860
+ }
4861
+ };
4862
+ var RecordedTraceImpl = class {
4863
+ traceId;
4864
+ rootSpan;
4865
+ spans;
4866
+ #rootRecord;
4867
+ #emitRecordedEvent;
4868
+ #spanMap;
4869
+ #canEmitRecordedEvent;
4870
+ #debugRecordedAnnotationUnavailable;
4871
+ constructor(args) {
4872
+ this.traceId = args.traceId;
4873
+ this.rootSpan = args.rootSpan;
4874
+ this.#rootRecord = args.rootRecord;
4875
+ this.spans = args.spans;
4876
+ this.#emitRecordedEvent = args.emitRecordedEvent;
4877
+ this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
4878
+ this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
4879
+ this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
4880
+ }
4881
+ getSpan(spanId) {
4882
+ return this.#spanMap.get(spanId) ?? null;
4883
+ }
4884
+ async addScore(score) {
4885
+ if (!this.#canEmitRecordedEvent()) {
4886
+ this.#debugRecordedAnnotationUnavailable({
4887
+ kind: "score",
4888
+ traceId: this.traceId
4889
+ });
4890
+ return;
4891
+ }
4892
+ await this.#emitRecordedEvent(buildScoreEvent({
4893
+ traceId: this.#rootRecord.traceId,
4894
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4895
+ score,
4896
+ inheritedMetadata: this.#rootRecord.metadata
4897
+ }));
4898
+ }
4899
+ async addFeedback(feedback) {
4900
+ if (!this.#canEmitRecordedEvent()) {
4901
+ this.#debugRecordedAnnotationUnavailable({
4902
+ kind: "feedback",
4903
+ traceId: this.traceId
4904
+ });
4905
+ return;
4906
+ }
4907
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4908
+ traceId: this.#rootRecord.traceId,
4909
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4910
+ feedback,
4911
+ inheritedMetadata: this.#rootRecord.metadata
4912
+ }));
4913
+ }
4914
+ };
4915
+ function findRootSpan(spans) {
4916
+ const spanIds = new Set(spans.map((span) => span.spanId));
4917
+ return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
4918
+ }
4919
+ function hydrateRecordedTrace(args) {
4920
+ const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
4921
+ const rootSpan = findRootSpan(trace.spans);
4922
+ if (!rootSpan) return null;
4923
+ const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
4924
+ raw,
4925
+ rootSpan,
4926
+ emitRecordedEvent,
4927
+ canEmitRecordedEvent,
4928
+ debugRecordedAnnotationUnavailable
4929
+ }));
4930
+ const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
4931
+ for (const span of recordedSpans) {
4932
+ if (!span.parentSpanId) continue;
4933
+ const parent = spanMap.get(span.parentSpanId);
4934
+ if (!parent) continue;
4935
+ span.parent = parent;
4936
+ parent.children.push(span);
4937
+ }
4938
+ const hydratedRootSpan = spanMap.get(rootSpan.spanId);
4939
+ if (!hydratedRootSpan) return null;
4940
+ return new RecordedTraceImpl({
4941
+ traceId: trace.traceId,
4942
+ rootSpan: hydratedRootSpan,
4943
+ rootRecord: rootSpan,
4944
+ spans: recordedSpans,
4945
+ emitRecordedEvent,
4946
+ canEmitRecordedEvent,
4947
+ debugRecordedAnnotationUnavailable
4948
+ });
4949
+ }
4950
+ // src/exporters/storage-annotation.ts
4951
+ const LOOKUP_DELAYS_MS = [
4952
+ 0,
4953
+ 100,
4954
+ 250,
4955
+ 500,
4956
+ 1e3,
4957
+ 2e3,
4958
+ 2e3
4959
+ ];
4960
+ /**
4961
+ * Resolve attached-storage context within a bounded retry window, including failed reads.
4962
+ * Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
4963
+ * Other destinations receive the original event independently.
4964
+ */
4965
+ async function resolveStorageAnnotation(event, storage, flushSpans) {
4966
+ const record = event.type === "score" ? event.score : event.feedback;
4967
+ if (record.correlationContext !== void 0) return event;
4968
+ if (!record.traceId) return null;
4969
+ let lastReadFailure;
4970
+ for (const delay of LOOKUP_DELAYS_MS) {
4971
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
4972
+ let trace;
4973
+ try {
4974
+ trace = await storage.getTrace({ traceId: record.traceId });
4975
+ lastReadFailure = void 0;
4976
+ } catch (error) {
4977
+ lastReadFailure = { error };
4978
+ }
4979
+ if (trace) {
4980
+ const resolved = resolveRecordedEventFromTrace(trace, event);
4981
+ if (resolved) return resolved;
4982
+ }
4983
+ if (delay === 0) await flushSpans();
4984
+ }
4985
+ if (lastReadFailure) throw lastReadFailure.error;
4986
+ return null;
4987
+ }
4988
+ // src/exporters/default.ts
4989
+ /**
4990
+ * Resolves the final tracing storage strategy based on config and observability store hints
4991
+ */
4992
+ function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4993
+ const observabilityStrategy = observabilityStorage.observabilityStrategy;
4994
+ if (config.strategy && config.strategy !== "auto") {
4995
+ if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4996
+ logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4997
+ userStrategy: config.strategy,
4998
+ storageAdapter: storageName,
4999
+ supportedStrategies: observabilityStrategy.supported,
5000
+ fallbackStrategy: observabilityStrategy.preferred
5001
+ });
5002
+ }
5003
+ return observabilityStrategy.preferred;
5004
+ }
5005
+ const FLUSH_SUCCEEDED$1 = { failed: false };
5006
+ /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5007
+ const MAX_FLUSH_ROUNDS$1 = 3;
5008
+ /**
5009
+ * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
5010
+ * This class is preserved unchanged so existing integrations (including code
5011
+ * that matches on the `mastra-default-observability-exporter` exporter name)
5012
+ * keep working. It will be removed in a future major version.
5013
+ *
5014
+ * Default storage-backed exporter. Buffers observability events and flushes them
5015
+ * in batches to the configured ObservabilityStorage backend with retry support.
5016
+ */
5017
+ var DefaultExporter = class extends BaseExporter {
5018
+ name = "mastra-default-observability-exporter";
5019
+ #config;
5020
+ #isInitializing = false;
5021
+ #initPromises = /* @__PURE__ */ new Set();
5022
+ #eventBuffer;
5023
+ #storage;
5024
+ #observabilityStorage;
5025
+ #resolvedStrategy;
5026
+ #flushTimer;
5027
+ /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5028
+ #inFlightFlushes = /* @__PURE__ */ new Set();
5029
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5030
+ #emitDropEvent;
5031
+ #unsupportedSignals = /* @__PURE__ */ new Set();
5032
+ constructor(config = {}) {
5033
+ super(config);
5034
+ this.#config = {
5035
+ ...config,
5036
+ maxBatchSize: config.maxBatchSize ?? 1e3,
5037
+ maxBufferSize: config.maxBufferSize ?? 1e4,
5038
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
5039
+ maxRetries: config.maxRetries ?? 4,
5040
+ retryDelayMs: config.retryDelayMs ?? 500,
5041
+ strategy: config.strategy ?? "auto"
5042
+ };
5043
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5044
+ }
5045
+ /**
5046
+ * Initialize the exporter (called after all dependencies are ready)
5047
+ */
5048
+ async init(options) {
5049
+ try {
5050
+ this.#isInitializing = true;
5051
+ this.#emitDropEvent = options.emitDropEvent;
5052
+ this.#storage = options.mastra?.getStorage();
5053
+ if (!this.#storage) {
5054
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
5055
+ return;
5056
+ }
5057
+ this.#observabilityStorage = await this.#storage.getStore("observability");
5058
+ if (!this.#observabilityStorage) {
5059
+ this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
5060
+ return;
5061
+ }
5062
+ if (!this.#resolvedStrategy) {
5063
+ this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
5064
+ this.logger.debug("tracing storage exporter initialized", {
5065
+ strategy: this.#resolvedStrategy,
5066
+ source: this.#config.strategy !== "auto" ? "user" : "auto",
5067
+ storageAdapter: this.#storage.constructor.name,
5068
+ maxBatchSize: this.#config.maxBatchSize,
5069
+ maxBatchWaitMs: this.#config.maxBatchWaitMs
5070
+ });
5071
+ }
5072
+ if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5073
+ } finally {
5074
+ this.#isInitializing = false;
5075
+ /**
5076
+ * Assumes caller waits until export of a parent span is completed before calling
5077
+ * export for child spans , order is not relevant for resolve
5078
+ */
5079
+ this.#initPromises.forEach((resolve) => {
5080
+ resolve();
5081
+ });
5082
+ this.#initPromises.clear();
5083
+ }
5084
+ }
5085
+ /**
5086
+ * Checks if buffer should be flushed based on size or time triggers
5087
+ */
5088
+ shouldFlush() {
5089
+ if (this.#resolvedStrategy === "realtime") return true;
5090
+ if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5091
+ if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
5092
+ if (this.#eventBuffer.totalSize > 0) {
5093
+ if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
5094
+ }
5095
+ return false;
5096
+ }
5097
+ /**
5098
+ * Schedules a flush using setTimeout
5099
+ */
5100
+ scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
5101
+ if (this.#flushTimer) clearTimeout(this.#flushTimer);
5102
+ this.#flushTimer = setTimeout(() => {
5103
+ this.#flushTimer = void 0;
5104
+ this.trackFlushBuffer().catch((error) => {
5105
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5106
+ });
5107
+ }, delayMs);
5108
+ }
5109
+ retryDelay(retryAttempt) {
5110
+ return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5111
+ }
5112
+ retryAttempt(events) {
5113
+ return events.reduce((earliestAttempt, event) => {
5114
+ if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
5115
+ return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
5116
+ }, void 0);
5117
+ }
5118
+ logStorageFailure(signal, events, retryAttempt, error) {
5119
+ this.logger.warn("Failed to persist observability events", {
5120
+ signal,
5121
+ eventCount: events.length,
5122
+ retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
5123
+ maxRetries: this.#config.maxRetries,
5124
+ ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
5125
+ error: error instanceof Error ? error.message : String(error)
5126
+ });
5127
+ }
5128
+ /**
5129
+ * Checks flush triggers and schedules/triggers flush as needed.
5130
+ * Called after adding any event to the buffer.
5131
+ * Returns the flush promise when flushing so callers can await it.
5132
+ */
5133
+ async handleBatchedFlush() {
5134
+ if (this.shouldFlush()) await this.trackFlushBuffer();
5135
+ else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5136
+ }
5137
+ sanitizeDropError(error) {
5138
+ if (error instanceof _mastra_core_error.MastraError) return {
5139
+ id: error.id,
5140
+ domain: String(error.domain),
5141
+ message: error.message
5142
+ };
5143
+ if (error instanceof Error) return { message: error.message };
5144
+ return { message: String(error) };
5145
+ }
5146
+ emitDrop(signal, reason, count, error) {
5147
+ if (count === 0) return;
5148
+ const dropEvent = {
5149
+ type: "drop",
5150
+ signal,
5151
+ reason,
5152
+ count,
5153
+ timestamp: /* @__PURE__ */ new Date(),
5154
+ exporterName: this.name,
5155
+ ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
5156
+ ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
5157
+ };
5158
+ this.#emitDropEvent?.(dropEvent);
5159
+ }
5160
+ /**
5161
+ * Flush a batch of create events for a single signal type.
5162
+ * On "not implemented" errors, disables the signal for future flushes.
5163
+ * On other errors, re-adds events to the buffer for retry.
5164
+ */
5165
+ async flushCreates(signal, events, storageCall) {
5166
+ if (events.length === 0) return FLUSH_SUCCEEDED$1;
5167
+ if (this.#unsupportedSignals.has(signal)) {
5168
+ this.emitDrop(signal, "unsupported-storage", events.length);
5169
+ return { failed: true };
5170
+ }
5171
+ try {
5172
+ await storageCall(events);
5173
+ return FLUSH_SUCCEEDED$1;
5174
+ } catch (error) {
5175
+ if (error instanceof _mastra_core_error.MastraError && error.domain === _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
4803
5176
  this.logger.warn(error.message);
4804
5177
  this.#unsupportedSignals.add(signal);
4805
5178
  this.emitDrop(signal, "unsupported-storage", events.length, error);
@@ -4926,7 +5299,10 @@ var DefaultExporter = class extends BaseExporter {
4926
5299
  case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
4927
5300
  }
4928
5301
  const flushResults = await Promise.all([
4929
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5302
+ this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5303
+ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
5304
+ onConflict: "ignore"
5305
+ })),
4930
5306
  this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
4931
5307
  this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
4932
5308
  this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
@@ -5003,22 +5379,46 @@ var DefaultExporter = class extends BaseExporter {
5003
5379
  this.#eventBuffer.addEvent(event);
5004
5380
  await this.handleBatchedFlush();
5005
5381
  }
5006
- /**
5007
- * Handle score events — buffer for batch flush.
5008
- */
5009
- async onScoreEvent(event) {
5010
- await this.waitForInit();
5011
- if (!this.#observabilityStorage) return;
5012
- this.#eventBuffer.addEvent(event);
5013
- await this.handleBatchedFlush();
5382
+ onScoreEvent(event) {
5383
+ return this.enqueueAnnotation(event);
5014
5384
  }
5015
- /**
5016
- * Handle feedback events — buffer for batch flush.
5017
- */
5018
- async onFeedbackEvent(event) {
5385
+ onFeedbackReplacementEvent(event) {
5386
+ return this.enqueueAnnotation(event);
5387
+ }
5388
+ onFeedbackEvent(event) {
5389
+ return this.enqueueAnnotation(event);
5390
+ }
5391
+ enqueueAnnotation(event) {
5392
+ const pending = this.storeAnnotation(event);
5393
+ this.#pendingAnnotations.add(pending);
5394
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
5395
+ return pending;
5396
+ }
5397
+ async storeAnnotation(event) {
5019
5398
  await this.waitForInit();
5020
5399
  if (!this.#observabilityStorage) return;
5021
- this.#eventBuffer.addEvent(event);
5400
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
5401
+ await Promise.allSettled([...this.#inFlightFlushes]);
5402
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5403
+ });
5404
+ if (!resolved) {
5405
+ const record = event.type === "score" ? event.score : event.feedback;
5406
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
5407
+ eventType: event.type,
5408
+ traceId: record.traceId,
5409
+ spanId: record.spanId
5410
+ });
5411
+ return;
5412
+ }
5413
+ if (resolved.type === "feedback_replacement") {
5414
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
5415
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
5416
+ return;
5417
+ }
5418
+ await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
5419
+ return;
5420
+ }
5421
+ this.#eventBuffer.addEvent(resolved);
5022
5422
  await this.handleBatchedFlush();
5023
5423
  }
5024
5424
  /**
@@ -5027,6 +5427,7 @@ var DefaultExporter = class extends BaseExporter {
5027
5427
  * are exported before the runtime instance is terminated.
5028
5428
  */
5029
5429
  async flush() {
5430
+ await Promise.allSettled([...this.#pendingAnnotations]);
5030
5431
  for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
5031
5432
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5032
5433
  if (this.#eventBuffer.totalSize > 0) {
@@ -5176,6 +5577,7 @@ var MastraStorageExporter = class extends BaseExporter {
5176
5577
  #flushTimer;
5177
5578
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5178
5579
  #inFlightFlushes = /* @__PURE__ */ new Set();
5580
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5179
5581
  #emitDropEvent;
5180
5582
  #unsupportedSignals = /* @__PURE__ */ new Set();
5181
5583
  constructor(config = {}) {
@@ -5546,7 +5948,10 @@ var MastraStorageExporter = class extends BaseExporter {
5546
5948
  case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5547
5949
  }
5548
5950
  const createTasks = [
5549
- () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5951
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5952
+ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
5953
+ onConflict: "ignore"
5954
+ })),
5550
5955
  () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
5551
5956
  () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
5552
5957
  () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
@@ -5627,22 +6032,46 @@ var MastraStorageExporter = class extends BaseExporter {
5627
6032
  this.#eventBuffer.addEvent(event);
5628
6033
  await this.handleBatchedFlush();
5629
6034
  }
5630
- /**
5631
- * Handle score events — buffer for batch flush.
5632
- */
5633
- async onScoreEvent(event) {
5634
- await this.ensureInitialized();
5635
- if (!this.#observabilityStorage) return;
5636
- this.#eventBuffer.addEvent(event);
5637
- await this.handleBatchedFlush();
6035
+ onScoreEvent(event) {
6036
+ return this.enqueueAnnotation(event);
5638
6037
  }
5639
- /**
5640
- * Handle feedback events — buffer for batch flush.
5641
- */
5642
- async onFeedbackEvent(event) {
6038
+ onFeedbackReplacementEvent(event) {
6039
+ return this.enqueueAnnotation(event);
6040
+ }
6041
+ onFeedbackEvent(event) {
6042
+ return this.enqueueAnnotation(event);
6043
+ }
6044
+ enqueueAnnotation(event) {
6045
+ const pending = this.storeAnnotation(event);
6046
+ this.#pendingAnnotations.add(pending);
6047
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
6048
+ return pending;
6049
+ }
6050
+ async storeAnnotation(event) {
5643
6051
  await this.ensureInitialized();
5644
6052
  if (!this.#observabilityStorage) return;
5645
- this.#eventBuffer.addEvent(event);
6053
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
6054
+ await Promise.allSettled([...this.#inFlightFlushes]);
6055
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
6056
+ });
6057
+ if (!resolved) {
6058
+ const record = event.type === "score" ? event.score : event.feedback;
6059
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
6060
+ eventType: event.type,
6061
+ traceId: record.traceId,
6062
+ spanId: record.spanId
6063
+ });
6064
+ return;
6065
+ }
6066
+ if (resolved.type === "feedback_replacement") {
6067
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
6068
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
6069
+ return;
6070
+ }
6071
+ await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
6072
+ return;
6073
+ }
6074
+ this.#eventBuffer.addEvent(resolved);
5646
6075
  await this.handleBatchedFlush();
5647
6076
  }
5648
6077
  /**
@@ -5651,6 +6080,7 @@ var MastraStorageExporter = class extends BaseExporter {
5651
6080
  * are exported before the runtime instance is terminated.
5652
6081
  */
5653
6082
  async flush() {
6083
+ await Promise.allSettled([...this.#pendingAnnotations]);
5654
6084
  if (this.#byteTracker) {
5655
6085
  if (!this.#observabilityStorage) return;
5656
6086
  this.#byteDrainers++;
@@ -6077,8 +6507,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6077
6507
  * Internal hook used by RecordedTrace/RecordedSpan hydration to route
6078
6508
  * non-tracing annotation events back through the normal exporter pipeline.
6079
6509
  */
6080
- __emitRecordedEvent(event) {
6081
- this.emitObservabilityEvent(event);
6510
+ __emitRecordedEvent(event, shouldHandle) {
6511
+ if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
6512
+ else this.emitObservabilityEvent(event);
6082
6513
  }
6083
6514
  /**
6084
6515
  * Internal hook used by the client observability proxy (`client/`)
@@ -8661,6 +9092,41 @@ var PlatformByteBatcher = class {
8661
9092
  };
8662
9093
  }
8663
9094
  };
9095
+ // src/exporters/platform-resolved-record.ts
9096
+ /** Deliver one feedback or score record whose span context must be resolved by Platform. */
9097
+ async function publishResolvedRecord(url, body, headers, method = "POST") {
9098
+ const deadline = AbortSignal.timeout(3e4);
9099
+ for (let attempt = 0; attempt < 6; attempt++) {
9100
+ const response = await fetch(url, {
9101
+ method,
9102
+ headers,
9103
+ body,
9104
+ signal: deadline
9105
+ });
9106
+ if (response.ok) {
9107
+ await response.body?.cancel();
9108
+ return;
9109
+ }
9110
+ const error = await response.json().catch(() => null);
9111
+ const code = error?.code ?? error?.error?.code;
9112
+ if (!(response.status === 404 && (code === "TRACE_NOT_FOUND" || code === "SPAN_NOT_FOUND") || response.status === 503 && code === "ANCHOR_LOOKUP_UNAVAILABLE") || attempt === 5) throw new Error(`Platform record delivery failed: HTTP ${response.status}${code ? ` (${code})` : ""}`);
9113
+ const retryAfter = response.headers.get("retry-after");
9114
+ const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
9115
+ const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
9116
+ await new Promise((resolve, reject) => {
9117
+ deadline.throwIfAborted();
9118
+ const timer = setTimeout(() => {
9119
+ deadline.removeEventListener("abort", abort);
9120
+ resolve();
9121
+ }, Math.min(delay, 3e4));
9122
+ function abort() {
9123
+ clearTimeout(timer);
9124
+ reject(deadline.reason);
9125
+ }
9126
+ deadline.addEventListener("abort", abort, { once: true });
9127
+ });
9128
+ }
9129
+ }
8664
9130
  // src/exporters/mastra-platform.ts
8665
9131
  const SIGNAL_PUBLISH_SUFFIXES = {
8666
9132
  traces: "/spans/publish",
@@ -8780,6 +9246,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8780
9246
  buffer;
8781
9247
  flushTimer = null;
8782
9248
  inFlightFlushes = /* @__PURE__ */ new Set();
9249
+ pendingRecords = /* @__PURE__ */ new Set();
8783
9250
  quotaPaused = false;
8784
9251
  quotaProbeTimer = null;
8785
9252
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
@@ -8816,6 +9283,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8816
9283
  maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
8817
9284
  maxRetries: config.maxRetries ?? 3,
8818
9285
  accessToken: accessToken || "",
9286
+ projectId,
8819
9287
  tracesEndpoint,
8820
9288
  logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
8821
9289
  metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
@@ -8857,17 +9325,58 @@ var MastraPlatformExporter = class extends BaseExporter {
8857
9325
  await this.handleBufferedEvent();
8858
9326
  }
8859
9327
  async onScoreEvent(event) {
8860
- if (this.isDisabled) return;
9328
+ if (this.isDisabled || this.shuttingDown) return;
9329
+ if (event.score.correlationContext == null) {
9330
+ this.enqueueResolvedRecord("score", event.score);
9331
+ return;
9332
+ }
8861
9333
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8862
9334
  this.addScoreToBuffer(event);
8863
9335
  await this.handleBufferedEvent();
8864
9336
  }
8865
9337
  async onFeedbackEvent(event) {
8866
- if (this.isDisabled) return;
9338
+ if (this.isDisabled || this.shuttingDown) return;
9339
+ if (event.feedback.correlationContext == null) {
9340
+ this.enqueueResolvedRecord("feedback", event.feedback);
9341
+ return;
9342
+ }
8867
9343
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8868
9344
  this.addFeedbackToBuffer(event);
8869
9345
  await this.handleBufferedEvent();
8870
9346
  }
9347
+ onFeedbackReplacementEvent(event) {
9348
+ if (this.isDisabled || this.shuttingDown) return;
9349
+ if (!event.feedback.feedbackId?.trim()) {
9350
+ this.logger.warn("Dropping feedback replacement: feedbackId is required");
9351
+ return;
9352
+ }
9353
+ this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
9354
+ }
9355
+ enqueueResolvedRecord(kind, record, replacementId) {
9356
+ if (!record.traceId?.trim()) {
9357
+ this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
9358
+ return;
9359
+ }
9360
+ let body;
9361
+ try {
9362
+ body = JSON.stringify({ [kind]: record });
9363
+ } catch (error) {
9364
+ this.logger.warn(`Dropping unserializable ${kind}`, { error });
9365
+ return;
9366
+ }
9367
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9368
+ const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
9369
+ if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
9370
+ const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
9371
+ const headers = {
9372
+ Authorization: `Bearer ${this.platformConfig.accessToken}`,
9373
+ "Content-Type": "application/json",
9374
+ ...projectId ? { "X-Mastra-Project-Id": projectId } : {}
9375
+ };
9376
+ this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
9377
+ const pending = publishResolvedRecord(url, body, headers, replacementId !== void 0 ? "PUT" : "POST").catch((error) => this.logger.warn(`Dropping ${kind} after Platform delivery failed`, { error })).finally(() => this.pendingRecords.delete(pending));
9378
+ this.pendingRecords.add(pending);
9379
+ }
8871
9380
  addToBuffer(event) {
8872
9381
  if (this.byteBatcher) {
8873
9382
  this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
@@ -9208,6 +9717,13 @@ var MastraPlatformExporter = class extends BaseExporter {
9208
9717
  * are exported before the runtime instance is terminated.
9209
9718
  */
9210
9719
  async flush() {
9720
+ if (this.isDisabled) return;
9721
+ do {
9722
+ await this.flushBatches();
9723
+ await Promise.allSettled([...this.pendingRecords]);
9724
+ } while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
9725
+ }
9726
+ async flushBatches() {
9211
9727
  if (this.isDisabled) return;
9212
9728
  if (this.byteBatcher) {
9213
9729
  await this.byteBatcher.flush();
@@ -10160,463 +10676,159 @@ var TestExporter = class extends BaseExporter {
10160
10676
  path,
10161
10677
  expected,
10162
10678
  actual
10163
- });
10164
- }
10165
- /**
10166
- * Check if a value is an __or__ marker object
10167
- */
10168
- #isOrMarker(value) {
10169
- return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10170
- }
10171
- /**
10172
- * Check if a value is an __any__ marker object
10173
- */
10174
- #isAnyMarker(value) {
10175
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10176
- if (!("__any__" in value)) return false;
10177
- const constraint = value.__any__;
10178
- return constraint === true || [
10179
- "string",
10180
- "number",
10181
- "boolean",
10182
- "object",
10183
- "array"
10184
- ].includes(constraint);
10185
- }
10186
- /**
10187
- * Check if a key should be skipped during comparison (metadata keys like __structure__)
10188
- */
10189
- #isMetadataKey(key) {
10190
- return key.startsWith("__") && key.endsWith("__");
10191
- }
10192
- /**
10193
- * Custom JSON replacer to handle Date objects and other special types
10194
- */
10195
- #jsonReplacer = (_key, value) => {
10196
- if (value instanceof Date) return value.toISOString();
10197
- return value;
10198
- };
10199
- /**
10200
- * Get all stored debug logs (internal exporter logging, not signal logs)
10201
- */
10202
- getLogs() {
10203
- return [...this.#debugLogs];
10204
- }
10205
- /**
10206
- * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10207
- */
10208
- dumpLogs() {
10209
- console.error("\n=== TestExporter Logs ===");
10210
- this.#debugLogs.forEach((log) => {
10211
- console.error(log);
10212
- });
10213
- console.error("=== End Logs ===\n");
10214
- }
10215
- /**
10216
- * Validate final state - useful for test assertions
10217
- *
10218
- * @returns Object with validation results
10219
- */
10220
- validateFinalState() {
10221
- const traceIds = this.getTraceIds();
10222
- const incompleteSpans = this.getIncompleteSpans();
10223
- const singleTraceId = traceIds.length === 1;
10224
- const allSpansComplete = incompleteSpans.length === 0;
10225
- return {
10226
- valid: singleTraceId && allSpansComplete,
10227
- singleTraceId,
10228
- allSpansComplete,
10229
- traceIds,
10230
- incompleteSpans
10231
- };
10679
+ });
10232
10680
  }
10233
10681
  /**
10234
- * Clear all collected events and state across all signals
10682
+ * Check if a value is an __or__ marker object
10235
10683
  */
10236
- clearEvents() {
10237
- this.#tracingEvents = [];
10238
- this.#spanStates.clear();
10239
- this.#logEvents = [];
10240
- this.#metricEvents = [];
10241
- this.#scoreEvents = [];
10242
- this.#feedbackEvents = [];
10243
- this.#debugLogs = [];
10684
+ #isOrMarker(value) {
10685
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10244
10686
  }
10245
10687
  /**
10246
- * Alias for clearEvents (compatibility with TestExporter)
10688
+ * Check if a value is an __any__ marker object
10247
10689
  */
10248
- reset() {
10249
- this.clearEvents();
10690
+ #isAnyMarker(value) {
10691
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10692
+ if (!("__any__" in value)) return false;
10693
+ const constraint = value.__any__;
10694
+ return constraint === true || [
10695
+ "string",
10696
+ "number",
10697
+ "boolean",
10698
+ "object",
10699
+ "array"
10700
+ ].includes(constraint);
10250
10701
  }
10251
10702
  /**
10252
- * Get internal metrics about the exporter's own activity.
10703
+ * Check if a key should be skipped during comparison (metadata keys like __structure__)
10253
10704
  */
10254
- getInternalMetrics() {
10255
- const json = this.toJSON({
10256
- includeEvents: false,
10257
- includeStats: false
10258
- });
10259
- return {
10260
- startedAt: this.#internalMetrics.startedAt,
10261
- lastEventAt: this.#internalMetrics.lastEventAt,
10262
- totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10263
- bySignal: { ...this.#internalMetrics.bySignal },
10264
- flushCount: this.#internalMetrics.flushCount,
10265
- estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10266
- };
10705
+ #isMetadataKey(key) {
10706
+ return key.startsWith("__") && key.endsWith("__");
10267
10707
  }
10268
10708
  /**
10269
- * Flush buffered data and log internal metrics summary.
10709
+ * Custom JSON replacer to handle Date objects and other special types
10270
10710
  */
10271
- async flush() {
10272
- this.#internalMetrics.flushCount++;
10273
- if (this.#config.logMetricsOnFlush) {
10274
- const metrics = this.getInternalMetrics();
10275
- const uptimeMs = Date.now() - metrics.startedAt.getTime();
10276
- const summary = [
10277
- `[TestExporter] flush #${metrics.flushCount} summary:`,
10278
- ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10279
- ` total events received: ${metrics.totalEventsReceived}`,
10280
- ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10281
- ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10282
- ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10283
- ].join("\n");
10284
- this.logger.info(summary);
10285
- }
10286
- }
10287
- async shutdown() {
10288
- await this.flush();
10289
- this.logger.info("TestExporter shutdown");
10290
- }
10711
+ #jsonReplacer = (_key, value) => {
10712
+ if (value instanceof Date) return value.toISOString();
10713
+ return value;
10714
+ };
10291
10715
  /**
10292
- * Extract unique spans from a list of events
10716
+ * Get all stored debug logs (internal exporter logging, not signal logs)
10293
10717
  */
10294
- #getUniqueSpansFromEvents(events) {
10295
- const spanMap = /* @__PURE__ */ new Map();
10296
- for (const event of events) {
10297
- const span = event.exportedSpan;
10298
- if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10299
- }
10300
- return Array.from(spanMap.values());
10301
- }
10302
- };
10303
- /**
10304
- * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10305
- */
10306
- const JsonExporter = TestExporter;
10307
- // src/instances/default.ts
10308
- var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10309
- constructor(config) {
10310
- super(config);
10311
- }
10312
- createSpan(options) {
10313
- return new DefaultSpan(options, this);
10718
+ getLogs() {
10719
+ return [...this.#debugLogs];
10314
10720
  }
10315
- };
10316
- // src/recorded.ts
10317
- function nullToUndefined(value) {
10318
- return value ?? void 0;
10319
- }
10320
- function mergeMetadata(base, extra) {
10321
- if (!base && !extra) return void 0;
10322
- return {
10323
- ...base ?? {},
10324
- ...extra ?? {}
10325
- };
10326
- }
10327
- function normalizeErrorInfo(error) {
10328
- if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
10329
- return {
10330
- message: error.message,
10331
- id: "id" in error && typeof error.id === "string" ? error.id : void 0,
10332
- name: "name" in error && typeof error.name === "string" ? error.name : void 0,
10333
- stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
10334
- domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
10335
- category: "category" in error && typeof error.category === "string" ? error.category : void 0,
10336
- details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
10337
- };
10338
- }
10339
- function buildCorrelationContext(span, rootSpan, parent) {
10340
- return {
10341
- tags: rootSpan.tags ?? void 0,
10342
- entityType: nullToUndefined(span.entityType),
10343
- entityId: nullToUndefined(span.entityId),
10344
- entityName: nullToUndefined(span.entityName),
10345
- parentEntityType: parent?.entityType ?? void 0,
10346
- parentEntityId: parent?.entityId ?? void 0,
10347
- parentEntityName: parent?.entityName ?? void 0,
10348
- rootEntityType: nullToUndefined(rootSpan.entityType),
10349
- rootEntityId: nullToUndefined(rootSpan.entityId),
10350
- rootEntityName: nullToUndefined(rootSpan.entityName),
10351
- userId: nullToUndefined(span.userId),
10352
- organizationId: nullToUndefined(span.organizationId),
10353
- resourceId: nullToUndefined(span.resourceId),
10354
- runId: nullToUndefined(span.runId),
10355
- sessionId: nullToUndefined(span.sessionId),
10356
- threadId: nullToUndefined(span.threadId),
10357
- requestId: nullToUndefined(span.requestId),
10358
- environment: nullToUndefined(span.environment),
10359
- source: nullToUndefined(span.source),
10360
- serviceName: nullToUndefined(span.serviceName),
10361
- experimentId: nullToUndefined(span.experimentId)
10362
- };
10363
- }
10364
- function buildScoreEvent(args) {
10365
- const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
10366
- return {
10367
- type: "score",
10368
- score: {
10369
- scoreId: generateSignalId(),
10370
- timestamp: /* @__PURE__ */ new Date(),
10371
- traceId,
10372
- spanId,
10373
- scorerId: score.scorerId,
10374
- scorerName: score.scorerName,
10375
- scorerVersion: score.scorerVersion,
10376
- source: score.source,
10377
- scoreSource: score.scoreSource,
10378
- score: score.score,
10379
- reason: score.reason,
10380
- experimentId: score.experimentId,
10381
- scoreTraceId: score.scoreTraceId,
10382
- targetEntityType: score.targetEntityType,
10383
- correlationContext,
10384
- metadata: mergeMetadata(inheritedMetadata, score.metadata)
10385
- }
10386
- };
10387
- }
10388
- function buildFeedbackEvent(args) {
10389
- const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
10390
- return {
10391
- type: "feedback",
10392
- feedback: {
10393
- feedbackId: generateSignalId(),
10394
- timestamp: /* @__PURE__ */ new Date(),
10395
- traceId,
10396
- spanId,
10397
- source: feedback.source,
10398
- feedbackSource: feedback.feedbackSource,
10399
- feedbackType: feedback.feedbackType,
10400
- value: feedback.value,
10401
- userId: feedback.userId,
10402
- feedbackUserId: feedback.feedbackUserId,
10403
- comment: feedback.comment,
10404
- sourceId: feedback.sourceId,
10405
- experimentId: feedback.experimentId,
10406
- correlationContext,
10407
- metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
10408
- }
10409
- };
10410
- }
10411
- function findSpanById(spans, spanId) {
10412
- if (!spanId) return void 0;
10413
- return spans.find((span) => span.spanId === spanId);
10414
- }
10415
- function buildRecordedScoreEventFromTrace(args) {
10416
- const rootSpan = findRootSpan(args.trace.spans);
10417
- if (!rootSpan) return null;
10418
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10419
- if (!span) return null;
10420
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10421
- return buildScoreEvent({
10422
- traceId: span.traceId,
10423
- spanId: args.spanId,
10424
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10425
- score: args.score,
10426
- inheritedMetadata: span.metadata
10427
- });
10428
- }
10429
- function buildRecordedFeedbackEventFromTrace(args) {
10430
- const rootSpan = findRootSpan(args.trace.spans);
10431
- if (!rootSpan) return null;
10432
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10433
- if (!span) return null;
10434
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10435
- return buildFeedbackEvent({
10436
- traceId: span.traceId,
10437
- spanId: args.spanId,
10438
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10439
- feedback: args.feedback,
10440
- inheritedMetadata: span.metadata
10441
- });
10442
- }
10443
- var RecordedSpanImpl = class {
10444
- id;
10445
- traceId;
10446
- name;
10447
- type;
10448
- entityType;
10449
- entityId;
10450
- entityName;
10451
- startTime;
10452
- endTime;
10453
- attributes;
10454
- metadata;
10455
- tags;
10456
- input;
10457
- output;
10458
- errorInfo;
10459
- requestContext;
10460
- isEvent;
10461
- isRootSpan;
10462
- parentSpanId;
10463
- parent;
10464
- children = [];
10465
- #raw;
10466
- #rootSpan;
10467
- #emitRecordedEvent;
10468
- #canEmitRecordedEvent;
10469
- #debugRecordedAnnotationUnavailable;
10470
- constructor(args) {
10471
- const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
10472
- this.#raw = raw;
10473
- this.#rootSpan = rootSpan;
10474
- this.#emitRecordedEvent = emitRecordedEvent;
10475
- this.#canEmitRecordedEvent = canEmitRecordedEvent;
10476
- this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
10477
- this.id = raw.spanId;
10478
- this.traceId = raw.traceId;
10479
- this.name = raw.name;
10480
- this.type = raw.spanType;
10481
- this.entityType = raw.entityType ?? void 0;
10482
- this.entityId = raw.entityId ?? void 0;
10483
- this.entityName = raw.entityName ?? void 0;
10484
- this.startTime = raw.startedAt;
10485
- this.endTime = raw.endedAt ?? void 0;
10486
- this.attributes = raw.attributes ?? void 0;
10487
- this.metadata = raw.metadata ?? void 0;
10488
- this.tags = raw.tags ?? void 0;
10489
- this.input = raw.input ?? void 0;
10490
- this.output = raw.output ?? void 0;
10491
- this.errorInfo = normalizeErrorInfo(raw.error);
10492
- this.requestContext = raw.requestContext ?? void 0;
10493
- this.isEvent = raw.isEvent;
10494
- this.isRootSpan = !raw.parentSpanId;
10495
- this.parentSpanId = raw.parentSpanId ?? void 0;
10721
+ /**
10722
+ * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10723
+ */
10724
+ dumpLogs() {
10725
+ console.error("\n=== TestExporter Logs ===");
10726
+ this.#debugLogs.forEach((log) => {
10727
+ console.error(log);
10728
+ });
10729
+ console.error("=== End Logs ===\n");
10496
10730
  }
10497
- async addScore(score) {
10498
- if (!this.#canEmitRecordedEvent()) {
10499
- this.#debugRecordedAnnotationUnavailable({
10500
- kind: "score",
10501
- traceId: this.traceId,
10502
- spanId: this.id
10503
- });
10504
- return;
10505
- }
10506
- await this.#emitRecordedEvent(buildScoreEvent({
10507
- traceId: this.#raw.traceId,
10508
- spanId: this.id,
10509
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10510
- score,
10511
- inheritedMetadata: this.#raw.metadata
10512
- }));
10731
+ /**
10732
+ * Validate final state - useful for test assertions
10733
+ *
10734
+ * @returns Object with validation results
10735
+ */
10736
+ validateFinalState() {
10737
+ const traceIds = this.getTraceIds();
10738
+ const incompleteSpans = this.getIncompleteSpans();
10739
+ const singleTraceId = traceIds.length === 1;
10740
+ const allSpansComplete = incompleteSpans.length === 0;
10741
+ return {
10742
+ valid: singleTraceId && allSpansComplete,
10743
+ singleTraceId,
10744
+ allSpansComplete,
10745
+ traceIds,
10746
+ incompleteSpans
10747
+ };
10513
10748
  }
10514
- async addFeedback(feedback) {
10515
- if (!this.#canEmitRecordedEvent()) {
10516
- this.#debugRecordedAnnotationUnavailable({
10517
- kind: "feedback",
10518
- traceId: this.traceId,
10519
- spanId: this.id
10520
- });
10521
- return;
10522
- }
10523
- await this.#emitRecordedEvent(buildFeedbackEvent({
10524
- traceId: this.#raw.traceId,
10525
- spanId: this.id,
10526
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10527
- feedback,
10528
- inheritedMetadata: this.#raw.metadata
10529
- }));
10749
+ /**
10750
+ * Clear all collected events and state across all signals
10751
+ */
10752
+ clearEvents() {
10753
+ this.#tracingEvents = [];
10754
+ this.#spanStates.clear();
10755
+ this.#logEvents = [];
10756
+ this.#metricEvents = [];
10757
+ this.#scoreEvents = [];
10758
+ this.#feedbackEvents = [];
10759
+ this.#debugLogs = [];
10530
10760
  }
10531
- };
10532
- var RecordedTraceImpl = class {
10533
- traceId;
10534
- rootSpan;
10535
- spans;
10536
- #rootRecord;
10537
- #emitRecordedEvent;
10538
- #spanMap;
10539
- #canEmitRecordedEvent;
10540
- #debugRecordedAnnotationUnavailable;
10541
- constructor(args) {
10542
- this.traceId = args.traceId;
10543
- this.rootSpan = args.rootSpan;
10544
- this.#rootRecord = args.rootRecord;
10545
- this.spans = args.spans;
10546
- this.#emitRecordedEvent = args.emitRecordedEvent;
10547
- this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
10548
- this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
10549
- this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
10761
+ /**
10762
+ * Alias for clearEvents (compatibility with TestExporter)
10763
+ */
10764
+ reset() {
10765
+ this.clearEvents();
10550
10766
  }
10551
- getSpan(spanId) {
10552
- return this.#spanMap.get(spanId) ?? null;
10767
+ /**
10768
+ * Get internal metrics about the exporter's own activity.
10769
+ */
10770
+ getInternalMetrics() {
10771
+ const json = this.toJSON({
10772
+ includeEvents: false,
10773
+ includeStats: false
10774
+ });
10775
+ return {
10776
+ startedAt: this.#internalMetrics.startedAt,
10777
+ lastEventAt: this.#internalMetrics.lastEventAt,
10778
+ totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10779
+ bySignal: { ...this.#internalMetrics.bySignal },
10780
+ flushCount: this.#internalMetrics.flushCount,
10781
+ estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10782
+ };
10553
10783
  }
10554
- async addScore(score) {
10555
- if (!this.#canEmitRecordedEvent()) {
10556
- this.#debugRecordedAnnotationUnavailable({
10557
- kind: "score",
10558
- traceId: this.traceId
10559
- });
10560
- return;
10784
+ /**
10785
+ * Flush buffered data and log internal metrics summary.
10786
+ */
10787
+ async flush() {
10788
+ this.#internalMetrics.flushCount++;
10789
+ if (this.#config.logMetricsOnFlush) {
10790
+ const metrics = this.getInternalMetrics();
10791
+ const uptimeMs = Date.now() - metrics.startedAt.getTime();
10792
+ const summary = [
10793
+ `[TestExporter] flush #${metrics.flushCount} summary:`,
10794
+ ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10795
+ ` total events received: ${metrics.totalEventsReceived}`,
10796
+ ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10797
+ ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10798
+ ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10799
+ ].join("\n");
10800
+ this.logger.info(summary);
10561
10801
  }
10562
- await this.#emitRecordedEvent(buildScoreEvent({
10563
- traceId: this.#rootRecord.traceId,
10564
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10565
- score,
10566
- inheritedMetadata: this.#rootRecord.metadata
10567
- }));
10568
10802
  }
10569
- async addFeedback(feedback) {
10570
- if (!this.#canEmitRecordedEvent()) {
10571
- this.#debugRecordedAnnotationUnavailable({
10572
- kind: "feedback",
10573
- traceId: this.traceId
10574
- });
10575
- return;
10803
+ async shutdown() {
10804
+ await this.flush();
10805
+ this.logger.info("TestExporter shutdown");
10806
+ }
10807
+ /**
10808
+ * Extract unique spans from a list of events
10809
+ */
10810
+ #getUniqueSpansFromEvents(events) {
10811
+ const spanMap = /* @__PURE__ */ new Map();
10812
+ for (const event of events) {
10813
+ const span = event.exportedSpan;
10814
+ if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10576
10815
  }
10577
- await this.#emitRecordedEvent(buildFeedbackEvent({
10578
- traceId: this.#rootRecord.traceId,
10579
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10580
- feedback,
10581
- inheritedMetadata: this.#rootRecord.metadata
10582
- }));
10816
+ return Array.from(spanMap.values());
10583
10817
  }
10584
10818
  };
10585
- function findRootSpan(spans) {
10586
- const spanIds = new Set(spans.map((span) => span.spanId));
10587
- return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
10588
- }
10589
- function hydrateRecordedTrace(args) {
10590
- const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
10591
- const rootSpan = findRootSpan(trace.spans);
10592
- if (!rootSpan) return null;
10593
- const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
10594
- raw,
10595
- rootSpan,
10596
- emitRecordedEvent,
10597
- canEmitRecordedEvent,
10598
- debugRecordedAnnotationUnavailable
10599
- }));
10600
- const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
10601
- for (const span of recordedSpans) {
10602
- if (!span.parentSpanId) continue;
10603
- const parent = spanMap.get(span.parentSpanId);
10604
- if (!parent) continue;
10605
- span.parent = parent;
10606
- parent.children.push(span);
10819
+ /**
10820
+ * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10821
+ */
10822
+ const JsonExporter = TestExporter;
10823
+ // src/instances/default.ts
10824
+ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10825
+ constructor(config) {
10826
+ super(config);
10607
10827
  }
10608
- const hydratedRootSpan = spanMap.get(rootSpan.spanId);
10609
- if (!hydratedRootSpan) return null;
10610
- return new RecordedTraceImpl({
10611
- traceId: trace.traceId,
10612
- rootSpan: hydratedRootSpan,
10613
- rootRecord: rootSpan,
10614
- spans: recordedSpans,
10615
- emitRecordedEvent,
10616
- canEmitRecordedEvent,
10617
- debugRecordedAnnotationUnavailable
10618
- });
10619
- }
10828
+ createSpan(options) {
10829
+ return new DefaultSpan(options, this);
10830
+ }
10831
+ };
10620
10832
  // src/registry.ts
10621
10833
  /**
10622
10834
  * Registry for Observability instances.
@@ -10923,23 +11135,6 @@ function isInstance(obj) {
10923
11135
  return obj instanceof BaseObservabilityInstance;
10924
11136
  }
10925
11137
  /**
10926
- * Delays (ms) between attempts to rehydrate a trace from storage when an
10927
- * annotation (score/feedback) targets a span that has not been flushed by
10928
- * the configured exporters yet. Exporters buffer and flush asynchronously:
10929
- * by default they flush at 1000 spans or after a 5000ms wait
10930
- * (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
10931
- * race the flush and be silently dropped. The schedule below sums to
10932
- * ~5.85s, covering the default flush interval with margin.
10933
- */
10934
- const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
10935
- 100,
10936
- 250,
10937
- 500,
10938
- 1e3,
10939
- 2e3,
10940
- 2e3
10941
- ];
10942
- /**
10943
11138
  * Manages observability instances and selects their configurations for Mastra operations.
10944
11139
  * Configure instances and exporters to collect and export telemetry.
10945
11140
  *
@@ -10966,6 +11161,7 @@ var Observability = class extends _mastra_core_base.MastraBase {
10966
11161
  #registry = new ObservabilityRegistry();
10967
11162
  #mastra;
10968
11163
  #clientObservabilityProxy;
11164
+ #pendingPersistedEvents = /* @__PURE__ */ new Set();
10969
11165
  constructor(config) {
10970
11166
  super({
10971
11167
  component: _mastra_core_logger.RegisteredLogger.OBSERVABILITY,
@@ -11106,50 +11302,47 @@ var Observability = class extends _mastra_core_base.MastraBase {
11106
11302
  async addScore(args) {
11107
11303
  const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11108
11304
  const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11109
- if (args.correlationContext) {
11110
- await this.#emitRecordedEvent(buildScoreEvent({
11111
- ...targetTraceId ? { traceId: targetTraceId } : {},
11112
- ...targetSpanId ? { spanId: targetSpanId } : {},
11113
- correlationContext: args.correlationContext,
11114
- score: args.score
11115
- }));
11116
- return;
11117
- }
11118
- if (!args.traceId) return;
11119
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
11120
- trace,
11121
- spanId: args.spanId,
11122
- score: args.score
11305
+ if (!targetTraceId && !args.correlationContext) return;
11306
+ await this.#emitRecordedEvent(buildScoreEvent({
11307
+ ...args,
11308
+ traceId: targetTraceId,
11309
+ spanId: targetSpanId
11123
11310
  }));
11124
- if (!event) {
11125
- this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11126
- return;
11127
- }
11128
- await this.#emitRecordedEvent(event);
11129
11311
  }
11130
11312
  async addFeedback(args) {
11131
- const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11132
- const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11133
- if (args.correlationContext) {
11134
- await this.#emitRecordedEvent(buildFeedbackEvent({
11135
- ...targetTraceId ? { traceId: targetTraceId } : {},
11136
- ...targetSpanId ? { spanId: targetSpanId } : {},
11137
- correlationContext: args.correlationContext,
11138
- feedback: args.feedback
11139
- }));
11140
- return;
11141
- }
11142
- if (!args.traceId) return;
11143
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
11144
- trace,
11145
- spanId: args.spanId,
11146
- feedback: args.feedback
11313
+ const traceId = args.traceId ?? args.correlationContext?.traceId;
11314
+ const spanId = args.spanId ?? args.correlationContext?.spanId;
11315
+ if (!traceId && !args.correlationContext) return;
11316
+ await this.#emitRecordedEvent(buildFeedbackEvent({
11317
+ ...args,
11318
+ traceId,
11319
+ spanId
11147
11320
  }));
11148
- if (!event) {
11149
- this.logger?.warn(`Feedback event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11150
- return;
11151
- }
11152
- await this.#emitRecordedEvent(event);
11321
+ }
11322
+ async replaceFeedback(args) {
11323
+ if (!args.traceId?.trim() || !args.feedback.feedbackId?.trim() || !Number.isFinite(args.feedback.timestamp?.getTime())) throw new Error("Feedback replacement requires traceId, feedbackId, and the original timestamp");
11324
+ await this.#emitRecordedEvent({
11325
+ type: "feedback_replacement",
11326
+ feedback: {
11327
+ ...args.feedback,
11328
+ traceId: args.traceId,
11329
+ spanId: args.spanId,
11330
+ correlationContext: args.correlationContext
11331
+ }
11332
+ });
11333
+ }
11334
+ /** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
11335
+ async __exportPersistedEvent(event) {
11336
+ const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
11337
+ const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
11338
+ this.#pendingPersistedEvents.add(pending);
11339
+ pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
11340
+ this.#pendingPersistedEvents.delete(pending);
11341
+ this.logger.error("Failed to notify exporters of persisted feedback/score", {
11342
+ error,
11343
+ eventType: event.type
11344
+ });
11345
+ });
11153
11346
  }
11154
11347
  /** Register a named observability instance, optionally marking it as default. */
11155
11348
  registerInstance(name, instance, isDefault = false) {
@@ -11186,12 +11379,18 @@ var Observability = class extends _mastra_core_base.MastraBase {
11186
11379
  }
11187
11380
  /** Flush all registered instances without shutting down. */
11188
11381
  async flush() {
11382
+ await this.#drainPersistedEvents();
11189
11383
  await this.#registry.flush();
11190
11384
  }
11191
11385
  /** Shut down all registered instances, flushing any pending data. */
11192
11386
  async shutdown() {
11387
+ await this.#drainPersistedEvents();
11193
11388
  await this.#registry.shutdown();
11194
11389
  }
11390
+ /** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
11391
+ async #drainPersistedEvents() {
11392
+ while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
11393
+ }
11195
11394
  /**
11196
11395
  * Returns the proxy responsible for client observability (W3C trace
11197
11396
  * context injection + OTLP/JSON payload reception for spans/logs
@@ -11213,40 +11412,22 @@ var Observability = class extends _mastra_core_base.MastraBase {
11213
11412
  if (!storage) return null;
11214
11413
  return await storage.getStore("observability") ?? null;
11215
11414
  }
11216
- /**
11217
- * Build a recorded score/feedback event from storage, retrying briefly to
11218
- * ride out the async exporter flush: annotations emitted right after a
11219
- * span ends can otherwise race the flush and be silently dropped.
11220
- */
11221
- async #buildRecordedEventWithRetry(traceId, build) {
11222
- for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
11223
- if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
11224
- const trace = await this.#getStoredTrace(traceId);
11225
- const event = trace ? build(trace) : null;
11226
- if (event) return event;
11227
- }
11228
- return null;
11229
- }
11230
- async #getStoredTrace(traceId) {
11231
- const observabilityStorage = await this.#getObservabilityStorage();
11232
- if (!observabilityStorage) return null;
11233
- return observabilityStorage.getTrace({ traceId });
11234
- }
11235
11415
  #getRecordedTraceInstance() {
11236
11416
  return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
11237
11417
  }
11238
- async #emitRecordedEvent(event) {
11418
+ /** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
11419
+ async #emitRecordedEvent(event, shouldHandle) {
11239
11420
  const instance = this.#getRecordedTraceInstance();
11240
11421
  if (!instance) {
11241
11422
  this.logger?.debug(event.type === "score" ? "Score event was dropped because no observability instance is registered" : "Feedback event was dropped because no observability instance is registered", { eventType: event.type });
11242
11423
  return;
11243
11424
  }
11244
11425
  if (instance instanceof BaseObservabilityInstance) {
11245
- instance.__emitRecordedEvent(event);
11426
+ instance.__emitRecordedEvent(event, shouldHandle);
11246
11427
  return;
11247
11428
  }
11248
11429
  const bridge = instance.getBridge();
11249
- const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11430
+ const handlerResults = [...instance.getExporters().filter((exporter) => !shouldHandle || shouldHandle(exporter)).map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge && (!shouldHandle || shouldHandle(bridge)) ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11250
11431
  if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
11251
11432
  }
11252
11433
  };