@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.cjs CHANGED
@@ -811,6 +811,7 @@ const observabilityInstanceConfigFields = {
811
811
  serviceName: zod_v4.z.string().min(1, "Service name is required"),
812
812
  sampling: samplingStrategySchema.optional(),
813
813
  exporters: zod_v4.z.array(zod_v4.z.any()).optional(),
814
+ retainStorageExporterOnPlatform: zod_v4.z.boolean().optional(),
814
815
  bridge: zod_v4.z.any().optional(),
815
816
  spanOutputProcessors: zod_v4.z.array(zod_v4.z.any()).optional(),
816
817
  includeInternalSpans: zod_v4.z.boolean().optional(),
@@ -2535,6 +2536,22 @@ var ModelSpanTracker = class {
2535
2536
  #currentInferenceSpan;
2536
2537
  #stepHasInference = false;
2537
2538
  #tracksProviderStream = false;
2539
+ /**
2540
+ * Provider completion of the open MODEL_INFERENCE, held until the processed
2541
+ * step supplies its output. The raw provider stream carries content before
2542
+ * output processors run, so the span keeps its provider end time and usage
2543
+ * from here but takes its output from the processed `step-finish`.
2544
+ */
2545
+ #pendingInferenceFinish;
2546
+ /**
2547
+ * Processed text and tool calls of the open MODEL_INFERENCE, for loops whose
2548
+ * `step-finish` payload carries only usage (the durable loop rewrites the
2549
+ * provider's `finish` into `step-finish`).
2550
+ */
2551
+ #inferenceContent = {
2552
+ text: "",
2553
+ toolCalls: []
2554
+ };
2538
2555
  #currentChunkSpan;
2539
2556
  #currentChunkType;
2540
2557
  #accumulator = {};
@@ -2622,6 +2639,7 @@ var ModelSpanTracker = class {
2622
2639
  */
2623
2640
  reportGenerationError(options) {
2624
2641
  this.#endChunkSpan();
2642
+ this.#settlePendingInference();
2625
2643
  const termination = options.outcome != null ? {
2626
2644
  outcome: options.outcome,
2627
2645
  stopReason: options.stopReason,
@@ -2670,6 +2688,7 @@ var ModelSpanTracker = class {
2670
2688
  spanOptions.attributes.costContext = providerCostContext ?? spanOptions.attributes.costContext;
2671
2689
  if (!spanOptions.attributes.costContext) spanOptions.attributes.costContext = getGatewayCostContext({ stepProviderMetadata });
2672
2690
  }
2691
+ this.#settlePendingInference();
2673
2692
  if (spanOptions.outcome === "abort" || spanOptions.stopReason === "timeout") {
2674
2693
  const termination = {
2675
2694
  outcome: spanOptions.outcome,
@@ -2766,7 +2785,15 @@ var ModelSpanTracker = class {
2766
2785
  this.#inferenceTimeToFirstTokenMs = void 0;
2767
2786
  }
2768
2787
  /**
2769
- * End the current MODEL_INFERENCE span when the provider stream finishes.
2788
+ * End the current MODEL_INFERENCE span.
2789
+ *
2790
+ * With `captureOutput: false` (the raw provider stream's `finish`), the span is
2791
+ * not ended yet: its provider end time, usage and finish reason are held until
2792
+ * the processed `step-finish` arrives, which ends it with the processed output
2793
+ * and the held end time. Tool work between the two does not count toward the
2794
+ * inference's duration, and exporters that treat MODEL_INFERENCE as the model
2795
+ * call still get the response.
2796
+ *
2770
2797
  * Fields are duplicated onto MODEL_STEP (in #endStepSpan) so existing
2771
2798
  * integrations that read usage/finishReason from the step span continue
2772
2799
  * to work unchanged.
@@ -2775,27 +2802,66 @@ var ModelSpanTracker = class {
2775
2802
  */
2776
2803
  #endInferenceSpan(payload, captureOutput = true) {
2777
2804
  if (!this.#currentInferenceSpan) return;
2778
- const { usage: rawUsage, ...otherOutput } = payload.output;
2779
- const usage = extractUsageMetrics(rawUsage, payload.metadata?.providerMetadata);
2780
- const responseModel = typeof payload.metadata?.modelId === "string" ? payload.metadata.modelId : void 0;
2781
- this.#currentInferenceSpan.end({
2805
+ if (!captureOutput) {
2806
+ this.#pendingInferenceFinish ??= {
2807
+ payload,
2808
+ endTime: /* @__PURE__ */ new Date(),
2809
+ streamAttributes: this.#inferenceStreamAttributes()
2810
+ };
2811
+ return;
2812
+ }
2813
+ const pending = this.#pendingInferenceFinish;
2814
+ const { usage: _usage, ...stepOutput } = payload.output ?? {};
2815
+ const output = "text" in stepOutput || "toolCalls" in stepOutput ? stepOutput : this.#inferenceContent;
2816
+ this.#closeInference(pending?.payload ?? payload, {
2817
+ output,
2818
+ endTime: pending?.endTime,
2819
+ streamAttributes: pending?.streamAttributes
2820
+ });
2821
+ }
2822
+ /**
2823
+ * End an inference whose provider stream already finished, without output.
2824
+ * Used when the step ends some other way than a processed `step-finish`
2825
+ * (error, abort, suspension, tripwire, a replacement attempt).
2826
+ */
2827
+ #settlePendingInference() {
2828
+ const pending = this.#pendingInferenceFinish;
2829
+ if (!pending) return;
2830
+ this.#closeInference(pending.payload, {
2831
+ endTime: pending.endTime,
2832
+ streamAttributes: pending.streamAttributes
2833
+ });
2834
+ }
2835
+ #closeInference(finish, options) {
2836
+ const span = this.#currentInferenceSpan;
2837
+ this.#pendingInferenceFinish = void 0;
2838
+ this.#inferenceContent = {
2839
+ text: "",
2840
+ toolCalls: []
2841
+ };
2842
+ if (!span) return;
2843
+ const usage = extractUsageMetrics(finish.output?.usage, finish.metadata?.providerMetadata);
2844
+ const responseModel = typeof finish.metadata?.modelId === "string" ? finish.metadata.modelId : void 0;
2845
+ const endOptions = {
2782
2846
  ..._mastra_core_observability.agentLoopTermination?.({
2783
2847
  stopCause: "model_finished",
2784
- finishReason: payload.stepResult.reason
2848
+ finishReason: finish.stepResult.reason
2785
2849
  }),
2786
- ...payload.stepResult.reason === "error" ? {
2850
+ ...finish.stepResult.reason === "error" ? {
2787
2851
  outcome: "error",
2788
2852
  stopReason: "model_error"
2789
2853
  } : {},
2790
- ...captureOutput ? { output: otherOutput } : {},
2854
+ ...options.output !== void 0 ? { output: options.output } : {},
2855
+ ...options.endTime ? { endTime: options.endTime } : {},
2791
2856
  attributes: {
2792
2857
  usage,
2793
- finishReason: payload.stepResult.reason,
2794
- warnings: payload.stepResult.warnings,
2795
- ...this.#inferenceStreamAttributes(),
2858
+ finishReason: finish.stepResult.reason,
2859
+ warnings: finish.stepResult.warnings,
2860
+ ...options.streamAttributes ?? this.#inferenceStreamAttributes(),
2796
2861
  ...responseModel?.trim() ? { responseModel } : {}
2797
2862
  }
2798
- });
2863
+ };
2864
+ span.end(endOptions);
2799
2865
  this.#currentInferenceSpan = void 0;
2800
2866
  this.#inferenceCompletionStartTime = void 0;
2801
2867
  }
@@ -2836,6 +2902,7 @@ var ModelSpanTracker = class {
2836
2902
  endAttempt(termination) {
2837
2903
  termination = interruptedByRun(termination);
2838
2904
  const payload = this.#pendingStepFinishPayload;
2905
+ this.#settlePendingInference();
2839
2906
  if (payload) this.#endStepSpan(payload, termination);
2840
2907
  else {
2841
2908
  this.#endChunkSpan();
@@ -2853,6 +2920,10 @@ var ModelSpanTracker = class {
2853
2920
  if (!this.#currentStepSpan || this.#currentInferenceSpan) return;
2854
2921
  this.#inferenceCompletionStartTime = void 0;
2855
2922
  this.#inferenceTimeToFirstTokenMs = void 0;
2923
+ this.#inferenceContent = {
2924
+ text: "",
2925
+ toolCalls: []
2926
+ };
2856
2927
  const input = extractStepInput(payload);
2857
2928
  const generationAttrs = this.#modelSpan?.attributes;
2858
2929
  const ctx = this.#inferenceContext;
@@ -2883,6 +2954,7 @@ var ModelSpanTracker = class {
2883
2954
  */
2884
2955
  interruptInference(termination) {
2885
2956
  this.#endChunkSpan();
2957
+ this.#settlePendingInference();
2886
2958
  if (!this.#currentInferenceSpan) return;
2887
2959
  this.#currentInferenceSpan.end({
2888
2960
  attributes: {
@@ -2902,6 +2974,7 @@ var ModelSpanTracker = class {
2902
2974
  /** End the open inference span, if any, with `error` and what it streamed. */
2903
2975
  failInference(error) {
2904
2976
  this.#endChunkSpan();
2977
+ this.#settlePendingInference();
2905
2978
  if (!this.#currentInferenceSpan) return;
2906
2979
  this.#currentInferenceSpan.error({
2907
2980
  error,
@@ -2981,6 +3054,7 @@ var ModelSpanTracker = class {
2981
3054
  const usage = chunk.payload.usage;
2982
3055
  if (!usage) return;
2983
3056
  this.#inModelResponse = false;
3057
+ this.#settlePendingInference();
2984
3058
  this.#endStepSpan({
2985
3059
  output: { usage },
2986
3060
  stepResult: {
@@ -3178,11 +3252,22 @@ var ModelSpanTracker = class {
3178
3252
  * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
3179
3253
  */
3180
3254
  wrapStream(stream, inferenceOnly = false) {
3255
+ let servedModelId;
3181
3256
  return stream.pipeThrough(new stream_web.TransformStream({ transform: (chunk, controller) => {
3182
3257
  if (inferenceOnly) {
3183
3258
  try {
3259
+ if (chunk.type === "response-metadata" && typeof chunk.payload?.modelId === "string") servedModelId = chunk.payload.modelId;
3184
3260
  if (MODEL_RESPONSE_CHUNK_TYPES.has(chunk.type)) this.#captureCompletionStartTime();
3185
- if (chunk.type === "finish") this.#endInferenceSpan(chunk.payload, false);
3261
+ if (chunk.type === "finish") {
3262
+ const payload = servedModelId && !chunk.payload?.metadata?.modelId ? {
3263
+ ...chunk.payload,
3264
+ metadata: {
3265
+ ...chunk.payload?.metadata,
3266
+ modelId: servedModelId
3267
+ }
3268
+ } : chunk.payload;
3269
+ this.#endInferenceSpan(payload, false);
3270
+ }
3186
3271
  } catch {}
3187
3272
  controller.enqueue(chunk);
3188
3273
  return;
@@ -3191,6 +3276,19 @@ var ModelSpanTracker = class {
3191
3276
  controller.enqueue(chunk);
3192
3277
  } }));
3193
3278
  }
3279
+ /** Keep the processed response of the open inference; see #inferenceContent. */
3280
+ #collectInferenceContent(chunk) {
3281
+ if (!this.#currentInferenceSpan) return;
3282
+ if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") this.#inferenceContent.text += chunk.payload.text;
3283
+ else if (chunk.type === "tool-call") {
3284
+ const { toolCallId, toolName, args } = chunk.payload;
3285
+ this.#inferenceContent.toolCalls.push({
3286
+ toolCallId,
3287
+ toolName,
3288
+ args
3289
+ });
3290
+ }
3291
+ }
3194
3292
  /** @internal Record a chunk only after output processors accept it. */
3195
3293
  recordChunk(chunk) {
3196
3294
  try {
@@ -3199,6 +3297,7 @@ var ModelSpanTracker = class {
3199
3297
  if (chunk.type === "tool-call-approval") this.#handleToolApprovalChunk(chunk);
3200
3298
  this.#endSuspendedStep(chunk);
3201
3299
  }
3300
+ this.#collectInferenceContent(chunk);
3202
3301
  switch (chunk.type) {
3203
3302
  case "text-start":
3204
3303
  case "text-delta":
@@ -3240,7 +3339,9 @@ var ModelSpanTracker = class {
3240
3339
  this.endAttempt(termination);
3241
3340
  break;
3242
3341
  }
3243
- case "finish": break;
3342
+ case "finish":
3343
+ this.#settlePendingInference();
3344
+ break;
3244
3345
  case "raw":
3245
3346
  case "start":
3246
3347
  case "response-metadata":
@@ -3987,7 +4088,8 @@ var DefaultSpan = class extends BaseSpan {
3987
4088
  if (options?.endTree) this.endOpenDescendants(options);
3988
4089
  if (options) this.applyOutcome(options);
3989
4090
  if (this.outcome === null) this.outcome = "unknown";
3990
- this.endTime = /* @__PURE__ */ new Date();
4091
+ const endTime = options?.endTime;
4092
+ this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
3991
4093
  this.detachFromParent();
3992
4094
  if (options?.metadata) this.metadata = {
3993
4095
  ...this.metadata,
@@ -5036,6 +5138,16 @@ var StorageByteTracker = class {
5036
5138
  };
5037
5139
  }
5038
5140
  };
5141
+ // src/exporters/storage-platform-policy.ts
5142
+ /**
5143
+ * Check the resolved observability domain, not the composite store's default backend.
5144
+ * Older or custom adapters without location metadata retain opt-in compatibility.
5145
+ */
5146
+ function skipLocalStorageOnPlatform(storage, logger) {
5147
+ if (!process.env.MASTRA_DEPLOYMENT_ID || storage.persistenceLocation !== "local") return false;
5148
+ logger.warn("Storage exporter disabled on Mastra Platform: local observability storage is not supported, even with retainStorageExporterOnPlatform: true. Use a remote observability storage provider.");
5149
+ return true;
5150
+ }
5039
5151
  // src/exporters/mastra-storage.ts
5040
5152
  /**
5041
5153
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -5131,6 +5243,11 @@ var MastraStorageExporter = class extends BaseExporter {
5131
5243
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
5132
5244
  return;
5133
5245
  }
5246
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5247
+ this.#observabilityStorage = void 0;
5248
+ this.#storage = void 0;
5249
+ return;
5250
+ }
5134
5251
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5135
5252
  if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5136
5253
  this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
@@ -5604,6 +5721,12 @@ function isMastraPlatformDeployment() {
5604
5721
  function isMastraBuiltInStorageExporter(exporter) {
5605
5722
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5606
5723
  }
5724
+ function isMastraDeprecatedStorageExporter(exporter) {
5725
+ return exporter instanceof DefaultExporter || exporter.name === "mastra-default-observability-exporter";
5726
+ }
5727
+ function shouldSkipStorageExporterOnPlatform(exporter, retainStorageExporterOnPlatform = false) {
5728
+ return isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter) && (!retainStorageExporterOnPlatform || isMastraDeprecatedStorageExporter(exporter));
5729
+ }
5607
5730
  // src/instances/base.ts
5608
5731
  /**
5609
5732
  * BaseObservability - Abstract base class for Observability implementations
@@ -5641,6 +5764,8 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5641
5764
  * a span's `metadata.environment` isn't set.
5642
5765
  */
5643
5766
  #mastraEnvironment;
5767
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5768
+ #hasApplicationLogger = false;
5644
5769
  /**
5645
5770
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5646
5771
  * we stash the lightweight provider/model from creation options so
@@ -5653,12 +5778,13 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5653
5778
  name: config.serviceName
5654
5779
  });
5655
5780
  const exporters = config.exporters ?? [];
5656
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5781
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5657
5782
  this.config = {
5658
5783
  serviceName: config.serviceName,
5659
5784
  name: config.name,
5660
5785
  sampling: config.sampling ?? { type: "always" },
5661
5786
  exporters: effectiveExporters,
5787
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5662
5788
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5663
5789
  bridge: config.bridge ?? void 0,
5664
5790
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5668,6 +5794,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5668
5794
  serializationOptions: config.serializationOptions,
5669
5795
  logging: config.logging
5670
5796
  };
5797
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5671
5798
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5672
5799
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5673
5800
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5680,6 +5807,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5680
5807
  */
5681
5808
  __setLogger(logger) {
5682
5809
  super.__setLogger(logger);
5810
+ this.#hasApplicationLogger = true;
5811
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5812
+ this.#pendingStorageExporterWarnings.clear();
5683
5813
  this.exporters.forEach((exporter) => {
5684
5814
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5685
5815
  });
@@ -5848,17 +5978,24 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5848
5978
  getExporters() {
5849
5979
  return [...this.exporters];
5850
5980
  }
5981
+ warnStorageExporterSkipped(exporter) {
5982
+ if (!this.#hasApplicationLogger) {
5983
+ this.#pendingStorageExporterWarnings.add(exporter);
5984
+ return;
5985
+ }
5986
+ 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.", {
5987
+ exporterName: exporter.name,
5988
+ serviceName: this.config.serviceName,
5989
+ instanceName: this.config.name
5990
+ });
5991
+ }
5851
5992
  /**
5852
5993
  * Register an additional exporter at runtime.
5853
5994
  * Adds to both the bus (for event routing) and the config (for getExporters).
5854
5995
  */
5855
5996
  registerExporter(exporter) {
5856
- if (isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter)) {
5857
- this.logger.warn("Storage exporter registration skipped on Mastra Platform", {
5858
- exporterName: exporter.name,
5859
- serviceName: this.config.serviceName,
5860
- instanceName: this.config.name
5861
- });
5997
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5998
+ this.warnStorageExporterSkipped(exporter);
5862
5999
  return;
5863
6000
  }
5864
6001
  this.observabilityBus.registerExporter(exporter);