@mastra/observability 1.24.0-alpha.4 → 1.24.0-alpha.6

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 (39) 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 +5 -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 +63 -53
  8. package/dist/docs/references/docs-observability-feedback.md +5 -7
  9. package/dist/docs/references/reference-observability-feedback.md +57 -14
  10. package/dist/docs/references/reference-observability-tracing-exporters-langfuse.md +24 -1
  11. package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +19 -16
  12. package/dist/exporters/default.d.ts +6 -7
  13. package/dist/exporters/default.d.ts.map +1 -1
  14. package/dist/exporters/event-buffer.d.ts +5 -2
  15. package/dist/exporters/event-buffer.d.ts.map +1 -1
  16. package/dist/exporters/keyed-queue.d.ts +6 -0
  17. package/dist/exporters/keyed-queue.d.ts.map +1 -0
  18. package/dist/exporters/mastra-platform.d.ts +8 -1
  19. package/dist/exporters/mastra-platform.d.ts.map +1 -1
  20. package/dist/exporters/mastra-storage.d.ts +6 -7
  21. package/dist/exporters/mastra-storage.d.ts.map +1 -1
  22. package/dist/exporters/platform-resolved-record.d.ts +3 -0
  23. package/dist/exporters/platform-resolved-record.d.ts.map +1 -0
  24. package/dist/exporters/storage-annotation.d.ts +12 -0
  25. package/dist/exporters/storage-annotation.d.ts.map +1 -0
  26. package/dist/exporters/storage-byte-tracker.d.ts +2 -3
  27. package/dist/exporters/storage-byte-tracker.d.ts.map +1 -1
  28. package/dist/index.cjs +994 -708
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.js +993 -709
  31. package/dist/index.js.map +1 -1
  32. package/dist/instances/base.d.ts +2 -1
  33. package/dist/instances/base.d.ts.map +1 -1
  34. package/dist/recorded.d.ts +4 -12
  35. package/dist/recorded.d.ts.map +1 -1
  36. package/dist/spans/base.d.ts +9 -0
  37. package/dist/spans/base.d.ts.map +1 -1
  38. package/dist/spans/default.d.ts.map +1 -1
  39. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -77,6 +77,12 @@ function routeToHandler(handler, event, logger) {
77
77
  }), handler.name, "score", logger);
78
78
  }
79
79
  break;
80
+ case "feedback_review_status":
81
+ if (handler.onFeedbackReviewStatusEvent) return catchAsyncResult(handler.onFeedbackReviewStatusEvent(event), handler.name, "feedback review status", logger);
82
+ break;
83
+ case "feedback_replacement":
84
+ if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
85
+ break;
80
86
  case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
81
87
  }
82
88
  } catch (err) {
@@ -577,6 +583,14 @@ function cleanEvent(event, options) {
577
583
  type: "score",
578
584
  score: deepClean(event.score, options)
579
585
  };
586
+ case "feedback_review_status": return {
587
+ type: event.type,
588
+ feedback: deepClean(event.feedback, options)
589
+ };
590
+ case "feedback_replacement": return {
591
+ type: event.type,
592
+ feedback: deepClean(event.feedback, options)
593
+ };
580
594
  case "feedback": return {
581
595
  type: "feedback",
582
596
  feedback: deepClean(event.feedback, options)
@@ -669,10 +683,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
669
683
  * emit() is synchronous — async handler promises are tracked internally
670
684
  * and can be drained via flush().
671
685
  */
672
- emit(event) {
686
+ emit(event, shouldHandle) {
673
687
  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));
688
+ for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
689
+ if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
676
690
  super.emit(cleaned);
677
691
  }
678
692
  /**
@@ -3444,6 +3458,34 @@ function mergeMetadata$1(parentMetadata, metadata) {
3444
3458
  }
3445
3459
  }
3446
3460
  // src/spans/base.ts
3461
+ /** Replaces error text exported from traces that hide input or output. */
3462
+ const REDACTED_ERROR_MESSAGE = "[REDACTED]";
3463
+ /**
3464
+ * The error as exported from a trace that hides input or output: keeps what
3465
+ * identifies the error (id, name, domain, category, stack frames) and drops
3466
+ * text and free-form details, which can quote the hidden data.
3467
+ */
3468
+ function redactErrorInfo(errorInfo, stackMessage) {
3469
+ if (!errorInfo) return errorInfo;
3470
+ const { id, name, domain, category, stack } = errorInfo;
3471
+ return {
3472
+ ...id !== void 0 ? { id } : {},
3473
+ ...name !== void 0 ? { name } : {},
3474
+ ...domain !== void 0 ? { domain } : {},
3475
+ ...category !== void 0 ? { category } : {},
3476
+ message: REDACTED_ERROR_MESSAGE,
3477
+ ...stack !== void 0 ? { stack: redactStackHeader(stack, stackMessage ?? errorInfo.message, errorInfo.name) } : {}
3478
+ };
3479
+ }
3480
+ /** Preserve stack frames only when they follow the complete captured message. */
3481
+ function redactStackHeader(stack, message, name = "Error") {
3482
+ const redactedHeader = `${name}: ${REDACTED_ERROR_MESSAGE}`;
3483
+ const separator = `: ${message}`;
3484
+ const separatorIndex = stack.indexOf(separator);
3485
+ if (separatorIndex <= 0 || stack.slice(0, separatorIndex).includes("\n")) return redactedHeader;
3486
+ const suffix = stack.slice(separatorIndex + separator.length);
3487
+ return suffix === "" || suffix.startsWith("\n") ? `${redactedHeader}${suffix}` : redactedHeader;
3488
+ }
3447
3489
  const LINEAGE_KEYS = [
3448
3490
  "parentEntityType",
3449
3491
  "parentEntityId",
@@ -3573,6 +3615,7 @@ var BaseSpan = class BaseSpan {
3573
3615
  stopReason;
3574
3616
  stopReasonContext;
3575
3617
  errorInfo;
3618
+ errorStackMessage;
3576
3619
  metadata;
3577
3620
  requestContext;
3578
3621
  tags;
@@ -3960,7 +4003,7 @@ var BaseSpan = class BaseSpan {
3960
4003
  endTime: this.endTime,
3961
4004
  input: hideInput ? void 0 : this.input,
3962
4005
  output: hideOutput ? void 0 : this.output,
3963
- errorInfo: this.errorInfo,
4006
+ errorInfo: hideInput || hideOutput ? redactErrorInfo(this.errorInfo, this.errorStackMessage) : this.errorInfo,
3964
4007
  ...this.outcome !== void 0 ? { outcome: this.outcome } : {},
3965
4008
  ...this.stopReason !== void 0 ? { stopReason: this.stopReason } : {},
3966
4009
  ...this.stopReasonContext !== void 0 ? { stopReasonContext: this.stopReasonContext } : {},
@@ -4112,6 +4155,8 @@ var DefaultSpan = class extends BaseSpan {
4112
4155
  };
4113
4156
  if (!this.isExcluded) {
4114
4157
  const apiDetails = apiCallErrorDetails(error);
4158
+ const stackError = error instanceof _mastra_core_error.MastraError && error.cause instanceof Error && error.cause.stack ? error.cause : error;
4159
+ this.errorStackMessage = stackError.message;
4115
4160
  this.errorInfo = deepClean(error instanceof _mastra_core_error.MastraError ? {
4116
4161
  id: error.id,
4117
4162
  details: apiDetails ? {
@@ -4122,7 +4167,7 @@ var DefaultSpan = class extends BaseSpan {
4122
4167
  domain: error.domain,
4123
4168
  message: error.message,
4124
4169
  name: error.name,
4125
- stack: error.cause instanceof Error && error.cause.stack || error.stack
4170
+ stack: stackError.stack
4126
4171
  } : {
4127
4172
  message: error.message,
4128
4173
  name: error.name,
@@ -4624,175 +4669,555 @@ var EventBuffer = class {
4624
4669
  });
4625
4670
  }
4626
4671
  };
4627
- // src/exporters/default.ts
4628
- /**
4629
- * Resolves the final tracing storage strategy based on config and observability store hints
4630
- */
4631
- function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4632
- const observabilityStrategy = observabilityStorage.observabilityStrategy;
4633
- if (config.strategy && config.strategy !== "auto") {
4634
- if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4635
- logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4636
- userStrategy: config.strategy,
4637
- storageAdapter: storageName,
4638
- supportedStrategies: observabilityStrategy.supported,
4639
- fallbackStrategy: observabilityStrategy.preferred
4640
- });
4641
- }
4642
- return observabilityStrategy.preferred;
4643
- }
4644
- const FLUSH_SUCCEEDED$1 = { failed: false };
4645
- /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
4646
- const MAX_FLUSH_ROUNDS$1 = 3;
4647
- /**
4648
- * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
4649
- * This class is preserved unchanged so existing integrations (including code
4650
- * that matches on the `mastra-default-observability-exporter` exporter name)
4651
- * keep working. It will be removed in a future major version.
4652
- *
4653
- * Default storage-backed exporter. Buffers observability events and flushes them
4654
- * in batches to the configured ObservabilityStorage backend with retry support.
4655
- */
4656
- var DefaultExporter = class extends BaseExporter {
4657
- name = "mastra-default-observability-exporter";
4658
- #config;
4659
- #isInitializing = false;
4660
- #initPromises = /* @__PURE__ */ new Set();
4661
- #eventBuffer;
4662
- #storage;
4663
- #observabilityStorage;
4664
- #resolvedStrategy;
4665
- #flushTimer;
4666
- /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
4667
- #inFlightFlushes = /* @__PURE__ */ new Set();
4668
- #emitDropEvent;
4669
- #unsupportedSignals = /* @__PURE__ */ new Set();
4670
- constructor(config = {}) {
4671
- super(config);
4672
- this.#config = {
4673
- ...config,
4674
- maxBatchSize: config.maxBatchSize ?? 1e3,
4675
- maxBufferSize: config.maxBufferSize ?? 1e4,
4676
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
4677
- maxRetries: config.maxRetries ?? 4,
4678
- retryDelayMs: config.retryDelayMs ?? 500,
4679
- strategy: config.strategy ?? "auto"
4672
+ // src/exporters/keyed-queue.ts
4673
+ /** Keep writes to one record ordered without blocking unrelated records. */
4674
+ var KeyedQueue = class {
4675
+ pending = /* @__PURE__ */ new Map();
4676
+ enqueue(key, write) {
4677
+ const current = (this.pending.get(key) ?? Promise.resolve()).catch(() => {}).then(write);
4678
+ this.pending.set(key, current);
4679
+ const cleanup = () => {
4680
+ if (this.pending.get(key) === current) this.pending.delete(key);
4680
4681
  };
4681
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
4682
- }
4683
- /**
4684
- * Initialize the exporter (called after all dependencies are ready)
4685
- */
4686
- async init(options) {
4687
- try {
4688
- this.#isInitializing = true;
4689
- this.#emitDropEvent = options.emitDropEvent;
4690
- this.#storage = options.mastra?.getStorage();
4691
- if (!this.#storage) {
4692
- this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
4693
- return;
4694
- }
4695
- this.#observabilityStorage = await this.#storage.getStore("observability");
4696
- if (!this.#observabilityStorage) {
4697
- this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
4698
- return;
4699
- }
4700
- if (!this.#resolvedStrategy) {
4701
- this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
4702
- this.logger.debug("tracing storage exporter initialized", {
4703
- strategy: this.#resolvedStrategy,
4704
- source: this.#config.strategy !== "auto" ? "user" : "auto",
4705
- storageAdapter: this.#storage.constructor.name,
4706
- maxBatchSize: this.#config.maxBatchSize,
4707
- maxBatchWaitMs: this.#config.maxBatchWaitMs
4708
- });
4709
- }
4710
- if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4711
- } finally {
4712
- this.#isInitializing = false;
4713
- /**
4714
- * Assumes caller waits until export of a parent span is completed before calling
4715
- * export for child spans , order is not relevant for resolve
4716
- */
4717
- this.#initPromises.forEach((resolve) => {
4718
- resolve();
4719
- });
4720
- this.#initPromises.clear();
4721
- }
4682
+ current.then(cleanup, cleanup);
4683
+ return current;
4722
4684
  }
4723
- /**
4724
- * Checks if buffer should be flushed based on size or time triggers
4725
- */
4726
- shouldFlush() {
4727
- if (this.#resolvedStrategy === "realtime") return true;
4728
- if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
4729
- if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
4730
- if (this.#eventBuffer.totalSize > 0) {
4731
- if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
4685
+ };
4686
+ // src/recorded.ts
4687
+ function nullToUndefined(value) {
4688
+ return value ?? void 0;
4689
+ }
4690
+ function mergeMetadata(base, extra) {
4691
+ if (!base && !extra) return void 0;
4692
+ return {
4693
+ ...base ?? {},
4694
+ ...extra ?? {}
4695
+ };
4696
+ }
4697
+ function normalizeErrorInfo(error) {
4698
+ if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
4699
+ return {
4700
+ message: error.message,
4701
+ id: "id" in error && typeof error.id === "string" ? error.id : void 0,
4702
+ name: "name" in error && typeof error.name === "string" ? error.name : void 0,
4703
+ stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
4704
+ domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
4705
+ category: "category" in error && typeof error.category === "string" ? error.category : void 0,
4706
+ details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
4707
+ };
4708
+ }
4709
+ function buildCorrelationContext(span, rootSpan, parent) {
4710
+ return {
4711
+ tags: rootSpan.tags ?? void 0,
4712
+ entityType: nullToUndefined(span.entityType),
4713
+ entityId: nullToUndefined(span.entityId),
4714
+ entityName: nullToUndefined(span.entityName),
4715
+ parentEntityType: parent?.entityType ?? void 0,
4716
+ parentEntityId: parent?.entityId ?? void 0,
4717
+ parentEntityName: parent?.entityName ?? void 0,
4718
+ rootEntityType: nullToUndefined(rootSpan.entityType),
4719
+ rootEntityId: nullToUndefined(rootSpan.entityId),
4720
+ rootEntityName: nullToUndefined(rootSpan.entityName),
4721
+ userId: nullToUndefined(span.userId),
4722
+ organizationId: nullToUndefined(span.organizationId),
4723
+ resourceId: nullToUndefined(span.resourceId),
4724
+ runId: nullToUndefined(span.runId),
4725
+ sessionId: nullToUndefined(span.sessionId),
4726
+ threadId: nullToUndefined(span.threadId),
4727
+ requestId: nullToUndefined(span.requestId),
4728
+ environment: nullToUndefined(span.environment),
4729
+ source: nullToUndefined(span.source),
4730
+ serviceName: nullToUndefined(span.serviceName),
4731
+ experimentId: nullToUndefined(span.experimentId)
4732
+ };
4733
+ }
4734
+ function buildScoreEvent(args) {
4735
+ const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
4736
+ return {
4737
+ type: "score",
4738
+ score: {
4739
+ scoreId: generateSignalId(),
4740
+ timestamp: /* @__PURE__ */ new Date(),
4741
+ traceId,
4742
+ spanId,
4743
+ scorerId: score.scorerId,
4744
+ scorerName: score.scorerName,
4745
+ scorerVersion: score.scorerVersion,
4746
+ source: score.source,
4747
+ scoreSource: score.scoreSource,
4748
+ score: score.score,
4749
+ reason: score.reason,
4750
+ experimentId: score.experimentId,
4751
+ scoreTraceId: score.scoreTraceId,
4752
+ targetEntityType: score.targetEntityType,
4753
+ correlationContext,
4754
+ metadata: mergeMetadata(inheritedMetadata, score.metadata)
4732
4755
  }
4733
- return false;
4734
- }
4735
- /**
4736
- * Schedules a flush using setTimeout
4737
- */
4738
- scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
4739
- if (this.#flushTimer) clearTimeout(this.#flushTimer);
4740
- this.#flushTimer = setTimeout(() => {
4741
- this.#flushTimer = void 0;
4742
- this.trackFlushBuffer().catch((error) => {
4743
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
4744
- });
4745
- }, delayMs);
4746
- }
4747
- retryDelay(retryAttempt) {
4748
- return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
4749
- }
4750
- retryAttempt(events) {
4751
- return events.reduce((earliestAttempt, event) => {
4752
- if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
4753
- return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
4754
- }, void 0);
4755
- }
4756
- logStorageFailure(signal, events, retryAttempt, error) {
4757
- this.logger.warn("Failed to persist observability events", {
4758
- signal,
4759
- eventCount: events.length,
4760
- retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
4761
- maxRetries: this.#config.maxRetries,
4762
- ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
4763
- error: error instanceof Error ? error.message : String(error)
4764
- });
4765
- }
4766
- /**
4767
- * Checks flush triggers and schedules/triggers flush as needed.
4768
- * Called after adding any event to the buffer.
4769
- * Returns the flush promise when flushing so callers can await it.
4770
- */
4771
- async handleBatchedFlush() {
4772
- if (this.shouldFlush()) await this.trackFlushBuffer();
4773
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
4774
- }
4775
- sanitizeDropError(error) {
4776
- if (error instanceof _mastra_core_error.MastraError) return {
4777
- id: error.id,
4778
- domain: String(error.domain),
4779
- message: error.message
4780
- };
4781
- if (error instanceof Error) return { message: error.message };
4782
- return { message: String(error) };
4783
- }
4784
- emitDrop(signal, reason, count, error) {
4785
- if (count === 0) return;
4786
- const dropEvent = {
4787
- type: "drop",
4788
- signal,
4789
- reason,
4790
- count,
4756
+ };
4757
+ }
4758
+ function buildFeedbackEvent(args) {
4759
+ const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
4760
+ return {
4761
+ type: "feedback",
4762
+ feedback: {
4763
+ feedbackId: generateSignalId(),
4791
4764
  timestamp: /* @__PURE__ */ new Date(),
4792
- exporterName: this.name,
4793
- ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
4794
- ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
4795
- };
4765
+ traceId,
4766
+ spanId,
4767
+ source: feedback.source,
4768
+ feedbackSource: feedback.feedbackSource,
4769
+ feedbackType: feedback.feedbackType,
4770
+ value: feedback.value,
4771
+ userId: feedback.userId,
4772
+ feedbackUserId: feedback.feedbackUserId,
4773
+ comment: feedback.comment,
4774
+ sourceId: feedback.sourceId,
4775
+ experimentId: feedback.experimentId,
4776
+ correlationContext,
4777
+ metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
4778
+ }
4779
+ };
4780
+ }
4781
+ function findSpanById(spans, spanId) {
4782
+ if (!spanId) return void 0;
4783
+ return spans.find((span) => span.spanId === spanId);
4784
+ }
4785
+ /** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
4786
+ function resolveRecordedEventFromTrace(trace, event) {
4787
+ const record = event.type === "score" ? event.score : event.feedback;
4788
+ const spans = trace.spans.filter((span) => span.traceId === record.traceId);
4789
+ const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
4790
+ if (!span) return null;
4791
+ const byId = new Map(spans.map((span) => [span.spanId, span]));
4792
+ let root = span;
4793
+ const visited = /* @__PURE__ */ new Set();
4794
+ while (root.parentSpanId) {
4795
+ if (visited.has(root.spanId)) return null;
4796
+ visited.add(root.spanId);
4797
+ const parent = byId.get(root.parentSpanId);
4798
+ if (!parent) return null;
4799
+ root = parent;
4800
+ }
4801
+ const context = {
4802
+ correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
4803
+ metadata: mergeMetadata(span.metadata, record.metadata)
4804
+ };
4805
+ return event.type === "score" ? {
4806
+ type: "score",
4807
+ score: {
4808
+ ...event.score,
4809
+ ...context
4810
+ }
4811
+ } : event.type === "feedback_replacement" ? {
4812
+ type: "feedback_replacement",
4813
+ feedback: {
4814
+ ...event.feedback,
4815
+ ...context
4816
+ }
4817
+ } : {
4818
+ type: "feedback",
4819
+ feedback: {
4820
+ ...event.feedback,
4821
+ ...context
4822
+ }
4823
+ };
4824
+ }
4825
+ var RecordedSpanImpl = class {
4826
+ id;
4827
+ traceId;
4828
+ name;
4829
+ type;
4830
+ entityType;
4831
+ entityId;
4832
+ entityName;
4833
+ startTime;
4834
+ endTime;
4835
+ attributes;
4836
+ metadata;
4837
+ tags;
4838
+ input;
4839
+ output;
4840
+ errorInfo;
4841
+ requestContext;
4842
+ isEvent;
4843
+ isRootSpan;
4844
+ parentSpanId;
4845
+ parent;
4846
+ children = [];
4847
+ #raw;
4848
+ #rootSpan;
4849
+ #emitRecordedEvent;
4850
+ #canEmitRecordedEvent;
4851
+ #debugRecordedAnnotationUnavailable;
4852
+ constructor(args) {
4853
+ const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
4854
+ this.#raw = raw;
4855
+ this.#rootSpan = rootSpan;
4856
+ this.#emitRecordedEvent = emitRecordedEvent;
4857
+ this.#canEmitRecordedEvent = canEmitRecordedEvent;
4858
+ this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
4859
+ this.id = raw.spanId;
4860
+ this.traceId = raw.traceId;
4861
+ this.name = raw.name;
4862
+ this.type = raw.spanType;
4863
+ this.entityType = raw.entityType ?? void 0;
4864
+ this.entityId = raw.entityId ?? void 0;
4865
+ this.entityName = raw.entityName ?? void 0;
4866
+ this.startTime = raw.startedAt;
4867
+ this.endTime = raw.endedAt ?? void 0;
4868
+ this.attributes = raw.attributes ?? void 0;
4869
+ this.metadata = raw.metadata ?? void 0;
4870
+ this.tags = raw.tags ?? void 0;
4871
+ this.input = raw.input ?? void 0;
4872
+ this.output = raw.output ?? void 0;
4873
+ this.errorInfo = normalizeErrorInfo(raw.error);
4874
+ this.requestContext = raw.requestContext ?? void 0;
4875
+ this.isEvent = raw.isEvent;
4876
+ this.isRootSpan = !raw.parentSpanId;
4877
+ this.parentSpanId = raw.parentSpanId ?? void 0;
4878
+ }
4879
+ async addScore(score) {
4880
+ if (!this.#canEmitRecordedEvent()) {
4881
+ this.#debugRecordedAnnotationUnavailable({
4882
+ kind: "score",
4883
+ traceId: this.traceId,
4884
+ spanId: this.id
4885
+ });
4886
+ return;
4887
+ }
4888
+ await this.#emitRecordedEvent(buildScoreEvent({
4889
+ traceId: this.#raw.traceId,
4890
+ spanId: this.id,
4891
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4892
+ score,
4893
+ inheritedMetadata: this.#raw.metadata
4894
+ }));
4895
+ }
4896
+ async addFeedback(feedback) {
4897
+ if (!this.#canEmitRecordedEvent()) {
4898
+ this.#debugRecordedAnnotationUnavailable({
4899
+ kind: "feedback",
4900
+ traceId: this.traceId,
4901
+ spanId: this.id
4902
+ });
4903
+ return;
4904
+ }
4905
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4906
+ traceId: this.#raw.traceId,
4907
+ spanId: this.id,
4908
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4909
+ feedback,
4910
+ inheritedMetadata: this.#raw.metadata
4911
+ }));
4912
+ }
4913
+ };
4914
+ var RecordedTraceImpl = class {
4915
+ traceId;
4916
+ rootSpan;
4917
+ spans;
4918
+ #rootRecord;
4919
+ #emitRecordedEvent;
4920
+ #spanMap;
4921
+ #canEmitRecordedEvent;
4922
+ #debugRecordedAnnotationUnavailable;
4923
+ constructor(args) {
4924
+ this.traceId = args.traceId;
4925
+ this.rootSpan = args.rootSpan;
4926
+ this.#rootRecord = args.rootRecord;
4927
+ this.spans = args.spans;
4928
+ this.#emitRecordedEvent = args.emitRecordedEvent;
4929
+ this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
4930
+ this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
4931
+ this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
4932
+ }
4933
+ getSpan(spanId) {
4934
+ return this.#spanMap.get(spanId) ?? null;
4935
+ }
4936
+ async addScore(score) {
4937
+ if (!this.#canEmitRecordedEvent()) {
4938
+ this.#debugRecordedAnnotationUnavailable({
4939
+ kind: "score",
4940
+ traceId: this.traceId
4941
+ });
4942
+ return;
4943
+ }
4944
+ await this.#emitRecordedEvent(buildScoreEvent({
4945
+ traceId: this.#rootRecord.traceId,
4946
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4947
+ score,
4948
+ inheritedMetadata: this.#rootRecord.metadata
4949
+ }));
4950
+ }
4951
+ async addFeedback(feedback) {
4952
+ if (!this.#canEmitRecordedEvent()) {
4953
+ this.#debugRecordedAnnotationUnavailable({
4954
+ kind: "feedback",
4955
+ traceId: this.traceId
4956
+ });
4957
+ return;
4958
+ }
4959
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4960
+ traceId: this.#rootRecord.traceId,
4961
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4962
+ feedback,
4963
+ inheritedMetadata: this.#rootRecord.metadata
4964
+ }));
4965
+ }
4966
+ };
4967
+ function findRootSpan(spans) {
4968
+ const spanIds = new Set(spans.map((span) => span.spanId));
4969
+ return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
4970
+ }
4971
+ function hydrateRecordedTrace(args) {
4972
+ const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
4973
+ const rootSpan = findRootSpan(trace.spans);
4974
+ if (!rootSpan) return null;
4975
+ const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
4976
+ raw,
4977
+ rootSpan,
4978
+ emitRecordedEvent,
4979
+ canEmitRecordedEvent,
4980
+ debugRecordedAnnotationUnavailable
4981
+ }));
4982
+ const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
4983
+ for (const span of recordedSpans) {
4984
+ if (!span.parentSpanId) continue;
4985
+ const parent = spanMap.get(span.parentSpanId);
4986
+ if (!parent) continue;
4987
+ span.parent = parent;
4988
+ parent.children.push(span);
4989
+ }
4990
+ const hydratedRootSpan = spanMap.get(rootSpan.spanId);
4991
+ if (!hydratedRootSpan) return null;
4992
+ return new RecordedTraceImpl({
4993
+ traceId: trace.traceId,
4994
+ rootSpan: hydratedRootSpan,
4995
+ rootRecord: rootSpan,
4996
+ spans: recordedSpans,
4997
+ emitRecordedEvent,
4998
+ canEmitRecordedEvent,
4999
+ debugRecordedAnnotationUnavailable
5000
+ });
5001
+ }
5002
+ // src/exporters/storage-annotation.ts
5003
+ const LOOKUP_DELAYS_MS = [
5004
+ 0,
5005
+ 100,
5006
+ 250,
5007
+ 500,
5008
+ 1e3,
5009
+ 2e3,
5010
+ 2e3
5011
+ ];
5012
+ /** Older stores may inherit a method that throws instead of omitting the hook. */
5013
+ async function updateStorageFeedbackReviewStatus(storage, feedback, logger) {
5014
+ if (typeof storage.updateFeedbackReviewStatus === "function") try {
5015
+ await storage.updateFeedbackReviewStatus(feedback);
5016
+ return;
5017
+ } catch (error) {
5018
+ if (typeof error !== "object" || error === null || !("id" in error) || error.id !== "OBSERVABILITY_STORAGE_UPDATE_FEEDBACK_REVIEW_STATUS_NOT_IMPLEMENTED") throw error;
5019
+ }
5020
+ logger.warn("Storage exporter skipped feedback review update: upgrade the storage adapter and @mastra/core");
5021
+ }
5022
+ /**
5023
+ * Resolve attached-storage context within a bounded retry window, including failed reads.
5024
+ * Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
5025
+ * Other destinations receive the original event independently.
5026
+ */
5027
+ async function resolveStorageAnnotation(event, storage, flushSpans) {
5028
+ const record = event.type === "score" ? event.score : event.feedback;
5029
+ if (record.correlationContext !== void 0) return event;
5030
+ if (!record.traceId) return null;
5031
+ let lastReadFailure;
5032
+ for (const delay of LOOKUP_DELAYS_MS) {
5033
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
5034
+ let trace;
5035
+ try {
5036
+ trace = await storage.getTrace({ traceId: record.traceId });
5037
+ lastReadFailure = void 0;
5038
+ } catch (error) {
5039
+ lastReadFailure = { error };
5040
+ }
5041
+ if (trace) {
5042
+ const resolved = resolveRecordedEventFromTrace(trace, event);
5043
+ if (resolved) return resolved;
5044
+ }
5045
+ if (delay === 0) await flushSpans();
5046
+ }
5047
+ if (lastReadFailure) throw lastReadFailure.error;
5048
+ return null;
5049
+ }
5050
+ // src/exporters/default.ts
5051
+ /**
5052
+ * Resolves the final tracing storage strategy based on config and observability store hints
5053
+ */
5054
+ function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
5055
+ const observabilityStrategy = observabilityStorage.observabilityStrategy;
5056
+ if (config.strategy && config.strategy !== "auto") {
5057
+ if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
5058
+ logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
5059
+ userStrategy: config.strategy,
5060
+ storageAdapter: storageName,
5061
+ supportedStrategies: observabilityStrategy.supported,
5062
+ fallbackStrategy: observabilityStrategy.preferred
5063
+ });
5064
+ }
5065
+ return observabilityStrategy.preferred;
5066
+ }
5067
+ const FLUSH_SUCCEEDED$1 = { failed: false };
5068
+ /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5069
+ const MAX_FLUSH_ROUNDS$1 = 3;
5070
+ /**
5071
+ * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
5072
+ * This class is preserved unchanged so existing integrations (including code
5073
+ * that matches on the `mastra-default-observability-exporter` exporter name)
5074
+ * keep working. It will be removed in a future major version.
5075
+ *
5076
+ * Default storage-backed exporter. Buffers observability events and flushes them
5077
+ * in batches to the configured ObservabilityStorage backend with retry support.
5078
+ */
5079
+ var DefaultExporter = class extends BaseExporter {
5080
+ name = "mastra-default-observability-exporter";
5081
+ #config;
5082
+ #isInitializing = false;
5083
+ #initPromises = /* @__PURE__ */ new Set();
5084
+ #eventBuffer;
5085
+ #storage;
5086
+ #observabilityStorage;
5087
+ #resolvedStrategy;
5088
+ #flushTimer;
5089
+ /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5090
+ #inFlightFlushes = /* @__PURE__ */ new Set();
5091
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5092
+ #feedbackWrites = new KeyedQueue();
5093
+ #emitDropEvent;
5094
+ #unsupportedSignals = /* @__PURE__ */ new Set();
5095
+ constructor(config = {}) {
5096
+ super(config);
5097
+ this.#config = {
5098
+ ...config,
5099
+ maxBatchSize: config.maxBatchSize ?? 1e3,
5100
+ maxBufferSize: config.maxBufferSize ?? 1e4,
5101
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
5102
+ maxRetries: config.maxRetries ?? 4,
5103
+ retryDelayMs: config.retryDelayMs ?? 500,
5104
+ strategy: config.strategy ?? "auto"
5105
+ };
5106
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5107
+ }
5108
+ /**
5109
+ * Initialize the exporter (called after all dependencies are ready)
5110
+ */
5111
+ async init(options) {
5112
+ try {
5113
+ this.#isInitializing = true;
5114
+ this.#emitDropEvent = options.emitDropEvent;
5115
+ this.#storage = options.mastra?.getStorage();
5116
+ if (!this.#storage) {
5117
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
5118
+ return;
5119
+ }
5120
+ this.#observabilityStorage = await this.#storage.getStore("observability");
5121
+ if (!this.#observabilityStorage) {
5122
+ this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
5123
+ return;
5124
+ }
5125
+ if (!this.#resolvedStrategy) {
5126
+ this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
5127
+ this.logger.debug("tracing storage exporter initialized", {
5128
+ strategy: this.#resolvedStrategy,
5129
+ source: this.#config.strategy !== "auto" ? "user" : "auto",
5130
+ storageAdapter: this.#storage.constructor.name,
5131
+ maxBatchSize: this.#config.maxBatchSize,
5132
+ maxBatchWaitMs: this.#config.maxBatchWaitMs
5133
+ });
5134
+ }
5135
+ if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5136
+ } finally {
5137
+ this.#isInitializing = false;
5138
+ /**
5139
+ * Assumes caller waits until export of a parent span is completed before calling
5140
+ * export for child spans , order is not relevant for resolve
5141
+ */
5142
+ this.#initPromises.forEach((resolve) => {
5143
+ resolve();
5144
+ });
5145
+ this.#initPromises.clear();
5146
+ }
5147
+ }
5148
+ /**
5149
+ * Checks if buffer should be flushed based on size or time triggers
5150
+ */
5151
+ shouldFlush() {
5152
+ if (this.#resolvedStrategy === "realtime") return true;
5153
+ if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5154
+ if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
5155
+ if (this.#eventBuffer.totalSize > 0) {
5156
+ if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
5157
+ }
5158
+ return false;
5159
+ }
5160
+ /**
5161
+ * Schedules a flush using setTimeout
5162
+ */
5163
+ scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
5164
+ if (this.#flushTimer) clearTimeout(this.#flushTimer);
5165
+ this.#flushTimer = setTimeout(() => {
5166
+ this.#flushTimer = void 0;
5167
+ this.trackFlushBuffer().catch((error) => {
5168
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5169
+ });
5170
+ }, delayMs);
5171
+ }
5172
+ retryDelay(retryAttempt) {
5173
+ return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5174
+ }
5175
+ retryAttempt(events) {
5176
+ return events.reduce((earliestAttempt, event) => {
5177
+ if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
5178
+ return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
5179
+ }, void 0);
5180
+ }
5181
+ logStorageFailure(signal, events, retryAttempt, error) {
5182
+ this.logger.warn("Failed to persist observability events", {
5183
+ signal,
5184
+ eventCount: events.length,
5185
+ retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
5186
+ maxRetries: this.#config.maxRetries,
5187
+ ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
5188
+ error: error instanceof Error ? error.message : String(error)
5189
+ });
5190
+ }
5191
+ /**
5192
+ * Checks flush triggers and schedules/triggers flush as needed.
5193
+ * Called after adding any event to the buffer.
5194
+ * Returns the flush promise when flushing so callers can await it.
5195
+ */
5196
+ async handleBatchedFlush() {
5197
+ if (this.shouldFlush()) await this.trackFlushBuffer();
5198
+ else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5199
+ }
5200
+ sanitizeDropError(error) {
5201
+ if (error instanceof _mastra_core_error.MastraError) return {
5202
+ id: error.id,
5203
+ domain: String(error.domain),
5204
+ message: error.message
5205
+ };
5206
+ if (error instanceof Error) return { message: error.message };
5207
+ return { message: String(error) };
5208
+ }
5209
+ emitDrop(signal, reason, count, error) {
5210
+ if (count === 0) return;
5211
+ const dropEvent = {
5212
+ type: "drop",
5213
+ signal,
5214
+ reason,
5215
+ count,
5216
+ timestamp: /* @__PURE__ */ new Date(),
5217
+ exporterName: this.name,
5218
+ ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
5219
+ ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
5220
+ };
4796
5221
  this.#emitDropEvent?.(dropEvent);
4797
5222
  }
4798
5223
  /**
@@ -4937,7 +5362,10 @@ var DefaultExporter = class extends BaseExporter {
4937
5362
  case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
4938
5363
  }
4939
5364
  const flushResults = await Promise.all([
4940
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5365
+ this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5366
+ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
5367
+ onConflict: "ignore"
5368
+ })),
4941
5369
  this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
4942
5370
  this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
4943
5371
  this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
@@ -5014,22 +5442,55 @@ var DefaultExporter = class extends BaseExporter {
5014
5442
  this.#eventBuffer.addEvent(event);
5015
5443
  await this.handleBatchedFlush();
5016
5444
  }
5017
- /**
5018
- * Handle score events — buffer for batch flush.
5019
- */
5020
- async onScoreEvent(event) {
5021
- await this.waitForInit();
5022
- if (!this.#observabilityStorage) return;
5023
- this.#eventBuffer.addEvent(event);
5024
- await this.handleBatchedFlush();
5445
+ onScoreEvent(event) {
5446
+ return this.enqueueAnnotation(event);
5025
5447
  }
5026
- /**
5027
- * Handle feedback events — buffer for batch flush.
5028
- */
5029
- async onFeedbackEvent(event) {
5448
+ onFeedbackReviewStatusEvent(event) {
5449
+ return this.enqueueAnnotation(event);
5450
+ }
5451
+ onFeedbackReplacementEvent(event) {
5452
+ return this.enqueueAnnotation(event);
5453
+ }
5454
+ onFeedbackEvent(event) {
5455
+ return this.enqueueAnnotation(event);
5456
+ }
5457
+ enqueueAnnotation(event) {
5458
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
5459
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
5460
+ this.#pendingAnnotations.add(pending);
5461
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
5462
+ return pending;
5463
+ }
5464
+ async storeAnnotation(event) {
5030
5465
  await this.waitForInit();
5031
5466
  if (!this.#observabilityStorage) return;
5032
- this.#eventBuffer.addEvent(event);
5467
+ if (event.type === "feedback_review_status") {
5468
+ await this.flushBufferedEvents();
5469
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
5470
+ return;
5471
+ }
5472
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
5473
+ await Promise.allSettled([...this.#inFlightFlushes]);
5474
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5475
+ });
5476
+ if (!resolved) {
5477
+ const record = event.type === "score" ? event.score : event.feedback;
5478
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
5479
+ eventType: event.type,
5480
+ traceId: record.traceId,
5481
+ spanId: record.spanId
5482
+ });
5483
+ return;
5484
+ }
5485
+ if (resolved.type === "feedback_replacement") {
5486
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
5487
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
5488
+ return;
5489
+ }
5490
+ await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
5491
+ return;
5492
+ }
5493
+ this.#eventBuffer.addEvent(resolved);
5033
5494
  await this.handleBatchedFlush();
5034
5495
  }
5035
5496
  /**
@@ -5038,6 +5499,10 @@ var DefaultExporter = class extends BaseExporter {
5038
5499
  * are exported before the runtime instance is terminated.
5039
5500
  */
5040
5501
  async flush() {
5502
+ await Promise.allSettled([...this.#pendingAnnotations]);
5503
+ await this.flushBufferedEvents();
5504
+ }
5505
+ async flushBufferedEvents() {
5041
5506
  for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
5042
5507
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5043
5508
  if (this.#eventBuffer.totalSize > 0) {
@@ -5187,6 +5652,8 @@ var MastraStorageExporter = class extends BaseExporter {
5187
5652
  #flushTimer;
5188
5653
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5189
5654
  #inFlightFlushes = /* @__PURE__ */ new Set();
5655
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5656
+ #feedbackWrites = new KeyedQueue();
5190
5657
  #emitDropEvent;
5191
5658
  #unsupportedSignals = /* @__PURE__ */ new Set();
5192
5659
  constructor(config = {}) {
@@ -5557,7 +6024,10 @@ var MastraStorageExporter = class extends BaseExporter {
5557
6024
  case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5558
6025
  }
5559
6026
  const createTasks = [
5560
- () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
6027
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
6028
+ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
6029
+ onConflict: "ignore"
6030
+ })),
5561
6031
  () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
5562
6032
  () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
5563
6033
  () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
@@ -5638,22 +6108,55 @@ var MastraStorageExporter = class extends BaseExporter {
5638
6108
  this.#eventBuffer.addEvent(event);
5639
6109
  await this.handleBatchedFlush();
5640
6110
  }
5641
- /**
5642
- * Handle score events — buffer for batch flush.
5643
- */
5644
- async onScoreEvent(event) {
5645
- await this.ensureInitialized();
5646
- if (!this.#observabilityStorage) return;
5647
- this.#eventBuffer.addEvent(event);
5648
- await this.handleBatchedFlush();
6111
+ onScoreEvent(event) {
6112
+ return this.enqueueAnnotation(event);
5649
6113
  }
5650
- /**
5651
- * Handle feedback events — buffer for batch flush.
5652
- */
5653
- async onFeedbackEvent(event) {
6114
+ onFeedbackReviewStatusEvent(event) {
6115
+ return this.enqueueAnnotation(event);
6116
+ }
6117
+ onFeedbackReplacementEvent(event) {
6118
+ return this.enqueueAnnotation(event);
6119
+ }
6120
+ onFeedbackEvent(event) {
6121
+ return this.enqueueAnnotation(event);
6122
+ }
6123
+ enqueueAnnotation(event) {
6124
+ const feedbackId = event.type === "score" ? void 0 : event.feedback.feedbackId;
6125
+ const pending = feedbackId ? this.#feedbackWrites.enqueue(feedbackId, () => this.storeAnnotation(event)) : this.storeAnnotation(event);
6126
+ this.#pendingAnnotations.add(pending);
6127
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
6128
+ return pending;
6129
+ }
6130
+ async storeAnnotation(event) {
5654
6131
  await this.ensureInitialized();
5655
6132
  if (!this.#observabilityStorage) return;
5656
- this.#eventBuffer.addEvent(event);
6133
+ if (event.type === "feedback_review_status") {
6134
+ await this.flushBufferedEvents();
6135
+ await updateStorageFeedbackReviewStatus(this.#observabilityStorage, event.feedback, this.logger);
6136
+ return;
6137
+ }
6138
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
6139
+ await Promise.allSettled([...this.#inFlightFlushes]);
6140
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
6141
+ });
6142
+ if (!resolved) {
6143
+ const record = event.type === "score" ? event.score : event.feedback;
6144
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
6145
+ eventType: event.type,
6146
+ traceId: record.traceId,
6147
+ spanId: record.spanId
6148
+ });
6149
+ return;
6150
+ }
6151
+ if (resolved.type === "feedback_replacement") {
6152
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
6153
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
6154
+ return;
6155
+ }
6156
+ await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
6157
+ return;
6158
+ }
6159
+ this.#eventBuffer.addEvent(resolved);
5657
6160
  await this.handleBatchedFlush();
5658
6161
  }
5659
6162
  /**
@@ -5662,6 +6165,10 @@ var MastraStorageExporter = class extends BaseExporter {
5662
6165
  * are exported before the runtime instance is terminated.
5663
6166
  */
5664
6167
  async flush() {
6168
+ await Promise.allSettled([...this.#pendingAnnotations]);
6169
+ await this.flushBufferedEvents();
6170
+ }
6171
+ async flushBufferedEvents() {
5665
6172
  if (this.#byteTracker) {
5666
6173
  if (!this.#observabilityStorage) return;
5667
6174
  this.#byteDrainers++;
@@ -6088,8 +6595,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6088
6595
  * Internal hook used by RecordedTrace/RecordedSpan hydration to route
6089
6596
  * non-tracing annotation events back through the normal exporter pipeline.
6090
6597
  */
6091
- __emitRecordedEvent(event) {
6092
- this.emitObservabilityEvent(event);
6598
+ __emitRecordedEvent(event, shouldHandle) {
6599
+ if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
6600
+ else this.emitObservabilityEvent(event);
6093
6601
  }
6094
6602
  /**
6095
6603
  * Internal hook used by the client observability proxy (`client/`)
@@ -8672,6 +9180,41 @@ var PlatformByteBatcher = class {
8672
9180
  };
8673
9181
  }
8674
9182
  };
9183
+ // src/exporters/platform-resolved-record.ts
9184
+ /** Deliver one feedback or score record whose span context must be resolved by Platform. */
9185
+ async function publishResolvedRecord(url, body, headers, method = "POST") {
9186
+ const deadline = AbortSignal.timeout(3e4);
9187
+ for (let attempt = 0; attempt < 6; attempt++) {
9188
+ const response = await fetch(url, {
9189
+ method,
9190
+ headers,
9191
+ body,
9192
+ signal: deadline
9193
+ });
9194
+ if (response.ok) {
9195
+ await response.body?.cancel();
9196
+ return;
9197
+ }
9198
+ const error = await response.json().catch(() => null);
9199
+ const code = error?.code ?? error?.error?.code;
9200
+ if (!(method === "PATCH" ? response.status === 404 && code === "FEEDBACK_NOT_FOUND" || response.status === 503 && code === "FEEDBACK_LOOKUP_UNAVAILABLE" : 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})` : ""}`);
9201
+ const retryAfter = response.headers.get("retry-after");
9202
+ const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
9203
+ const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
9204
+ await new Promise((resolve, reject) => {
9205
+ deadline.throwIfAborted();
9206
+ const timer = setTimeout(() => {
9207
+ deadline.removeEventListener("abort", abort);
9208
+ resolve();
9209
+ }, Math.min(delay, 3e4));
9210
+ function abort() {
9211
+ clearTimeout(timer);
9212
+ reject(deadline.reason);
9213
+ }
9214
+ deadline.addEventListener("abort", abort, { once: true });
9215
+ });
9216
+ }
9217
+ }
8675
9218
  // src/exporters/mastra-platform.ts
8676
9219
  const SIGNAL_PUBLISH_SUFFIXES = {
8677
9220
  traces: "/spans/publish",
@@ -8791,6 +9334,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8791
9334
  buffer;
8792
9335
  flushTimer = null;
8793
9336
  inFlightFlushes = /* @__PURE__ */ new Set();
9337
+ pendingRecords = /* @__PURE__ */ new Set();
9338
+ feedbackUpdates = new KeyedQueue();
8794
9339
  quotaPaused = false;
8795
9340
  quotaProbeTimer = null;
8796
9341
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
@@ -8827,6 +9372,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8827
9372
  maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
8828
9373
  maxRetries: config.maxRetries ?? 3,
8829
9374
  accessToken: accessToken || "",
9375
+ projectId,
8830
9376
  tracesEndpoint,
8831
9377
  logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
8832
9378
  metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
@@ -8868,17 +9414,73 @@ var MastraPlatformExporter = class extends BaseExporter {
8868
9414
  await this.handleBufferedEvent();
8869
9415
  }
8870
9416
  async onScoreEvent(event) {
8871
- if (this.isDisabled) return;
9417
+ if (this.isDisabled || this.shuttingDown) return;
9418
+ if (event.score.correlationContext == null) {
9419
+ this.enqueueResolvedRecord("score", event.score);
9420
+ return;
9421
+ }
8872
9422
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8873
9423
  this.addScoreToBuffer(event);
8874
9424
  await this.handleBufferedEvent();
8875
9425
  }
8876
9426
  async onFeedbackEvent(event) {
8877
- if (this.isDisabled) return;
9427
+ if (this.isDisabled || this.shuttingDown) return;
9428
+ if (event.feedback.correlationContext == null) {
9429
+ this.enqueueResolvedRecord("feedback", event.feedback);
9430
+ return;
9431
+ }
8878
9432
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8879
9433
  this.addFeedbackToBuffer(event);
8880
9434
  await this.handleBufferedEvent();
8881
9435
  }
9436
+ onFeedbackReplacementEvent(event) {
9437
+ if (this.isDisabled || this.shuttingDown) return;
9438
+ if (!event.feedback.feedbackId?.trim()) {
9439
+ this.logger.warn("Dropping feedback replacement: feedbackId is required");
9440
+ return;
9441
+ }
9442
+ this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
9443
+ }
9444
+ onFeedbackReviewStatusEvent(event) {
9445
+ if (this.isDisabled || this.shuttingDown) return;
9446
+ const { feedbackId, reviewStatus } = event.feedback;
9447
+ if (!feedbackId?.trim() || !["needs-review", "reviewed"].includes(reviewStatus)) {
9448
+ this.logger.warn("Dropping feedback review update: feedbackId and reviewStatus are required");
9449
+ return;
9450
+ }
9451
+ const url = new URL(`/api/observability/feedback/${encodeURIComponent(feedbackId)}/review-status`, this.platformConfig.feedbackEndpoint);
9452
+ this.enqueueInteractiveWrite("feedback", url, JSON.stringify({ reviewStatus }), "PATCH", feedbackId);
9453
+ }
9454
+ enqueueResolvedRecord(kind, record, replacementId) {
9455
+ if (!record.traceId?.trim()) {
9456
+ this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
9457
+ return;
9458
+ }
9459
+ let body;
9460
+ try {
9461
+ body = JSON.stringify({ [kind]: record });
9462
+ } catch (error) {
9463
+ this.logger.warn(`Dropping unserializable ${kind}`, { error });
9464
+ return;
9465
+ }
9466
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9467
+ const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
9468
+ if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
9469
+ this.enqueueInteractiveWrite(kind, url, body, replacementId !== void 0 ? "PUT" : "POST", replacementId);
9470
+ }
9471
+ enqueueInteractiveWrite(kind, url, body, method, feedbackId) {
9472
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9473
+ const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
9474
+ const headers = {
9475
+ Authorization: `Bearer ${this.platformConfig.accessToken}`,
9476
+ "Content-Type": "application/json",
9477
+ ...projectId ? { "X-Mastra-Project-Id": projectId } : {}
9478
+ };
9479
+ this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
9480
+ const send = () => publishResolvedRecord(url, body, headers, method);
9481
+ const pending = (feedbackId !== void 0 ? this.feedbackUpdates.enqueue(feedbackId, send) : send()).catch((error) => this.logger.warn(`Dropping ${kind} after Platform delivery failed`, { error })).finally(() => this.pendingRecords.delete(pending));
9482
+ this.pendingRecords.add(pending);
9483
+ }
8882
9484
  addToBuffer(event) {
8883
9485
  if (this.byteBatcher) {
8884
9486
  this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
@@ -9219,6 +9821,13 @@ var MastraPlatformExporter = class extends BaseExporter {
9219
9821
  * are exported before the runtime instance is terminated.
9220
9822
  */
9221
9823
  async flush() {
9824
+ if (this.isDisabled) return;
9825
+ do {
9826
+ await this.flushBatches();
9827
+ await Promise.allSettled([...this.pendingRecords]);
9828
+ } while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
9829
+ }
9830
+ async flushBatches() {
9222
9831
  if (this.isDisabled) return;
9223
9832
  if (this.byteBatcher) {
9224
9833
  await this.byteBatcher.flush();
@@ -10176,458 +10785,154 @@ var TestExporter = class extends BaseExporter {
10176
10785
  /**
10177
10786
  * Check if a value is an __or__ marker object
10178
10787
  */
10179
- #isOrMarker(value) {
10180
- return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10181
- }
10182
- /**
10183
- * Check if a value is an __any__ marker object
10184
- */
10185
- #isAnyMarker(value) {
10186
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10187
- if (!("__any__" in value)) return false;
10188
- const constraint = value.__any__;
10189
- return constraint === true || [
10190
- "string",
10191
- "number",
10192
- "boolean",
10193
- "object",
10194
- "array"
10195
- ].includes(constraint);
10196
- }
10197
- /**
10198
- * Check if a key should be skipped during comparison (metadata keys like __structure__)
10199
- */
10200
- #isMetadataKey(key) {
10201
- return key.startsWith("__") && key.endsWith("__");
10202
- }
10203
- /**
10204
- * Custom JSON replacer to handle Date objects and other special types
10205
- */
10206
- #jsonReplacer = (_key, value) => {
10207
- if (value instanceof Date) return value.toISOString();
10208
- return value;
10209
- };
10210
- /**
10211
- * Get all stored debug logs (internal exporter logging, not signal logs)
10212
- */
10213
- getLogs() {
10214
- return [...this.#debugLogs];
10215
- }
10216
- /**
10217
- * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10218
- */
10219
- dumpLogs() {
10220
- console.error("\n=== TestExporter Logs ===");
10221
- this.#debugLogs.forEach((log) => {
10222
- console.error(log);
10223
- });
10224
- console.error("=== End Logs ===\n");
10225
- }
10226
- /**
10227
- * Validate final state - useful for test assertions
10228
- *
10229
- * @returns Object with validation results
10230
- */
10231
- validateFinalState() {
10232
- const traceIds = this.getTraceIds();
10233
- const incompleteSpans = this.getIncompleteSpans();
10234
- const singleTraceId = traceIds.length === 1;
10235
- const allSpansComplete = incompleteSpans.length === 0;
10236
- return {
10237
- valid: singleTraceId && allSpansComplete,
10238
- singleTraceId,
10239
- allSpansComplete,
10240
- traceIds,
10241
- incompleteSpans
10242
- };
10788
+ #isOrMarker(value) {
10789
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10243
10790
  }
10244
10791
  /**
10245
- * Clear all collected events and state across all signals
10792
+ * Check if a value is an __any__ marker object
10246
10793
  */
10247
- clearEvents() {
10248
- this.#tracingEvents = [];
10249
- this.#spanStates.clear();
10250
- this.#logEvents = [];
10251
- this.#metricEvents = [];
10252
- this.#scoreEvents = [];
10253
- this.#feedbackEvents = [];
10254
- this.#debugLogs = [];
10794
+ #isAnyMarker(value) {
10795
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10796
+ if (!("__any__" in value)) return false;
10797
+ const constraint = value.__any__;
10798
+ return constraint === true || [
10799
+ "string",
10800
+ "number",
10801
+ "boolean",
10802
+ "object",
10803
+ "array"
10804
+ ].includes(constraint);
10255
10805
  }
10256
10806
  /**
10257
- * Alias for clearEvents (compatibility with TestExporter)
10807
+ * Check if a key should be skipped during comparison (metadata keys like __structure__)
10258
10808
  */
10259
- reset() {
10260
- this.clearEvents();
10809
+ #isMetadataKey(key) {
10810
+ return key.startsWith("__") && key.endsWith("__");
10261
10811
  }
10262
10812
  /**
10263
- * Get internal metrics about the exporter's own activity.
10813
+ * Custom JSON replacer to handle Date objects and other special types
10264
10814
  */
10265
- getInternalMetrics() {
10266
- const json = this.toJSON({
10267
- includeEvents: false,
10268
- includeStats: false
10269
- });
10270
- return {
10271
- startedAt: this.#internalMetrics.startedAt,
10272
- lastEventAt: this.#internalMetrics.lastEventAt,
10273
- totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10274
- bySignal: { ...this.#internalMetrics.bySignal },
10275
- flushCount: this.#internalMetrics.flushCount,
10276
- estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10277
- };
10278
- }
10815
+ #jsonReplacer = (_key, value) => {
10816
+ if (value instanceof Date) return value.toISOString();
10817
+ return value;
10818
+ };
10279
10819
  /**
10280
- * Flush buffered data and log internal metrics summary.
10820
+ * Get all stored debug logs (internal exporter logging, not signal logs)
10281
10821
  */
10282
- async flush() {
10283
- this.#internalMetrics.flushCount++;
10284
- if (this.#config.logMetricsOnFlush) {
10285
- const metrics = this.getInternalMetrics();
10286
- const uptimeMs = Date.now() - metrics.startedAt.getTime();
10287
- const summary = [
10288
- `[TestExporter] flush #${metrics.flushCount} summary:`,
10289
- ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10290
- ` total events received: ${metrics.totalEventsReceived}`,
10291
- ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10292
- ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10293
- ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10294
- ].join("\n");
10295
- this.logger.info(summary);
10296
- }
10297
- }
10298
- async shutdown() {
10299
- await this.flush();
10300
- this.logger.info("TestExporter shutdown");
10822
+ getLogs() {
10823
+ return [...this.#debugLogs];
10301
10824
  }
10302
10825
  /**
10303
- * Extract unique spans from a list of events
10826
+ * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10304
10827
  */
10305
- #getUniqueSpansFromEvents(events) {
10306
- const spanMap = /* @__PURE__ */ new Map();
10307
- for (const event of events) {
10308
- const span = event.exportedSpan;
10309
- if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10310
- }
10311
- return Array.from(spanMap.values());
10312
- }
10313
- };
10314
- /**
10315
- * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10316
- */
10317
- const JsonExporter = TestExporter;
10318
- // src/instances/default.ts
10319
- var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10320
- constructor(config) {
10321
- super(config);
10322
- }
10323
- createSpan(options) {
10324
- return new DefaultSpan(options, this);
10325
- }
10326
- };
10327
- // src/recorded.ts
10328
- function nullToUndefined(value) {
10329
- return value ?? void 0;
10330
- }
10331
- function mergeMetadata(base, extra) {
10332
- if (!base && !extra) return void 0;
10333
- return {
10334
- ...base ?? {},
10335
- ...extra ?? {}
10336
- };
10337
- }
10338
- function normalizeErrorInfo(error) {
10339
- if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
10340
- return {
10341
- message: error.message,
10342
- id: "id" in error && typeof error.id === "string" ? error.id : void 0,
10343
- name: "name" in error && typeof error.name === "string" ? error.name : void 0,
10344
- stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
10345
- domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
10346
- category: "category" in error && typeof error.category === "string" ? error.category : void 0,
10347
- details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
10348
- };
10349
- }
10350
- function buildCorrelationContext(span, rootSpan, parent) {
10351
- return {
10352
- tags: rootSpan.tags ?? void 0,
10353
- entityType: nullToUndefined(span.entityType),
10354
- entityId: nullToUndefined(span.entityId),
10355
- entityName: nullToUndefined(span.entityName),
10356
- parentEntityType: parent?.entityType ?? void 0,
10357
- parentEntityId: parent?.entityId ?? void 0,
10358
- parentEntityName: parent?.entityName ?? void 0,
10359
- rootEntityType: nullToUndefined(rootSpan.entityType),
10360
- rootEntityId: nullToUndefined(rootSpan.entityId),
10361
- rootEntityName: nullToUndefined(rootSpan.entityName),
10362
- userId: nullToUndefined(span.userId),
10363
- organizationId: nullToUndefined(span.organizationId),
10364
- resourceId: nullToUndefined(span.resourceId),
10365
- runId: nullToUndefined(span.runId),
10366
- sessionId: nullToUndefined(span.sessionId),
10367
- threadId: nullToUndefined(span.threadId),
10368
- requestId: nullToUndefined(span.requestId),
10369
- environment: nullToUndefined(span.environment),
10370
- source: nullToUndefined(span.source),
10371
- serviceName: nullToUndefined(span.serviceName),
10372
- experimentId: nullToUndefined(span.experimentId)
10373
- };
10374
- }
10375
- function buildScoreEvent(args) {
10376
- const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
10377
- return {
10378
- type: "score",
10379
- score: {
10380
- scoreId: generateSignalId(),
10381
- timestamp: /* @__PURE__ */ new Date(),
10382
- traceId,
10383
- spanId,
10384
- scorerId: score.scorerId,
10385
- scorerName: score.scorerName,
10386
- scorerVersion: score.scorerVersion,
10387
- source: score.source,
10388
- scoreSource: score.scoreSource,
10389
- score: score.score,
10390
- reason: score.reason,
10391
- experimentId: score.experimentId,
10392
- scoreTraceId: score.scoreTraceId,
10393
- targetEntityType: score.targetEntityType,
10394
- correlationContext,
10395
- metadata: mergeMetadata(inheritedMetadata, score.metadata)
10396
- }
10397
- };
10398
- }
10399
- function buildFeedbackEvent(args) {
10400
- const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
10401
- return {
10402
- type: "feedback",
10403
- feedback: {
10404
- feedbackId: generateSignalId(),
10405
- timestamp: /* @__PURE__ */ new Date(),
10406
- traceId,
10407
- spanId,
10408
- source: feedback.source,
10409
- feedbackSource: feedback.feedbackSource,
10410
- feedbackType: feedback.feedbackType,
10411
- value: feedback.value,
10412
- userId: feedback.userId,
10413
- feedbackUserId: feedback.feedbackUserId,
10414
- comment: feedback.comment,
10415
- sourceId: feedback.sourceId,
10416
- experimentId: feedback.experimentId,
10417
- correlationContext,
10418
- metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
10419
- }
10420
- };
10421
- }
10422
- function findSpanById(spans, spanId) {
10423
- if (!spanId) return void 0;
10424
- return spans.find((span) => span.spanId === spanId);
10425
- }
10426
- function buildRecordedScoreEventFromTrace(args) {
10427
- const rootSpan = findRootSpan(args.trace.spans);
10428
- if (!rootSpan) return null;
10429
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10430
- if (!span) return null;
10431
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10432
- return buildScoreEvent({
10433
- traceId: span.traceId,
10434
- spanId: args.spanId,
10435
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10436
- score: args.score,
10437
- inheritedMetadata: span.metadata
10438
- });
10439
- }
10440
- function buildRecordedFeedbackEventFromTrace(args) {
10441
- const rootSpan = findRootSpan(args.trace.spans);
10442
- if (!rootSpan) return null;
10443
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10444
- if (!span) return null;
10445
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10446
- return buildFeedbackEvent({
10447
- traceId: span.traceId,
10448
- spanId: args.spanId,
10449
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10450
- feedback: args.feedback,
10451
- inheritedMetadata: span.metadata
10452
- });
10453
- }
10454
- var RecordedSpanImpl = class {
10455
- id;
10456
- traceId;
10457
- name;
10458
- type;
10459
- entityType;
10460
- entityId;
10461
- entityName;
10462
- startTime;
10463
- endTime;
10464
- attributes;
10465
- metadata;
10466
- tags;
10467
- input;
10468
- output;
10469
- errorInfo;
10470
- requestContext;
10471
- isEvent;
10472
- isRootSpan;
10473
- parentSpanId;
10474
- parent;
10475
- children = [];
10476
- #raw;
10477
- #rootSpan;
10478
- #emitRecordedEvent;
10479
- #canEmitRecordedEvent;
10480
- #debugRecordedAnnotationUnavailable;
10481
- constructor(args) {
10482
- const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
10483
- this.#raw = raw;
10484
- this.#rootSpan = rootSpan;
10485
- this.#emitRecordedEvent = emitRecordedEvent;
10486
- this.#canEmitRecordedEvent = canEmitRecordedEvent;
10487
- this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
10488
- this.id = raw.spanId;
10489
- this.traceId = raw.traceId;
10490
- this.name = raw.name;
10491
- this.type = raw.spanType;
10492
- this.entityType = raw.entityType ?? void 0;
10493
- this.entityId = raw.entityId ?? void 0;
10494
- this.entityName = raw.entityName ?? void 0;
10495
- this.startTime = raw.startedAt;
10496
- this.endTime = raw.endedAt ?? void 0;
10497
- this.attributes = raw.attributes ?? void 0;
10498
- this.metadata = raw.metadata ?? void 0;
10499
- this.tags = raw.tags ?? void 0;
10500
- this.input = raw.input ?? void 0;
10501
- this.output = raw.output ?? void 0;
10502
- this.errorInfo = normalizeErrorInfo(raw.error);
10503
- this.requestContext = raw.requestContext ?? void 0;
10504
- this.isEvent = raw.isEvent;
10505
- this.isRootSpan = !raw.parentSpanId;
10506
- this.parentSpanId = raw.parentSpanId ?? void 0;
10828
+ dumpLogs() {
10829
+ console.error("\n=== TestExporter Logs ===");
10830
+ this.#debugLogs.forEach((log) => {
10831
+ console.error(log);
10832
+ });
10833
+ console.error("=== End Logs ===\n");
10507
10834
  }
10508
- async addScore(score) {
10509
- if (!this.#canEmitRecordedEvent()) {
10510
- this.#debugRecordedAnnotationUnavailable({
10511
- kind: "score",
10512
- traceId: this.traceId,
10513
- spanId: this.id
10514
- });
10515
- return;
10516
- }
10517
- await this.#emitRecordedEvent(buildScoreEvent({
10518
- traceId: this.#raw.traceId,
10519
- spanId: this.id,
10520
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10521
- score,
10522
- inheritedMetadata: this.#raw.metadata
10523
- }));
10835
+ /**
10836
+ * Validate final state - useful for test assertions
10837
+ *
10838
+ * @returns Object with validation results
10839
+ */
10840
+ validateFinalState() {
10841
+ const traceIds = this.getTraceIds();
10842
+ const incompleteSpans = this.getIncompleteSpans();
10843
+ const singleTraceId = traceIds.length === 1;
10844
+ const allSpansComplete = incompleteSpans.length === 0;
10845
+ return {
10846
+ valid: singleTraceId && allSpansComplete,
10847
+ singleTraceId,
10848
+ allSpansComplete,
10849
+ traceIds,
10850
+ incompleteSpans
10851
+ };
10524
10852
  }
10525
- async addFeedback(feedback) {
10526
- if (!this.#canEmitRecordedEvent()) {
10527
- this.#debugRecordedAnnotationUnavailable({
10528
- kind: "feedback",
10529
- traceId: this.traceId,
10530
- spanId: this.id
10531
- });
10532
- return;
10533
- }
10534
- await this.#emitRecordedEvent(buildFeedbackEvent({
10535
- traceId: this.#raw.traceId,
10536
- spanId: this.id,
10537
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10538
- feedback,
10539
- inheritedMetadata: this.#raw.metadata
10540
- }));
10853
+ /**
10854
+ * Clear all collected events and state across all signals
10855
+ */
10856
+ clearEvents() {
10857
+ this.#tracingEvents = [];
10858
+ this.#spanStates.clear();
10859
+ this.#logEvents = [];
10860
+ this.#metricEvents = [];
10861
+ this.#scoreEvents = [];
10862
+ this.#feedbackEvents = [];
10863
+ this.#debugLogs = [];
10541
10864
  }
10542
- };
10543
- var RecordedTraceImpl = class {
10544
- traceId;
10545
- rootSpan;
10546
- spans;
10547
- #rootRecord;
10548
- #emitRecordedEvent;
10549
- #spanMap;
10550
- #canEmitRecordedEvent;
10551
- #debugRecordedAnnotationUnavailable;
10552
- constructor(args) {
10553
- this.traceId = args.traceId;
10554
- this.rootSpan = args.rootSpan;
10555
- this.#rootRecord = args.rootRecord;
10556
- this.spans = args.spans;
10557
- this.#emitRecordedEvent = args.emitRecordedEvent;
10558
- this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
10559
- this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
10560
- this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
10865
+ /**
10866
+ * Alias for clearEvents (compatibility with TestExporter)
10867
+ */
10868
+ reset() {
10869
+ this.clearEvents();
10561
10870
  }
10562
- getSpan(spanId) {
10563
- return this.#spanMap.get(spanId) ?? null;
10871
+ /**
10872
+ * Get internal metrics about the exporter's own activity.
10873
+ */
10874
+ getInternalMetrics() {
10875
+ const json = this.toJSON({
10876
+ includeEvents: false,
10877
+ includeStats: false
10878
+ });
10879
+ return {
10880
+ startedAt: this.#internalMetrics.startedAt,
10881
+ lastEventAt: this.#internalMetrics.lastEventAt,
10882
+ totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10883
+ bySignal: { ...this.#internalMetrics.bySignal },
10884
+ flushCount: this.#internalMetrics.flushCount,
10885
+ estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10886
+ };
10564
10887
  }
10565
- async addScore(score) {
10566
- if (!this.#canEmitRecordedEvent()) {
10567
- this.#debugRecordedAnnotationUnavailable({
10568
- kind: "score",
10569
- traceId: this.traceId
10570
- });
10571
- return;
10888
+ /**
10889
+ * Flush buffered data and log internal metrics summary.
10890
+ */
10891
+ async flush() {
10892
+ this.#internalMetrics.flushCount++;
10893
+ if (this.#config.logMetricsOnFlush) {
10894
+ const metrics = this.getInternalMetrics();
10895
+ const uptimeMs = Date.now() - metrics.startedAt.getTime();
10896
+ const summary = [
10897
+ `[TestExporter] flush #${metrics.flushCount} summary:`,
10898
+ ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10899
+ ` total events received: ${metrics.totalEventsReceived}`,
10900
+ ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10901
+ ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10902
+ ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10903
+ ].join("\n");
10904
+ this.logger.info(summary);
10572
10905
  }
10573
- await this.#emitRecordedEvent(buildScoreEvent({
10574
- traceId: this.#rootRecord.traceId,
10575
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10576
- score,
10577
- inheritedMetadata: this.#rootRecord.metadata
10578
- }));
10579
10906
  }
10580
- async addFeedback(feedback) {
10581
- if (!this.#canEmitRecordedEvent()) {
10582
- this.#debugRecordedAnnotationUnavailable({
10583
- kind: "feedback",
10584
- traceId: this.traceId
10585
- });
10586
- return;
10907
+ async shutdown() {
10908
+ await this.flush();
10909
+ this.logger.info("TestExporter shutdown");
10910
+ }
10911
+ /**
10912
+ * Extract unique spans from a list of events
10913
+ */
10914
+ #getUniqueSpansFromEvents(events) {
10915
+ const spanMap = /* @__PURE__ */ new Map();
10916
+ for (const event of events) {
10917
+ const span = event.exportedSpan;
10918
+ if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10587
10919
  }
10588
- await this.#emitRecordedEvent(buildFeedbackEvent({
10589
- traceId: this.#rootRecord.traceId,
10590
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10591
- feedback,
10592
- inheritedMetadata: this.#rootRecord.metadata
10593
- }));
10920
+ return Array.from(spanMap.values());
10594
10921
  }
10595
10922
  };
10596
- function findRootSpan(spans) {
10597
- const spanIds = new Set(spans.map((span) => span.spanId));
10598
- return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
10599
- }
10600
- function hydrateRecordedTrace(args) {
10601
- const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
10602
- const rootSpan = findRootSpan(trace.spans);
10603
- if (!rootSpan) return null;
10604
- const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
10605
- raw,
10606
- rootSpan,
10607
- emitRecordedEvent,
10608
- canEmitRecordedEvent,
10609
- debugRecordedAnnotationUnavailable
10610
- }));
10611
- const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
10612
- for (const span of recordedSpans) {
10613
- if (!span.parentSpanId) continue;
10614
- const parent = spanMap.get(span.parentSpanId);
10615
- if (!parent) continue;
10616
- span.parent = parent;
10617
- parent.children.push(span);
10923
+ /**
10924
+ * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10925
+ */
10926
+ const JsonExporter = TestExporter;
10927
+ // src/instances/default.ts
10928
+ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10929
+ constructor(config) {
10930
+ super(config);
10618
10931
  }
10619
- const hydratedRootSpan = spanMap.get(rootSpan.spanId);
10620
- if (!hydratedRootSpan) return null;
10621
- return new RecordedTraceImpl({
10622
- traceId: trace.traceId,
10623
- rootSpan: hydratedRootSpan,
10624
- rootRecord: rootSpan,
10625
- spans: recordedSpans,
10626
- emitRecordedEvent,
10627
- canEmitRecordedEvent,
10628
- debugRecordedAnnotationUnavailable
10629
- });
10630
- }
10932
+ createSpan(options) {
10933
+ return new DefaultSpan(options, this);
10934
+ }
10935
+ };
10631
10936
  // src/registry.ts
10632
10937
  /**
10633
10938
  * Registry for Observability instances.
@@ -10934,23 +11239,6 @@ function isInstance(obj) {
10934
11239
  return obj instanceof BaseObservabilityInstance;
10935
11240
  }
10936
11241
  /**
10937
- * Delays (ms) between attempts to rehydrate a trace from storage when an
10938
- * annotation (score/feedback) targets a span that has not been flushed by
10939
- * the configured exporters yet. Exporters buffer and flush asynchronously:
10940
- * by default they flush at 1000 spans or after a 5000ms wait
10941
- * (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
10942
- * race the flush and be silently dropped. The schedule below sums to
10943
- * ~5.85s, covering the default flush interval with margin.
10944
- */
10945
- const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
10946
- 100,
10947
- 250,
10948
- 500,
10949
- 1e3,
10950
- 2e3,
10951
- 2e3
10952
- ];
10953
- /**
10954
11242
  * Manages observability instances and selects their configurations for Mastra operations.
10955
11243
  * Configure instances and exporters to collect and export telemetry.
10956
11244
  *
@@ -10977,6 +11265,7 @@ var Observability = class extends _mastra_core_base.MastraBase {
10977
11265
  #registry = new ObservabilityRegistry();
10978
11266
  #mastra;
10979
11267
  #clientObservabilityProxy;
11268
+ #pendingPersistedEvents = /* @__PURE__ */ new Set();
10980
11269
  constructor(config) {
10981
11270
  super({
10982
11271
  component: _mastra_core_logger.RegisteredLogger.OBSERVABILITY,
@@ -11117,50 +11406,57 @@ var Observability = class extends _mastra_core_base.MastraBase {
11117
11406
  async addScore(args) {
11118
11407
  const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11119
11408
  const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11120
- if (args.correlationContext) {
11121
- await this.#emitRecordedEvent(buildScoreEvent({
11122
- ...targetTraceId ? { traceId: targetTraceId } : {},
11123
- ...targetSpanId ? { spanId: targetSpanId } : {},
11124
- correlationContext: args.correlationContext,
11125
- score: args.score
11126
- }));
11127
- return;
11128
- }
11129
- if (!args.traceId) return;
11130
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
11131
- trace,
11132
- spanId: args.spanId,
11133
- score: args.score
11409
+ if (!targetTraceId && !args.correlationContext) return;
11410
+ await this.#emitRecordedEvent(buildScoreEvent({
11411
+ ...args,
11412
+ traceId: targetTraceId,
11413
+ spanId: targetSpanId
11134
11414
  }));
11135
- if (!event) {
11136
- this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11137
- return;
11138
- }
11139
- await this.#emitRecordedEvent(event);
11140
11415
  }
11141
11416
  async addFeedback(args) {
11142
- const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11143
- const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11144
- if (args.correlationContext) {
11145
- await this.#emitRecordedEvent(buildFeedbackEvent({
11146
- ...targetTraceId ? { traceId: targetTraceId } : {},
11147
- ...targetSpanId ? { spanId: targetSpanId } : {},
11148
- correlationContext: args.correlationContext,
11149
- feedback: args.feedback
11150
- }));
11151
- return;
11152
- }
11153
- if (!args.traceId) return;
11154
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
11155
- trace,
11156
- spanId: args.spanId,
11157
- feedback: args.feedback
11417
+ const traceId = args.traceId ?? args.correlationContext?.traceId;
11418
+ const spanId = args.spanId ?? args.correlationContext?.spanId;
11419
+ if (!traceId && !args.correlationContext) return;
11420
+ await this.#emitRecordedEvent(buildFeedbackEvent({
11421
+ ...args,
11422
+ traceId,
11423
+ spanId
11158
11424
  }));
11159
- if (!event) {
11160
- this.logger?.warn(`Feedback event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11161
- return;
11162
- }
11163
- await this.#emitRecordedEvent(event);
11425
+ }
11426
+ async replaceFeedback(args) {
11427
+ 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");
11428
+ await this.#emitRecordedEvent({
11429
+ type: "feedback_replacement",
11430
+ feedback: {
11431
+ ...args.feedback,
11432
+ traceId: args.traceId,
11433
+ spanId: args.spanId,
11434
+ correlationContext: args.correlationContext
11435
+ }
11436
+ });
11437
+ }
11438
+ async updateFeedbackReviewStatus(args) {
11439
+ if (!args.feedbackId?.trim() || !["needs-review", "reviewed"].includes(args.reviewStatus)) throw new Error("Feedback review update requires feedbackId and a valid reviewStatus");
11440
+ await this.#emitRecordedEvent({
11441
+ type: "feedback_review_status",
11442
+ feedback: {
11443
+ feedbackId: args.feedbackId,
11444
+ reviewStatus: args.reviewStatus
11445
+ }
11446
+ });
11447
+ }
11448
+ /** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
11449
+ async __exportPersistedEvent(event) {
11450
+ const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
11451
+ const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
11452
+ this.#pendingPersistedEvents.add(pending);
11453
+ pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
11454
+ this.#pendingPersistedEvents.delete(pending);
11455
+ this.logger.error("Failed to notify exporters of persisted feedback/score", {
11456
+ error,
11457
+ eventType: event.type
11458
+ });
11459
+ });
11164
11460
  }
11165
11461
  /** Register a named observability instance, optionally marking it as default. */
11166
11462
  registerInstance(name, instance, isDefault = false) {
@@ -11197,12 +11493,18 @@ var Observability = class extends _mastra_core_base.MastraBase {
11197
11493
  }
11198
11494
  /** Flush all registered instances without shutting down. */
11199
11495
  async flush() {
11496
+ await this.#drainPersistedEvents();
11200
11497
  await this.#registry.flush();
11201
11498
  }
11202
11499
  /** Shut down all registered instances, flushing any pending data. */
11203
11500
  async shutdown() {
11501
+ await this.#drainPersistedEvents();
11204
11502
  await this.#registry.shutdown();
11205
11503
  }
11504
+ /** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
11505
+ async #drainPersistedEvents() {
11506
+ while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
11507
+ }
11206
11508
  /**
11207
11509
  * Returns the proxy responsible for client observability (W3C trace
11208
11510
  * context injection + OTLP/JSON payload reception for spans/logs
@@ -11224,40 +11526,22 @@ var Observability = class extends _mastra_core_base.MastraBase {
11224
11526
  if (!storage) return null;
11225
11527
  return await storage.getStore("observability") ?? null;
11226
11528
  }
11227
- /**
11228
- * Build a recorded score/feedback event from storage, retrying briefly to
11229
- * ride out the async exporter flush: annotations emitted right after a
11230
- * span ends can otherwise race the flush and be silently dropped.
11231
- */
11232
- async #buildRecordedEventWithRetry(traceId, build) {
11233
- for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
11234
- if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
11235
- const trace = await this.#getStoredTrace(traceId);
11236
- const event = trace ? build(trace) : null;
11237
- if (event) return event;
11238
- }
11239
- return null;
11240
- }
11241
- async #getStoredTrace(traceId) {
11242
- const observabilityStorage = await this.#getObservabilityStorage();
11243
- if (!observabilityStorage) return null;
11244
- return observabilityStorage.getTrace({ traceId });
11245
- }
11246
11529
  #getRecordedTraceInstance() {
11247
11530
  return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
11248
11531
  }
11249
- async #emitRecordedEvent(event) {
11532
+ /** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
11533
+ async #emitRecordedEvent(event, shouldHandle) {
11250
11534
  const instance = this.#getRecordedTraceInstance();
11251
11535
  if (!instance) {
11252
11536
  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 });
11253
11537
  return;
11254
11538
  }
11255
11539
  if (instance instanceof BaseObservabilityInstance) {
11256
- instance.__emitRecordedEvent(event);
11540
+ instance.__emitRecordedEvent(event, shouldHandle);
11257
11541
  return;
11258
11542
  }
11259
11543
  const bridge = instance.getBridge();
11260
- const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11544
+ 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");
11261
11545
  if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
11262
11546
  }
11263
11547
  };
@@ -11344,6 +11628,7 @@ exports.OBSERVABILITY_CAPABILITIES_HEADER = OBSERVABILITY_CAPABILITIES_HEADER;
11344
11628
  exports.Observability = Observability;
11345
11629
  exports.ObservabilityBus = ObservabilityBus;
11346
11630
  exports.QUOTA_PAUSE_CAPABILITY = QUOTA_PAUSE_CAPABILITY;
11631
+ exports.REDACTED_ERROR_MESSAGE = REDACTED_ERROR_MESSAGE;
11347
11632
  exports.SamplingStrategyType = SamplingStrategyType;
11348
11633
  exports.SensitiveDataFilter = SensitiveDataFilter;
11349
11634
  exports.TestExporter = TestExporter;
@@ -11370,6 +11655,7 @@ exports.otlpSeverityToLogLevel = otlpSeverityToLogLevel;
11370
11655
  exports.parseBaggage = parseBaggage;
11371
11656
  exports.parseTraceparent = parseTraceparent;
11372
11657
  exports.reconstructSerializedMap = reconstructSerializedMap;
11658
+ exports.redactErrorInfo = redactErrorInfo;
11373
11659
  exports.routeToHandler = routeToHandler;
11374
11660
  exports.samplingStrategySchema = samplingStrategySchema;
11375
11661
  exports.serializationOptionsSchema = serializationOptionsSchema;