@mastra/observability 1.23.2-alpha.1 → 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.
Files changed (34) hide show
  1. package/dist/config.d.ts +13 -0
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/docs/SKILL.md +1 -1
  4. package/dist/docs/assets/SOURCE_MAP.json +42 -42
  5. package/dist/docs/references/docs-observability-integrations-exporters-mastra-storage.md +41 -0
  6. package/dist/docs/references/integrations-observability-arize.md +1 -1
  7. package/dist/docs/references/reference-observability-tracing-configuration.md +3 -0
  8. package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +33 -0
  9. package/dist/docs/references/reference-observability-tracing-exporters-mastra-storage-exporter.md +30 -0
  10. package/dist/exporters/event-buffer.d.ts +9 -0
  11. package/dist/exporters/event-buffer.d.ts.map +1 -1
  12. package/dist/exporters/mastra-platform.d.ts +10 -0
  13. package/dist/exporters/mastra-platform.d.ts.map +1 -1
  14. package/dist/exporters/mastra-storage.d.ts +4 -0
  15. package/dist/exporters/mastra-storage.d.ts.map +1 -1
  16. package/dist/exporters/platform-byte-batcher.d.ts +42 -0
  17. package/dist/exporters/platform-byte-batcher.d.ts.map +1 -0
  18. package/dist/exporters/storage-byte-tracker.d.ts +31 -0
  19. package/dist/exporters/storage-byte-tracker.d.ts.map +1 -0
  20. package/dist/exporters/storage-platform-policy.d.ts +8 -0
  21. package/dist/exporters/storage-platform-policy.d.ts.map +1 -0
  22. package/dist/index.cjs +622 -110
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.js +622 -110
  25. package/dist/index.js.map +1 -1
  26. package/dist/instances/base.d.ts +1 -0
  27. package/dist/instances/base.d.ts.map +1 -1
  28. package/dist/instances/platform-policy.d.ts +2 -0
  29. package/dist/instances/platform-policy.d.ts.map +1 -1
  30. package/dist/metrics/pricing-data.json +916 -618
  31. package/dist/model-tracing.d.ts.map +1 -1
  32. package/dist/spans/default.d.ts +8 -0
  33. package/dist/spans/default.d.ts.map +1 -1
  34. package/package.json +3 -3
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,
@@ -4308,8 +4399,11 @@ var EventBuffer = class {
4308
4399
  #firstEventTime;
4309
4400
  #storageStrategy;
4310
4401
  #maxRetries;
4402
+ #byteTracker;
4403
+ #preferUpdates = false;
4311
4404
  constructor(args) {
4312
4405
  this.#maxRetries = args.maxRetries;
4406
+ this.#byteTracker = args.byteTracker;
4313
4407
  }
4314
4408
  /** Initialize with a storage strategy and replay any pre-init events. */
4315
4409
  init(args) {
@@ -4329,18 +4423,20 @@ var EventBuffer = class {
4329
4423
  if (!this.#firstEventTime) this.#firstEventTime = /* @__PURE__ */ new Date();
4330
4424
  }
4331
4425
  pushCreate(event) {
4332
- this.setFirstEventTime();
4333
- this.#creates.push({
4426
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4334
4427
  ...event,
4335
4428
  retryCount: 0
4336
- });
4429
+ };
4430
+ this.setFirstEventTime();
4431
+ this.#creates.push(buffered);
4337
4432
  }
4338
4433
  pushUpdate(event) {
4339
- this.setFirstEventTime();
4340
- this.#updates.push({
4434
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4341
4435
  ...event,
4342
4436
  retryCount: 0
4343
- });
4437
+ };
4438
+ this.setFirstEventTime();
4439
+ this.#updates.push(buffered);
4344
4440
  }
4345
4441
  /** Route an event to the create or update buffer based on its type and the storage strategy. */
4346
4442
  addEvent(event) {
@@ -4356,8 +4452,8 @@ var EventBuffer = class {
4356
4452
  switch (this.#storageStrategy) {
4357
4453
  case "realtime":
4358
4454
  case "batch-with-updates":
4359
- if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4360
4455
  this.pushCreate(event);
4456
+ if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4361
4457
  break;
4362
4458
  case "event-sourced": this.pushCreate(event);
4363
4459
  }
@@ -4385,8 +4481,10 @@ var EventBuffer = class {
4385
4481
  reAddCreates(events) {
4386
4482
  const retryable = [];
4387
4483
  const dropped = [];
4388
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4389
- else dropped.push(e);
4484
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4485
+ retryable.push(e);
4486
+ this.#byteTracker?.enqueue(e);
4487
+ } else dropped.push(e);
4390
4488
  if (retryable.length > 0) {
4391
4489
  this.setFirstEventTime();
4392
4490
  this.#creates.push(...retryable);
@@ -4397,14 +4495,64 @@ var EventBuffer = class {
4397
4495
  reAddUpdates(events) {
4398
4496
  const retryable = [];
4399
4497
  const dropped = [];
4400
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4401
- else dropped.push(e);
4498
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4499
+ retryable.push(e);
4500
+ this.#byteTracker?.enqueue(e);
4501
+ } else dropped.push(e);
4402
4502
  if (retryable.length > 0) {
4403
4503
  this.setFirstEventTime();
4404
4504
  this.#updates.push(...retryable);
4405
4505
  }
4406
4506
  return dropped;
4407
4507
  }
4508
+ /** Alternate creates and eligible updates so either queue can make progress under load. */
4509
+ takeByteBatch(maxRecords) {
4510
+ const tracker = this.#byteTracker;
4511
+ const creates = [];
4512
+ const updates = [];
4513
+ const selectedUpdates = /* @__PURE__ */ new Set();
4514
+ let updateIndex = 0;
4515
+ let bytes = 0;
4516
+ while (creates.length + updates.length < maxRecords && bytes < tracker.config.maxBatchBytes) {
4517
+ while (updateIndex < this.#updates.length) {
4518
+ const event = this.#updates[updateIndex];
4519
+ if (!("exportedSpan" in event) || !this.isAwaitingCreate(event.exportedSpan)) break;
4520
+ updateIndex++;
4521
+ }
4522
+ const create = this.#creates[creates.length];
4523
+ const update = this.#updates[updateIndex];
4524
+ if (!create && !update) break;
4525
+ const takeUpdate = !!update && (!create || this.#preferUpdates);
4526
+ const event = takeUpdate ? update : create;
4527
+ if (takeUpdate) {
4528
+ updates.push(event);
4529
+ selectedUpdates.add(updateIndex++);
4530
+ } else creates.push(event);
4531
+ this.#preferUpdates = !takeUpdate;
4532
+ tracker.dequeue(event);
4533
+ bytes += tracker.size(event);
4534
+ }
4535
+ this.#creates.splice(0, creates.length);
4536
+ this.#updates = this.#updates.filter((_, index) => !selectedUpdates.has(index));
4537
+ if (this.totalSize === 0) this.#firstEventTime = void 0;
4538
+ return {
4539
+ creates,
4540
+ updates
4541
+ };
4542
+ }
4543
+ /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4544
+ releaseByteBatch(events) {
4545
+ if (!this.#byteTracker) return;
4546
+ for (const event of events) {
4547
+ if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4548
+ this.forgetDroppedCreates([event]);
4549
+ if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4550
+ traceId: event.exportedSpan.traceId,
4551
+ spanId: event.exportedSpan.id,
4552
+ updates: {}
4553
+ }] });
4554
+ }
4555
+ }
4408
4556
  /** Snapshot of buffered create events. */
4409
4557
  get creates() {
4410
4558
  return [...this.#creates];
@@ -4918,6 +5066,77 @@ function withSpanPreviews(span) {
4918
5066
  return span;
4919
5067
  }
4920
5068
  }
5069
+ // src/exporters/storage-byte-tracker.ts
5070
+ function resolveStorageByteBatching(config) {
5071
+ const resolved = {
5072
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
5073
+ maxConcurrentWrites: config.maxConcurrentWrites ?? 1
5074
+ };
5075
+ for (const [key, value] of Object.entries(resolved)) if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`byteBatching.${key} must be a positive safe integer`);
5076
+ return resolved;
5077
+ }
5078
+ /** Counts each admitted event once until persistence or a definitive drop, even across retries. */
5079
+ var StorageByteTracker = class {
5080
+ config;
5081
+ sizes = /* @__PURE__ */ new WeakMap();
5082
+ queued = /* @__PURE__ */ new WeakSet();
5083
+ pendingBytes = 0;
5084
+ pendingRecords = 0;
5085
+ queuedBytes = 0;
5086
+ constructor(config) {
5087
+ this.config = config;
5088
+ }
5089
+ capture(event) {
5090
+ const snapshot = {
5091
+ ...structuredClone(event),
5092
+ retryCount: 0
5093
+ };
5094
+ const bytes = Buffer.byteLength(JSON.stringify(snapshot)) + 1;
5095
+ this.sizes.set(snapshot, bytes);
5096
+ this.pendingBytes += bytes;
5097
+ this.pendingRecords++;
5098
+ this.enqueue(snapshot);
5099
+ return snapshot;
5100
+ }
5101
+ size(event) {
5102
+ return this.sizes.get(event) ?? 0;
5103
+ }
5104
+ enqueue(event) {
5105
+ if (!this.queued.has(event)) {
5106
+ this.queued.add(event);
5107
+ this.queuedBytes += this.size(event);
5108
+ }
5109
+ }
5110
+ dequeue(event) {
5111
+ if (this.queued.delete(event)) this.queuedBytes -= this.size(event);
5112
+ }
5113
+ releaseIfUnqueued(event) {
5114
+ if (this.queued.has(event)) return false;
5115
+ const bytes = this.sizes.get(event);
5116
+ if (bytes === void 0) return false;
5117
+ this.sizes.delete(event);
5118
+ this.pendingBytes -= bytes;
5119
+ this.pendingRecords--;
5120
+ return true;
5121
+ }
5122
+ stats(activeWrites) {
5123
+ return {
5124
+ pendingBytes: this.pendingBytes,
5125
+ pendingRecords: this.pendingRecords,
5126
+ activeWrites
5127
+ };
5128
+ }
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
+ }
4921
5140
  // src/exporters/mastra-storage.ts
4922
5141
  /**
4923
5142
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -4948,6 +5167,9 @@ var MastraStorageExporter = class extends BaseExporter {
4948
5167
  #initializationPromise;
4949
5168
  #wasUnavailable = false;
4950
5169
  #eventBuffer;
5170
+ #byteTracker;
5171
+ #byteRetryAt = 0;
5172
+ #byteDrainers = 0;
4951
5173
  #storage;
4952
5174
  #observabilityStorage;
4953
5175
  #resolvedStrategy;
@@ -4967,7 +5189,14 @@ var MastraStorageExporter = class extends BaseExporter {
4967
5189
  retryDelayMs: config.retryDelayMs ?? 500,
4968
5190
  strategy: config.strategy ?? "auto"
4969
5191
  };
4970
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5192
+ if (config.byteBatching) {
5193
+ if (!Number.isSafeInteger(this.#config.maxBatchSize) || this.#config.maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte mode");
5194
+ this.#byteTracker = new StorageByteTracker(resolveStorageByteBatching(config.byteBatching));
5195
+ }
5196
+ this.#eventBuffer = new EventBuffer({
5197
+ maxRetries: this.#config.maxRetries ?? 4,
5198
+ byteTracker: this.#byteTracker
5199
+ });
4971
5200
  }
4972
5201
  /**
4973
5202
  * Initialize the exporter (called after all dependencies are ready)
@@ -5003,7 +5232,17 @@ var MastraStorageExporter = class extends BaseExporter {
5003
5232
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
5004
5233
  return;
5005
5234
  }
5235
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5236
+ this.#observabilityStorage = void 0;
5237
+ this.#storage = void 0;
5238
+ return;
5239
+ }
5006
5240
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5241
+ if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5242
+ this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
5243
+ this.#byteTracker = void 0;
5244
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries });
5245
+ }
5007
5246
  this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5008
5247
  this.logger.debug("tracing storage exporter initialized", {
5009
5248
  strategy: this.#resolvedStrategy,
@@ -5028,6 +5267,7 @@ var MastraStorageExporter = class extends BaseExporter {
5028
5267
  * Checks if buffer should be flushed based on size or time triggers
5029
5268
  */
5030
5269
  shouldFlush() {
5270
+ if (this.#byteTracker && this.#byteTracker.queuedBytes >= this.#byteTracker.config.maxBatchBytes) return true;
5031
5271
  if (this.#resolvedStrategy === "realtime") return true;
5032
5272
  if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5033
5273
  if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
@@ -5073,8 +5313,11 @@ var MastraStorageExporter = class extends BaseExporter {
5073
5313
  * Returns the flush promise when flushing so callers can await it.
5074
5314
  */
5075
5315
  async handleBatchedFlush() {
5076
- if (this.shouldFlush()) await this.trackFlushBuffer();
5077
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5316
+ if (this.shouldFlush()) {
5317
+ const writing = this.trackFlushBuffer();
5318
+ if (this.#byteTracker) writing.catch((error) => this.logger.error("Byte batch flush failed", { error }));
5319
+ else await writing;
5320
+ } else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5078
5321
  }
5079
5322
  sanitizeDropError(error) {
5080
5323
  if (error instanceof _mastra_core_error.MastraError) return {
@@ -5216,7 +5459,26 @@ var MastraStorageExporter = class extends BaseExporter {
5216
5459
  * that a timer or size trigger started on their own.
5217
5460
  */
5218
5461
  trackFlushBuffer() {
5219
- const promise = this.flushBuffer().finally(() => this.#inFlightFlushes.delete(promise));
5462
+ if (this.#byteTracker) {
5463
+ const concurrency = this.#resolvedStrategy === "insert-only" || this.#resolvedStrategy === "event-sourced" ? this.#byteTracker.config.maxConcurrentWrites : 1;
5464
+ if (this.#inFlightFlushes.size >= concurrency) return Promise.resolve();
5465
+ const delay = this.#byteRetryAt - Date.now();
5466
+ if (delay > 0) {
5467
+ this.scheduleFlush(delay);
5468
+ return Promise.resolve();
5469
+ }
5470
+ }
5471
+ let reschedule = true;
5472
+ const promise = this.flushBuffer().catch((error) => {
5473
+ reschedule = false;
5474
+ throw error;
5475
+ }).finally(() => {
5476
+ this.#inFlightFlushes.delete(promise);
5477
+ if (reschedule && this.#byteTracker && this.#eventBuffer.totalSize > 0) {
5478
+ const delay = Math.max(0, this.#byteRetryAt - Date.now());
5479
+ this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5480
+ }
5481
+ });
5220
5482
  this.#inFlightFlushes.add(promise);
5221
5483
  return promise;
5222
5484
  }
@@ -5244,77 +5506,97 @@ var MastraStorageExporter = class extends BaseExporter {
5244
5506
  if (this.#eventBuffer.totalSize === 0) return;
5245
5507
  const startTime = Date.now();
5246
5508
  const batchSize = this.#eventBuffer.totalSize;
5247
- const creates = this.#eventBuffer.creates;
5248
- const updates = this.#eventBuffer.updates;
5249
- this.#eventBuffer.reset();
5250
- const createFeedbackEvents = [];
5251
- const createLogEvents = [];
5252
- const createMetricEvents = [];
5253
- const createScoreEvents = [];
5254
- const createSpanEvents = [];
5255
- const updateSpanEvents = [];
5256
- const endSpanEvents = [];
5257
- for (const createEvent of creates) switch (createEvent.type) {
5258
- case "feedback":
5259
- createFeedbackEvents.push(createEvent);
5260
- break;
5261
- case "log":
5262
- createLogEvents.push(createEvent);
5263
- break;
5264
- case "metric":
5265
- createMetricEvents.push(createEvent);
5266
- break;
5267
- case "score":
5268
- createScoreEvents.push(createEvent);
5269
- break;
5270
- default: createSpanEvents.push(createEvent);
5271
- }
5272
- for (const updateEvent of updates) switch (updateEvent.type) {
5273
- case _mastra_core_observability.TracingEventType.SPAN_UPDATED:
5274
- updateSpanEvents.push(updateEvent);
5275
- break;
5276
- case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5509
+ const { creates, updates } = this.#byteTracker ? this.#eventBuffer.takeByteBatch(this.#config.maxBatchSize) : {
5510
+ creates: this.#eventBuffer.creates,
5511
+ updates: this.#eventBuffer.updates
5512
+ };
5513
+ if (this.#byteTracker && creates.length === 0 && updates.length === 0 && this.#inFlightFlushes.size === 0) {
5514
+ const message = "MastraStorageExporter flush made no progress: queued events have no eligible batch.";
5515
+ this.logger.error(message, { bufferedEvents: this.#eventBuffer.totalSize });
5516
+ throw new Error(message);
5277
5517
  }
5278
- const flushResults = await Promise.all([
5279
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5280
- this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
5281
- this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
5282
- this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
5283
- this.flushCreates("tracing", createSpanEvents, async (events) => {
5284
- const records = events.map((t) => (0, _mastra_core_storage.buildCreateSpanRecord)(t.exportedSpan));
5285
- await this.#observabilityStorage.batchCreateSpans({ records });
5286
- this.#eventBuffer.addCreatedSpans({ records });
5287
- })
5288
- ]);
5289
- const deferredUpdates = [];
5290
- flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5291
- flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5292
- let deferredDropCount = 0;
5293
- if (deferredUpdates.length > 0) {
5294
- if (this.#unsupportedSignals.has("tracing")) {
5295
- deferredDropCount = deferredUpdates.length;
5296
- this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5297
- deferredUpdates.length = 0;
5298
- } else {
5299
- deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5300
- this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5518
+ if (!this.#byteTracker) this.#eventBuffer.reset();
5519
+ try {
5520
+ const createFeedbackEvents = [];
5521
+ const createLogEvents = [];
5522
+ const createMetricEvents = [];
5523
+ const createScoreEvents = [];
5524
+ const createSpanEvents = [];
5525
+ const updateSpanEvents = [];
5526
+ const endSpanEvents = [];
5527
+ for (const createEvent of creates) switch (createEvent.type) {
5528
+ case "feedback":
5529
+ createFeedbackEvents.push(createEvent);
5530
+ break;
5531
+ case "log":
5532
+ createLogEvents.push(createEvent);
5533
+ break;
5534
+ case "metric":
5535
+ createMetricEvents.push(createEvent);
5536
+ break;
5537
+ case "score":
5538
+ createScoreEvents.push(createEvent);
5539
+ break;
5540
+ default: createSpanEvents.push(createEvent);
5301
5541
  }
5302
- }
5303
- const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5304
- if (result.retryAttempt === void 0) return earliestAttempt;
5305
- return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5306
- }, void 0);
5307
- if (retryAttempt !== void 0) this.scheduleFlush(this.retryDelay(retryAttempt));
5308
- if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5309
- const elapsed = Date.now() - startTime;
5310
- this.logger.debug("Batch flushed", {
5311
- strategy: this.#resolvedStrategy,
5312
- batchSize,
5313
- durationMs: elapsed,
5314
- deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5315
- });
5542
+ for (const updateEvent of updates) switch (updateEvent.type) {
5543
+ case _mastra_core_observability.TracingEventType.SPAN_UPDATED:
5544
+ updateSpanEvents.push(updateEvent);
5545
+ break;
5546
+ case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5547
+ }
5548
+ const createTasks = [
5549
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5550
+ () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
5551
+ () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
5552
+ () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
5553
+ () => this.flushCreates("tracing", createSpanEvents, async (events) => {
5554
+ const records = events.map((t) => (0, _mastra_core_storage.buildCreateSpanRecord)(t.exportedSpan));
5555
+ await this.#observabilityStorage.batchCreateSpans({ records });
5556
+ this.#eventBuffer.addCreatedSpans({ records });
5557
+ })
5558
+ ];
5559
+ const flushResults = [];
5560
+ if (this.#byteTracker) for (const task of createTasks) flushResults.push(await task());
5561
+ else flushResults.push(...await Promise.all(createTasks.map((task) => task())));
5562
+ const deferredUpdates = [];
5563
+ flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5564
+ flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5565
+ let deferredDropCount = 0;
5566
+ if (deferredUpdates.length > 0) {
5567
+ if (this.#unsupportedSignals.has("tracing")) {
5568
+ deferredDropCount = deferredUpdates.length;
5569
+ this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5570
+ deferredUpdates.length = 0;
5571
+ } else {
5572
+ deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5573
+ this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5574
+ }
5575
+ }
5576
+ const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5577
+ if (result.retryAttempt === void 0) return earliestAttempt;
5578
+ return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5579
+ }, void 0);
5580
+ if (retryAttempt !== void 0) {
5581
+ if (this.#byteTracker) this.#byteRetryAt = Date.now() + this.retryDelay(retryAttempt);
5582
+ this.scheduleFlush(this.retryDelay(retryAttempt));
5583
+ }
5584
+ if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5585
+ const elapsed = Date.now() - startTime;
5586
+ this.logger.debug("Batch flushed", {
5587
+ strategy: this.#resolvedStrategy,
5588
+ batchSize,
5589
+ durationMs: elapsed,
5590
+ deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5591
+ });
5592
+ }
5593
+ } finally {
5594
+ this.#eventBuffer.releaseByteBatch([...creates, ...updates]);
5316
5595
  }
5317
5596
  }
5597
+ getByteBatchingStats() {
5598
+ return this.#byteTracker?.stats(this.#inFlightFlushes.size);
5599
+ }
5318
5600
  async _exportTracingEvent(event) {
5319
5601
  await this.ensureInitialized();
5320
5602
  if (!this.#observabilityStorage) {
@@ -5369,6 +5651,21 @@ var MastraStorageExporter = class extends BaseExporter {
5369
5651
  * are exported before the runtime instance is terminated.
5370
5652
  */
5371
5653
  async flush() {
5654
+ if (this.#byteTracker) {
5655
+ if (!this.#observabilityStorage) return;
5656
+ this.#byteDrainers++;
5657
+ try {
5658
+ while (this.#eventBuffer.totalSize || this.#inFlightFlushes.size) {
5659
+ if (this.#inFlightFlushes.size) await Promise.allSettled([...this.#inFlightFlushes]);
5660
+ const delay = this.#byteRetryAt - Date.now();
5661
+ if (delay > 0 && this.#eventBuffer.totalSize) await new Promise((resolve) => setTimeout(resolve, delay));
5662
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5663
+ }
5664
+ } finally {
5665
+ this.#byteDrainers--;
5666
+ }
5667
+ return;
5668
+ }
5372
5669
  for (let round = 0; round < MAX_FLUSH_ROUNDS; round++) {
5373
5670
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5374
5671
  if (this.#eventBuffer.totalSize > 0) {
@@ -5385,10 +5682,22 @@ var MastraStorageExporter = class extends BaseExporter {
5385
5682
  clearTimeout(this.#flushTimer);
5386
5683
  this.#flushTimer = void 0;
5387
5684
  }
5388
- await this.flush();
5389
- if (this.#flushTimer) {
5390
- clearTimeout(this.#flushTimer);
5391
- this.#flushTimer = void 0;
5685
+ try {
5686
+ await this.flush();
5687
+ } catch (error) {
5688
+ const mastraError = new _mastra_core_error.MastraError({
5689
+ id: "MASTRA_STORAGE_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN",
5690
+ domain: _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY,
5691
+ category: _mastra_core_error.ErrorCategory.SYSTEM,
5692
+ details: { remainingEvents: this.#eventBuffer.totalSize }
5693
+ }, error);
5694
+ this.logger.trackException(mastraError);
5695
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
5696
+ } finally {
5697
+ if (this.#flushTimer) {
5698
+ clearTimeout(this.#flushTimer);
5699
+ this.#flushTimer = void 0;
5700
+ }
5392
5701
  }
5393
5702
  this.logger.info("MastraStorageExporter shutdown complete");
5394
5703
  }
@@ -5401,6 +5710,12 @@ function isMastraPlatformDeployment() {
5401
5710
  function isMastraBuiltInStorageExporter(exporter) {
5402
5711
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5403
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
+ }
5404
5719
  // src/instances/base.ts
5405
5720
  /**
5406
5721
  * BaseObservability - Abstract base class for Observability implementations
@@ -5438,6 +5753,8 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5438
5753
  * a span's `metadata.environment` isn't set.
5439
5754
  */
5440
5755
  #mastraEnvironment;
5756
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5757
+ #hasApplicationLogger = false;
5441
5758
  /**
5442
5759
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5443
5760
  * we stash the lightweight provider/model from creation options so
@@ -5450,12 +5767,13 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5450
5767
  name: config.serviceName
5451
5768
  });
5452
5769
  const exporters = config.exporters ?? [];
5453
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5770
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5454
5771
  this.config = {
5455
5772
  serviceName: config.serviceName,
5456
5773
  name: config.name,
5457
5774
  sampling: config.sampling ?? { type: "always" },
5458
5775
  exporters: effectiveExporters,
5776
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5459
5777
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5460
5778
  bridge: config.bridge ?? void 0,
5461
5779
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5465,6 +5783,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5465
5783
  serializationOptions: config.serializationOptions,
5466
5784
  logging: config.logging
5467
5785
  };
5786
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5468
5787
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5469
5788
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5470
5789
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5477,6 +5796,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5477
5796
  */
5478
5797
  __setLogger(logger) {
5479
5798
  super.__setLogger(logger);
5799
+ this.#hasApplicationLogger = true;
5800
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5801
+ this.#pendingStorageExporterWarnings.clear();
5480
5802
  this.exporters.forEach((exporter) => {
5481
5803
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5482
5804
  });
@@ -5645,17 +5967,24 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
5645
5967
  getExporters() {
5646
5968
  return [...this.exporters];
5647
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
+ }
5648
5981
  /**
5649
5982
  * Register an additional exporter at runtime.
5650
5983
  * Adds to both the bus (for event routing) and the config (for getExporters).
5651
5984
  */
5652
5985
  registerExporter(exporter) {
5653
- if (isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter)) {
5654
- this.logger.warn("Storage exporter registration skipped on Mastra Platform", {
5655
- exporterName: exporter.name,
5656
- serviceName: this.config.serviceName,
5657
- instanceName: this.config.name
5658
- });
5986
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5987
+ this.warnStorageExporterSkipped(exporter);
5659
5988
  return;
5660
5989
  }
5661
5990
  this.observabilityBus.registerExporter(exporter);
@@ -8211,6 +8540,127 @@ var ConsoleExporter = class extends BaseExporter {
8211
8540
  this.logger.info("ConsoleExporter shutdown");
8212
8541
  }
8213
8542
  };
8543
+ // src/exporters/platform-byte-batcher.ts
8544
+ function resolveByteBatchingConfig(config) {
8545
+ const resolved = {
8546
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
8547
+ maxConcurrentUploads: config.maxConcurrentUploads ?? 2,
8548
+ uploadTimeoutMs: config.uploadTimeoutMs ?? 3e4
8549
+ };
8550
+ for (const [name, value] of Object.entries(resolved)) if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`byteBatching.${name} must be a positive safe integer`);
8551
+ if (resolved.maxBatchBytes < 32) throw new Error("byteBatching.maxBatchBytes must be at least 32");
8552
+ if (resolved.uploadTimeoutMs > 2147483647) throw new Error("byteBatching.uploadTimeoutMs must fit in a Node.js timer");
8553
+ return resolved;
8554
+ }
8555
+ /**
8556
+ * Serialize each record once, before retaining it. The accounting includes open
8557
+ * batches, ready batches and uploads until they settle. This tracks retained
8558
+ * JSON bytes for diagnostics; queued bytes are not capped.
8559
+ */
8560
+ var PlatformByteBatcher = class {
8561
+ config;
8562
+ maxBatchSize;
8563
+ maxBatchWaitMs;
8564
+ segments;
8565
+ send;
8566
+ onError;
8567
+ open = /* @__PURE__ */ new Map();
8568
+ ready = [];
8569
+ active = /* @__PURE__ */ new Set();
8570
+ timer;
8571
+ pendingBytes = 0;
8572
+ constructor(config, maxBatchSize, maxBatchWaitMs, segments, send, onError) {
8573
+ this.config = config;
8574
+ this.maxBatchSize = maxBatchSize;
8575
+ this.maxBatchWaitMs = maxBatchWaitMs;
8576
+ this.segments = segments;
8577
+ this.send = send;
8578
+ this.onError = onError;
8579
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte batching mode");
8580
+ if (!Number.isSafeInteger(maxBatchWaitMs) || maxBatchWaitMs <= 0 || maxBatchWaitMs > 2147483647) throw new Error("maxBatchWaitMs must be a positive integer that fits in a Node.js timer");
8581
+ }
8582
+ add(signal, record) {
8583
+ const json = JSON.stringify(record);
8584
+ if (json === void 0) throw new Error("Record has no JSON representation");
8585
+ const prefix = `{"${this.segments[signal]}":[`;
8586
+ const envelopeBytes = Buffer.byteLength(prefix) + 2;
8587
+ const recordBytes = Buffer.byteLength(json);
8588
+ let batch = this.open.get(signal);
8589
+ if (batch && recordBytes + envelopeBytes > this.config.maxBatchBytes) {
8590
+ this.seal(signal);
8591
+ batch = void 0;
8592
+ }
8593
+ const extraBytes = recordBytes + (batch ? 1 : envelopeBytes);
8594
+ if (!batch) {
8595
+ batch = {
8596
+ signal,
8597
+ prefix,
8598
+ records: [],
8599
+ bytes: envelopeBytes
8600
+ };
8601
+ this.open.set(signal, batch);
8602
+ }
8603
+ batch.bytes += recordBytes + (batch.records.length ? 1 : 0);
8604
+ batch.records.push(json);
8605
+ this.pendingBytes += extraBytes;
8606
+ if (batch.records.length >= this.maxBatchSize || batch.bytes >= this.config.maxBatchBytes) this.seal(signal);
8607
+ this.pump();
8608
+ if (this.open.size && !this.timer) this.timer = setTimeout(() => {
8609
+ this.timer = void 0;
8610
+ this.sealAll();
8611
+ this.pump();
8612
+ }, this.maxBatchWaitMs);
8613
+ }
8614
+ seal(signal) {
8615
+ const batch = this.open.get(signal);
8616
+ if (batch) {
8617
+ this.open.delete(signal);
8618
+ this.ready.push(batch);
8619
+ }
8620
+ }
8621
+ sealAll() {
8622
+ if (this.timer) clearTimeout(this.timer);
8623
+ this.timer = void 0;
8624
+ for (const signal of this.open.keys()) this.seal(signal);
8625
+ }
8626
+ pump() {
8627
+ while (this.ready.length && this.active.size < this.config.maxConcurrentUploads) {
8628
+ const batch = this.ready.shift();
8629
+ const task = Promise.resolve().then(async () => {
8630
+ const count = batch.records.length;
8631
+ const body = batch.prefix + batch.records.join(",") + "]}";
8632
+ batch.records = [];
8633
+ await this.send(batch.signal, body, count);
8634
+ }).catch((error) => this.onError(error)).finally(() => {
8635
+ this.pendingBytes -= batch.bytes;
8636
+ this.active.delete(task);
8637
+ this.pump();
8638
+ });
8639
+ this.active.add(task);
8640
+ }
8641
+ }
8642
+ /** Drop unsent batches after auth/quota rejection. In-flight uploads still remain accounted for. */
8643
+ clearQueued() {
8644
+ if (this.timer) clearTimeout(this.timer);
8645
+ this.timer = void 0;
8646
+ for (const batch of [...this.open.values(), ...this.ready]) this.pendingBytes -= batch.bytes;
8647
+ this.open.clear();
8648
+ this.ready = [];
8649
+ }
8650
+ async flush() {
8651
+ do {
8652
+ this.sealAll();
8653
+ this.pump();
8654
+ await Promise.allSettled([...this.active]);
8655
+ } while (this.open.size || this.ready.length || this.active.size);
8656
+ }
8657
+ getStats() {
8658
+ return {
8659
+ pendingBytes: this.pendingBytes,
8660
+ activeUploads: this.active.size
8661
+ };
8662
+ }
8663
+ };
8214
8664
  // src/exporters/mastra-platform.ts
8215
8665
  const SIGNAL_PUBLISH_SUFFIXES = {
8216
8666
  traces: "/spans/publish",
@@ -8334,6 +8784,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8334
8784
  quotaProbeTimer = null;
8335
8785
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
8336
8786
  shuttingDown = false;
8787
+ byteBatcher;
8788
+ byteUploadTimeoutMs;
8337
8789
  constructor(config = {}) {
8338
8790
  super(config);
8339
8791
  if (config.projectId !== void 0 && !VALID_PROJECT_ID.test(config.projectId)) throw createInvalidProjectIdError(config.projectId);
@@ -8371,6 +8823,11 @@ var MastraPlatformExporter = class extends BaseExporter {
8371
8823
  feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config.feedbackEndpoint)
8372
8824
  };
8373
8825
  this.authFailureCooldown = new AuthFailureCooldown("MastraPlatformExporter", () => this.logger);
8826
+ if (config.byteBatching) {
8827
+ const byteConfig = resolveByteBatchingConfig(config.byteBatching);
8828
+ this.byteUploadTimeoutMs = byteConfig.uploadTimeoutMs;
8829
+ this.byteBatcher = new PlatformByteBatcher(byteConfig, this.platformConfig.maxBatchSize, this.platformConfig.maxBatchWaitMs, SIGNAL_PUBLISH_SEGMENTS, (signal, body, count) => this.flushByteBatch(signal, body, count), (error) => this.logger.error("Byte batch upload failed", { error }));
8830
+ }
8374
8831
  this.buffer = {
8375
8832
  spans: [],
8376
8833
  logs: [],
@@ -8412,27 +8869,47 @@ var MastraPlatformExporter = class extends BaseExporter {
8412
8869
  await this.handleBufferedEvent();
8413
8870
  }
8414
8871
  addToBuffer(event) {
8872
+ if (this.byteBatcher) {
8873
+ this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
8874
+ return;
8875
+ }
8415
8876
  this.markBufferStart();
8416
8877
  const spanRecord = this.formatSpan(event.exportedSpan);
8417
8878
  this.buffer.spans.push(spanRecord);
8418
8879
  this.buffer.totalSize++;
8419
8880
  }
8420
8881
  addLogToBuffer(event) {
8882
+ if (this.byteBatcher) {
8883
+ this.byteBatcher.add("logs", this.formatLog(event.log));
8884
+ return;
8885
+ }
8421
8886
  this.markBufferStart();
8422
8887
  this.buffer.logs.push(this.formatLog(event.log));
8423
8888
  this.buffer.totalSize++;
8424
8889
  }
8425
8890
  addMetricToBuffer(event) {
8891
+ if (this.byteBatcher) {
8892
+ this.byteBatcher.add("metrics", this.formatMetric(event.metric));
8893
+ return;
8894
+ }
8426
8895
  this.markBufferStart();
8427
8896
  this.buffer.metrics.push(this.formatMetric(event.metric));
8428
8897
  this.buffer.totalSize++;
8429
8898
  }
8430
8899
  addScoreToBuffer(event) {
8900
+ if (this.byteBatcher) {
8901
+ this.byteBatcher.add("scores", this.formatScore(event.score));
8902
+ return;
8903
+ }
8431
8904
  this.markBufferStart();
8432
8905
  this.buffer.scores.push(this.formatScore(event.score));
8433
8906
  this.buffer.totalSize++;
8434
8907
  }
8435
8908
  addFeedbackToBuffer(event) {
8909
+ if (this.byteBatcher) {
8910
+ this.byteBatcher.add("feedback", this.formatFeedback(event.feedback));
8911
+ return;
8912
+ }
8436
8913
  this.markBufferStart();
8437
8914
  this.buffer.feedback.push(this.formatFeedback(event.feedback));
8438
8915
  this.buffer.totalSize++;
@@ -8465,6 +8942,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8465
8942
  return { ...feedback };
8466
8943
  }
8467
8944
  async handleBufferedEvent() {
8945
+ if (this.byteBatcher) return;
8468
8946
  if (this.shouldFlush()) this.flush().catch((error) => {
8469
8947
  this.logger.error("Batch flush failed", { error: error instanceof Error ? error.message : String(error) });
8470
8948
  });
@@ -8561,6 +9039,9 @@ var MastraPlatformExporter = class extends BaseExporter {
8561
9039
  return JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records });
8562
9040
  }
8563
9041
  async batchUpload(signal, records) {
9042
+ await this.uploadBody(signal, this.buildPublishBody(signal, records));
9043
+ }
9044
+ async uploadBody(signal, body) {
8564
9045
  const endpointMap = {
8565
9046
  traces: this.platformConfig.tracesEndpoint,
8566
9047
  logs: this.platformConfig.logsEndpoint,
@@ -8571,7 +9052,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8571
9052
  const options = {
8572
9053
  method: "POST",
8573
9054
  headers: this.buildPublishHeaders(),
8574
- body: this.buildPublishBody(signal, records)
9055
+ body,
9056
+ ...this.byteUploadTimeoutMs ? { signal: AbortSignal.timeout(this.byteUploadTimeoutMs) } : {}
8575
9057
  };
8576
9058
  let quotaResponse;
8577
9059
  let response;
@@ -8591,6 +9073,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8591
9073
  throw error;
8592
9074
  }
8593
9075
  if (isObservabilityDisabled(response)) this.enterQuotaPause(parseQuotaRetryAfterSeconds(response));
9076
+ await response.body?.cancel().catch(() => {});
8594
9077
  }
8595
9078
  /**
8596
9079
  * Enter the quota-exhausted paused state: drop buffered events, stop the
@@ -8602,6 +9085,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8602
9085
  this.quotaProbeIntervalSeconds = retryAfterSeconds;
8603
9086
  if (this.quotaPaused) return;
8604
9087
  this.quotaPaused = true;
9088
+ this.byteBatcher?.clearQueued();
8605
9089
  if (this.flushTimer) {
8606
9090
  clearTimeout(this.flushTimer);
8607
9091
  this.flushTimer = null;
@@ -8650,6 +9134,30 @@ var MastraPlatformExporter = class extends BaseExporter {
8650
9134
  }
8651
9135
  this.scheduleQuotaProbe();
8652
9136
  }
9137
+ /** Current queued and active serialized JSON bytes; undefined in count mode. */
9138
+ getByteBatchingStats() {
9139
+ return this.byteBatcher?.getStats();
9140
+ }
9141
+ async flushByteBatch(signal, body, count) {
9142
+ if (this.quotaPaused || this.authFailureCooldown.dropEventsIfCoolingDown(count)) return;
9143
+ try {
9144
+ await this.uploadBody(signal, body);
9145
+ this.authFailureCooldown.reset();
9146
+ } catch (error) {
9147
+ if (isAuthFailureError(error)) {
9148
+ this.authFailureCooldown.recordFailure({
9149
+ status: error.status,
9150
+ failedSignals: [signal],
9151
+ droppedBatchSize: count
9152
+ });
9153
+ this.byteBatcher?.clearQueued();
9154
+ } else this.logger.error("Byte batch upload failed after retries, dropping batch", {
9155
+ signal,
9156
+ droppedBatchSize: count,
9157
+ error
9158
+ });
9159
+ }
9160
+ }
8653
9161
  async flushSignalBatch(signal, records) {
8654
9162
  if (records.length === 0) return {
8655
9163
  signal,
@@ -8701,6 +9209,10 @@ var MastraPlatformExporter = class extends BaseExporter {
8701
9209
  */
8702
9210
  async flush() {
8703
9211
  if (this.isDisabled) return;
9212
+ if (this.byteBatcher) {
9213
+ await this.byteBatcher.flush();
9214
+ return;
9215
+ }
8704
9216
  while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
8705
9217
  if (this.buffer.totalSize > 0) {
8706
9218
  this.logger.debug("Flushing buffered events", { bufferedEvents: this.buffer.totalSize });
@@ -8733,8 +9245,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8733
9245
  const mastraError = new _mastra_core_error.MastraError({
8734
9246
  id: `MASTRA_PLATFORM_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
8735
9247
  domain: _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY,
8736
- category: _mastra_core_error.ErrorCategory.USER,
8737
- details: { remainingEvents: this.buffer.totalSize }
9248
+ category: _mastra_core_error.ErrorCategory.SYSTEM,
9249
+ details: this.byteBatcher ? { pendingBytes: this.byteBatcher.getStats().pendingBytes } : { remainingEvents: this.buffer.totalSize }
8738
9250
  }, error);
8739
9251
  this.logger.trackException(mastraError);
8740
9252
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);