@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.js CHANGED
@@ -786,6 +786,7 @@ const observabilityInstanceConfigFields = {
786
786
  serviceName: z.string().min(1, "Service name is required"),
787
787
  sampling: samplingStrategySchema.optional(),
788
788
  exporters: z.array(z.any()).optional(),
789
+ retainStorageExporterOnPlatform: z.boolean().optional(),
789
790
  bridge: z.any().optional(),
790
791
  spanOutputProcessors: z.array(z.any()).optional(),
791
792
  includeInternalSpans: z.boolean().optional(),
@@ -2510,6 +2511,22 @@ var ModelSpanTracker = class {
2510
2511
  #currentInferenceSpan;
2511
2512
  #stepHasInference = false;
2512
2513
  #tracksProviderStream = false;
2514
+ /**
2515
+ * Provider completion of the open MODEL_INFERENCE, held until the processed
2516
+ * step supplies its output. The raw provider stream carries content before
2517
+ * output processors run, so the span keeps its provider end time and usage
2518
+ * from here but takes its output from the processed `step-finish`.
2519
+ */
2520
+ #pendingInferenceFinish;
2521
+ /**
2522
+ * Processed text and tool calls of the open MODEL_INFERENCE, for loops whose
2523
+ * `step-finish` payload carries only usage (the durable loop rewrites the
2524
+ * provider's `finish` into `step-finish`).
2525
+ */
2526
+ #inferenceContent = {
2527
+ text: "",
2528
+ toolCalls: []
2529
+ };
2513
2530
  #currentChunkSpan;
2514
2531
  #currentChunkType;
2515
2532
  #accumulator = {};
@@ -2597,6 +2614,7 @@ var ModelSpanTracker = class {
2597
2614
  */
2598
2615
  reportGenerationError(options) {
2599
2616
  this.#endChunkSpan();
2617
+ this.#settlePendingInference();
2600
2618
  const termination = options.outcome != null ? {
2601
2619
  outcome: options.outcome,
2602
2620
  stopReason: options.stopReason,
@@ -2645,6 +2663,7 @@ var ModelSpanTracker = class {
2645
2663
  spanOptions.attributes.costContext = providerCostContext ?? spanOptions.attributes.costContext;
2646
2664
  if (!spanOptions.attributes.costContext) spanOptions.attributes.costContext = getGatewayCostContext({ stepProviderMetadata });
2647
2665
  }
2666
+ this.#settlePendingInference();
2648
2667
  if (spanOptions.outcome === "abort" || spanOptions.stopReason === "timeout") {
2649
2668
  const termination = {
2650
2669
  outcome: spanOptions.outcome,
@@ -2741,7 +2760,15 @@ var ModelSpanTracker = class {
2741
2760
  this.#inferenceTimeToFirstTokenMs = void 0;
2742
2761
  }
2743
2762
  /**
2744
- * End the current MODEL_INFERENCE span when the provider stream finishes.
2763
+ * End the current MODEL_INFERENCE span.
2764
+ *
2765
+ * With `captureOutput: false` (the raw provider stream's `finish`), the span is
2766
+ * not ended yet: its provider end time, usage and finish reason are held until
2767
+ * the processed `step-finish` arrives, which ends it with the processed output
2768
+ * and the held end time. Tool work between the two does not count toward the
2769
+ * inference's duration, and exporters that treat MODEL_INFERENCE as the model
2770
+ * call still get the response.
2771
+ *
2745
2772
  * Fields are duplicated onto MODEL_STEP (in #endStepSpan) so existing
2746
2773
  * integrations that read usage/finishReason from the step span continue
2747
2774
  * to work unchanged.
@@ -2750,27 +2777,66 @@ var ModelSpanTracker = class {
2750
2777
  */
2751
2778
  #endInferenceSpan(payload, captureOutput = true) {
2752
2779
  if (!this.#currentInferenceSpan) return;
2753
- const { usage: rawUsage, ...otherOutput } = payload.output;
2754
- const usage = extractUsageMetrics(rawUsage, payload.metadata?.providerMetadata);
2755
- const responseModel = typeof payload.metadata?.modelId === "string" ? payload.metadata.modelId : void 0;
2756
- this.#currentInferenceSpan.end({
2780
+ if (!captureOutput) {
2781
+ this.#pendingInferenceFinish ??= {
2782
+ payload,
2783
+ endTime: /* @__PURE__ */ new Date(),
2784
+ streamAttributes: this.#inferenceStreamAttributes()
2785
+ };
2786
+ return;
2787
+ }
2788
+ const pending = this.#pendingInferenceFinish;
2789
+ const { usage: _usage, ...stepOutput } = payload.output ?? {};
2790
+ const output = "text" in stepOutput || "toolCalls" in stepOutput ? stepOutput : this.#inferenceContent;
2791
+ this.#closeInference(pending?.payload ?? payload, {
2792
+ output,
2793
+ endTime: pending?.endTime,
2794
+ streamAttributes: pending?.streamAttributes
2795
+ });
2796
+ }
2797
+ /**
2798
+ * End an inference whose provider stream already finished, without output.
2799
+ * Used when the step ends some other way than a processed `step-finish`
2800
+ * (error, abort, suspension, tripwire, a replacement attempt).
2801
+ */
2802
+ #settlePendingInference() {
2803
+ const pending = this.#pendingInferenceFinish;
2804
+ if (!pending) return;
2805
+ this.#closeInference(pending.payload, {
2806
+ endTime: pending.endTime,
2807
+ streamAttributes: pending.streamAttributes
2808
+ });
2809
+ }
2810
+ #closeInference(finish, options) {
2811
+ const span = this.#currentInferenceSpan;
2812
+ this.#pendingInferenceFinish = void 0;
2813
+ this.#inferenceContent = {
2814
+ text: "",
2815
+ toolCalls: []
2816
+ };
2817
+ if (!span) return;
2818
+ const usage = extractUsageMetrics(finish.output?.usage, finish.metadata?.providerMetadata);
2819
+ const responseModel = typeof finish.metadata?.modelId === "string" ? finish.metadata.modelId : void 0;
2820
+ const endOptions = {
2757
2821
  ...coreObservability.agentLoopTermination?.({
2758
2822
  stopCause: "model_finished",
2759
- finishReason: payload.stepResult.reason
2823
+ finishReason: finish.stepResult.reason
2760
2824
  }),
2761
- ...payload.stepResult.reason === "error" ? {
2825
+ ...finish.stepResult.reason === "error" ? {
2762
2826
  outcome: "error",
2763
2827
  stopReason: "model_error"
2764
2828
  } : {},
2765
- ...captureOutput ? { output: otherOutput } : {},
2829
+ ...options.output !== void 0 ? { output: options.output } : {},
2830
+ ...options.endTime ? { endTime: options.endTime } : {},
2766
2831
  attributes: {
2767
2832
  usage,
2768
- finishReason: payload.stepResult.reason,
2769
- warnings: payload.stepResult.warnings,
2770
- ...this.#inferenceStreamAttributes(),
2833
+ finishReason: finish.stepResult.reason,
2834
+ warnings: finish.stepResult.warnings,
2835
+ ...options.streamAttributes ?? this.#inferenceStreamAttributes(),
2771
2836
  ...responseModel?.trim() ? { responseModel } : {}
2772
2837
  }
2773
- });
2838
+ };
2839
+ span.end(endOptions);
2774
2840
  this.#currentInferenceSpan = void 0;
2775
2841
  this.#inferenceCompletionStartTime = void 0;
2776
2842
  }
@@ -2811,6 +2877,7 @@ var ModelSpanTracker = class {
2811
2877
  endAttempt(termination) {
2812
2878
  termination = interruptedByRun(termination);
2813
2879
  const payload = this.#pendingStepFinishPayload;
2880
+ this.#settlePendingInference();
2814
2881
  if (payload) this.#endStepSpan(payload, termination);
2815
2882
  else {
2816
2883
  this.#endChunkSpan();
@@ -2828,6 +2895,10 @@ var ModelSpanTracker = class {
2828
2895
  if (!this.#currentStepSpan || this.#currentInferenceSpan) return;
2829
2896
  this.#inferenceCompletionStartTime = void 0;
2830
2897
  this.#inferenceTimeToFirstTokenMs = void 0;
2898
+ this.#inferenceContent = {
2899
+ text: "",
2900
+ toolCalls: []
2901
+ };
2831
2902
  const input = extractStepInput(payload);
2832
2903
  const generationAttrs = this.#modelSpan?.attributes;
2833
2904
  const ctx = this.#inferenceContext;
@@ -2858,6 +2929,7 @@ var ModelSpanTracker = class {
2858
2929
  */
2859
2930
  interruptInference(termination) {
2860
2931
  this.#endChunkSpan();
2932
+ this.#settlePendingInference();
2861
2933
  if (!this.#currentInferenceSpan) return;
2862
2934
  this.#currentInferenceSpan.end({
2863
2935
  attributes: {
@@ -2877,6 +2949,7 @@ var ModelSpanTracker = class {
2877
2949
  /** End the open inference span, if any, with `error` and what it streamed. */
2878
2950
  failInference(error) {
2879
2951
  this.#endChunkSpan();
2952
+ this.#settlePendingInference();
2880
2953
  if (!this.#currentInferenceSpan) return;
2881
2954
  this.#currentInferenceSpan.error({
2882
2955
  error,
@@ -2956,6 +3029,7 @@ var ModelSpanTracker = class {
2956
3029
  const usage = chunk.payload.usage;
2957
3030
  if (!usage) return;
2958
3031
  this.#inModelResponse = false;
3032
+ this.#settlePendingInference();
2959
3033
  this.#endStepSpan({
2960
3034
  output: { usage },
2961
3035
  stepResult: {
@@ -3166,6 +3240,19 @@ var ModelSpanTracker = class {
3166
3240
  controller.enqueue(chunk);
3167
3241
  } }));
3168
3242
  }
3243
+ /** Keep the processed response of the open inference; see #inferenceContent. */
3244
+ #collectInferenceContent(chunk) {
3245
+ if (!this.#currentInferenceSpan) return;
3246
+ if (chunk.type === "text-delta" && typeof chunk.payload.text === "string") this.#inferenceContent.text += chunk.payload.text;
3247
+ else if (chunk.type === "tool-call") {
3248
+ const { toolCallId, toolName, args } = chunk.payload;
3249
+ this.#inferenceContent.toolCalls.push({
3250
+ toolCallId,
3251
+ toolName,
3252
+ args
3253
+ });
3254
+ }
3255
+ }
3169
3256
  /** @internal Record a chunk only after output processors accept it. */
3170
3257
  recordChunk(chunk) {
3171
3258
  try {
@@ -3174,6 +3261,7 @@ var ModelSpanTracker = class {
3174
3261
  if (chunk.type === "tool-call-approval") this.#handleToolApprovalChunk(chunk);
3175
3262
  this.#endSuspendedStep(chunk);
3176
3263
  }
3264
+ this.#collectInferenceContent(chunk);
3177
3265
  switch (chunk.type) {
3178
3266
  case "text-start":
3179
3267
  case "text-delta":
@@ -3215,7 +3303,9 @@ var ModelSpanTracker = class {
3215
3303
  this.endAttempt(termination);
3216
3304
  break;
3217
3305
  }
3218
- case "finish": break;
3306
+ case "finish":
3307
+ this.#settlePendingInference();
3308
+ break;
3219
3309
  case "raw":
3220
3310
  case "start":
3221
3311
  case "response-metadata":
@@ -3962,7 +4052,8 @@ var DefaultSpan = class extends BaseSpan {
3962
4052
  if (options?.endTree) this.endOpenDescendants(options);
3963
4053
  if (options) this.applyOutcome(options);
3964
4054
  if (this.outcome === null) this.outcome = "unknown";
3965
- this.endTime = /* @__PURE__ */ new Date();
4055
+ const endTime = options?.endTime;
4056
+ this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
3966
4057
  this.detachFromParent();
3967
4058
  if (options?.metadata) this.metadata = {
3968
4059
  ...this.metadata,
@@ -4283,8 +4374,11 @@ var EventBuffer = class {
4283
4374
  #firstEventTime;
4284
4375
  #storageStrategy;
4285
4376
  #maxRetries;
4377
+ #byteTracker;
4378
+ #preferUpdates = false;
4286
4379
  constructor(args) {
4287
4380
  this.#maxRetries = args.maxRetries;
4381
+ this.#byteTracker = args.byteTracker;
4288
4382
  }
4289
4383
  /** Initialize with a storage strategy and replay any pre-init events. */
4290
4384
  init(args) {
@@ -4304,18 +4398,20 @@ var EventBuffer = class {
4304
4398
  if (!this.#firstEventTime) this.#firstEventTime = /* @__PURE__ */ new Date();
4305
4399
  }
4306
4400
  pushCreate(event) {
4307
- this.setFirstEventTime();
4308
- this.#creates.push({
4401
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4309
4402
  ...event,
4310
4403
  retryCount: 0
4311
- });
4404
+ };
4405
+ this.setFirstEventTime();
4406
+ this.#creates.push(buffered);
4312
4407
  }
4313
4408
  pushUpdate(event) {
4314
- this.setFirstEventTime();
4315
- this.#updates.push({
4409
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4316
4410
  ...event,
4317
4411
  retryCount: 0
4318
- });
4412
+ };
4413
+ this.setFirstEventTime();
4414
+ this.#updates.push(buffered);
4319
4415
  }
4320
4416
  /** Route an event to the create or update buffer based on its type and the storage strategy. */
4321
4417
  addEvent(event) {
@@ -4331,8 +4427,8 @@ var EventBuffer = class {
4331
4427
  switch (this.#storageStrategy) {
4332
4428
  case "realtime":
4333
4429
  case "batch-with-updates":
4334
- if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4335
4430
  this.pushCreate(event);
4431
+ if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4336
4432
  break;
4337
4433
  case "event-sourced": this.pushCreate(event);
4338
4434
  }
@@ -4360,8 +4456,10 @@ var EventBuffer = class {
4360
4456
  reAddCreates(events) {
4361
4457
  const retryable = [];
4362
4458
  const dropped = [];
4363
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4364
- else dropped.push(e);
4459
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4460
+ retryable.push(e);
4461
+ this.#byteTracker?.enqueue(e);
4462
+ } else dropped.push(e);
4365
4463
  if (retryable.length > 0) {
4366
4464
  this.setFirstEventTime();
4367
4465
  this.#creates.push(...retryable);
@@ -4372,14 +4470,64 @@ var EventBuffer = class {
4372
4470
  reAddUpdates(events) {
4373
4471
  const retryable = [];
4374
4472
  const dropped = [];
4375
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4376
- else dropped.push(e);
4473
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4474
+ retryable.push(e);
4475
+ this.#byteTracker?.enqueue(e);
4476
+ } else dropped.push(e);
4377
4477
  if (retryable.length > 0) {
4378
4478
  this.setFirstEventTime();
4379
4479
  this.#updates.push(...retryable);
4380
4480
  }
4381
4481
  return dropped;
4382
4482
  }
4483
+ /** Alternate creates and eligible updates so either queue can make progress under load. */
4484
+ takeByteBatch(maxRecords) {
4485
+ const tracker = this.#byteTracker;
4486
+ const creates = [];
4487
+ const updates = [];
4488
+ const selectedUpdates = /* @__PURE__ */ new Set();
4489
+ let updateIndex = 0;
4490
+ let bytes = 0;
4491
+ while (creates.length + updates.length < maxRecords && bytes < tracker.config.maxBatchBytes) {
4492
+ while (updateIndex < this.#updates.length) {
4493
+ const event = this.#updates[updateIndex];
4494
+ if (!("exportedSpan" in event) || !this.isAwaitingCreate(event.exportedSpan)) break;
4495
+ updateIndex++;
4496
+ }
4497
+ const create = this.#creates[creates.length];
4498
+ const update = this.#updates[updateIndex];
4499
+ if (!create && !update) break;
4500
+ const takeUpdate = !!update && (!create || this.#preferUpdates);
4501
+ const event = takeUpdate ? update : create;
4502
+ if (takeUpdate) {
4503
+ updates.push(event);
4504
+ selectedUpdates.add(updateIndex++);
4505
+ } else creates.push(event);
4506
+ this.#preferUpdates = !takeUpdate;
4507
+ tracker.dequeue(event);
4508
+ bytes += tracker.size(event);
4509
+ }
4510
+ this.#creates.splice(0, creates.length);
4511
+ this.#updates = this.#updates.filter((_, index) => !selectedUpdates.has(index));
4512
+ if (this.totalSize === 0) this.#firstEventTime = void 0;
4513
+ return {
4514
+ creates,
4515
+ updates
4516
+ };
4517
+ }
4518
+ /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4519
+ releaseByteBatch(events) {
4520
+ if (!this.#byteTracker) return;
4521
+ for (const event of events) {
4522
+ if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4523
+ this.forgetDroppedCreates([event]);
4524
+ if (event.type === TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4525
+ traceId: event.exportedSpan.traceId,
4526
+ spanId: event.exportedSpan.id,
4527
+ updates: {}
4528
+ }] });
4529
+ }
4530
+ }
4383
4531
  /** Snapshot of buffered create events. */
4384
4532
  get creates() {
4385
4533
  return [...this.#creates];
@@ -4893,6 +5041,77 @@ function withSpanPreviews(span) {
4893
5041
  return span;
4894
5042
  }
4895
5043
  }
5044
+ // src/exporters/storage-byte-tracker.ts
5045
+ function resolveStorageByteBatching(config) {
5046
+ const resolved = {
5047
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
5048
+ maxConcurrentWrites: config.maxConcurrentWrites ?? 1
5049
+ };
5050
+ 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`);
5051
+ return resolved;
5052
+ }
5053
+ /** Counts each admitted event once until persistence or a definitive drop, even across retries. */
5054
+ var StorageByteTracker = class {
5055
+ config;
5056
+ sizes = /* @__PURE__ */ new WeakMap();
5057
+ queued = /* @__PURE__ */ new WeakSet();
5058
+ pendingBytes = 0;
5059
+ pendingRecords = 0;
5060
+ queuedBytes = 0;
5061
+ constructor(config) {
5062
+ this.config = config;
5063
+ }
5064
+ capture(event) {
5065
+ const snapshot = {
5066
+ ...structuredClone(event),
5067
+ retryCount: 0
5068
+ };
5069
+ const bytes = Buffer.byteLength(JSON.stringify(snapshot)) + 1;
5070
+ this.sizes.set(snapshot, bytes);
5071
+ this.pendingBytes += bytes;
5072
+ this.pendingRecords++;
5073
+ this.enqueue(snapshot);
5074
+ return snapshot;
5075
+ }
5076
+ size(event) {
5077
+ return this.sizes.get(event) ?? 0;
5078
+ }
5079
+ enqueue(event) {
5080
+ if (!this.queued.has(event)) {
5081
+ this.queued.add(event);
5082
+ this.queuedBytes += this.size(event);
5083
+ }
5084
+ }
5085
+ dequeue(event) {
5086
+ if (this.queued.delete(event)) this.queuedBytes -= this.size(event);
5087
+ }
5088
+ releaseIfUnqueued(event) {
5089
+ if (this.queued.has(event)) return false;
5090
+ const bytes = this.sizes.get(event);
5091
+ if (bytes === void 0) return false;
5092
+ this.sizes.delete(event);
5093
+ this.pendingBytes -= bytes;
5094
+ this.pendingRecords--;
5095
+ return true;
5096
+ }
5097
+ stats(activeWrites) {
5098
+ return {
5099
+ pendingBytes: this.pendingBytes,
5100
+ pendingRecords: this.pendingRecords,
5101
+ activeWrites
5102
+ };
5103
+ }
5104
+ };
5105
+ // src/exporters/storage-platform-policy.ts
5106
+ /**
5107
+ * Check the resolved observability domain, not the composite store's default backend.
5108
+ * Older or custom adapters without location metadata retain opt-in compatibility.
5109
+ */
5110
+ function skipLocalStorageOnPlatform(storage, logger) {
5111
+ if (!process.env.MASTRA_DEPLOYMENT_ID || storage.persistenceLocation !== "local") return false;
5112
+ logger.warn("Storage exporter disabled on Mastra Platform: local observability storage is not supported, even with retainStorageExporterOnPlatform: true. Use a remote observability storage provider.");
5113
+ return true;
5114
+ }
4896
5115
  // src/exporters/mastra-storage.ts
4897
5116
  /**
4898
5117
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -4923,6 +5142,9 @@ var MastraStorageExporter = class extends BaseExporter {
4923
5142
  #initializationPromise;
4924
5143
  #wasUnavailable = false;
4925
5144
  #eventBuffer;
5145
+ #byteTracker;
5146
+ #byteRetryAt = 0;
5147
+ #byteDrainers = 0;
4926
5148
  #storage;
4927
5149
  #observabilityStorage;
4928
5150
  #resolvedStrategy;
@@ -4942,7 +5164,14 @@ var MastraStorageExporter = class extends BaseExporter {
4942
5164
  retryDelayMs: config.retryDelayMs ?? 500,
4943
5165
  strategy: config.strategy ?? "auto"
4944
5166
  };
4945
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5167
+ if (config.byteBatching) {
5168
+ if (!Number.isSafeInteger(this.#config.maxBatchSize) || this.#config.maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte mode");
5169
+ this.#byteTracker = new StorageByteTracker(resolveStorageByteBatching(config.byteBatching));
5170
+ }
5171
+ this.#eventBuffer = new EventBuffer({
5172
+ maxRetries: this.#config.maxRetries ?? 4,
5173
+ byteTracker: this.#byteTracker
5174
+ });
4946
5175
  }
4947
5176
  /**
4948
5177
  * Initialize the exporter (called after all dependencies are ready)
@@ -4978,7 +5207,17 @@ var MastraStorageExporter = class extends BaseExporter {
4978
5207
  this.warnUnavailable("MastraStorageExporter unavailable: Observability storage not available. Traces will not be persisted until storage becomes available.");
4979
5208
  return;
4980
5209
  }
5210
+ if (skipLocalStorageOnPlatform(this.#observabilityStorage, this.logger)) {
5211
+ this.#observabilityStorage = void 0;
5212
+ this.#storage = void 0;
5213
+ return;
5214
+ }
4981
5215
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5216
+ if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5217
+ this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
5218
+ this.#byteTracker = void 0;
5219
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries });
5220
+ }
4982
5221
  this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4983
5222
  this.logger.debug("tracing storage exporter initialized", {
4984
5223
  strategy: this.#resolvedStrategy,
@@ -5003,6 +5242,7 @@ var MastraStorageExporter = class extends BaseExporter {
5003
5242
  * Checks if buffer should be flushed based on size or time triggers
5004
5243
  */
5005
5244
  shouldFlush() {
5245
+ if (this.#byteTracker && this.#byteTracker.queuedBytes >= this.#byteTracker.config.maxBatchBytes) return true;
5006
5246
  if (this.#resolvedStrategy === "realtime") return true;
5007
5247
  if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5008
5248
  if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
@@ -5048,8 +5288,11 @@ var MastraStorageExporter = class extends BaseExporter {
5048
5288
  * Returns the flush promise when flushing so callers can await it.
5049
5289
  */
5050
5290
  async handleBatchedFlush() {
5051
- if (this.shouldFlush()) await this.trackFlushBuffer();
5052
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5291
+ if (this.shouldFlush()) {
5292
+ const writing = this.trackFlushBuffer();
5293
+ if (this.#byteTracker) writing.catch((error) => this.logger.error("Byte batch flush failed", { error }));
5294
+ else await writing;
5295
+ } else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5053
5296
  }
5054
5297
  sanitizeDropError(error) {
5055
5298
  if (error instanceof MastraError) return {
@@ -5191,7 +5434,26 @@ var MastraStorageExporter = class extends BaseExporter {
5191
5434
  * that a timer or size trigger started on their own.
5192
5435
  */
5193
5436
  trackFlushBuffer() {
5194
- const promise = this.flushBuffer().finally(() => this.#inFlightFlushes.delete(promise));
5437
+ if (this.#byteTracker) {
5438
+ const concurrency = this.#resolvedStrategy === "insert-only" || this.#resolvedStrategy === "event-sourced" ? this.#byteTracker.config.maxConcurrentWrites : 1;
5439
+ if (this.#inFlightFlushes.size >= concurrency) return Promise.resolve();
5440
+ const delay = this.#byteRetryAt - Date.now();
5441
+ if (delay > 0) {
5442
+ this.scheduleFlush(delay);
5443
+ return Promise.resolve();
5444
+ }
5445
+ }
5446
+ let reschedule = true;
5447
+ const promise = this.flushBuffer().catch((error) => {
5448
+ reschedule = false;
5449
+ throw error;
5450
+ }).finally(() => {
5451
+ this.#inFlightFlushes.delete(promise);
5452
+ if (reschedule && this.#byteTracker && this.#eventBuffer.totalSize > 0) {
5453
+ const delay = Math.max(0, this.#byteRetryAt - Date.now());
5454
+ this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5455
+ }
5456
+ });
5195
5457
  this.#inFlightFlushes.add(promise);
5196
5458
  return promise;
5197
5459
  }
@@ -5219,77 +5481,97 @@ var MastraStorageExporter = class extends BaseExporter {
5219
5481
  if (this.#eventBuffer.totalSize === 0) return;
5220
5482
  const startTime = Date.now();
5221
5483
  const batchSize = this.#eventBuffer.totalSize;
5222
- const creates = this.#eventBuffer.creates;
5223
- const updates = this.#eventBuffer.updates;
5224
- this.#eventBuffer.reset();
5225
- const createFeedbackEvents = [];
5226
- const createLogEvents = [];
5227
- const createMetricEvents = [];
5228
- const createScoreEvents = [];
5229
- const createSpanEvents = [];
5230
- const updateSpanEvents = [];
5231
- const endSpanEvents = [];
5232
- for (const createEvent of creates) switch (createEvent.type) {
5233
- case "feedback":
5234
- createFeedbackEvents.push(createEvent);
5235
- break;
5236
- case "log":
5237
- createLogEvents.push(createEvent);
5238
- break;
5239
- case "metric":
5240
- createMetricEvents.push(createEvent);
5241
- break;
5242
- case "score":
5243
- createScoreEvents.push(createEvent);
5244
- break;
5245
- default: createSpanEvents.push(createEvent);
5246
- }
5247
- for (const updateEvent of updates) switch (updateEvent.type) {
5248
- case TracingEventType.SPAN_UPDATED:
5249
- updateSpanEvents.push(updateEvent);
5250
- break;
5251
- case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5484
+ const { creates, updates } = this.#byteTracker ? this.#eventBuffer.takeByteBatch(this.#config.maxBatchSize) : {
5485
+ creates: this.#eventBuffer.creates,
5486
+ updates: this.#eventBuffer.updates
5487
+ };
5488
+ if (this.#byteTracker && creates.length === 0 && updates.length === 0 && this.#inFlightFlushes.size === 0) {
5489
+ const message = "MastraStorageExporter flush made no progress: queued events have no eligible batch.";
5490
+ this.logger.error(message, { bufferedEvents: this.#eventBuffer.totalSize });
5491
+ throw new Error(message);
5252
5492
  }
5253
- const flushResults = await Promise.all([
5254
- this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5255
- this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
5256
- this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
5257
- this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
5258
- this.flushCreates("tracing", createSpanEvents, async (events) => {
5259
- const records = events.map((t) => buildCreateSpanRecord(t.exportedSpan));
5260
- await this.#observabilityStorage.batchCreateSpans({ records });
5261
- this.#eventBuffer.addCreatedSpans({ records });
5262
- })
5263
- ]);
5264
- const deferredUpdates = [];
5265
- flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5266
- flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5267
- let deferredDropCount = 0;
5268
- if (deferredUpdates.length > 0) {
5269
- if (this.#unsupportedSignals.has("tracing")) {
5270
- deferredDropCount = deferredUpdates.length;
5271
- this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5272
- deferredUpdates.length = 0;
5273
- } else {
5274
- deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5275
- this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5493
+ if (!this.#byteTracker) this.#eventBuffer.reset();
5494
+ try {
5495
+ const createFeedbackEvents = [];
5496
+ const createLogEvents = [];
5497
+ const createMetricEvents = [];
5498
+ const createScoreEvents = [];
5499
+ const createSpanEvents = [];
5500
+ const updateSpanEvents = [];
5501
+ const endSpanEvents = [];
5502
+ for (const createEvent of creates) switch (createEvent.type) {
5503
+ case "feedback":
5504
+ createFeedbackEvents.push(createEvent);
5505
+ break;
5506
+ case "log":
5507
+ createLogEvents.push(createEvent);
5508
+ break;
5509
+ case "metric":
5510
+ createMetricEvents.push(createEvent);
5511
+ break;
5512
+ case "score":
5513
+ createScoreEvents.push(createEvent);
5514
+ break;
5515
+ default: createSpanEvents.push(createEvent);
5276
5516
  }
5277
- }
5278
- const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5279
- if (result.retryAttempt === void 0) return earliestAttempt;
5280
- return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5281
- }, void 0);
5282
- if (retryAttempt !== void 0) this.scheduleFlush(this.retryDelay(retryAttempt));
5283
- if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5284
- const elapsed = Date.now() - startTime;
5285
- this.logger.debug("Batch flushed", {
5286
- strategy: this.#resolvedStrategy,
5287
- batchSize,
5288
- durationMs: elapsed,
5289
- deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5290
- });
5517
+ for (const updateEvent of updates) switch (updateEvent.type) {
5518
+ case TracingEventType.SPAN_UPDATED:
5519
+ updateSpanEvents.push(updateEvent);
5520
+ break;
5521
+ case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5522
+ }
5523
+ const createTasks = [
5524
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5525
+ () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
5526
+ () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
5527
+ () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
5528
+ () => this.flushCreates("tracing", createSpanEvents, async (events) => {
5529
+ const records = events.map((t) => buildCreateSpanRecord(t.exportedSpan));
5530
+ await this.#observabilityStorage.batchCreateSpans({ records });
5531
+ this.#eventBuffer.addCreatedSpans({ records });
5532
+ })
5533
+ ];
5534
+ const flushResults = [];
5535
+ if (this.#byteTracker) for (const task of createTasks) flushResults.push(await task());
5536
+ else flushResults.push(...await Promise.all(createTasks.map((task) => task())));
5537
+ const deferredUpdates = [];
5538
+ flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5539
+ flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5540
+ let deferredDropCount = 0;
5541
+ if (deferredUpdates.length > 0) {
5542
+ if (this.#unsupportedSignals.has("tracing")) {
5543
+ deferredDropCount = deferredUpdates.length;
5544
+ this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5545
+ deferredUpdates.length = 0;
5546
+ } else {
5547
+ deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5548
+ this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5549
+ }
5550
+ }
5551
+ const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5552
+ if (result.retryAttempt === void 0) return earliestAttempt;
5553
+ return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5554
+ }, void 0);
5555
+ if (retryAttempt !== void 0) {
5556
+ if (this.#byteTracker) this.#byteRetryAt = Date.now() + this.retryDelay(retryAttempt);
5557
+ this.scheduleFlush(this.retryDelay(retryAttempt));
5558
+ }
5559
+ if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5560
+ const elapsed = Date.now() - startTime;
5561
+ this.logger.debug("Batch flushed", {
5562
+ strategy: this.#resolvedStrategy,
5563
+ batchSize,
5564
+ durationMs: elapsed,
5565
+ deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5566
+ });
5567
+ }
5568
+ } finally {
5569
+ this.#eventBuffer.releaseByteBatch([...creates, ...updates]);
5291
5570
  }
5292
5571
  }
5572
+ getByteBatchingStats() {
5573
+ return this.#byteTracker?.stats(this.#inFlightFlushes.size);
5574
+ }
5293
5575
  async _exportTracingEvent(event) {
5294
5576
  await this.ensureInitialized();
5295
5577
  if (!this.#observabilityStorage) {
@@ -5344,6 +5626,21 @@ var MastraStorageExporter = class extends BaseExporter {
5344
5626
  * are exported before the runtime instance is terminated.
5345
5627
  */
5346
5628
  async flush() {
5629
+ if (this.#byteTracker) {
5630
+ if (!this.#observabilityStorage) return;
5631
+ this.#byteDrainers++;
5632
+ try {
5633
+ while (this.#eventBuffer.totalSize || this.#inFlightFlushes.size) {
5634
+ if (this.#inFlightFlushes.size) await Promise.allSettled([...this.#inFlightFlushes]);
5635
+ const delay = this.#byteRetryAt - Date.now();
5636
+ if (delay > 0 && this.#eventBuffer.totalSize) await new Promise((resolve) => setTimeout(resolve, delay));
5637
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5638
+ }
5639
+ } finally {
5640
+ this.#byteDrainers--;
5641
+ }
5642
+ return;
5643
+ }
5347
5644
  for (let round = 0; round < MAX_FLUSH_ROUNDS; round++) {
5348
5645
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5349
5646
  if (this.#eventBuffer.totalSize > 0) {
@@ -5360,10 +5657,22 @@ var MastraStorageExporter = class extends BaseExporter {
5360
5657
  clearTimeout(this.#flushTimer);
5361
5658
  this.#flushTimer = void 0;
5362
5659
  }
5363
- await this.flush();
5364
- if (this.#flushTimer) {
5365
- clearTimeout(this.#flushTimer);
5366
- this.#flushTimer = void 0;
5660
+ try {
5661
+ await this.flush();
5662
+ } catch (error) {
5663
+ const mastraError = new MastraError({
5664
+ id: "MASTRA_STORAGE_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN",
5665
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
5666
+ category: ErrorCategory.SYSTEM,
5667
+ details: { remainingEvents: this.#eventBuffer.totalSize }
5668
+ }, error);
5669
+ this.logger.trackException(mastraError);
5670
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
5671
+ } finally {
5672
+ if (this.#flushTimer) {
5673
+ clearTimeout(this.#flushTimer);
5674
+ this.#flushTimer = void 0;
5675
+ }
5367
5676
  }
5368
5677
  this.logger.info("MastraStorageExporter shutdown complete");
5369
5678
  }
@@ -5376,6 +5685,12 @@ function isMastraPlatformDeployment() {
5376
5685
  function isMastraBuiltInStorageExporter(exporter) {
5377
5686
  return exporter instanceof MastraStorageExporter || exporter instanceof DefaultExporter || MASTRA_BUILT_IN_STORAGE_EXPORTER_NAMES.has(exporter.name);
5378
5687
  }
5688
+ function isMastraDeprecatedStorageExporter(exporter) {
5689
+ return exporter instanceof DefaultExporter || exporter.name === "mastra-default-observability-exporter";
5690
+ }
5691
+ function shouldSkipStorageExporterOnPlatform(exporter, retainStorageExporterOnPlatform = false) {
5692
+ return isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter) && (!retainStorageExporterOnPlatform || isMastraDeprecatedStorageExporter(exporter));
5693
+ }
5379
5694
  // src/instances/base.ts
5380
5695
  /**
5381
5696
  * BaseObservability - Abstract base class for Observability implementations
@@ -5413,6 +5728,8 @@ var BaseObservabilityInstance = class extends MastraBase {
5413
5728
  * a span's `metadata.environment` isn't set.
5414
5729
  */
5415
5730
  #mastraEnvironment;
5731
+ #pendingStorageExporterWarnings = /* @__PURE__ */ new Set();
5732
+ #hasApplicationLogger = false;
5416
5733
  /**
5417
5734
  * For excluded MODEL_GENERATION spans whose constructor clears `attributes`,
5418
5735
  * we stash the lightweight provider/model from creation options so
@@ -5425,12 +5742,13 @@ var BaseObservabilityInstance = class extends MastraBase {
5425
5742
  name: config.serviceName
5426
5743
  });
5427
5744
  const exporters = config.exporters ?? [];
5428
- const effectiveExporters = isMastraPlatformDeployment() ? exporters.filter((exporter) => !isMastraBuiltInStorageExporter(exporter)) : exporters;
5745
+ const effectiveExporters = exporters.filter((exporter) => !shouldSkipStorageExporterOnPlatform(exporter, config.retainStorageExporterOnPlatform));
5429
5746
  this.config = {
5430
5747
  serviceName: config.serviceName,
5431
5748
  name: config.name,
5432
5749
  sampling: config.sampling ?? { type: "always" },
5433
5750
  exporters: effectiveExporters,
5751
+ retainStorageExporterOnPlatform: config.retainStorageExporterOnPlatform ?? false,
5434
5752
  spanOutputProcessors: config.spanOutputProcessors ?? [],
5435
5753
  bridge: config.bridge ?? void 0,
5436
5754
  includeInternalSpans: config.includeInternalSpans ?? false,
@@ -5440,6 +5758,7 @@ var BaseObservabilityInstance = class extends MastraBase {
5440
5758
  serializationOptions: config.serializationOptions,
5441
5759
  logging: config.logging
5442
5760
  };
5761
+ for (const exporter of exporters) if (!effectiveExporters.includes(exporter)) this.warnStorageExporterSkipped(exporter);
5443
5762
  this.cardinalityFilter = new CardinalityFilter(config.cardinality);
5444
5763
  this.observabilityBus = new ObservabilityBus({ serializationOptions: this.config.serializationOptions });
5445
5764
  for (const exporter of this.exporters) this.observabilityBus.registerExporter(exporter);
@@ -5452,6 +5771,9 @@ var BaseObservabilityInstance = class extends MastraBase {
5452
5771
  */
5453
5772
  __setLogger(logger) {
5454
5773
  super.__setLogger(logger);
5774
+ this.#hasApplicationLogger = true;
5775
+ for (const exporter of this.#pendingStorageExporterWarnings) this.warnStorageExporterSkipped(exporter);
5776
+ this.#pendingStorageExporterWarnings.clear();
5455
5777
  this.exporters.forEach((exporter) => {
5456
5778
  if (typeof exporter.__setLogger === "function") exporter.__setLogger(logger);
5457
5779
  });
@@ -5620,17 +5942,24 @@ var BaseObservabilityInstance = class extends MastraBase {
5620
5942
  getExporters() {
5621
5943
  return [...this.exporters];
5622
5944
  }
5945
+ warnStorageExporterSkipped(exporter) {
5946
+ if (!this.#hasApplicationLogger) {
5947
+ this.#pendingStorageExporterWarnings.add(exporter);
5948
+ return;
5949
+ }
5950
+ 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.", {
5951
+ exporterName: exporter.name,
5952
+ serviceName: this.config.serviceName,
5953
+ instanceName: this.config.name
5954
+ });
5955
+ }
5623
5956
  /**
5624
5957
  * Register an additional exporter at runtime.
5625
5958
  * Adds to both the bus (for event routing) and the config (for getExporters).
5626
5959
  */
5627
5960
  registerExporter(exporter) {
5628
- if (isMastraPlatformDeployment() && isMastraBuiltInStorageExporter(exporter)) {
5629
- this.logger.warn("Storage exporter registration skipped on Mastra Platform", {
5630
- exporterName: exporter.name,
5631
- serviceName: this.config.serviceName,
5632
- instanceName: this.config.name
5633
- });
5961
+ if (shouldSkipStorageExporterOnPlatform(exporter, this.config.retainStorageExporterOnPlatform)) {
5962
+ this.warnStorageExporterSkipped(exporter);
5634
5963
  return;
5635
5964
  }
5636
5965
  this.observabilityBus.registerExporter(exporter);
@@ -8186,6 +8515,127 @@ var ConsoleExporter = class extends BaseExporter {
8186
8515
  this.logger.info("ConsoleExporter shutdown");
8187
8516
  }
8188
8517
  };
8518
+ // src/exporters/platform-byte-batcher.ts
8519
+ function resolveByteBatchingConfig(config) {
8520
+ const resolved = {
8521
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
8522
+ maxConcurrentUploads: config.maxConcurrentUploads ?? 2,
8523
+ uploadTimeoutMs: config.uploadTimeoutMs ?? 3e4
8524
+ };
8525
+ 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`);
8526
+ if (resolved.maxBatchBytes < 32) throw new Error("byteBatching.maxBatchBytes must be at least 32");
8527
+ if (resolved.uploadTimeoutMs > 2147483647) throw new Error("byteBatching.uploadTimeoutMs must fit in a Node.js timer");
8528
+ return resolved;
8529
+ }
8530
+ /**
8531
+ * Serialize each record once, before retaining it. The accounting includes open
8532
+ * batches, ready batches and uploads until they settle. This tracks retained
8533
+ * JSON bytes for diagnostics; queued bytes are not capped.
8534
+ */
8535
+ var PlatformByteBatcher = class {
8536
+ config;
8537
+ maxBatchSize;
8538
+ maxBatchWaitMs;
8539
+ segments;
8540
+ send;
8541
+ onError;
8542
+ open = /* @__PURE__ */ new Map();
8543
+ ready = [];
8544
+ active = /* @__PURE__ */ new Set();
8545
+ timer;
8546
+ pendingBytes = 0;
8547
+ constructor(config, maxBatchSize, maxBatchWaitMs, segments, send, onError) {
8548
+ this.config = config;
8549
+ this.maxBatchSize = maxBatchSize;
8550
+ this.maxBatchWaitMs = maxBatchWaitMs;
8551
+ this.segments = segments;
8552
+ this.send = send;
8553
+ this.onError = onError;
8554
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte batching mode");
8555
+ if (!Number.isSafeInteger(maxBatchWaitMs) || maxBatchWaitMs <= 0 || maxBatchWaitMs > 2147483647) throw new Error("maxBatchWaitMs must be a positive integer that fits in a Node.js timer");
8556
+ }
8557
+ add(signal, record) {
8558
+ const json = JSON.stringify(record);
8559
+ if (json === void 0) throw new Error("Record has no JSON representation");
8560
+ const prefix = `{"${this.segments[signal]}":[`;
8561
+ const envelopeBytes = Buffer.byteLength(prefix) + 2;
8562
+ const recordBytes = Buffer.byteLength(json);
8563
+ let batch = this.open.get(signal);
8564
+ if (batch && recordBytes + envelopeBytes > this.config.maxBatchBytes) {
8565
+ this.seal(signal);
8566
+ batch = void 0;
8567
+ }
8568
+ const extraBytes = recordBytes + (batch ? 1 : envelopeBytes);
8569
+ if (!batch) {
8570
+ batch = {
8571
+ signal,
8572
+ prefix,
8573
+ records: [],
8574
+ bytes: envelopeBytes
8575
+ };
8576
+ this.open.set(signal, batch);
8577
+ }
8578
+ batch.bytes += recordBytes + (batch.records.length ? 1 : 0);
8579
+ batch.records.push(json);
8580
+ this.pendingBytes += extraBytes;
8581
+ if (batch.records.length >= this.maxBatchSize || batch.bytes >= this.config.maxBatchBytes) this.seal(signal);
8582
+ this.pump();
8583
+ if (this.open.size && !this.timer) this.timer = setTimeout(() => {
8584
+ this.timer = void 0;
8585
+ this.sealAll();
8586
+ this.pump();
8587
+ }, this.maxBatchWaitMs);
8588
+ }
8589
+ seal(signal) {
8590
+ const batch = this.open.get(signal);
8591
+ if (batch) {
8592
+ this.open.delete(signal);
8593
+ this.ready.push(batch);
8594
+ }
8595
+ }
8596
+ sealAll() {
8597
+ if (this.timer) clearTimeout(this.timer);
8598
+ this.timer = void 0;
8599
+ for (const signal of this.open.keys()) this.seal(signal);
8600
+ }
8601
+ pump() {
8602
+ while (this.ready.length && this.active.size < this.config.maxConcurrentUploads) {
8603
+ const batch = this.ready.shift();
8604
+ const task = Promise.resolve().then(async () => {
8605
+ const count = batch.records.length;
8606
+ const body = batch.prefix + batch.records.join(",") + "]}";
8607
+ batch.records = [];
8608
+ await this.send(batch.signal, body, count);
8609
+ }).catch((error) => this.onError(error)).finally(() => {
8610
+ this.pendingBytes -= batch.bytes;
8611
+ this.active.delete(task);
8612
+ this.pump();
8613
+ });
8614
+ this.active.add(task);
8615
+ }
8616
+ }
8617
+ /** Drop unsent batches after auth/quota rejection. In-flight uploads still remain accounted for. */
8618
+ clearQueued() {
8619
+ if (this.timer) clearTimeout(this.timer);
8620
+ this.timer = void 0;
8621
+ for (const batch of [...this.open.values(), ...this.ready]) this.pendingBytes -= batch.bytes;
8622
+ this.open.clear();
8623
+ this.ready = [];
8624
+ }
8625
+ async flush() {
8626
+ do {
8627
+ this.sealAll();
8628
+ this.pump();
8629
+ await Promise.allSettled([...this.active]);
8630
+ } while (this.open.size || this.ready.length || this.active.size);
8631
+ }
8632
+ getStats() {
8633
+ return {
8634
+ pendingBytes: this.pendingBytes,
8635
+ activeUploads: this.active.size
8636
+ };
8637
+ }
8638
+ };
8189
8639
  // src/exporters/mastra-platform.ts
8190
8640
  const SIGNAL_PUBLISH_SUFFIXES = {
8191
8641
  traces: "/spans/publish",
@@ -8309,6 +8759,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8309
8759
  quotaProbeTimer = null;
8310
8760
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
8311
8761
  shuttingDown = false;
8762
+ byteBatcher;
8763
+ byteUploadTimeoutMs;
8312
8764
  constructor(config = {}) {
8313
8765
  super(config);
8314
8766
  if (config.projectId !== void 0 && !VALID_PROJECT_ID.test(config.projectId)) throw createInvalidProjectIdError(config.projectId);
@@ -8346,6 +8798,11 @@ var MastraPlatformExporter = class extends BaseExporter {
8346
8798
  feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config.feedbackEndpoint)
8347
8799
  };
8348
8800
  this.authFailureCooldown = new AuthFailureCooldown("MastraPlatformExporter", () => this.logger);
8801
+ if (config.byteBatching) {
8802
+ const byteConfig = resolveByteBatchingConfig(config.byteBatching);
8803
+ this.byteUploadTimeoutMs = byteConfig.uploadTimeoutMs;
8804
+ 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 }));
8805
+ }
8349
8806
  this.buffer = {
8350
8807
  spans: [],
8351
8808
  logs: [],
@@ -8387,27 +8844,47 @@ var MastraPlatformExporter = class extends BaseExporter {
8387
8844
  await this.handleBufferedEvent();
8388
8845
  }
8389
8846
  addToBuffer(event) {
8847
+ if (this.byteBatcher) {
8848
+ this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
8849
+ return;
8850
+ }
8390
8851
  this.markBufferStart();
8391
8852
  const spanRecord = this.formatSpan(event.exportedSpan);
8392
8853
  this.buffer.spans.push(spanRecord);
8393
8854
  this.buffer.totalSize++;
8394
8855
  }
8395
8856
  addLogToBuffer(event) {
8857
+ if (this.byteBatcher) {
8858
+ this.byteBatcher.add("logs", this.formatLog(event.log));
8859
+ return;
8860
+ }
8396
8861
  this.markBufferStart();
8397
8862
  this.buffer.logs.push(this.formatLog(event.log));
8398
8863
  this.buffer.totalSize++;
8399
8864
  }
8400
8865
  addMetricToBuffer(event) {
8866
+ if (this.byteBatcher) {
8867
+ this.byteBatcher.add("metrics", this.formatMetric(event.metric));
8868
+ return;
8869
+ }
8401
8870
  this.markBufferStart();
8402
8871
  this.buffer.metrics.push(this.formatMetric(event.metric));
8403
8872
  this.buffer.totalSize++;
8404
8873
  }
8405
8874
  addScoreToBuffer(event) {
8875
+ if (this.byteBatcher) {
8876
+ this.byteBatcher.add("scores", this.formatScore(event.score));
8877
+ return;
8878
+ }
8406
8879
  this.markBufferStart();
8407
8880
  this.buffer.scores.push(this.formatScore(event.score));
8408
8881
  this.buffer.totalSize++;
8409
8882
  }
8410
8883
  addFeedbackToBuffer(event) {
8884
+ if (this.byteBatcher) {
8885
+ this.byteBatcher.add("feedback", this.formatFeedback(event.feedback));
8886
+ return;
8887
+ }
8411
8888
  this.markBufferStart();
8412
8889
  this.buffer.feedback.push(this.formatFeedback(event.feedback));
8413
8890
  this.buffer.totalSize++;
@@ -8440,6 +8917,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8440
8917
  return { ...feedback };
8441
8918
  }
8442
8919
  async handleBufferedEvent() {
8920
+ if (this.byteBatcher) return;
8443
8921
  if (this.shouldFlush()) this.flush().catch((error) => {
8444
8922
  this.logger.error("Batch flush failed", { error: error instanceof Error ? error.message : String(error) });
8445
8923
  });
@@ -8536,6 +9014,9 @@ var MastraPlatformExporter = class extends BaseExporter {
8536
9014
  return JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records });
8537
9015
  }
8538
9016
  async batchUpload(signal, records) {
9017
+ await this.uploadBody(signal, this.buildPublishBody(signal, records));
9018
+ }
9019
+ async uploadBody(signal, body) {
8539
9020
  const endpointMap = {
8540
9021
  traces: this.platformConfig.tracesEndpoint,
8541
9022
  logs: this.platformConfig.logsEndpoint,
@@ -8546,7 +9027,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8546
9027
  const options = {
8547
9028
  method: "POST",
8548
9029
  headers: this.buildPublishHeaders(),
8549
- body: this.buildPublishBody(signal, records)
9030
+ body,
9031
+ ...this.byteUploadTimeoutMs ? { signal: AbortSignal.timeout(this.byteUploadTimeoutMs) } : {}
8550
9032
  };
8551
9033
  let quotaResponse;
8552
9034
  let response;
@@ -8566,6 +9048,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8566
9048
  throw error;
8567
9049
  }
8568
9050
  if (isObservabilityDisabled(response)) this.enterQuotaPause(parseQuotaRetryAfterSeconds(response));
9051
+ await response.body?.cancel().catch(() => {});
8569
9052
  }
8570
9053
  /**
8571
9054
  * Enter the quota-exhausted paused state: drop buffered events, stop the
@@ -8577,6 +9060,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8577
9060
  this.quotaProbeIntervalSeconds = retryAfterSeconds;
8578
9061
  if (this.quotaPaused) return;
8579
9062
  this.quotaPaused = true;
9063
+ this.byteBatcher?.clearQueued();
8580
9064
  if (this.flushTimer) {
8581
9065
  clearTimeout(this.flushTimer);
8582
9066
  this.flushTimer = null;
@@ -8625,6 +9109,30 @@ var MastraPlatformExporter = class extends BaseExporter {
8625
9109
  }
8626
9110
  this.scheduleQuotaProbe();
8627
9111
  }
9112
+ /** Current queued and active serialized JSON bytes; undefined in count mode. */
9113
+ getByteBatchingStats() {
9114
+ return this.byteBatcher?.getStats();
9115
+ }
9116
+ async flushByteBatch(signal, body, count) {
9117
+ if (this.quotaPaused || this.authFailureCooldown.dropEventsIfCoolingDown(count)) return;
9118
+ try {
9119
+ await this.uploadBody(signal, body);
9120
+ this.authFailureCooldown.reset();
9121
+ } catch (error) {
9122
+ if (isAuthFailureError(error)) {
9123
+ this.authFailureCooldown.recordFailure({
9124
+ status: error.status,
9125
+ failedSignals: [signal],
9126
+ droppedBatchSize: count
9127
+ });
9128
+ this.byteBatcher?.clearQueued();
9129
+ } else this.logger.error("Byte batch upload failed after retries, dropping batch", {
9130
+ signal,
9131
+ droppedBatchSize: count,
9132
+ error
9133
+ });
9134
+ }
9135
+ }
8628
9136
  async flushSignalBatch(signal, records) {
8629
9137
  if (records.length === 0) return {
8630
9138
  signal,
@@ -8676,6 +9184,10 @@ var MastraPlatformExporter = class extends BaseExporter {
8676
9184
  */
8677
9185
  async flush() {
8678
9186
  if (this.isDisabled) return;
9187
+ if (this.byteBatcher) {
9188
+ await this.byteBatcher.flush();
9189
+ return;
9190
+ }
8679
9191
  while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
8680
9192
  if (this.buffer.totalSize > 0) {
8681
9193
  this.logger.debug("Flushing buffered events", { bufferedEvents: this.buffer.totalSize });
@@ -8708,8 +9220,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8708
9220
  const mastraError = new MastraError({
8709
9221
  id: `MASTRA_PLATFORM_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
8710
9222
  domain: ErrorDomain.MASTRA_OBSERVABILITY,
8711
- category: ErrorCategory.USER,
8712
- details: { remainingEvents: this.buffer.totalSize }
9223
+ category: ErrorCategory.SYSTEM,
9224
+ details: this.byteBatcher ? { pendingBytes: this.byteBatcher.getStats().pendingBytes } : { remainingEvents: this.buffer.totalSize }
8713
9225
  }, error);
8714
9226
  this.logger.trackException(mastraError);
8715
9227
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);