@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.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: {
@@ -3191,6 +3265,19 @@ var ModelSpanTracker = class {
3191
3265
  controller.enqueue(chunk);
3192
3266
  } }));
3193
3267
  }
3268
+ /** Keep the processed response of the open inference; see #inferenceContent. */
3269
+ #collectInferenceContent(chunk) {
3270
+ if (!this.#currentInferenceSpan) return;
3271
+ if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") this.#inferenceContent.text += chunk.payload.text;
3272
+ else if (chunk.type === "tool-call") {
3273
+ const { toolCallId, toolName, args } = chunk.payload;
3274
+ this.#inferenceContent.toolCalls.push({
3275
+ toolCallId,
3276
+ toolName,
3277
+ args
3278
+ });
3279
+ }
3280
+ }
3194
3281
  /** @internal Record a chunk only after output processors accept it. */
3195
3282
  recordChunk(chunk) {
3196
3283
  try {
@@ -3199,6 +3286,7 @@ var ModelSpanTracker = class {
3199
3286
  if (chunk.type === "tool-call-approval") this.#handleToolApprovalChunk(chunk);
3200
3287
  this.#endSuspendedStep(chunk);
3201
3288
  }
3289
+ this.#collectInferenceContent(chunk);
3202
3290
  switch (chunk.type) {
3203
3291
  case "text-start":
3204
3292
  case "text-delta":
@@ -3240,7 +3328,9 @@ var ModelSpanTracker = class {
3240
3328
  this.endAttempt(termination);
3241
3329
  break;
3242
3330
  }
3243
- case "finish": break;
3331
+ case "finish":
3332
+ this.#settlePendingInference();
3333
+ break;
3244
3334
  case "raw":
3245
3335
  case "start":
3246
3336
  case "response-metadata":
@@ -3987,7 +4077,8 @@ var DefaultSpan = class extends BaseSpan {
3987
4077
  if (options?.endTree) this.endOpenDescendants(options);
3988
4078
  if (options) this.applyOutcome(options);
3989
4079
  if (this.outcome === null) this.outcome = "unknown";
3990
- this.endTime = /* @__PURE__ */ new Date();
4080
+ const endTime = options?.endTime;
4081
+ this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
3991
4082
  this.detachFromParent();
3992
4083
  if (options?.metadata) this.metadata = {
3993
4084
  ...this.metadata,
@@ -5036,6 +5127,16 @@ var StorageByteTracker = class {
5036
5127
  };
5037
5128
  }
5038
5129
  };
5130
+ // src/exporters/storage-platform-policy.ts
5131
+ /**
5132
+ * Check the resolved observability domain, not the composite store's default backend.
5133
+ * Older or custom adapters without location metadata retain opt-in compatibility.
5134
+ */
5135
+ function skipLocalStorageOnPlatform(storage, logger) {
5136
+ if (!process.env.MASTRA_DEPLOYMENT_ID || storage.persistenceLocation !== "local") return false;
5137
+ logger.warn("Storage exporter disabled on Mastra Platform: local observability storage is not supported, even with retainStorageExporterOnPlatform: true. Use a remote observability storage provider.");
5138
+ return true;
5139
+ }
5039
5140
  // src/exporters/mastra-storage.ts
5040
5141
  /**
5041
5142
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -5131,6 +5232,11 @@ var MastraStorageExporter = class extends BaseExporter {
5131
5232
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
5132
5233
  return;
5133
5234
  }
5235
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5236
+ this.#observabilityStorage = void 0;
5237
+ this.#storage = void 0;
5238
+ return;
5239
+ }
5134
5240
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5135
5241
  if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5136
5242
  this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
@@ -5604,6 +5710,12 @@ function isMastraPlatformDeployment() {
5604
5710
  function isMastraBuiltInStorageExporter(exporter) {
5605
5711
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5606
5712
  }
5713
+ function isMastraDeprecatedStorageExporter(exporter) {
5714
+ return exporter instanceof DefaultExporter || exporter.name === "mastra-default-observability-exporter";
5715
+ }
5716
+ function shouldSkipStorageExporterOnPlatform(exporter, retainStorageExporterOnPlatform = false) {
5717
+ return isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter) && (!retainStorageExporterOnPlatform || isMastraDeprecatedStorageExporter(exporter));
5718
+ }
5607
5719
  // src/instances/base.ts
5608
5720
  /**
5609
5721
  * BaseObservability - Abstract base class for Observability implementations
@@ -5641,6 +5753,8 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5641
5753
  * a span's `metadata.environment` isn't set.
5642
5754
  */
5643
5755
  #mastraEnvironment;
5756
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5757
+ #hasApplicationLogger = false;
5644
5758
  /**
5645
5759
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5646
5760
  * we stash the lightweight provider/model from creation options so
@@ -5653,12 +5767,13 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5653
5767
  name: config.serviceName
5654
5768
  });
5655
5769
  const exporters = config.exporters ?? [];
5656
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5770
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5657
5771
  this.config = {
5658
5772
  serviceName: config.serviceName,
5659
5773
  name: config.name,
5660
5774
  sampling: config.sampling ?? { type: "always" },
5661
5775
  exporters: effectiveExporters,
5776
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5662
5777
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5663
5778
  bridge: config.bridge ?? void 0,
5664
5779
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5668,6 +5783,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5668
5783
  serializationOptions: config.serializationOptions,
5669
5784
  logging: config.logging
5670
5785
  };
5786
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5671
5787
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5672
5788
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5673
5789
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5680,6 +5796,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5680
5796
  */
5681
5797
  __setLogger(logger) {
5682
5798
  super.__setLogger(logger);
5799
+ this.#hasApplicationLogger = true;
5800
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5801
+ this.#pendingStorageExporterWarnings.clear();
5683
5802
  this.exporters.forEach((exporter) => {
5684
5803
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5685
5804
  });
@@ -5848,17 +5967,24 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5848
5967
  getExporters() {
5849
5968
  return [...this.exporters];
5850
5969
  }
5970
+ warnStorageExporterSkipped(exporter) {
5971
+ if (!this.#hasApplicationLogger) {
5972
+ this.#pendingStorageExporterWarnings.add(exporter);
5973
+ return;
5974
+ }
5975
+ 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.", {
5976
+ exporterName: exporter.name,
5977
+ serviceName: this.config.serviceName,
5978
+ instanceName: this.config.name
5979
+ });
5980
+ }
5851
5981
  /**
5852
5982
  * Register an additional exporter at runtime.
5853
5983
  * Adds to both the bus (for event routing) and the config (for getExporters).
5854
5984
  */
5855
5985
  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
- });
5986
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5987
+ this.warnStorageExporterSkipped(exporter);
5862
5988
  return;
5863
5989
  }
5864
5990
  this.observabilityBus.registerExporter(exporter);