@mastra/observability 1.24.0-alpha.4 → 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 (33) 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 +900 -730
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.js +900 -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/recorded.d.ts +4 -12
  32. package/dist/recorded.d.ts.map +1 -1
  33. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -52,6 +52,9 @@ function routeToHandler(handler, event, logger) {
52
52
  }), handler.name, "score", logger);
53
53
  }
54
54
  break;
55
+ case "feedback_replacement":
56
+ if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
57
+ break;
55
58
  case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
56
59
  }
57
60
  } catch (err) {
@@ -552,6 +555,10 @@ function cleanEvent(event, options) {
552
555
  type: "score",
553
556
  score: deepClean(event.score, options)
554
557
  };
558
+ case "feedback_replacement": return {
559
+ type: event.type,
560
+ feedback: deepClean(event.feedback, options)
561
+ };
555
562
  case "feedback": return {
556
563
  type: "feedback",
557
564
  feedback: deepClean(event.feedback, options)
@@ -644,10 +651,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
644
651
  * emit() is synchronous — async handler promises are tracked internally
645
652
  * and can be drained via flush().
646
653
  */
647
- emit(event) {
654
+ emit(event, shouldHandle) {
648
655
  const cleaned = cleanEvent(event, this.deepCleanOptions);
649
- for (const exporter of this.exporters) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
650
- if (this.bridge) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
656
+ for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
657
+ if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
651
658
  super.emit(cleaned);
652
659
  }
653
660
  /**
@@ -4599,194 +4606,549 @@ var EventBuffer = class {
4599
4606
  });
4600
4607
  }
4601
4608
  };
4602
- // src/exporters/default.ts
4603
- /**
4604
- * Resolves the final tracing storage strategy based on config and observability store hints
4605
- */
4606
- function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4607
- const observabilityStrategy = observabilityStorage.observabilityStrategy;
4608
- if (config.strategy && config.strategy !== "auto") {
4609
- if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4610
- logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4611
- userStrategy: config.strategy,
4612
- storageAdapter: storageName,
4613
- supportedStrategies: observabilityStrategy.supported,
4614
- fallbackStrategy: observabilityStrategy.preferred
4615
- });
4616
- }
4617
- return observabilityStrategy.preferred;
4609
+ // src/recorded.ts
4610
+ function nullToUndefined(value) {
4611
+ return value ?? void 0;
4618
4612
  }
4619
- const FLUSH_SUCCEEDED$1 = { failed: false };
4620
- /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
4621
- const MAX_FLUSH_ROUNDS$1 = 3;
4622
- /**
4623
- * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
4624
- * This class is preserved unchanged so existing integrations (including code
4625
- * that matches on the `mastra-default-observability-exporter` exporter name)
4626
- * keep working. It will be removed in a future major version.
4627
- *
4628
- * Default storage-backed exporter. Buffers observability events and flushes them
4629
- * in batches to the configured ObservabilityStorage backend with retry support.
4630
- */
4631
- var DefaultExporter = class extends BaseExporter {
4632
- name = "mastra-default-observability-exporter";
4633
- #config;
4634
- #isInitializing = false;
4635
- #initPromises = /* @__PURE__ */ new Set();
4636
- #eventBuffer;
4637
- #storage;
4638
- #observabilityStorage;
4639
- #resolvedStrategy;
4640
- #flushTimer;
4641
- /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
4642
- #inFlightFlushes = /* @__PURE__ */ new Set();
4643
- #emitDropEvent;
4644
- #unsupportedSignals = /* @__PURE__ */ new Set();
4645
- constructor(config = {}) {
4646
- super(config);
4647
- this.#config = {
4648
- ...config,
4649
- maxBatchSize: config.maxBatchSize ?? 1e3,
4650
- maxBufferSize: config.maxBufferSize ?? 1e4,
4651
- maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
4652
- maxRetries: config.maxRetries ?? 4,
4653
- retryDelayMs: config.retryDelayMs ?? 500,
4654
- strategy: config.strategy ?? "auto"
4655
- };
4656
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
4657
- }
4658
- /**
4659
- * Initialize the exporter (called after all dependencies are ready)
4660
- */
4661
- async init(options) {
4662
- try {
4663
- this.#isInitializing = true;
4664
- this.#emitDropEvent = options.emitDropEvent;
4665
- this.#storage = options.mastra?.getStorage();
4666
- if (!this.#storage) {
4667
- this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
4668
- return;
4669
- }
4670
- this.#observabilityStorage = await this.#storage.getStore("observability");
4671
- if (!this.#observabilityStorage) {
4672
- this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
4673
- return;
4674
- }
4675
- if (!this.#resolvedStrategy) {
4676
- this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
4677
- this.logger.debug("tracing storage exporter initialized", {
4678
- strategy: this.#resolvedStrategy,
4679
- source: this.#config.strategy !== "auto" ? "user" : "auto",
4680
- storageAdapter: this.#storage.constructor.name,
4681
- maxBatchSize: this.#config.maxBatchSize,
4682
- maxBatchWaitMs: this.#config.maxBatchWaitMs
4683
- });
4684
- }
4685
- if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4686
- } finally {
4687
- this.#isInitializing = false;
4688
- /**
4689
- * Assumes caller waits until export of a parent span is completed before calling
4690
- * export for child spans , order is not relevant for resolve
4691
- */
4692
- this.#initPromises.forEach((resolve) => {
4693
- resolve();
4694
- });
4695
- this.#initPromises.clear();
4696
- }
4697
- }
4698
- /**
4699
- * Checks if buffer should be flushed based on size or time triggers
4700
- */
4701
- shouldFlush() {
4702
- if (this.#resolvedStrategy === "realtime") return true;
4703
- if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
4704
- if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
4705
- if (this.#eventBuffer.totalSize > 0) {
4706
- if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
4707
- }
4708
- return false;
4709
- }
4710
- /**
4711
- * Schedules a flush using setTimeout
4712
- */
4713
- scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
4714
- if (this.#flushTimer) clearTimeout(this.#flushTimer);
4715
- this.#flushTimer = setTimeout(() => {
4716
- this.#flushTimer = void 0;
4717
- this.trackFlushBuffer().catch((error) => {
4718
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
4719
- });
4720
- }, delayMs);
4721
- }
4722
- retryDelay(retryAttempt) {
4723
- return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
4724
- }
4725
- retryAttempt(events) {
4726
- return events.reduce((earliestAttempt, event) => {
4727
- if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
4728
- return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
4729
- }, void 0);
4730
- }
4731
- logStorageFailure(signal, events, retryAttempt, error) {
4732
- this.logger.warn("Failed to persist observability events", {
4733
- signal,
4734
- eventCount: events.length,
4735
- retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
4736
- maxRetries: this.#config.maxRetries,
4737
- ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
4738
- error: error instanceof Error ? error.message : String(error)
4739
- });
4740
- }
4741
- /**
4742
- * Checks flush triggers and schedules/triggers flush as needed.
4743
- * Called after adding any event to the buffer.
4744
- * Returns the flush promise when flushing so callers can await it.
4745
- */
4746
- async handleBatchedFlush() {
4747
- if (this.shouldFlush()) await this.trackFlushBuffer();
4748
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
4749
- }
4750
- sanitizeDropError(error) {
4751
- if (error instanceof MastraError) return {
4752
- id: error.id,
4753
- domain: String(error.domain),
4754
- message: error.message
4755
- };
4756
- if (error instanceof Error) return { message: error.message };
4757
- return { message: String(error) };
4758
- }
4759
- emitDrop(signal, reason, count, error) {
4760
- if (count === 0) return;
4761
- const dropEvent = {
4762
- type: "drop",
4763
- signal,
4764
- reason,
4765
- count,
4613
+ function mergeMetadata(base, extra) {
4614
+ if (!base && !extra) return void 0;
4615
+ return {
4616
+ ...base ?? {},
4617
+ ...extra ?? {}
4618
+ };
4619
+ }
4620
+ function normalizeErrorInfo(error) {
4621
+ if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
4622
+ return {
4623
+ message: error.message,
4624
+ id: "id" in error && typeof error.id === "string" ? error.id : void 0,
4625
+ name: "name" in error && typeof error.name === "string" ? error.name : void 0,
4626
+ stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
4627
+ domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
4628
+ category: "category" in error && typeof error.category === "string" ? error.category : void 0,
4629
+ details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
4630
+ };
4631
+ }
4632
+ function buildCorrelationContext(span, rootSpan, parent) {
4633
+ return {
4634
+ tags: rootSpan.tags ?? void 0,
4635
+ entityType: nullToUndefined(span.entityType),
4636
+ entityId: nullToUndefined(span.entityId),
4637
+ entityName: nullToUndefined(span.entityName),
4638
+ parentEntityType: parent?.entityType ?? void 0,
4639
+ parentEntityId: parent?.entityId ?? void 0,
4640
+ parentEntityName: parent?.entityName ?? void 0,
4641
+ rootEntityType: nullToUndefined(rootSpan.entityType),
4642
+ rootEntityId: nullToUndefined(rootSpan.entityId),
4643
+ rootEntityName: nullToUndefined(rootSpan.entityName),
4644
+ userId: nullToUndefined(span.userId),
4645
+ organizationId: nullToUndefined(span.organizationId),
4646
+ resourceId: nullToUndefined(span.resourceId),
4647
+ runId: nullToUndefined(span.runId),
4648
+ sessionId: nullToUndefined(span.sessionId),
4649
+ threadId: nullToUndefined(span.threadId),
4650
+ requestId: nullToUndefined(span.requestId),
4651
+ environment: nullToUndefined(span.environment),
4652
+ source: nullToUndefined(span.source),
4653
+ serviceName: nullToUndefined(span.serviceName),
4654
+ experimentId: nullToUndefined(span.experimentId)
4655
+ };
4656
+ }
4657
+ function buildScoreEvent(args) {
4658
+ const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
4659
+ return {
4660
+ type: "score",
4661
+ score: {
4662
+ scoreId: generateSignalId(),
4766
4663
  timestamp: /* @__PURE__ */ new Date(),
4767
- exporterName: this.name,
4768
- ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
4769
- ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
4770
- };
4771
- this.#emitDropEvent?.(dropEvent);
4772
- }
4773
- /**
4774
- * Flush a batch of create events for a single signal type.
4775
- * On "not implemented" errors, disables the signal for future flushes.
4776
- * On other errors, re-adds events to the buffer for retry.
4777
- */
4778
- async flushCreates(signal, events, storageCall) {
4779
- if (events.length === 0) return FLUSH_SUCCEEDED$1;
4780
- if (this.#unsupportedSignals.has(signal)) {
4781
- this.emitDrop(signal, "unsupported-storage", events.length);
4782
- return { failed: true };
4664
+ traceId,
4665
+ spanId,
4666
+ scorerId: score.scorerId,
4667
+ scorerName: score.scorerName,
4668
+ scorerVersion: score.scorerVersion,
4669
+ source: score.source,
4670
+ scoreSource: score.scoreSource,
4671
+ score: score.score,
4672
+ reason: score.reason,
4673
+ experimentId: score.experimentId,
4674
+ scoreTraceId: score.scoreTraceId,
4675
+ targetEntityType: score.targetEntityType,
4676
+ correlationContext,
4677
+ metadata: mergeMetadata(inheritedMetadata, score.metadata)
4783
4678
  }
4784
- try {
4785
- await storageCall(events);
4786
- return FLUSH_SUCCEEDED$1;
4787
- } catch (error) {
4788
- if (error instanceof MastraError && error.domain === ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
4789
- this.logger.warn(error.message);
4679
+ };
4680
+ }
4681
+ function buildFeedbackEvent(args) {
4682
+ const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
4683
+ return {
4684
+ type: "feedback",
4685
+ feedback: {
4686
+ feedbackId: generateSignalId(),
4687
+ timestamp: /* @__PURE__ */ new Date(),
4688
+ traceId,
4689
+ spanId,
4690
+ source: feedback.source,
4691
+ feedbackSource: feedback.feedbackSource,
4692
+ feedbackType: feedback.feedbackType,
4693
+ value: feedback.value,
4694
+ userId: feedback.userId,
4695
+ feedbackUserId: feedback.feedbackUserId,
4696
+ comment: feedback.comment,
4697
+ sourceId: feedback.sourceId,
4698
+ experimentId: feedback.experimentId,
4699
+ correlationContext,
4700
+ metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
4701
+ }
4702
+ };
4703
+ }
4704
+ function findSpanById(spans, spanId) {
4705
+ if (!spanId) return void 0;
4706
+ return spans.find((span) => span.spanId === spanId);
4707
+ }
4708
+ /** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
4709
+ function resolveRecordedEventFromTrace(trace, event) {
4710
+ const record = event.type === "score" ? event.score : event.feedback;
4711
+ const spans = trace.spans.filter((span) => span.traceId === record.traceId);
4712
+ const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
4713
+ if (!span) return null;
4714
+ const byId = new Map(spans.map((span) => [span.spanId, span]));
4715
+ let root = span;
4716
+ const visited = /* @__PURE__ */ new Set();
4717
+ while (root.parentSpanId) {
4718
+ if (visited.has(root.spanId)) return null;
4719
+ visited.add(root.spanId);
4720
+ const parent = byId.get(root.parentSpanId);
4721
+ if (!parent) return null;
4722
+ root = parent;
4723
+ }
4724
+ const context = {
4725
+ correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
4726
+ metadata: mergeMetadata(span.metadata, record.metadata)
4727
+ };
4728
+ return event.type === "score" ? {
4729
+ type: "score",
4730
+ score: {
4731
+ ...event.score,
4732
+ ...context
4733
+ }
4734
+ } : event.type === "feedback_replacement" ? {
4735
+ type: "feedback_replacement",
4736
+ feedback: {
4737
+ ...event.feedback,
4738
+ ...context
4739
+ }
4740
+ } : {
4741
+ type: "feedback",
4742
+ feedback: {
4743
+ ...event.feedback,
4744
+ ...context
4745
+ }
4746
+ };
4747
+ }
4748
+ var RecordedSpanImpl = class {
4749
+ id;
4750
+ traceId;
4751
+ name;
4752
+ type;
4753
+ entityType;
4754
+ entityId;
4755
+ entityName;
4756
+ startTime;
4757
+ endTime;
4758
+ attributes;
4759
+ metadata;
4760
+ tags;
4761
+ input;
4762
+ output;
4763
+ errorInfo;
4764
+ requestContext;
4765
+ isEvent;
4766
+ isRootSpan;
4767
+ parentSpanId;
4768
+ parent;
4769
+ children = [];
4770
+ #raw;
4771
+ #rootSpan;
4772
+ #emitRecordedEvent;
4773
+ #canEmitRecordedEvent;
4774
+ #debugRecordedAnnotationUnavailable;
4775
+ constructor(args) {
4776
+ const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
4777
+ this.#raw = raw;
4778
+ this.#rootSpan = rootSpan;
4779
+ this.#emitRecordedEvent = emitRecordedEvent;
4780
+ this.#canEmitRecordedEvent = canEmitRecordedEvent;
4781
+ this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
4782
+ this.id = raw.spanId;
4783
+ this.traceId = raw.traceId;
4784
+ this.name = raw.name;
4785
+ this.type = raw.spanType;
4786
+ this.entityType = raw.entityType ?? void 0;
4787
+ this.entityId = raw.entityId ?? void 0;
4788
+ this.entityName = raw.entityName ?? void 0;
4789
+ this.startTime = raw.startedAt;
4790
+ this.endTime = raw.endedAt ?? void 0;
4791
+ this.attributes = raw.attributes ?? void 0;
4792
+ this.metadata = raw.metadata ?? void 0;
4793
+ this.tags = raw.tags ?? void 0;
4794
+ this.input = raw.input ?? void 0;
4795
+ this.output = raw.output ?? void 0;
4796
+ this.errorInfo = normalizeErrorInfo(raw.error);
4797
+ this.requestContext = raw.requestContext ?? void 0;
4798
+ this.isEvent = raw.isEvent;
4799
+ this.isRootSpan = !raw.parentSpanId;
4800
+ this.parentSpanId = raw.parentSpanId ?? void 0;
4801
+ }
4802
+ async addScore(score) {
4803
+ if (!this.#canEmitRecordedEvent()) {
4804
+ this.#debugRecordedAnnotationUnavailable({
4805
+ kind: "score",
4806
+ traceId: this.traceId,
4807
+ spanId: this.id
4808
+ });
4809
+ return;
4810
+ }
4811
+ await this.#emitRecordedEvent(buildScoreEvent({
4812
+ traceId: this.#raw.traceId,
4813
+ spanId: this.id,
4814
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4815
+ score,
4816
+ inheritedMetadata: this.#raw.metadata
4817
+ }));
4818
+ }
4819
+ async addFeedback(feedback) {
4820
+ if (!this.#canEmitRecordedEvent()) {
4821
+ this.#debugRecordedAnnotationUnavailable({
4822
+ kind: "feedback",
4823
+ traceId: this.traceId,
4824
+ spanId: this.id
4825
+ });
4826
+ return;
4827
+ }
4828
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4829
+ traceId: this.#raw.traceId,
4830
+ spanId: this.id,
4831
+ correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
4832
+ feedback,
4833
+ inheritedMetadata: this.#raw.metadata
4834
+ }));
4835
+ }
4836
+ };
4837
+ var RecordedTraceImpl = class {
4838
+ traceId;
4839
+ rootSpan;
4840
+ spans;
4841
+ #rootRecord;
4842
+ #emitRecordedEvent;
4843
+ #spanMap;
4844
+ #canEmitRecordedEvent;
4845
+ #debugRecordedAnnotationUnavailable;
4846
+ constructor(args) {
4847
+ this.traceId = args.traceId;
4848
+ this.rootSpan = args.rootSpan;
4849
+ this.#rootRecord = args.rootRecord;
4850
+ this.spans = args.spans;
4851
+ this.#emitRecordedEvent = args.emitRecordedEvent;
4852
+ this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
4853
+ this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
4854
+ this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
4855
+ }
4856
+ getSpan(spanId) {
4857
+ return this.#spanMap.get(spanId) ?? null;
4858
+ }
4859
+ async addScore(score) {
4860
+ if (!this.#canEmitRecordedEvent()) {
4861
+ this.#debugRecordedAnnotationUnavailable({
4862
+ kind: "score",
4863
+ traceId: this.traceId
4864
+ });
4865
+ return;
4866
+ }
4867
+ await this.#emitRecordedEvent(buildScoreEvent({
4868
+ traceId: this.#rootRecord.traceId,
4869
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4870
+ score,
4871
+ inheritedMetadata: this.#rootRecord.metadata
4872
+ }));
4873
+ }
4874
+ async addFeedback(feedback) {
4875
+ if (!this.#canEmitRecordedEvent()) {
4876
+ this.#debugRecordedAnnotationUnavailable({
4877
+ kind: "feedback",
4878
+ traceId: this.traceId
4879
+ });
4880
+ return;
4881
+ }
4882
+ await this.#emitRecordedEvent(buildFeedbackEvent({
4883
+ traceId: this.#rootRecord.traceId,
4884
+ correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
4885
+ feedback,
4886
+ inheritedMetadata: this.#rootRecord.metadata
4887
+ }));
4888
+ }
4889
+ };
4890
+ function findRootSpan(spans) {
4891
+ const spanIds = new Set(spans.map((span) => span.spanId));
4892
+ return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
4893
+ }
4894
+ function hydrateRecordedTrace(args) {
4895
+ const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
4896
+ const rootSpan = findRootSpan(trace.spans);
4897
+ if (!rootSpan) return null;
4898
+ const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
4899
+ raw,
4900
+ rootSpan,
4901
+ emitRecordedEvent,
4902
+ canEmitRecordedEvent,
4903
+ debugRecordedAnnotationUnavailable
4904
+ }));
4905
+ const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
4906
+ for (const span of recordedSpans) {
4907
+ if (!span.parentSpanId) continue;
4908
+ const parent = spanMap.get(span.parentSpanId);
4909
+ if (!parent) continue;
4910
+ span.parent = parent;
4911
+ parent.children.push(span);
4912
+ }
4913
+ const hydratedRootSpan = spanMap.get(rootSpan.spanId);
4914
+ if (!hydratedRootSpan) return null;
4915
+ return new RecordedTraceImpl({
4916
+ traceId: trace.traceId,
4917
+ rootSpan: hydratedRootSpan,
4918
+ rootRecord: rootSpan,
4919
+ spans: recordedSpans,
4920
+ emitRecordedEvent,
4921
+ canEmitRecordedEvent,
4922
+ debugRecordedAnnotationUnavailable
4923
+ });
4924
+ }
4925
+ // src/exporters/storage-annotation.ts
4926
+ const LOOKUP_DELAYS_MS = [
4927
+ 0,
4928
+ 100,
4929
+ 250,
4930
+ 500,
4931
+ 1e3,
4932
+ 2e3,
4933
+ 2e3
4934
+ ];
4935
+ /**
4936
+ * Resolve attached-storage context within a bounded retry window, including failed reads.
4937
+ * Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
4938
+ * Other destinations receive the original event independently.
4939
+ */
4940
+ async function resolveStorageAnnotation(event, storage, flushSpans) {
4941
+ const record = event.type === "score" ? event.score : event.feedback;
4942
+ if (record.correlationContext !== void 0) return event;
4943
+ if (!record.traceId) return null;
4944
+ let lastReadFailure;
4945
+ for (const delay of LOOKUP_DELAYS_MS) {
4946
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
4947
+ let trace;
4948
+ try {
4949
+ trace = await storage.getTrace({ traceId: record.traceId });
4950
+ lastReadFailure = void 0;
4951
+ } catch (error) {
4952
+ lastReadFailure = { error };
4953
+ }
4954
+ if (trace) {
4955
+ const resolved = resolveRecordedEventFromTrace(trace, event);
4956
+ if (resolved) return resolved;
4957
+ }
4958
+ if (delay === 0) await flushSpans();
4959
+ }
4960
+ if (lastReadFailure) throw lastReadFailure.error;
4961
+ return null;
4962
+ }
4963
+ // src/exporters/default.ts
4964
+ /**
4965
+ * Resolves the final tracing storage strategy based on config and observability store hints
4966
+ */
4967
+ function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
4968
+ const observabilityStrategy = observabilityStorage.observabilityStrategy;
4969
+ if (config.strategy && config.strategy !== "auto") {
4970
+ if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
4971
+ logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
4972
+ userStrategy: config.strategy,
4973
+ storageAdapter: storageName,
4974
+ supportedStrategies: observabilityStrategy.supported,
4975
+ fallbackStrategy: observabilityStrategy.preferred
4976
+ });
4977
+ }
4978
+ return observabilityStrategy.preferred;
4979
+ }
4980
+ const FLUSH_SUCCEEDED$1 = { failed: false };
4981
+ /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
4982
+ const MAX_FLUSH_ROUNDS$1 = 3;
4983
+ /**
4984
+ * @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
4985
+ * This class is preserved unchanged so existing integrations (including code
4986
+ * that matches on the `mastra-default-observability-exporter` exporter name)
4987
+ * keep working. It will be removed in a future major version.
4988
+ *
4989
+ * Default storage-backed exporter. Buffers observability events and flushes them
4990
+ * in batches to the configured ObservabilityStorage backend with retry support.
4991
+ */
4992
+ var DefaultExporter = class extends BaseExporter {
4993
+ name = "mastra-default-observability-exporter";
4994
+ #config;
4995
+ #isInitializing = false;
4996
+ #initPromises = /* @__PURE__ */ new Set();
4997
+ #eventBuffer;
4998
+ #storage;
4999
+ #observabilityStorage;
5000
+ #resolvedStrategy;
5001
+ #flushTimer;
5002
+ /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5003
+ #inFlightFlushes = /* @__PURE__ */ new Set();
5004
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5005
+ #emitDropEvent;
5006
+ #unsupportedSignals = /* @__PURE__ */ new Set();
5007
+ constructor(config = {}) {
5008
+ super(config);
5009
+ this.#config = {
5010
+ ...config,
5011
+ maxBatchSize: config.maxBatchSize ?? 1e3,
5012
+ maxBufferSize: config.maxBufferSize ?? 1e4,
5013
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
5014
+ maxRetries: config.maxRetries ?? 4,
5015
+ retryDelayMs: config.retryDelayMs ?? 500,
5016
+ strategy: config.strategy ?? "auto"
5017
+ };
5018
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5019
+ }
5020
+ /**
5021
+ * Initialize the exporter (called after all dependencies are ready)
5022
+ */
5023
+ async init(options) {
5024
+ try {
5025
+ this.#isInitializing = true;
5026
+ this.#emitDropEvent = options.emitDropEvent;
5027
+ this.#storage = options.mastra?.getStorage();
5028
+ if (!this.#storage) {
5029
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
5030
+ return;
5031
+ }
5032
+ this.#observabilityStorage = await this.#storage.getStore("observability");
5033
+ if (!this.#observabilityStorage) {
5034
+ this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
5035
+ return;
5036
+ }
5037
+ if (!this.#resolvedStrategy) {
5038
+ this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
5039
+ this.logger.debug("tracing storage exporter initialized", {
5040
+ strategy: this.#resolvedStrategy,
5041
+ source: this.#config.strategy !== "auto" ? "user" : "auto",
5042
+ storageAdapter: this.#storage.constructor.name,
5043
+ maxBatchSize: this.#config.maxBatchSize,
5044
+ maxBatchWaitMs: this.#config.maxBatchWaitMs
5045
+ });
5046
+ }
5047
+ if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5048
+ } finally {
5049
+ this.#isInitializing = false;
5050
+ /**
5051
+ * Assumes caller waits until export of a parent span is completed before calling
5052
+ * export for child spans , order is not relevant for resolve
5053
+ */
5054
+ this.#initPromises.forEach((resolve) => {
5055
+ resolve();
5056
+ });
5057
+ this.#initPromises.clear();
5058
+ }
5059
+ }
5060
+ /**
5061
+ * Checks if buffer should be flushed based on size or time triggers
5062
+ */
5063
+ shouldFlush() {
5064
+ if (this.#resolvedStrategy === "realtime") return true;
5065
+ if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5066
+ if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
5067
+ if (this.#eventBuffer.totalSize > 0) {
5068
+ if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
5069
+ }
5070
+ return false;
5071
+ }
5072
+ /**
5073
+ * Schedules a flush using setTimeout
5074
+ */
5075
+ scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
5076
+ if (this.#flushTimer) clearTimeout(this.#flushTimer);
5077
+ this.#flushTimer = setTimeout(() => {
5078
+ this.#flushTimer = void 0;
5079
+ this.trackFlushBuffer().catch((error) => {
5080
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5081
+ });
5082
+ }, delayMs);
5083
+ }
5084
+ retryDelay(retryAttempt) {
5085
+ return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5086
+ }
5087
+ retryAttempt(events) {
5088
+ return events.reduce((earliestAttempt, event) => {
5089
+ if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
5090
+ return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
5091
+ }, void 0);
5092
+ }
5093
+ logStorageFailure(signal, events, retryAttempt, error) {
5094
+ this.logger.warn("Failed to persist observability events", {
5095
+ signal,
5096
+ eventCount: events.length,
5097
+ retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
5098
+ maxRetries: this.#config.maxRetries,
5099
+ ...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
5100
+ error: error instanceof Error ? error.message : String(error)
5101
+ });
5102
+ }
5103
+ /**
5104
+ * Checks flush triggers and schedules/triggers flush as needed.
5105
+ * Called after adding any event to the buffer.
5106
+ * Returns the flush promise when flushing so callers can await it.
5107
+ */
5108
+ async handleBatchedFlush() {
5109
+ if (this.shouldFlush()) await this.trackFlushBuffer();
5110
+ else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5111
+ }
5112
+ sanitizeDropError(error) {
5113
+ if (error instanceof MastraError) return {
5114
+ id: error.id,
5115
+ domain: String(error.domain),
5116
+ message: error.message
5117
+ };
5118
+ if (error instanceof Error) return { message: error.message };
5119
+ return { message: String(error) };
5120
+ }
5121
+ emitDrop(signal, reason, count, error) {
5122
+ if (count === 0) return;
5123
+ const dropEvent = {
5124
+ type: "drop",
5125
+ signal,
5126
+ reason,
5127
+ count,
5128
+ timestamp: /* @__PURE__ */ new Date(),
5129
+ exporterName: this.name,
5130
+ ...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
5131
+ ...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
5132
+ };
5133
+ this.#emitDropEvent?.(dropEvent);
5134
+ }
5135
+ /**
5136
+ * Flush a batch of create events for a single signal type.
5137
+ * On "not implemented" errors, disables the signal for future flushes.
5138
+ * On other errors, re-adds events to the buffer for retry.
5139
+ */
5140
+ async flushCreates(signal, events, storageCall) {
5141
+ if (events.length === 0) return FLUSH_SUCCEEDED$1;
5142
+ if (this.#unsupportedSignals.has(signal)) {
5143
+ this.emitDrop(signal, "unsupported-storage", events.length);
5144
+ return { failed: true };
5145
+ }
5146
+ try {
5147
+ await storageCall(events);
5148
+ return FLUSH_SUCCEEDED$1;
5149
+ } catch (error) {
5150
+ if (error instanceof MastraError && error.domain === ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
5151
+ this.logger.warn(error.message);
4790
5152
  this.#unsupportedSignals.add(signal);
4791
5153
  this.emitDrop(signal, "unsupported-storage", events.length, error);
4792
5154
  return { failed: true };
@@ -4912,7 +5274,10 @@ var DefaultExporter = class extends BaseExporter {
4912
5274
  case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
4913
5275
  }
4914
5276
  const flushResults = await Promise.all([
4915
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5277
+ this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5278
+ feedbacks: events.map((f) => buildFeedbackRecord(f)),
5279
+ onConflict: "ignore"
5280
+ })),
4916
5281
  this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
4917
5282
  this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
4918
5283
  this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
@@ -4989,22 +5354,46 @@ var DefaultExporter = class extends BaseExporter {
4989
5354
  this.#eventBuffer.addEvent(event);
4990
5355
  await this.handleBatchedFlush();
4991
5356
  }
4992
- /**
4993
- * Handle score events — buffer for batch flush.
4994
- */
4995
- async onScoreEvent(event) {
4996
- await this.waitForInit();
4997
- if (!this.#observabilityStorage) return;
4998
- this.#eventBuffer.addEvent(event);
4999
- await this.handleBatchedFlush();
5357
+ onScoreEvent(event) {
5358
+ return this.enqueueAnnotation(event);
5000
5359
  }
5001
- /**
5002
- * Handle feedback events — buffer for batch flush.
5003
- */
5004
- async onFeedbackEvent(event) {
5360
+ onFeedbackReplacementEvent(event) {
5361
+ return this.enqueueAnnotation(event);
5362
+ }
5363
+ onFeedbackEvent(event) {
5364
+ return this.enqueueAnnotation(event);
5365
+ }
5366
+ enqueueAnnotation(event) {
5367
+ const pending = this.storeAnnotation(event);
5368
+ this.#pendingAnnotations.add(pending);
5369
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
5370
+ return pending;
5371
+ }
5372
+ async storeAnnotation(event) {
5005
5373
  await this.waitForInit();
5006
5374
  if (!this.#observabilityStorage) return;
5007
- this.#eventBuffer.addEvent(event);
5375
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
5376
+ await Promise.allSettled([...this.#inFlightFlushes]);
5377
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5378
+ });
5379
+ if (!resolved) {
5380
+ const record = event.type === "score" ? event.score : event.feedback;
5381
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
5382
+ eventType: event.type,
5383
+ traceId: record.traceId,
5384
+ spanId: record.spanId
5385
+ });
5386
+ return;
5387
+ }
5388
+ if (resolved.type === "feedback_replacement") {
5389
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
5390
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
5391
+ return;
5392
+ }
5393
+ await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
5394
+ return;
5395
+ }
5396
+ this.#eventBuffer.addEvent(resolved);
5008
5397
  await this.handleBatchedFlush();
5009
5398
  }
5010
5399
  /**
@@ -5013,6 +5402,7 @@ var DefaultExporter = class extends BaseExporter {
5013
5402
  * are exported before the runtime instance is terminated.
5014
5403
  */
5015
5404
  async flush() {
5405
+ await Promise.allSettled([...this.#pendingAnnotations]);
5016
5406
  for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
5017
5407
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5018
5408
  if (this.#eventBuffer.totalSize > 0) {
@@ -5162,6 +5552,7 @@ var MastraStorageExporter = class extends BaseExporter {
5162
5552
  #flushTimer;
5163
5553
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5164
5554
  #inFlightFlushes = /* @__PURE__ */ new Set();
5555
+ #pendingAnnotations = /* @__PURE__ */ new Set();
5165
5556
  #emitDropEvent;
5166
5557
  #unsupportedSignals = /* @__PURE__ */ new Set();
5167
5558
  constructor(config = {}) {
@@ -5532,7 +5923,10 @@ var MastraStorageExporter = class extends BaseExporter {
5532
5923
  case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5533
5924
  }
5534
5925
  const createTasks = [
5535
- () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5926
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
5927
+ feedbacks: events.map((f) => buildFeedbackRecord(f)),
5928
+ onConflict: "ignore"
5929
+ })),
5536
5930
  () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
5537
5931
  () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
5538
5932
  () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
@@ -5613,22 +6007,46 @@ var MastraStorageExporter = class extends BaseExporter {
5613
6007
  this.#eventBuffer.addEvent(event);
5614
6008
  await this.handleBatchedFlush();
5615
6009
  }
5616
- /**
5617
- * Handle score events — buffer for batch flush.
5618
- */
5619
- async onScoreEvent(event) {
5620
- await this.ensureInitialized();
5621
- if (!this.#observabilityStorage) return;
5622
- this.#eventBuffer.addEvent(event);
5623
- await this.handleBatchedFlush();
6010
+ onScoreEvent(event) {
6011
+ return this.enqueueAnnotation(event);
5624
6012
  }
5625
- /**
5626
- * Handle feedback events — buffer for batch flush.
5627
- */
5628
- async onFeedbackEvent(event) {
6013
+ onFeedbackReplacementEvent(event) {
6014
+ return this.enqueueAnnotation(event);
6015
+ }
6016
+ onFeedbackEvent(event) {
6017
+ return this.enqueueAnnotation(event);
6018
+ }
6019
+ enqueueAnnotation(event) {
6020
+ const pending = this.storeAnnotation(event);
6021
+ this.#pendingAnnotations.add(pending);
6022
+ pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
6023
+ return pending;
6024
+ }
6025
+ async storeAnnotation(event) {
5629
6026
  await this.ensureInitialized();
5630
6027
  if (!this.#observabilityStorage) return;
5631
- this.#eventBuffer.addEvent(event);
6028
+ const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
6029
+ await Promise.allSettled([...this.#inFlightFlushes]);
6030
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
6031
+ });
6032
+ if (!resolved) {
6033
+ const record = event.type === "score" ? event.score : event.feedback;
6034
+ this.logger.warn("Storage export dropped because the target trace/span was not found", {
6035
+ eventType: event.type,
6036
+ traceId: record.traceId,
6037
+ spanId: record.spanId
6038
+ });
6039
+ return;
6040
+ }
6041
+ if (resolved.type === "feedback_replacement") {
6042
+ if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
6043
+ this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
6044
+ return;
6045
+ }
6046
+ await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
6047
+ return;
6048
+ }
6049
+ this.#eventBuffer.addEvent(resolved);
5632
6050
  await this.handleBatchedFlush();
5633
6051
  }
5634
6052
  /**
@@ -5637,6 +6055,7 @@ var MastraStorageExporter = class extends BaseExporter {
5637
6055
  * are exported before the runtime instance is terminated.
5638
6056
  */
5639
6057
  async flush() {
6058
+ await Promise.allSettled([...this.#pendingAnnotations]);
5640
6059
  if (this.#byteTracker) {
5641
6060
  if (!this.#observabilityStorage) return;
5642
6061
  this.#byteDrainers++;
@@ -6063,8 +6482,9 @@ var BaseObservabilityInstance = class extends MastraBase {
6063
6482
  * Internal hook used by RecordedTrace/RecordedSpan hydration to route
6064
6483
  * non-tracing annotation events back through the normal exporter pipeline.
6065
6484
  */
6066
- __emitRecordedEvent(event) {
6067
- this.emitObservabilityEvent(event);
6485
+ __emitRecordedEvent(event, shouldHandle) {
6486
+ if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
6487
+ else this.emitObservabilityEvent(event);
6068
6488
  }
6069
6489
  /**
6070
6490
  * Internal hook used by the client observability proxy (`client/`)
@@ -8647,6 +9067,41 @@ var PlatformByteBatcher = class {
8647
9067
  };
8648
9068
  }
8649
9069
  };
9070
+ // src/exporters/platform-resolved-record.ts
9071
+ /** Deliver one feedback or score record whose span context must be resolved by Platform. */
9072
+ async function publishResolvedRecord(url, body, headers, method = "POST") {
9073
+ const deadline = AbortSignal.timeout(3e4);
9074
+ for (let attempt = 0; attempt < 6; attempt++) {
9075
+ const response = await fetch(url, {
9076
+ method,
9077
+ headers,
9078
+ body,
9079
+ signal: deadline
9080
+ });
9081
+ if (response.ok) {
9082
+ await response.body?.cancel();
9083
+ return;
9084
+ }
9085
+ const error = await response.json().catch(() => null);
9086
+ const code = error?.code ?? error?.error?.code;
9087
+ 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})` : ""}`);
9088
+ const retryAfter = response.headers.get("retry-after");
9089
+ const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
9090
+ const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
9091
+ await new Promise((resolve, reject) => {
9092
+ deadline.throwIfAborted();
9093
+ const timer = setTimeout(() => {
9094
+ deadline.removeEventListener("abort", abort);
9095
+ resolve();
9096
+ }, Math.min(delay, 3e4));
9097
+ function abort() {
9098
+ clearTimeout(timer);
9099
+ reject(deadline.reason);
9100
+ }
9101
+ deadline.addEventListener("abort", abort, { once: true });
9102
+ });
9103
+ }
9104
+ }
8650
9105
  // src/exporters/mastra-platform.ts
8651
9106
  const SIGNAL_PUBLISH_SUFFIXES = {
8652
9107
  traces: "/spans/publish",
@@ -8766,6 +9221,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8766
9221
  buffer;
8767
9222
  flushTimer = null;
8768
9223
  inFlightFlushes = /* @__PURE__ */ new Set();
9224
+ pendingRecords = /* @__PURE__ */ new Set();
8769
9225
  quotaPaused = false;
8770
9226
  quotaProbeTimer = null;
8771
9227
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
@@ -8802,6 +9258,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8802
9258
  maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
8803
9259
  maxRetries: config.maxRetries ?? 3,
8804
9260
  accessToken: accessToken || "",
9261
+ projectId,
8805
9262
  tracesEndpoint,
8806
9263
  logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
8807
9264
  metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
@@ -8843,17 +9300,58 @@ var MastraPlatformExporter = class extends BaseExporter {
8843
9300
  await this.handleBufferedEvent();
8844
9301
  }
8845
9302
  async onScoreEvent(event) {
8846
- if (this.isDisabled) return;
9303
+ if (this.isDisabled || this.shuttingDown) return;
9304
+ if (event.score.correlationContext == null) {
9305
+ this.enqueueResolvedRecord("score", event.score);
9306
+ return;
9307
+ }
8847
9308
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8848
9309
  this.addScoreToBuffer(event);
8849
9310
  await this.handleBufferedEvent();
8850
9311
  }
8851
9312
  async onFeedbackEvent(event) {
8852
- if (this.isDisabled) return;
9313
+ if (this.isDisabled || this.shuttingDown) return;
9314
+ if (event.feedback.correlationContext == null) {
9315
+ this.enqueueResolvedRecord("feedback", event.feedback);
9316
+ return;
9317
+ }
8853
9318
  if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
8854
9319
  this.addFeedbackToBuffer(event);
8855
9320
  await this.handleBufferedEvent();
8856
9321
  }
9322
+ onFeedbackReplacementEvent(event) {
9323
+ if (this.isDisabled || this.shuttingDown) return;
9324
+ if (!event.feedback.feedbackId?.trim()) {
9325
+ this.logger.warn("Dropping feedback replacement: feedbackId is required");
9326
+ return;
9327
+ }
9328
+ this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
9329
+ }
9330
+ enqueueResolvedRecord(kind, record, replacementId) {
9331
+ if (!record.traceId?.trim()) {
9332
+ this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
9333
+ return;
9334
+ }
9335
+ let body;
9336
+ try {
9337
+ body = JSON.stringify({ [kind]: record });
9338
+ } catch (error) {
9339
+ this.logger.warn(`Dropping unserializable ${kind}`, { error });
9340
+ return;
9341
+ }
9342
+ const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
9343
+ const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
9344
+ if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
9345
+ const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
9346
+ const headers = {
9347
+ Authorization: `Bearer ${this.platformConfig.accessToken}`,
9348
+ "Content-Type": "application/json",
9349
+ ...projectId ? { "X-Mastra-Project-Id": projectId } : {}
9350
+ };
9351
+ this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
9352
+ 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));
9353
+ this.pendingRecords.add(pending);
9354
+ }
8857
9355
  addToBuffer(event) {
8858
9356
  if (this.byteBatcher) {
8859
9357
  this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
@@ -9194,6 +9692,13 @@ var MastraPlatformExporter = class extends BaseExporter {
9194
9692
  * are exported before the runtime instance is terminated.
9195
9693
  */
9196
9694
  async flush() {
9695
+ if (this.isDisabled) return;
9696
+ do {
9697
+ await this.flushBatches();
9698
+ await Promise.allSettled([...this.pendingRecords]);
9699
+ } while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
9700
+ }
9701
+ async flushBatches() {
9197
9702
  if (this.isDisabled) return;
9198
9703
  if (this.byteBatcher) {
9199
9704
  await this.byteBatcher.flush();
@@ -10146,463 +10651,159 @@ var TestExporter = class extends BaseExporter {
10146
10651
  path,
10147
10652
  expected,
10148
10653
  actual
10149
- });
10150
- }
10151
- /**
10152
- * Check if a value is an __or__ marker object
10153
- */
10154
- #isOrMarker(value) {
10155
- return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10156
- }
10157
- /**
10158
- * Check if a value is an __any__ marker object
10159
- */
10160
- #isAnyMarker(value) {
10161
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10162
- if (!("__any__" in value)) return false;
10163
- const constraint = value.__any__;
10164
- return constraint === true || [
10165
- "string",
10166
- "number",
10167
- "boolean",
10168
- "object",
10169
- "array"
10170
- ].includes(constraint);
10171
- }
10172
- /**
10173
- * Check if a key should be skipped during comparison (metadata keys like __structure__)
10174
- */
10175
- #isMetadataKey(key) {
10176
- return key.startsWith("__") && key.endsWith("__");
10177
- }
10178
- /**
10179
- * Custom JSON replacer to handle Date objects and other special types
10180
- */
10181
- #jsonReplacer = (_key, value) => {
10182
- if (value instanceof Date) return value.toISOString();
10183
- return value;
10184
- };
10185
- /**
10186
- * Get all stored debug logs (internal exporter logging, not signal logs)
10187
- */
10188
- getLogs() {
10189
- return [...this.#debugLogs];
10190
- }
10191
- /**
10192
- * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10193
- */
10194
- dumpLogs() {
10195
- console.error("\n=== TestExporter Logs ===");
10196
- this.#debugLogs.forEach((log) => {
10197
- console.error(log);
10198
- });
10199
- console.error("=== End Logs ===\n");
10200
- }
10201
- /**
10202
- * Validate final state - useful for test assertions
10203
- *
10204
- * @returns Object with validation results
10205
- */
10206
- validateFinalState() {
10207
- const traceIds = this.getTraceIds();
10208
- const incompleteSpans = this.getIncompleteSpans();
10209
- const singleTraceId = traceIds.length === 1;
10210
- const allSpansComplete = incompleteSpans.length === 0;
10211
- return {
10212
- valid: singleTraceId && allSpansComplete,
10213
- singleTraceId,
10214
- allSpansComplete,
10215
- traceIds,
10216
- incompleteSpans
10217
- };
10654
+ });
10218
10655
  }
10219
10656
  /**
10220
- * Clear all collected events and state across all signals
10657
+ * Check if a value is an __or__ marker object
10221
10658
  */
10222
- clearEvents() {
10223
- this.#tracingEvents = [];
10224
- this.#spanStates.clear();
10225
- this.#logEvents = [];
10226
- this.#metricEvents = [];
10227
- this.#scoreEvents = [];
10228
- this.#feedbackEvents = [];
10229
- this.#debugLogs = [];
10659
+ #isOrMarker(value) {
10660
+ return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
10230
10661
  }
10231
10662
  /**
10232
- * Alias for clearEvents (compatibility with TestExporter)
10663
+ * Check if a value is an __any__ marker object
10233
10664
  */
10234
- reset() {
10235
- this.clearEvents();
10665
+ #isAnyMarker(value) {
10666
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10667
+ if (!("__any__" in value)) return false;
10668
+ const constraint = value.__any__;
10669
+ return constraint === true || [
10670
+ "string",
10671
+ "number",
10672
+ "boolean",
10673
+ "object",
10674
+ "array"
10675
+ ].includes(constraint);
10236
10676
  }
10237
10677
  /**
10238
- * Get internal metrics about the exporter's own activity.
10678
+ * Check if a key should be skipped during comparison (metadata keys like __structure__)
10239
10679
  */
10240
- getInternalMetrics() {
10241
- const json = this.toJSON({
10242
- includeEvents: false,
10243
- includeStats: false
10244
- });
10245
- return {
10246
- startedAt: this.#internalMetrics.startedAt,
10247
- lastEventAt: this.#internalMetrics.lastEventAt,
10248
- totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10249
- bySignal: { ...this.#internalMetrics.bySignal },
10250
- flushCount: this.#internalMetrics.flushCount,
10251
- estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10252
- };
10680
+ #isMetadataKey(key) {
10681
+ return key.startsWith("__") && key.endsWith("__");
10253
10682
  }
10254
10683
  /**
10255
- * Flush buffered data and log internal metrics summary.
10684
+ * Custom JSON replacer to handle Date objects and other special types
10256
10685
  */
10257
- async flush() {
10258
- this.#internalMetrics.flushCount++;
10259
- if (this.#config.logMetricsOnFlush) {
10260
- const metrics = this.getInternalMetrics();
10261
- const uptimeMs = Date.now() - metrics.startedAt.getTime();
10262
- const summary = [
10263
- `[TestExporter] flush #${metrics.flushCount} summary:`,
10264
- ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10265
- ` total events received: ${metrics.totalEventsReceived}`,
10266
- ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10267
- ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10268
- ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10269
- ].join("\n");
10270
- this.logger.info(summary);
10271
- }
10272
- }
10273
- async shutdown() {
10274
- await this.flush();
10275
- this.logger.info("TestExporter shutdown");
10276
- }
10686
+ #jsonReplacer = (_key, value) => {
10687
+ if (value instanceof Date) return value.toISOString();
10688
+ return value;
10689
+ };
10277
10690
  /**
10278
- * Extract unique spans from a list of events
10691
+ * Get all stored debug logs (internal exporter logging, not signal logs)
10279
10692
  */
10280
- #getUniqueSpansFromEvents(events) {
10281
- const spanMap = /* @__PURE__ */ new Map();
10282
- for (const event of events) {
10283
- const span = event.exportedSpan;
10284
- if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10285
- }
10286
- return Array.from(spanMap.values());
10287
- }
10288
- };
10289
- /**
10290
- * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10291
- */
10292
- const JsonExporter = TestExporter;
10293
- // src/instances/default.ts
10294
- var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10295
- constructor(config) {
10296
- super(config);
10297
- }
10298
- createSpan(options) {
10299
- return new DefaultSpan(options, this);
10693
+ getLogs() {
10694
+ return [...this.#debugLogs];
10300
10695
  }
10301
- };
10302
- // src/recorded.ts
10303
- function nullToUndefined(value) {
10304
- return value ?? void 0;
10305
- }
10306
- function mergeMetadata(base, extra) {
10307
- if (!base && !extra) return void 0;
10308
- return {
10309
- ...base ?? {},
10310
- ...extra ?? {}
10311
- };
10312
- }
10313
- function normalizeErrorInfo(error) {
10314
- if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
10315
- return {
10316
- message: error.message,
10317
- id: "id" in error && typeof error.id === "string" ? error.id : void 0,
10318
- name: "name" in error && typeof error.name === "string" ? error.name : void 0,
10319
- stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
10320
- domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
10321
- category: "category" in error && typeof error.category === "string" ? error.category : void 0,
10322
- details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
10323
- };
10324
- }
10325
- function buildCorrelationContext(span, rootSpan, parent) {
10326
- return {
10327
- tags: rootSpan.tags ?? void 0,
10328
- entityType: nullToUndefined(span.entityType),
10329
- entityId: nullToUndefined(span.entityId),
10330
- entityName: nullToUndefined(span.entityName),
10331
- parentEntityType: parent?.entityType ?? void 0,
10332
- parentEntityId: parent?.entityId ?? void 0,
10333
- parentEntityName: parent?.entityName ?? void 0,
10334
- rootEntityType: nullToUndefined(rootSpan.entityType),
10335
- rootEntityId: nullToUndefined(rootSpan.entityId),
10336
- rootEntityName: nullToUndefined(rootSpan.entityName),
10337
- userId: nullToUndefined(span.userId),
10338
- organizationId: nullToUndefined(span.organizationId),
10339
- resourceId: nullToUndefined(span.resourceId),
10340
- runId: nullToUndefined(span.runId),
10341
- sessionId: nullToUndefined(span.sessionId),
10342
- threadId: nullToUndefined(span.threadId),
10343
- requestId: nullToUndefined(span.requestId),
10344
- environment: nullToUndefined(span.environment),
10345
- source: nullToUndefined(span.source),
10346
- serviceName: nullToUndefined(span.serviceName),
10347
- experimentId: nullToUndefined(span.experimentId)
10348
- };
10349
- }
10350
- function buildScoreEvent(args) {
10351
- const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
10352
- return {
10353
- type: "score",
10354
- score: {
10355
- scoreId: generateSignalId(),
10356
- timestamp: /* @__PURE__ */ new Date(),
10357
- traceId,
10358
- spanId,
10359
- scorerId: score.scorerId,
10360
- scorerName: score.scorerName,
10361
- scorerVersion: score.scorerVersion,
10362
- source: score.source,
10363
- scoreSource: score.scoreSource,
10364
- score: score.score,
10365
- reason: score.reason,
10366
- experimentId: score.experimentId,
10367
- scoreTraceId: score.scoreTraceId,
10368
- targetEntityType: score.targetEntityType,
10369
- correlationContext,
10370
- metadata: mergeMetadata(inheritedMetadata, score.metadata)
10371
- }
10372
- };
10373
- }
10374
- function buildFeedbackEvent(args) {
10375
- const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
10376
- return {
10377
- type: "feedback",
10378
- feedback: {
10379
- feedbackId: generateSignalId(),
10380
- timestamp: /* @__PURE__ */ new Date(),
10381
- traceId,
10382
- spanId,
10383
- source: feedback.source,
10384
- feedbackSource: feedback.feedbackSource,
10385
- feedbackType: feedback.feedbackType,
10386
- value: feedback.value,
10387
- userId: feedback.userId,
10388
- feedbackUserId: feedback.feedbackUserId,
10389
- comment: feedback.comment,
10390
- sourceId: feedback.sourceId,
10391
- experimentId: feedback.experimentId,
10392
- correlationContext,
10393
- metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
10394
- }
10395
- };
10396
- }
10397
- function findSpanById(spans, spanId) {
10398
- if (!spanId) return void 0;
10399
- return spans.find((span) => span.spanId === spanId);
10400
- }
10401
- function buildRecordedScoreEventFromTrace(args) {
10402
- const rootSpan = findRootSpan(args.trace.spans);
10403
- if (!rootSpan) return null;
10404
- const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
10405
- if (!span) return null;
10406
- const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
10407
- return buildScoreEvent({
10408
- traceId: span.traceId,
10409
- spanId: args.spanId,
10410
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10411
- score: args.score,
10412
- inheritedMetadata: span.metadata
10413
- });
10414
- }
10415
- function buildRecordedFeedbackEventFromTrace(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 buildFeedbackEvent({
10422
- traceId: span.traceId,
10423
- spanId: args.spanId,
10424
- correlationContext: buildCorrelationContext(span, rootSpan, parent),
10425
- feedback: args.feedback,
10426
- inheritedMetadata: span.metadata
10427
- });
10428
- }
10429
- var RecordedSpanImpl = class {
10430
- id;
10431
- traceId;
10432
- name;
10433
- type;
10434
- entityType;
10435
- entityId;
10436
- entityName;
10437
- startTime;
10438
- endTime;
10439
- attributes;
10440
- metadata;
10441
- tags;
10442
- input;
10443
- output;
10444
- errorInfo;
10445
- requestContext;
10446
- isEvent;
10447
- isRootSpan;
10448
- parentSpanId;
10449
- parent;
10450
- children = [];
10451
- #raw;
10452
- #rootSpan;
10453
- #emitRecordedEvent;
10454
- #canEmitRecordedEvent;
10455
- #debugRecordedAnnotationUnavailable;
10456
- constructor(args) {
10457
- const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
10458
- this.#raw = raw;
10459
- this.#rootSpan = rootSpan;
10460
- this.#emitRecordedEvent = emitRecordedEvent;
10461
- this.#canEmitRecordedEvent = canEmitRecordedEvent;
10462
- this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
10463
- this.id = raw.spanId;
10464
- this.traceId = raw.traceId;
10465
- this.name = raw.name;
10466
- this.type = raw.spanType;
10467
- this.entityType = raw.entityType ?? void 0;
10468
- this.entityId = raw.entityId ?? void 0;
10469
- this.entityName = raw.entityName ?? void 0;
10470
- this.startTime = raw.startedAt;
10471
- this.endTime = raw.endedAt ?? void 0;
10472
- this.attributes = raw.attributes ?? void 0;
10473
- this.metadata = raw.metadata ?? void 0;
10474
- this.tags = raw.tags ?? void 0;
10475
- this.input = raw.input ?? void 0;
10476
- this.output = raw.output ?? void 0;
10477
- this.errorInfo = normalizeErrorInfo(raw.error);
10478
- this.requestContext = raw.requestContext ?? void 0;
10479
- this.isEvent = raw.isEvent;
10480
- this.isRootSpan = !raw.parentSpanId;
10481
- this.parentSpanId = raw.parentSpanId ?? void 0;
10696
+ /**
10697
+ * Dump debug logs to console for debugging (uses console.error for visibility in test output)
10698
+ */
10699
+ dumpLogs() {
10700
+ console.error("\n=== TestExporter Logs ===");
10701
+ this.#debugLogs.forEach((log) => {
10702
+ console.error(log);
10703
+ });
10704
+ console.error("=== End Logs ===\n");
10482
10705
  }
10483
- async addScore(score) {
10484
- if (!this.#canEmitRecordedEvent()) {
10485
- this.#debugRecordedAnnotationUnavailable({
10486
- kind: "score",
10487
- traceId: this.traceId,
10488
- spanId: this.id
10489
- });
10490
- return;
10491
- }
10492
- await this.#emitRecordedEvent(buildScoreEvent({
10493
- traceId: this.#raw.traceId,
10494
- spanId: this.id,
10495
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10496
- score,
10497
- inheritedMetadata: this.#raw.metadata
10498
- }));
10706
+ /**
10707
+ * Validate final state - useful for test assertions
10708
+ *
10709
+ * @returns Object with validation results
10710
+ */
10711
+ validateFinalState() {
10712
+ const traceIds = this.getTraceIds();
10713
+ const incompleteSpans = this.getIncompleteSpans();
10714
+ const singleTraceId = traceIds.length === 1;
10715
+ const allSpansComplete = incompleteSpans.length === 0;
10716
+ return {
10717
+ valid: singleTraceId && allSpansComplete,
10718
+ singleTraceId,
10719
+ allSpansComplete,
10720
+ traceIds,
10721
+ incompleteSpans
10722
+ };
10499
10723
  }
10500
- async addFeedback(feedback) {
10501
- if (!this.#canEmitRecordedEvent()) {
10502
- this.#debugRecordedAnnotationUnavailable({
10503
- kind: "feedback",
10504
- traceId: this.traceId,
10505
- spanId: this.id
10506
- });
10507
- return;
10508
- }
10509
- await this.#emitRecordedEvent(buildFeedbackEvent({
10510
- traceId: this.#raw.traceId,
10511
- spanId: this.id,
10512
- correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
10513
- feedback,
10514
- inheritedMetadata: this.#raw.metadata
10515
- }));
10724
+ /**
10725
+ * Clear all collected events and state across all signals
10726
+ */
10727
+ clearEvents() {
10728
+ this.#tracingEvents = [];
10729
+ this.#spanStates.clear();
10730
+ this.#logEvents = [];
10731
+ this.#metricEvents = [];
10732
+ this.#scoreEvents = [];
10733
+ this.#feedbackEvents = [];
10734
+ this.#debugLogs = [];
10516
10735
  }
10517
- };
10518
- var RecordedTraceImpl = class {
10519
- traceId;
10520
- rootSpan;
10521
- spans;
10522
- #rootRecord;
10523
- #emitRecordedEvent;
10524
- #spanMap;
10525
- #canEmitRecordedEvent;
10526
- #debugRecordedAnnotationUnavailable;
10527
- constructor(args) {
10528
- this.traceId = args.traceId;
10529
- this.rootSpan = args.rootSpan;
10530
- this.#rootRecord = args.rootRecord;
10531
- this.spans = args.spans;
10532
- this.#emitRecordedEvent = args.emitRecordedEvent;
10533
- this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
10534
- this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
10535
- this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
10736
+ /**
10737
+ * Alias for clearEvents (compatibility with TestExporter)
10738
+ */
10739
+ reset() {
10740
+ this.clearEvents();
10536
10741
  }
10537
- getSpan(spanId) {
10538
- return this.#spanMap.get(spanId) ?? null;
10742
+ /**
10743
+ * Get internal metrics about the exporter's own activity.
10744
+ */
10745
+ getInternalMetrics() {
10746
+ const json = this.toJSON({
10747
+ includeEvents: false,
10748
+ includeStats: false
10749
+ });
10750
+ return {
10751
+ startedAt: this.#internalMetrics.startedAt,
10752
+ lastEventAt: this.#internalMetrics.lastEventAt,
10753
+ totalEventsReceived: this.#internalMetrics.totalEventsReceived,
10754
+ bySignal: { ...this.#internalMetrics.bySignal },
10755
+ flushCount: this.#internalMetrics.flushCount,
10756
+ estimatedJsonBytes: new TextEncoder().encode(json).byteLength
10757
+ };
10539
10758
  }
10540
- async addScore(score) {
10541
- if (!this.#canEmitRecordedEvent()) {
10542
- this.#debugRecordedAnnotationUnavailable({
10543
- kind: "score",
10544
- traceId: this.traceId
10545
- });
10546
- return;
10759
+ /**
10760
+ * Flush buffered data and log internal metrics summary.
10761
+ */
10762
+ async flush() {
10763
+ this.#internalMetrics.flushCount++;
10764
+ if (this.#config.logMetricsOnFlush) {
10765
+ const metrics = this.getInternalMetrics();
10766
+ const uptimeMs = Date.now() - metrics.startedAt.getTime();
10767
+ const summary = [
10768
+ `[TestExporter] flush #${metrics.flushCount} summary:`,
10769
+ ` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
10770
+ ` total events received: ${metrics.totalEventsReceived}`,
10771
+ ` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
10772
+ ` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
10773
+ ` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
10774
+ ].join("\n");
10775
+ this.logger.info(summary);
10547
10776
  }
10548
- await this.#emitRecordedEvent(buildScoreEvent({
10549
- traceId: this.#rootRecord.traceId,
10550
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10551
- score,
10552
- inheritedMetadata: this.#rootRecord.metadata
10553
- }));
10554
10777
  }
10555
- async addFeedback(feedback) {
10556
- if (!this.#canEmitRecordedEvent()) {
10557
- this.#debugRecordedAnnotationUnavailable({
10558
- kind: "feedback",
10559
- traceId: this.traceId
10560
- });
10561
- return;
10778
+ async shutdown() {
10779
+ await this.flush();
10780
+ this.logger.info("TestExporter shutdown");
10781
+ }
10782
+ /**
10783
+ * Extract unique spans from a list of events
10784
+ */
10785
+ #getUniqueSpansFromEvents(events) {
10786
+ const spanMap = /* @__PURE__ */ new Map();
10787
+ for (const event of events) {
10788
+ const span = event.exportedSpan;
10789
+ if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
10562
10790
  }
10563
- await this.#emitRecordedEvent(buildFeedbackEvent({
10564
- traceId: this.#rootRecord.traceId,
10565
- correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
10566
- feedback,
10567
- inheritedMetadata: this.#rootRecord.metadata
10568
- }));
10791
+ return Array.from(spanMap.values());
10569
10792
  }
10570
10793
  };
10571
- function findRootSpan(spans) {
10572
- const spanIds = new Set(spans.map((span) => span.spanId));
10573
- return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
10574
- }
10575
- function hydrateRecordedTrace(args) {
10576
- const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
10577
- const rootSpan = findRootSpan(trace.spans);
10578
- if (!rootSpan) return null;
10579
- const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
10580
- raw,
10581
- rootSpan,
10582
- emitRecordedEvent,
10583
- canEmitRecordedEvent,
10584
- debugRecordedAnnotationUnavailable
10585
- }));
10586
- const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
10587
- for (const span of recordedSpans) {
10588
- if (!span.parentSpanId) continue;
10589
- const parent = spanMap.get(span.parentSpanId);
10590
- if (!parent) continue;
10591
- span.parent = parent;
10592
- parent.children.push(span);
10794
+ /**
10795
+ * @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
10796
+ */
10797
+ const JsonExporter = TestExporter;
10798
+ // src/instances/default.ts
10799
+ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
10800
+ constructor(config) {
10801
+ super(config);
10593
10802
  }
10594
- const hydratedRootSpan = spanMap.get(rootSpan.spanId);
10595
- if (!hydratedRootSpan) return null;
10596
- return new RecordedTraceImpl({
10597
- traceId: trace.traceId,
10598
- rootSpan: hydratedRootSpan,
10599
- rootRecord: rootSpan,
10600
- spans: recordedSpans,
10601
- emitRecordedEvent,
10602
- canEmitRecordedEvent,
10603
- debugRecordedAnnotationUnavailable
10604
- });
10605
- }
10803
+ createSpan(options) {
10804
+ return new DefaultSpan(options, this);
10805
+ }
10806
+ };
10606
10807
  // src/registry.ts
10607
10808
  /**
10608
10809
  * Registry for Observability instances.
@@ -10909,23 +11110,6 @@ function isInstance(obj) {
10909
11110
  return obj instanceof BaseObservabilityInstance;
10910
11111
  }
10911
11112
  /**
10912
- * Delays (ms) between attempts to rehydrate a trace from storage when an
10913
- * annotation (score/feedback) targets a span that has not been flushed by
10914
- * the configured exporters yet. Exporters buffer and flush asynchronously:
10915
- * by default they flush at 1000 spans or after a 5000ms wait
10916
- * (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
10917
- * race the flush and be silently dropped. The schedule below sums to
10918
- * ~5.85s, covering the default flush interval with margin.
10919
- */
10920
- const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
10921
- 100,
10922
- 250,
10923
- 500,
10924
- 1e3,
10925
- 2e3,
10926
- 2e3
10927
- ];
10928
- /**
10929
11113
  * Manages observability instances and selects their configurations for Mastra operations.
10930
11114
  * Configure instances and exporters to collect and export telemetry.
10931
11115
  *
@@ -10952,6 +11136,7 @@ var Observability = class extends MastraBase {
10952
11136
  #registry = new ObservabilityRegistry();
10953
11137
  #mastra;
10954
11138
  #clientObservabilityProxy;
11139
+ #pendingPersistedEvents = /* @__PURE__ */ new Set();
10955
11140
  constructor(config) {
10956
11141
  super({
10957
11142
  component: RegisteredLogger.OBSERVABILITY,
@@ -11092,50 +11277,47 @@ var Observability = class extends MastraBase {
11092
11277
  async addScore(args) {
11093
11278
  const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11094
11279
  const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11095
- if (args.correlationContext) {
11096
- await this.#emitRecordedEvent(buildScoreEvent({
11097
- ...targetTraceId ? { traceId: targetTraceId } : {},
11098
- ...targetSpanId ? { spanId: targetSpanId } : {},
11099
- correlationContext: args.correlationContext,
11100
- score: args.score
11101
- }));
11102
- return;
11103
- }
11104
- if (!args.traceId) return;
11105
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
11106
- trace,
11107
- spanId: args.spanId,
11108
- score: args.score
11280
+ if (!targetTraceId && !args.correlationContext) return;
11281
+ await this.#emitRecordedEvent(buildScoreEvent({
11282
+ ...args,
11283
+ traceId: targetTraceId,
11284
+ spanId: targetSpanId
11109
11285
  }));
11110
- if (!event) {
11111
- this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11112
- return;
11113
- }
11114
- await this.#emitRecordedEvent(event);
11115
11286
  }
11116
11287
  async addFeedback(args) {
11117
- const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
11118
- const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
11119
- if (args.correlationContext) {
11120
- await this.#emitRecordedEvent(buildFeedbackEvent({
11121
- ...targetTraceId ? { traceId: targetTraceId } : {},
11122
- ...targetSpanId ? { spanId: targetSpanId } : {},
11123
- correlationContext: args.correlationContext,
11124
- feedback: args.feedback
11125
- }));
11126
- return;
11127
- }
11128
- if (!args.traceId) return;
11129
- const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
11130
- trace,
11131
- spanId: args.spanId,
11132
- feedback: args.feedback
11288
+ const traceId = args.traceId ?? args.correlationContext?.traceId;
11289
+ const spanId = args.spanId ?? args.correlationContext?.spanId;
11290
+ if (!traceId && !args.correlationContext) return;
11291
+ await this.#emitRecordedEvent(buildFeedbackEvent({
11292
+ ...args,
11293
+ traceId,
11294
+ spanId
11133
11295
  }));
11134
- if (!event) {
11135
- this.logger?.warn(`Feedback event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
11136
- return;
11137
- }
11138
- await this.#emitRecordedEvent(event);
11296
+ }
11297
+ async replaceFeedback(args) {
11298
+ 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");
11299
+ await this.#emitRecordedEvent({
11300
+ type: "feedback_replacement",
11301
+ feedback: {
11302
+ ...args.feedback,
11303
+ traceId: args.traceId,
11304
+ spanId: args.spanId,
11305
+ correlationContext: args.correlationContext
11306
+ }
11307
+ });
11308
+ }
11309
+ /** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
11310
+ async __exportPersistedEvent(event) {
11311
+ const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
11312
+ const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
11313
+ this.#pendingPersistedEvents.add(pending);
11314
+ pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
11315
+ this.#pendingPersistedEvents.delete(pending);
11316
+ this.logger.error("Failed to notify exporters of persisted feedback/score", {
11317
+ error,
11318
+ eventType: event.type
11319
+ });
11320
+ });
11139
11321
  }
11140
11322
  /** Register a named observability instance, optionally marking it as default. */
11141
11323
  registerInstance(name, instance, isDefault = false) {
@@ -11172,12 +11354,18 @@ var Observability = class extends MastraBase {
11172
11354
  }
11173
11355
  /** Flush all registered instances without shutting down. */
11174
11356
  async flush() {
11357
+ await this.#drainPersistedEvents();
11175
11358
  await this.#registry.flush();
11176
11359
  }
11177
11360
  /** Shut down all registered instances, flushing any pending data. */
11178
11361
  async shutdown() {
11362
+ await this.#drainPersistedEvents();
11179
11363
  await this.#registry.shutdown();
11180
11364
  }
11365
+ /** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
11366
+ async #drainPersistedEvents() {
11367
+ while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
11368
+ }
11181
11369
  /**
11182
11370
  * Returns the proxy responsible for client observability (W3C trace
11183
11371
  * context injection + OTLP/JSON payload reception for spans/logs
@@ -11199,40 +11387,22 @@ var Observability = class extends MastraBase {
11199
11387
  if (!storage) return null;
11200
11388
  return await storage.getStore("observability") ?? null;
11201
11389
  }
11202
- /**
11203
- * Build a recorded score/feedback event from storage, retrying briefly to
11204
- * ride out the async exporter flush: annotations emitted right after a
11205
- * span ends can otherwise race the flush and be silently dropped.
11206
- */
11207
- async #buildRecordedEventWithRetry(traceId, build) {
11208
- for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
11209
- if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
11210
- const trace = await this.#getStoredTrace(traceId);
11211
- const event = trace ? build(trace) : null;
11212
- if (event) return event;
11213
- }
11214
- return null;
11215
- }
11216
- async #getStoredTrace(traceId) {
11217
- const observabilityStorage = await this.#getObservabilityStorage();
11218
- if (!observabilityStorage) return null;
11219
- return observabilityStorage.getTrace({ traceId });
11220
- }
11221
11390
  #getRecordedTraceInstance() {
11222
11391
  return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
11223
11392
  }
11224
- async #emitRecordedEvent(event) {
11393
+ /** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
11394
+ async #emitRecordedEvent(event, shouldHandle) {
11225
11395
  const instance = this.#getRecordedTraceInstance();
11226
11396
  if (!instance) {
11227
11397
  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 });
11228
11398
  return;
11229
11399
  }
11230
11400
  if (instance instanceof BaseObservabilityInstance) {
11231
- instance.__emitRecordedEvent(event);
11401
+ instance.__emitRecordedEvent(event, shouldHandle);
11232
11402
  return;
11233
11403
  }
11234
11404
  const bridge = instance.getBridge();
11235
- const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
11405
+ 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");
11236
11406
  if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
11237
11407
  }
11238
11408
  };