@mastra/observability 1.12.0 → 1.13.0-alpha.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @mastra/observability
2
2
 
3
+ ## 1.13.0-alpha.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Roll up token usage from internal MODEL_GENERATION spans onto the closest exported ancestor span. When `tracingPolicy.internal` filters a model call out of exported traces, its tokens used to disappear from both the trace UI and metrics. Now: ([#16434](https://github.com/mastra-ai/mastra/pull/16434))
8
+ - The visible ancestor (e.g. `PROCESSOR_RUN`, `AGENT_RUN`) gets an `internalUsage` attribute summing the tokens consumed by its hidden descendants — so a Mastra-owned processor that runs an internal agent (moderation, PII detector, structured output, etc.) shows its aggregate cost on the visible `PROCESSOR_RUN` span.
9
+ - Token / cost metrics still emit, but are attributed via labels to the visible ancestor instead of the hidden agent.
10
+
11
+ No action required — the rollup applies automatically whenever an internal `MODEL_GENERATION` ends inside a non-internal ancestor.
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [[`8cdb86c`](https://github.com/mastra-ai/mastra/commit/8cdb86ceed1137bc2768e147dce85a0692b9fb26), [`eda90c5`](https://github.com/mastra-ai/mastra/commit/eda90c5bfd7de11805ecc9f4552716c895fbaf78), [`afc004f`](https://github.com/mastra-ai/mastra/commit/afc004f5cc7e30697809e7021820b9f5881e6719), [`408be73`](https://github.com/mastra-ai/mastra/commit/408be73449dfab92b51eab8c6623b6c443debc25)]:
16
+ - @mastra/core@1.36.0-alpha.1
17
+
3
18
  ## 1.12.0
4
19
 
5
20
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../src/features.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,eAAO,MAAM,qBAAqB,EAAE,WAAW,CAAC,MAAM,CAAqC,CAAC"}
1
+ {"version":3,"file":"features.d.ts","sourceRoot":"","sources":["../src/features.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,eAAO,MAAM,qBAAqB,EAAE,WAAW,CAAC,MAAM,CAA8D,CAAC"}
package/dist/index.cjs CHANGED
@@ -19029,6 +19029,7 @@ var PricingRegistry = class _PricingRegistry {
19029
19029
  constructor(pricingModels) {
19030
19030
  this.pricingModels = pricingModels;
19031
19031
  }
19032
+ pricingModels;
19032
19033
  static globalRegistry = null;
19033
19034
  static fromText(pricingModelText) {
19034
19035
  return new _PricingRegistry(parsePricingModelText(pricingModelText));
@@ -19432,6 +19433,9 @@ function emitTokenMetrics(span, metrics) {
19432
19433
  }
19433
19434
  emitUsageMetrics(attrs, attrs.usage, metrics);
19434
19435
  }
19436
+ function emitTokenMetricsForUsage(usage, provider, model, metrics) {
19437
+ emitUsageMetrics({ provider, model }, usage, metrics);
19438
+ }
19435
19439
  function emitAutoExtractedMetrics(span, metrics) {
19436
19440
  emitDurationMetrics(span, metrics);
19437
19441
  emitTokenMetrics(span, metrics);
@@ -19593,6 +19597,46 @@ function extractUsageMetrics(usage, providerMetadata) {
19593
19597
  function sumDefinedValues(obj, keys) {
19594
19598
  return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
19595
19599
  }
19600
+ function addOptional(a, b) {
19601
+ if (a === void 0 && b === void 0) return void 0;
19602
+ return (a ?? 0) + (b ?? 0);
19603
+ }
19604
+ function mergeInputDetails(a, b) {
19605
+ if (!a) return b ? { ...b } : void 0;
19606
+ if (!b) return { ...a };
19607
+ return {
19608
+ text: addOptional(a.text, b.text),
19609
+ cacheRead: addOptional(a.cacheRead, b.cacheRead),
19610
+ cacheWrite: addOptional(a.cacheWrite, b.cacheWrite),
19611
+ audio: addOptional(a.audio, b.audio),
19612
+ image: addOptional(a.image, b.image)
19613
+ };
19614
+ }
19615
+ function mergeOutputDetails(a, b) {
19616
+ if (!a) return b ? { ...b } : void 0;
19617
+ if (!b) return { ...a };
19618
+ return {
19619
+ text: addOptional(a.text, b.text),
19620
+ reasoning: addOptional(a.reasoning, b.reasoning),
19621
+ audio: addOptional(a.audio, b.audio),
19622
+ image: addOptional(a.image, b.image)
19623
+ };
19624
+ }
19625
+ function addUsageStats(a, b) {
19626
+ if (!a) {
19627
+ return {
19628
+ ...b,
19629
+ inputDetails: b.inputDetails ? { ...b.inputDetails } : void 0,
19630
+ outputDetails: b.outputDetails ? { ...b.outputDetails } : void 0
19631
+ };
19632
+ }
19633
+ return {
19634
+ inputTokens: addOptional(a.inputTokens, b.inputTokens),
19635
+ outputTokens: addOptional(a.outputTokens, b.outputTokens),
19636
+ inputDetails: mergeInputDetails(a.inputDetails, b.inputDetails),
19637
+ outputDetails: mergeOutputDetails(a.outputDetails, b.outputDetails)
19638
+ };
19639
+ }
19596
19640
 
19597
19641
  // src/model-tracing.ts
19598
19642
  function supportsModelInference() {
@@ -21122,7 +21166,7 @@ var BaseObservabilityInstance = class extends base.MastraBase {
21122
21166
  * This ensures all spans emit events regardless of implementation
21123
21167
  */
21124
21168
  wireSpanLifecycle(span) {
21125
- if (!this.config.includeInternalSpans && span.isInternal) {
21169
+ if (!this.config.includeInternalSpans && span.isInternal && span.type !== observability.SpanType.MODEL_GENERATION) {
21126
21170
  return;
21127
21171
  }
21128
21172
  const originalEnd = span.end.bind(span);
@@ -21132,7 +21176,11 @@ var BaseObservabilityInstance = class extends base.MastraBase {
21132
21176
  this.logger.warn(`End event is not available on event spans`);
21133
21177
  return;
21134
21178
  }
21179
+ const rollupTarget = this.captureModelUsageRollup(span, options);
21135
21180
  originalEnd(options);
21181
+ if (rollupTarget) {
21182
+ this.applyUsageRollup(rollupTarget);
21183
+ }
21136
21184
  this.emitSpanEnded(span);
21137
21185
  };
21138
21186
  span.update = (options) => {
@@ -21306,6 +21354,70 @@ var BaseObservabilityInstance = class extends base.MastraBase {
21306
21354
  this.emitTracingEvent(event);
21307
21355
  }
21308
21356
  }
21357
+ /**
21358
+ * When an internal MODEL_GENERATION span ends, capture the rollup payload
21359
+ * (usage, provider, model, target ancestor) needed to attribute its cost
21360
+ * to the closest exported ancestor span. Returns undefined when no rollup
21361
+ * applies — non-MODEL_GENERATION spans, spans that will be exported, or
21362
+ * spans whose usage isn't available at end time.
21363
+ */
21364
+ captureModelUsageRollup(span, endOptions) {
21365
+ if (span.type !== observability.SpanType.MODEL_GENERATION) return void 0;
21366
+ if (!span.isInternal || this.config.includeInternalSpans) return void 0;
21367
+ const endAttrs = endOptions?.attributes ?? void 0;
21368
+ const liveAttrs = span.attributes;
21369
+ const usage = endAttrs?.usage ?? liveAttrs?.usage;
21370
+ if (!usage) return void 0;
21371
+ const ancestor = this.findExportedAncestor(span);
21372
+ if (!ancestor) return void 0;
21373
+ const provider = endAttrs?.provider ?? liveAttrs?.provider;
21374
+ const model = endAttrs?.responseModel ?? endAttrs?.model ?? liveAttrs?.responseModel ?? liveAttrs?.model;
21375
+ return { ancestor, usage, provider, model };
21376
+ }
21377
+ /**
21378
+ * Accumulate usage onto the ancestor's `internalUsage` attribute (for trace
21379
+ * UI visibility) and emit auto-extracted token metrics now, using the
21380
+ * ancestor's metrics context so cost / token labels point at the visible
21381
+ * span instead of the hidden agent that incurred them.
21382
+ */
21383
+ applyUsageRollup(target) {
21384
+ const { ancestor, usage, provider, model } = target;
21385
+ const attrs = ancestor.attributes;
21386
+ attrs.internalUsage = addUsageStats(attrs.internalUsage, usage);
21387
+ try {
21388
+ emitTokenMetricsForUsage(usage, provider, model, this.getMetricsContext(ancestor));
21389
+ } catch (err) {
21390
+ this.logger.error("[Observability] Usage rollup metric emission error:", err);
21391
+ }
21392
+ }
21393
+ /**
21394
+ * Walk up the parent chain to find the closest ancestor that will actually
21395
+ * reach exporters. Skips both internal-filtered ancestors and ancestors
21396
+ * whose type matches `excludeSpanTypes`, so the rollup target is one whose
21397
+ * mutated `internalUsage` attribute is visible in exported traces.
21398
+ *
21399
+ * Note: this does not preemptively run `spanFilter` — that filter can be
21400
+ * async and have side effects, so the rare case of a `spanFilter`-dropped
21401
+ * ancestor falls through.
21402
+ */
21403
+ findExportedAncestor(span) {
21404
+ let ancestor = span.parent;
21405
+ while (ancestor && this.isFilteredFromExport(ancestor)) {
21406
+ ancestor = ancestor.parent;
21407
+ }
21408
+ return ancestor;
21409
+ }
21410
+ /**
21411
+ * Returns true when a span would be dropped by `getSpanForExport` for a
21412
+ * reason cheap to check up-front (internal-span filtering or
21413
+ * `excludeSpanTypes`). Used by `findExportedAncestor` to skip rollup
21414
+ * targets that would silently lose their `internalUsage` attribute.
21415
+ */
21416
+ isFilteredFromExport(span) {
21417
+ if (span.isInternal && !this.config.includeInternalSpans) return true;
21418
+ if (this.config.excludeSpanTypes?.includes(span.type)) return true;
21419
+ return false;
21420
+ }
21309
21421
  /**
21310
21422
  * Emit a tracing event through the bus.
21311
21423
  *
@@ -22256,7 +22368,7 @@ var Observability = class extends base.MastraBase {
22256
22368
  };
22257
22369
 
22258
22370
  // src/features.ts
22259
- var observabilityFeatures = /* @__PURE__ */ new Set(["model-inference-span"]);
22371
+ var observabilityFeatures = /* @__PURE__ */ new Set(["model-inference-span", "internal-usage-rollup"]);
22260
22372
 
22261
22373
  // src/tracing-options.ts
22262
22374
  function buildTracingOptions(...updaters) {