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

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.
package/dist/index.js CHANGED
@@ -786,6 +786,7 @@ const observabilityInstanceConfigFields = {
786
786
  serviceName: z.string().min(1, "Service name is required"),
787
787
  sampling: samplingStrategySchema.optional(),
788
788
  exporters: z.array(z.any()).optional(),
789
+ retainStorageExporterOnPlatform: z.boolean().optional(),
789
790
  bridge: z.any().optional(),
790
791
  spanOutputProcessors: z.array(z.any()).optional(),
791
792
  includeInternalSpans: z.boolean().optional(),
@@ -2510,6 +2511,22 @@ var ModelSpanTracker = class {
2510
2511
  #currentInferenceSpan;
2511
2512
  #stepHasInference = false;
2512
2513
  #tracksProviderStream = false;
2514
+ /**
2515
+ * Provider completion of the open MODEL_INFERENCE, held until the processed
2516
+ * step supplies its output. The raw provider stream carries content before
2517
+ * output processors run, so the span keeps its provider end time and usage
2518
+ * from here but takes its output from the processed `step-finish`.
2519
+ */
2520
+ #pendingInferenceFinish;
2521
+ /**
2522
+ * Processed text and tool calls of the open MODEL_INFERENCE, for loops whose
2523
+ * `step-finish` payload carries only usage (the durable loop rewrites the
2524
+ * provider's `finish` into `step-finish`).
2525
+ */
2526
+ #inferenceContent = {
2527
+ text: "",
2528
+ toolCalls: []
2529
+ };
2513
2530
  #currentChunkSpan;
2514
2531
  #currentChunkType;
2515
2532
  #accumulator = {};
@@ -2597,6 +2614,7 @@ var ModelSpanTracker = class {
2597
2614
  */
2598
2615
  reportGenerationError(options) {
2599
2616
  this.#endChunkSpan();
2617
+ this.#settlePendingInference();
2600
2618
  const termination = options.outcome != null ? {
2601
2619
  outcome: options.outcome,
2602
2620
  stopReason: options.stopReason,
@@ -2645,6 +2663,7 @@ var ModelSpanTracker = class {
2645
2663
  spanOptions.attributes.costContext = providerCostContext ?? spanOptions.attributes.costContext;
2646
2664
  if (!spanOptions.attributes.costContext) spanOptions.attributes.costContext = getGatewayCostContext({ stepProviderMetadata });
2647
2665
  }
2666
+ this.#settlePendingInference();
2648
2667
  if (spanOptions.outcome === "abort" || spanOptions.stopReason === "timeout") {
2649
2668
  const termination = {
2650
2669
  outcome: spanOptions.outcome,
@@ -2741,7 +2760,15 @@ var ModelSpanTracker = class {
2741
2760
  this.#inferenceTimeToFirstTokenMs = void 0;
2742
2761
  }
2743
2762
  /**
2744
- * End the current MODEL_INFERENCE span when the provider stream finishes.
2763
+ * End the current MODEL_INFERENCE span.
2764
+ *
2765
+ * With `captureOutput: false` (the raw provider stream's `finish`), the span is
2766
+ * not ended yet: its provider end time, usage and finish reason are held until
2767
+ * the processed `step-finish` arrives, which ends it with the processed output
2768
+ * and the held end time. Tool work between the two does not count toward the
2769
+ * inference's duration, and exporters that treat MODEL_INFERENCE as the model
2770
+ * call still get the response.
2771
+ *
2745
2772
  * Fields are duplicated onto MODEL_STEP (in #endStepSpan) so existing
2746
2773
  * integrations that read usage/finishReason from the step span continue
2747
2774
  * to work unchanged.
@@ -2750,27 +2777,66 @@ var ModelSpanTracker = class {
2750
2777
  */
2751
2778
  #endInferenceSpan(payload, captureOutput = true) {
2752
2779
  if (!this.#currentInferenceSpan) return;
2753
- const { usage: rawUsage, ...otherOutput } = payload.output;
2754
- const usage = extractUsageMetrics(rawUsage, payload.metadata?.providerMetadata);
2755
- const responseModel = typeof payload.metadata?.modelId === "string" ? payload.metadata.modelId : void 0;
2756
- this.#currentInferenceSpan.end({
2780
+ if (!captureOutput) {
2781
+ this.#pendingInferenceFinish ??= {
2782
+ payload,
2783
+ endTime: /* @__PURE__ */ new Date(),
2784
+ streamAttributes: this.#inferenceStreamAttributes()
2785
+ };
2786
+ return;
2787
+ }
2788
+ const pending = this.#pendingInferenceFinish;
2789
+ const { usage: _usage, ...stepOutput } = payload.output ?? {};
2790
+ const output = "text" in stepOutput || "toolCalls" in stepOutput ? stepOutput : this.#inferenceContent;
2791
+ this.#closeInference(pending?.payload ?? payload, {
2792
+ output,
2793
+ endTime: pending?.endTime,
2794
+ streamAttributes: pending?.streamAttributes
2795
+ });
2796
+ }
2797
+ /**
2798
+ * End an inference whose provider stream already finished, without output.
2799
+ * Used when the step ends some other way than a processed `step-finish`
2800
+ * (error, abort, suspension, tripwire, a replacement attempt).
2801
+ */
2802
+ #settlePendingInference() {
2803
+ const pending = this.#pendingInferenceFinish;
2804
+ if (!pending) return;
2805
+ this.#closeInference(pending.payload, {
2806
+ endTime: pending.endTime,
2807
+ streamAttributes: pending.streamAttributes
2808
+ });
2809
+ }
2810
+ #closeInference(finish, options) {
2811
+ const span = this.#currentInferenceSpan;
2812
+ this.#pendingInferenceFinish = void 0;
2813
+ this.#inferenceContent = {
2814
+ text: "",
2815
+ toolCalls: []
2816
+ };
2817
+ if (!span) return;
2818
+ const usage = extractUsageMetrics(finish.output?.usage, finish.metadata?.providerMetadata);
2819
+ const responseModel = typeof finish.metadata?.modelId === "string" ? finish.metadata.modelId : void 0;
2820
+ const endOptions = {
2757
2821
  ...coreObservability.agentLoopTermination?.({
2758
2822
  stopCause: "model_finished",
2759
- finishReason: payload.stepResult.reason
2823
+ finishReason: finish.stepResult.reason
2760
2824
  }),
2761
- ...payload.stepResult.reason === "error" ? {
2825
+ ...finish.stepResult.reason === "error" ? {
2762
2826
  outcome: "error",
2763
2827
  stopReason: "model_error"
2764
2828
  } : {},
2765
- ...captureOutput ? { output: otherOutput } : {},
2829
+ ...options.output !== void 0 ? { output: options.output } : {},
2830
+ ...options.endTime ? { endTime: options.endTime } : {},
2766
2831
  attributes: {
2767
2832
  usage,
2768
- finishReason: payload.stepResult.reason,
2769
- warnings: payload.stepResult.warnings,
2770
- ...this.#inferenceStreamAttributes(),
2833
+ finishReason: finish.stepResult.reason,
2834
+ warnings: finish.stepResult.warnings,
2835
+ ...options.streamAttributes ?? this.#inferenceStreamAttributes(),
2771
2836
  ...responseModel?.trim() ? { responseModel } : {}
2772
2837
  }
2773
- });
2838
+ };
2839
+ span.end(endOptions);
2774
2840
  this.#currentInferenceSpan = void 0;
2775
2841
  this.#inferenceCompletionStartTime = void 0;
2776
2842
  }
@@ -2811,6 +2877,7 @@ var ModelSpanTracker = class {
2811
2877
  endAttempt(termination) {
2812
2878
  termination = interruptedByRun(termination);
2813
2879
  const payload = this.#pendingStepFinishPayload;
2880
+ this.#settlePendingInference();
2814
2881
  if (payload) this.#endStepSpan(payload, termination);
2815
2882
  else {
2816
2883
  this.#endChunkSpan();
@@ -2828,6 +2895,10 @@ var ModelSpanTracker = class {
2828
2895
  if (!this.#currentStepSpan || this.#currentInferenceSpan) return;
2829
2896
  this.#inferenceCompletionStartTime = void 0;
2830
2897
  this.#inferenceTimeToFirstTokenMs = void 0;
2898
+ this.#inferenceContent = {
2899
+ text: "",
2900
+ toolCalls: []
2901
+ };
2831
2902
  const input = extractStepInput(payload);
2832
2903
  const generationAttrs = this.#modelSpan?.attributes;
2833
2904
  const ctx = this.#inferenceContext;
@@ -2858,6 +2929,7 @@ var ModelSpanTracker = class {
2858
2929
  */
2859
2930
  interruptInference(termination) {
2860
2931
  this.#endChunkSpan();
2932
+ this.#settlePendingInference();
2861
2933
  if (!this.#currentInferenceSpan) return;
2862
2934
  this.#currentInferenceSpan.end({
2863
2935
  attributes: {
@@ -2877,6 +2949,7 @@ var ModelSpanTracker = class {
2877
2949
  /** End the open inference span, if any, with `error` and what it streamed. */
2878
2950
  failInference(error) {
2879
2951
  this.#endChunkSpan();
2952
+ this.#settlePendingInference();
2880
2953
  if (!this.#currentInferenceSpan) return;
2881
2954
  this.#currentInferenceSpan.error({
2882
2955
  error,
@@ -2956,6 +3029,7 @@ var ModelSpanTracker = class {
2956
3029
  const usage = chunk.payload.usage;
2957
3030
  if (!usage) return;
2958
3031
  this.#inModelResponse = false;
3032
+ this.#settlePendingInference();
2959
3033
  this.#endStepSpan({
2960
3034
  output: { usage },
2961
3035
  stepResult: {
@@ -3166,6 +3240,19 @@ var ModelSpanTracker = class {
3166
3240
  controller.enqueue(chunk);
3167
3241
  } }));
3168
3242
  }
3243
+ /** Keep the processed response of the open inference; see #inferenceContent. */
3244
+ #collectInferenceContent(chunk) {
3245
+ if (!this.#currentInferenceSpan) return;
3246
+ if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") this.#inferenceContent.text += chunk.payload.text;
3247
+ else if (chunk.type === "tool-call") {
3248
+ const { toolCallId, toolName, args } = chunk.payload;
3249
+ this.#inferenceContent.toolCalls.push({
3250
+ toolCallId,
3251
+ toolName,
3252
+ args
3253
+ });
3254
+ }
3255
+ }
3169
3256
  /** @internal Record a chunk only after output processors accept it. */
3170
3257
  recordChunk(chunk) {
3171
3258
  try {
@@ -3174,6 +3261,7 @@ var ModelSpanTracker = class {
3174
3261
  if (chunk.type === "tool-call-approval") this.#handleToolApprovalChunk(chunk);
3175
3262
  this.#endSuspendedStep(chunk);
3176
3263
  }
3264
+ this.#collectInferenceContent(chunk);
3177
3265
  switch (chunk.type) {
3178
3266
  case "text-start":
3179
3267
  case "text-delta":
@@ -3215,7 +3303,9 @@ var ModelSpanTracker = class {
3215
3303
  this.endAttempt(termination);
3216
3304
  break;
3217
3305
  }
3218
- case "finish": break;
3306
+ case "finish":
3307
+ this.#settlePendingInference();
3308
+ break;
3219
3309
  case "raw":
3220
3310
  case "start":
3221
3311
  case "response-metadata":
@@ -3962,7 +4052,8 @@ var DefaultSpan = class extends BaseSpan {
3962
4052
  if (options?.endTree) this.endOpenDescendants(options);
3963
4053
  if (options) this.applyOutcome(options);
3964
4054
  if (this.outcome === null) this.outcome = "unknown";
3965
- this.endTime = /* @__PURE__ */ new Date();
4055
+ const endTime = options?.endTime;
4056
+ this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
3966
4057
  this.detachFromParent();
3967
4058
  if (options?.metadata) this.metadata = {
3968
4059
  ...this.metadata,
@@ -5011,6 +5102,16 @@ var StorageByteTracker = class {
5011
5102
  };
5012
5103
  }
5013
5104
  };
5105
+ // src/exporters/storage-platform-policy.ts
5106
+ /**
5107
+ * Check the resolved observability domain, not the composite store's default backend.
5108
+ * Older or custom adapters without location metadata retain opt-in compatibility.
5109
+ */
5110
+ function skipLocalStorageOnPlatform(storage, logger) {
5111
+ if (!process.env.MASTRA_DEPLOYMENT_ID || storage.persistenceLocation !== "local") return false;
5112
+ logger.warn("Storage exporter disabled on Mastra Platform: local observability storage is not supported, even with retainStorageExporterOnPlatform: true. Use a remote observability storage provider.");
5113
+ return true;
5114
+ }
5014
5115
  // src/exporters/mastra-storage.ts
5015
5116
  /**
5016
5117
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -5106,6 +5207,11 @@ var MastraStorageExporter = class extends BaseExporter {
5106
5207
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
5107
5208
  return;
5108
5209
  }
5210
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5211
+ this.#observabilityStorage = void 0;
5212
+ this.#storage = void 0;
5213
+ return;
5214
+ }
5109
5215
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5110
5216
  if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5111
5217
  this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
@@ -5579,6 +5685,12 @@ function isMastraPlatformDeployment() {
5579
5685
  function isMastraBuiltInStorageExporter(exporter) {
5580
5686
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5581
5687
  }
5688
+ function isMastraDeprecatedStorageExporter(exporter) {
5689
+ return exporter instanceof DefaultExporter || exporter.name === "mastra-default-observability-exporter";
5690
+ }
5691
+ function shouldSkipStorageExporterOnPlatform(exporter, retainStorageExporterOnPlatform = false) {
5692
+ return isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter) && (!retainStorageExporterOnPlatform || isMastraDeprecatedStorageExporter(exporter));
5693
+ }
5582
5694
  // src/instances/base.ts
5583
5695
  /**
5584
5696
  * BaseObservability - Abstract base class for Observability implementations
@@ -5616,6 +5728,8 @@ var BaseObservabilityInstance = class extends MastraBase {
5616
5728
  * a span's `metadata.environment` isn't set.
5617
5729
  */
5618
5730
  #mastraEnvironment;
5731
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5732
+ #hasApplicationLogger = false;
5619
5733
  /**
5620
5734
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5621
5735
  * we stash the lightweight provider/model from creation options so
@@ -5628,12 +5742,13 @@ var BaseObservabilityInstance = class extends MastraBase {
5628
5742
  name: config.serviceName
5629
5743
  });
5630
5744
  const exporters = config.exporters ?? [];
5631
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5745
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5632
5746
  this.config = {
5633
5747
  serviceName: config.serviceName,
5634
5748
  name: config.name,
5635
5749
  sampling: config.sampling ?? { type: "always" },
5636
5750
  exporters: effectiveExporters,
5751
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5637
5752
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5638
5753
  bridge: config.bridge ?? void 0,
5639
5754
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5643,6 +5758,7 @@ var BaseObservabilityInstance = class extends MastraBase {
5643
5758
  serializationOptions: config.serializationOptions,
5644
5759
  logging: config.logging
5645
5760
  };
5761
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5646
5762
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5647
5763
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5648
5764
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5655,6 +5771,9 @@ var BaseObservabilityInstance = class extends MastraBase {
5655
5771
  */
5656
5772
  __setLogger(logger) {
5657
5773
  super.__setLogger(logger);
5774
+ this.#hasApplicationLogger = true;
5775
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5776
+ this.#pendingStorageExporterWarnings.clear();
5658
5777
  this.exporters.forEach((exporter) => {
5659
5778
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5660
5779
  });
@@ -5823,17 +5942,24 @@ var BaseObservabilityInstance = class extends MastraBase {
5823
5942
  getExporters() {
5824
5943
  return [...this.exporters];
5825
5944
  }
5945
+ warnStorageExporterSkipped(exporter) {
5946
+ if (!this.#hasApplicationLogger) {
5947
+ this.#pendingStorageExporterWarnings.add(exporter);
5948
+ return;
5949
+ }
5950
+ this.logger.warn(isMastraDeprecatedStorageExporter(exporter) ? "Deprecated DefaultExporter skipped on Mastra Platform. Use MastraStorageExporter with retainStorageExporterOnPlatform: true for remote storage export." : "Storage exporter skipped on Mastra Platform. Set retainStorageExporterOnPlatform: true on this observability config to allow remote storage export.", {
5951
+ exporterName: exporter.name,
5952
+ serviceName: this.config.serviceName,
5953
+ instanceName: this.config.name
5954
+ });
5955
+ }
5826
5956
  /**
5827
5957
  * Register an additional exporter at runtime.
5828
5958
  * Adds to both the bus (for event routing) and the config (for getExporters).
5829
5959
  */
5830
5960
  registerExporter(exporter) {
5831
- if (isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter)) {
5832
- this.logger.warn("Storage exporter registration skipped on Mastra Platform", {
5833
- exporterName: exporter.name,
5834
- serviceName: this.config.serviceName,
5835
- instanceName: this.config.name
5836
- });
5961
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5962
+ this.warnStorageExporterSkipped(exporter);
5837
5963
  return;
5838
5964
  }
5839
5965
  this.observabilityBus.registerExporter(exporter);