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

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: {
@@ -3153,11 +3227,22 @@ var ModelSpanTracker = class {
3153
3227
  * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
3154
3228
  */
3155
3229
  wrapStream(stream, inferenceOnly = false) {
3230
+ let servedModelId;
3156
3231
  return stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {
3157
3232
  if (inferenceOnly) {
3158
3233
  try {
3234
+ if (chunk.type === "response-metadata" && typeof chunk.payload?.modelId === "string") servedModelId = chunk.payload.modelId;
3159
3235
  if (MODEL_RESPONSE_CHUNK_TYPES.has(chunk.type)) this.#captureCompletionStartTime();
3160
- if (chunk.type === "finish") this.#endInferenceSpan(chunk.payload, false);
3236
+ if (chunk.type === "finish") {
3237
+ const payload = servedModelId && !chunk.payload?.metadata?.modelId ? {
3238
+ ...chunk.payload,
3239
+ metadata: {
3240
+ ...chunk.payload?.metadata,
3241
+ modelId: servedModelId
3242
+ }
3243
+ } : chunk.payload;
3244
+ this.#endInferenceSpan(payload, false);
3245
+ }
3161
3246
  } catch {}
3162
3247
  controller.enqueue(chunk);
3163
3248
  return;
@@ -3166,6 +3251,19 @@ var ModelSpanTracker = class {
3166
3251
  controller.enqueue(chunk);
3167
3252
  } }));
3168
3253
  }
3254
+ /** Keep the processed response of the open inference; see #inferenceContent. */
3255
+ #collectInferenceContent(chunk) {
3256
+ if (!this.#currentInferenceSpan) return;
3257
+ if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") this.#inferenceContent.text += chunk.payload.text;
3258
+ else if (chunk.type === "tool-call") {
3259
+ const { toolCallId, toolName, args } = chunk.payload;
3260
+ this.#inferenceContent.toolCalls.push({
3261
+ toolCallId,
3262
+ toolName,
3263
+ args
3264
+ });
3265
+ }
3266
+ }
3169
3267
  /** @internal Record a chunk only after output processors accept it. */
3170
3268
  recordChunk(chunk) {
3171
3269
  try {
@@ -3174,6 +3272,7 @@ var ModelSpanTracker = class {
3174
3272
  if (chunk.type === "tool-call-approval") this.#handleToolApprovalChunk(chunk);
3175
3273
  this.#endSuspendedStep(chunk);
3176
3274
  }
3275
+ this.#collectInferenceContent(chunk);
3177
3276
  switch (chunk.type) {
3178
3277
  case "text-start":
3179
3278
  case "text-delta":
@@ -3215,7 +3314,9 @@ var ModelSpanTracker = class {
3215
3314
  this.endAttempt(termination);
3216
3315
  break;
3217
3316
  }
3218
- case "finish": break;
3317
+ case "finish":
3318
+ this.#settlePendingInference();
3319
+ break;
3219
3320
  case "raw":
3220
3321
  case "start":
3221
3322
  case "response-metadata":
@@ -3962,7 +4063,8 @@ var DefaultSpan = class extends BaseSpan {
3962
4063
  if (options?.endTree) this.endOpenDescendants(options);
3963
4064
  if (options) this.applyOutcome(options);
3964
4065
  if (this.outcome === null) this.outcome = "unknown";
3965
- this.endTime = /* @__PURE__ */ new Date();
4066
+ const endTime = options?.endTime;
4067
+ this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
3966
4068
  this.detachFromParent();
3967
4069
  if (options?.metadata) this.metadata = {
3968
4070
  ...this.metadata,
@@ -5011,6 +5113,16 @@ var StorageByteTracker = class {
5011
5113
  };
5012
5114
  }
5013
5115
  };
5116
+ // src/exporters/storage-platform-policy.ts
5117
+ /**
5118
+ * Check the resolved observability domain, not the composite store's default backend.
5119
+ * Older or custom adapters without location metadata retain opt-in compatibility.
5120
+ */
5121
+ function skipLocalStorageOnPlatform(storage, logger) {
5122
+ if (!process.env.MASTRA_DEPLOYMENT_ID || storage.persistenceLocation !== "local") return false;
5123
+ logger.warn("Storage exporter disabled on Mastra Platform: local observability storage is not supported, even with retainStorageExporterOnPlatform: true. Use a remote observability storage provider.");
5124
+ return true;
5125
+ }
5014
5126
  // src/exporters/mastra-storage.ts
5015
5127
  /**
5016
5128
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -5106,6 +5218,11 @@ var MastraStorageExporter = class extends BaseExporter {
5106
5218
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
5107
5219
  return;
5108
5220
  }
5221
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5222
+ this.#observabilityStorage = void 0;
5223
+ this.#storage = void 0;
5224
+ return;
5225
+ }
5109
5226
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5110
5227
  if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5111
5228
  this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
@@ -5579,6 +5696,12 @@ function isMastraPlatformDeployment() {
5579
5696
  function isMastraBuiltInStorageExporter(exporter) {
5580
5697
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5581
5698
  }
5699
+ function isMastraDeprecatedStorageExporter(exporter) {
5700
+ return exporter instanceof DefaultExporter || exporter.name === "mastra-default-observability-exporter";
5701
+ }
5702
+ function shouldSkipStorageExporterOnPlatform(exporter, retainStorageExporterOnPlatform = false) {
5703
+ return isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter) && (!retainStorageExporterOnPlatform || isMastraDeprecatedStorageExporter(exporter));
5704
+ }
5582
5705
  // src/instances/base.ts
5583
5706
  /**
5584
5707
  * BaseObservability - Abstract base class for Observability implementations
@@ -5616,6 +5739,8 @@ var BaseObservabilityInstance = class extends MastraBase {
5616
5739
  * a span's `metadata.environment` isn't set.
5617
5740
  */
5618
5741
  #mastraEnvironment;
5742
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5743
+ #hasApplicationLogger = false;
5619
5744
  /**
5620
5745
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5621
5746
  * we stash the lightweight provider/model from creation options so
@@ -5628,12 +5753,13 @@ var BaseObservabilityInstance = class extends MastraBase {
5628
5753
  name: config.serviceName
5629
5754
  });
5630
5755
  const exporters = config.exporters ?? [];
5631
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5756
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5632
5757
  this.config = {
5633
5758
  serviceName: config.serviceName,
5634
5759
  name: config.name,
5635
5760
  sampling: config.sampling ?? { type: "always" },
5636
5761
  exporters: effectiveExporters,
5762
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5637
5763
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5638
5764
  bridge: config.bridge ?? void 0,
5639
5765
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5643,6 +5769,7 @@ var BaseObservabilityInstance = class extends MastraBase {
5643
5769
  serializationOptions: config.serializationOptions,
5644
5770
  logging: config.logging
5645
5771
  };
5772
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5646
5773
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5647
5774
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5648
5775
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5655,6 +5782,9 @@ var BaseObservabilityInstance = class extends MastraBase {
5655
5782
  */
5656
5783
  __setLogger(logger) {
5657
5784
  super.__setLogger(logger);
5785
+ this.#hasApplicationLogger = true;
5786
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5787
+ this.#pendingStorageExporterWarnings.clear();
5658
5788
  this.exporters.forEach((exporter) => {
5659
5789
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5660
5790
  });
@@ -5823,17 +5953,24 @@ var BaseObservabilityInstance = class extends MastraBase {
5823
5953
  getExporters() {
5824
5954
  return [...this.exporters];
5825
5955
  }
5956
+ warnStorageExporterSkipped(exporter) {
5957
+ if (!this.#hasApplicationLogger) {
5958
+ this.#pendingStorageExporterWarnings.add(exporter);
5959
+ return;
5960
+ }
5961
+ 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.", {
5962
+ exporterName: exporter.name,
5963
+ serviceName: this.config.serviceName,
5964
+ instanceName: this.config.name
5965
+ });
5966
+ }
5826
5967
  /**
5827
5968
  * Register an additional exporter at runtime.
5828
5969
  * Adds to both the bus (for event routing) and the config (for getExporters).
5829
5970
  */
5830
5971
  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
- });
5972
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5973
+ this.warnStorageExporterSkipped(exporter);
5837
5974
  return;
5838
5975
  }
5839
5976
  this.observabilityBus.registerExporter(exporter);