@mastra/observability 1.23.2-alpha.0 → 1.24.0-alpha.2

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 (53) hide show
  1. package/dist/docs/SKILL.md +62 -0
  2. package/dist/docs/assets/SOURCE_MAP.json +272 -0
  3. package/dist/docs/references/docs-mastra-platform-observability.md +416 -0
  4. package/dist/docs/references/docs-observability-feedback.md +204 -0
  5. package/dist/docs/references/docs-observability-integrations-exporters-mastra-storage.md +255 -0
  6. package/dist/docs/references/docs-observability-logging.md +253 -0
  7. package/dist/docs/references/docs-observability-metrics-overview.md +108 -0
  8. package/dist/docs/references/docs-observability-overview.md +235 -0
  9. package/dist/docs/references/docs-observability-tracing-overview.md +1009 -0
  10. package/dist/docs/references/docs-studio-observability.md +125 -0
  11. package/dist/docs/references/integrations-observability-arize.md +278 -0
  12. package/dist/docs/references/integrations-observability-arthur.md +167 -0
  13. package/dist/docs/references/integrations-observability-braintrust.md +205 -0
  14. package/dist/docs/references/integrations-observability-confident-ai.md +166 -0
  15. package/dist/docs/references/integrations-observability-datadog.md +545 -0
  16. package/dist/docs/references/integrations-observability-laminar.md +112 -0
  17. package/dist/docs/references/integrations-observability-langfuse.md +321 -0
  18. package/dist/docs/references/integrations-observability-langsmith.md +235 -0
  19. package/dist/docs/references/integrations-observability-opentelemetry.md +902 -0
  20. package/dist/docs/references/integrations-observability-posthog.md +207 -0
  21. package/dist/docs/references/integrations-observability-sentry.md +212 -0
  22. package/dist/docs/references/reference-file-based-agents-observability.md +34 -0
  23. package/dist/docs/references/reference-observability-feedback.md +464 -0
  24. package/dist/docs/references/reference-observability-metrics-automatic-metrics.md +154 -0
  25. package/dist/docs/references/reference-observability-tracing-bridges-datadog.md +218 -0
  26. package/dist/docs/references/reference-observability-tracing-bridges-otel.md +166 -0
  27. package/dist/docs/references/reference-observability-tracing-configuration.md +225 -0
  28. package/dist/docs/references/reference-observability-tracing-exporters-cloud-exporter.md +251 -0
  29. package/dist/docs/references/reference-observability-tracing-exporters-console-exporter.md +138 -0
  30. package/dist/docs/references/reference-observability-tracing-exporters-datadog.md +126 -0
  31. package/dist/docs/references/reference-observability-tracing-exporters-default-exporter.md +183 -0
  32. package/dist/docs/references/reference-observability-tracing-exporters-langfuse.md +145 -0
  33. package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +328 -0
  34. package/dist/docs/references/reference-observability-tracing-exporters-mastra-storage-exporter.md +227 -0
  35. package/dist/docs/references/reference-observability-tracing-exporters-sentry.md +190 -0
  36. package/dist/docs/references/reference-observability-tracing-processors-sensitive-data-filter.md +205 -0
  37. package/dist/docs/references/reference-observability-tracing-span-filtering.md +99 -0
  38. package/dist/exporters/event-buffer.d.ts +9 -0
  39. package/dist/exporters/event-buffer.d.ts.map +1 -1
  40. package/dist/exporters/mastra-platform.d.ts +10 -0
  41. package/dist/exporters/mastra-platform.d.ts.map +1 -1
  42. package/dist/exporters/mastra-storage.d.ts +4 -0
  43. package/dist/exporters/mastra-storage.d.ts.map +1 -1
  44. package/dist/exporters/platform-byte-batcher.d.ts +42 -0
  45. package/dist/exporters/platform-byte-batcher.d.ts.map +1 -0
  46. package/dist/exporters/storage-byte-tracker.d.ts +31 -0
  47. package/dist/exporters/storage-byte-tracker.d.ts.map +1 -0
  48. package/dist/index.cjs +477 -93
  49. package/dist/index.cjs.map +1 -1
  50. package/dist/index.js +477 -93
  51. package/dist/index.js.map +1 -1
  52. package/dist/metrics/pricing-data.json +1183 -921
  53. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -4308,8 +4308,11 @@ var EventBuffer = class {
4308
4308
  #firstEventTime;
4309
4309
  #storageStrategy;
4310
4310
  #maxRetries;
4311
+ #byteTracker;
4312
+ #preferUpdates = false;
4311
4313
  constructor(args) {
4312
4314
  this.#maxRetries = args.maxRetries;
4315
+ this.#byteTracker = args.byteTracker;
4313
4316
  }
4314
4317
  /** Initialize with a storage strategy and replay any pre-init events. */
4315
4318
  init(args) {
@@ -4329,18 +4332,20 @@ var EventBuffer = class {
4329
4332
  if (!this.#firstEventTime) this.#firstEventTime = /* @__PURE__ */ new Date();
4330
4333
  }
4331
4334
  pushCreate(event) {
4332
- this.setFirstEventTime();
4333
- this.#creates.push({
4335
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4334
4336
  ...event,
4335
4337
  retryCount: 0
4336
- });
4338
+ };
4339
+ this.setFirstEventTime();
4340
+ this.#creates.push(buffered);
4337
4341
  }
4338
4342
  pushUpdate(event) {
4339
- this.setFirstEventTime();
4340
- this.#updates.push({
4343
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4341
4344
  ...event,
4342
4345
  retryCount: 0
4343
- });
4346
+ };
4347
+ this.setFirstEventTime();
4348
+ this.#updates.push(buffered);
4344
4349
  }
4345
4350
  /** Route an event to the create or update buffer based on its type and the storage strategy. */
4346
4351
  addEvent(event) {
@@ -4356,8 +4361,8 @@ var EventBuffer = class {
4356
4361
  switch (this.#storageStrategy) {
4357
4362
  case "realtime":
4358
4363
  case "batch-with-updates":
4359
- if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4360
4364
  this.pushCreate(event);
4365
+ if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4361
4366
  break;
4362
4367
  case "event-sourced": this.pushCreate(event);
4363
4368
  }
@@ -4385,8 +4390,10 @@ var EventBuffer = class {
4385
4390
  reAddCreates(events) {
4386
4391
  const retryable = [];
4387
4392
  const dropped = [];
4388
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4389
- else dropped.push(e);
4393
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4394
+ retryable.push(e);
4395
+ this.#byteTracker?.enqueue(e);
4396
+ } else dropped.push(e);
4390
4397
  if (retryable.length > 0) {
4391
4398
  this.setFirstEventTime();
4392
4399
  this.#creates.push(...retryable);
@@ -4397,14 +4404,64 @@ var EventBuffer = class {
4397
4404
  reAddUpdates(events) {
4398
4405
  const retryable = [];
4399
4406
  const dropped = [];
4400
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4401
- else dropped.push(e);
4407
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4408
+ retryable.push(e);
4409
+ this.#byteTracker?.enqueue(e);
4410
+ } else dropped.push(e);
4402
4411
  if (retryable.length > 0) {
4403
4412
  this.setFirstEventTime();
4404
4413
  this.#updates.push(...retryable);
4405
4414
  }
4406
4415
  return dropped;
4407
4416
  }
4417
+ /** Alternate creates and eligible updates so either queue can make progress under load. */
4418
+ takeByteBatch(maxRecords) {
4419
+ const tracker = this.#byteTracker;
4420
+ const creates = [];
4421
+ const updates = [];
4422
+ const selectedUpdates = /* @__PURE__ */ new Set();
4423
+ let updateIndex = 0;
4424
+ let bytes = 0;
4425
+ while (creates.length + updates.length < maxRecords && bytes < tracker.config.maxBatchBytes) {
4426
+ while (updateIndex < this.#updates.length) {
4427
+ const event = this.#updates[updateIndex];
4428
+ if (!("exportedSpan" in event) || !this.isAwaitingCreate(event.exportedSpan)) break;
4429
+ updateIndex++;
4430
+ }
4431
+ const create = this.#creates[creates.length];
4432
+ const update = this.#updates[updateIndex];
4433
+ if (!create && !update) break;
4434
+ const takeUpdate = !!update && (!create || this.#preferUpdates);
4435
+ const event = takeUpdate ? update : create;
4436
+ if (takeUpdate) {
4437
+ updates.push(event);
4438
+ selectedUpdates.add(updateIndex++);
4439
+ } else creates.push(event);
4440
+ this.#preferUpdates = !takeUpdate;
4441
+ tracker.dequeue(event);
4442
+ bytes += tracker.size(event);
4443
+ }
4444
+ this.#creates.splice(0, creates.length);
4445
+ this.#updates = this.#updates.filter((_, index) => !selectedUpdates.has(index));
4446
+ if (this.totalSize === 0) this.#firstEventTime = void 0;
4447
+ return {
4448
+ creates,
4449
+ updates
4450
+ };
4451
+ }
4452
+ /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4453
+ releaseByteBatch(events) {
4454
+ if (!this.#byteTracker) return;
4455
+ for (const event of events) {
4456
+ if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4457
+ this.forgetDroppedCreates([event]);
4458
+ if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4459
+ traceId: event.exportedSpan.traceId,
4460
+ spanId: event.exportedSpan.id,
4461
+ updates: {}
4462
+ }] });
4463
+ }
4464
+ }
4408
4465
  /** Snapshot of buffered create events. */
4409
4466
  get creates() {
4410
4467
  return [...this.#creates];
@@ -4918,6 +4975,67 @@ function withSpanPreviews(span) {
4918
4975
  return span;
4919
4976
  }
4920
4977
  }
4978
+ // src/exporters/storage-byte-tracker.ts
4979
+ function resolveStorageByteBatching(config) {
4980
+ const resolved = {
4981
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
4982
+ maxConcurrentWrites: config.maxConcurrentWrites ?? 1
4983
+ };
4984
+ 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`);
4985
+ return resolved;
4986
+ }
4987
+ /** Counts each admitted event once until persistence or a definitive drop, even across retries. */
4988
+ var StorageByteTracker = class {
4989
+ config;
4990
+ sizes = /* @__PURE__ */ new WeakMap();
4991
+ queued = /* @__PURE__ */ new WeakSet();
4992
+ pendingBytes = 0;
4993
+ pendingRecords = 0;
4994
+ queuedBytes = 0;
4995
+ constructor(config) {
4996
+ this.config = config;
4997
+ }
4998
+ capture(event) {
4999
+ const snapshot = {
5000
+ ...structuredClone(event),
5001
+ retryCount: 0
5002
+ };
5003
+ const bytes = Buffer.byteLength(JSON.stringify(snapshot)) + 1;
5004
+ this.sizes.set(snapshot, bytes);
5005
+ this.pendingBytes += bytes;
5006
+ this.pendingRecords++;
5007
+ this.enqueue(snapshot);
5008
+ return snapshot;
5009
+ }
5010
+ size(event) {
5011
+ return this.sizes.get(event) ?? 0;
5012
+ }
5013
+ enqueue(event) {
5014
+ if (!this.queued.has(event)) {
5015
+ this.queued.add(event);
5016
+ this.queuedBytes += this.size(event);
5017
+ }
5018
+ }
5019
+ dequeue(event) {
5020
+ if (this.queued.delete(event)) this.queuedBytes -= this.size(event);
5021
+ }
5022
+ releaseIfUnqueued(event) {
5023
+ if (this.queued.has(event)) return false;
5024
+ const bytes = this.sizes.get(event);
5025
+ if (bytes === void 0) return false;
5026
+ this.sizes.delete(event);
5027
+ this.pendingBytes -= bytes;
5028
+ this.pendingRecords--;
5029
+ return true;
5030
+ }
5031
+ stats(activeWrites) {
5032
+ return {
5033
+ pendingBytes: this.pendingBytes,
5034
+ pendingRecords: this.pendingRecords,
5035
+ activeWrites
5036
+ };
5037
+ }
5038
+ };
4921
5039
  // src/exporters/mastra-storage.ts
4922
5040
  /**
4923
5041
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -4948,6 +5066,9 @@ var MastraStorageExporter = class extends BaseExporter {
4948
5066
  #initializationPromise;
4949
5067
  #wasUnavailable = false;
4950
5068
  #eventBuffer;
5069
+ #byteTracker;
5070
+ #byteRetryAt = 0;
5071
+ #byteDrainers = 0;
4951
5072
  #storage;
4952
5073
  #observabilityStorage;
4953
5074
  #resolvedStrategy;
@@ -4967,7 +5088,14 @@ var MastraStorageExporter = class extends BaseExporter {
4967
5088
  retryDelayMs: config.retryDelayMs ?? 500,
4968
5089
  strategy: config.strategy ?? "auto"
4969
5090
  };
4970
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5091
+ if (config.byteBatching) {
5092
+ if (!Number.isSafeInteger(this.#config.maxBatchSize) || this.#config.maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte mode");
5093
+ this.#byteTracker = new StorageByteTracker(resolveStorageByteBatching(config.byteBatching));
5094
+ }
5095
+ this.#eventBuffer = new EventBuffer({
5096
+ maxRetries: this.#config.maxRetries ?? 4,
5097
+ byteTracker: this.#byteTracker
5098
+ });
4971
5099
  }
4972
5100
  /**
4973
5101
  * Initialize the exporter (called after all dependencies are ready)
@@ -5004,6 +5132,11 @@ var MastraStorageExporter = class extends BaseExporter {
5004
5132
  return;
5005
5133
  }
5006
5134
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5135
+ if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5136
+ this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
5137
+ this.#byteTracker = void 0;
5138
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries });
5139
+ }
5007
5140
  this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
5008
5141
  this.logger.debug("tracing storage exporter initialized", {
5009
5142
  strategy: this.#resolvedStrategy,
@@ -5028,6 +5161,7 @@ var MastraStorageExporter = class extends BaseExporter {
5028
5161
  * Checks if buffer should be flushed based on size or time triggers
5029
5162
  */
5030
5163
  shouldFlush() {
5164
+ if (this.#byteTracker && this.#byteTracker.queuedBytes >= this.#byteTracker.config.maxBatchBytes) return true;
5031
5165
  if (this.#resolvedStrategy === "realtime") return true;
5032
5166
  if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5033
5167
  if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
@@ -5073,8 +5207,11 @@ var MastraStorageExporter = class extends BaseExporter {
5073
5207
  * Returns the flush promise when flushing so callers can await it.
5074
5208
  */
5075
5209
  async handleBatchedFlush() {
5076
- if (this.shouldFlush()) await this.trackFlushBuffer();
5077
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5210
+ if (this.shouldFlush()) {
5211
+ const writing = this.trackFlushBuffer();
5212
+ if (this.#byteTracker) writing.catch((error) => this.logger.error("Byte batch flush failed", { error }));
5213
+ else await writing;
5214
+ } else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5078
5215
  }
5079
5216
  sanitizeDropError(error) {
5080
5217
  if (error instanceof _mastra_core_error.MastraError) return {
@@ -5216,7 +5353,26 @@ var MastraStorageExporter = class extends BaseExporter {
5216
5353
  * that a timer or size trigger started on their own.
5217
5354
  */
5218
5355
  trackFlushBuffer() {
5219
- const promise = this.flushBuffer().finally(() => this.#inFlightFlushes.delete(promise));
5356
+ if (this.#byteTracker) {
5357
+ const concurrency = this.#resolvedStrategy === "insert-only" || this.#resolvedStrategy === "event-sourced" ? this.#byteTracker.config.maxConcurrentWrites : 1;
5358
+ if (this.#inFlightFlushes.size >= concurrency) return Promise.resolve();
5359
+ const delay = this.#byteRetryAt - Date.now();
5360
+ if (delay > 0) {
5361
+ this.scheduleFlush(delay);
5362
+ return Promise.resolve();
5363
+ }
5364
+ }
5365
+ let reschedule = true;
5366
+ const promise = this.flushBuffer().catch((error) => {
5367
+ reschedule = false;
5368
+ throw error;
5369
+ }).finally(() => {
5370
+ this.#inFlightFlushes.delete(promise);
5371
+ if (reschedule && this.#byteTracker && this.#eventBuffer.totalSize > 0) {
5372
+ const delay = Math.max(0, this.#byteRetryAt - Date.now());
5373
+ this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5374
+ }
5375
+ });
5220
5376
  this.#inFlightFlushes.add(promise);
5221
5377
  return promise;
5222
5378
  }
@@ -5244,76 +5400,96 @@ var MastraStorageExporter = class extends BaseExporter {
5244
5400
  if (this.#eventBuffer.totalSize === 0) return;
5245
5401
  const startTime = Date.now();
5246
5402
  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);
5403
+ const { creates, updates } = this.#byteTracker ? this.#eventBuffer.takeByteBatch(this.#config.maxBatchSize) : {
5404
+ creates: this.#eventBuffer.creates,
5405
+ updates: this.#eventBuffer.updates
5406
+ };
5407
+ if (this.#byteTracker && creates.length === 0 && updates.length === 0 && this.#inFlightFlushes.size === 0) {
5408
+ const message = "MastraStorageExporter flush made no progress: queued events have no eligible batch.";
5409
+ this.logger.error(message, { bufferedEvents: this.#eventBuffer.totalSize });
5410
+ throw new Error(message);
5277
5411
  }
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);
5412
+ if (!this.#byteTracker) this.#eventBuffer.reset();
5413
+ try {
5414
+ const createFeedbackEvents = [];
5415
+ const createLogEvents = [];
5416
+ const createMetricEvents = [];
5417
+ const createScoreEvents = [];
5418
+ const createSpanEvents = [];
5419
+ const updateSpanEvents = [];
5420
+ const endSpanEvents = [];
5421
+ for (const createEvent of creates) switch (createEvent.type) {
5422
+ case "feedback":
5423
+ createFeedbackEvents.push(createEvent);
5424
+ break;
5425
+ case "log":
5426
+ createLogEvents.push(createEvent);
5427
+ break;
5428
+ case "metric":
5429
+ createMetricEvents.push(createEvent);
5430
+ break;
5431
+ case "score":
5432
+ createScoreEvents.push(createEvent);
5433
+ break;
5434
+ default: createSpanEvents.push(createEvent);
5301
5435
  }
5436
+ for (const updateEvent of updates) switch (updateEvent.type) {
5437
+ case _mastra_core_observability.TracingEventType.SPAN_UPDATED:
5438
+ updateSpanEvents.push(updateEvent);
5439
+ break;
5440
+ case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5441
+ }
5442
+ const createTasks = [
5443
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)) })),
5444
+ () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
5445
+ () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
5446
+ () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
5447
+ () => this.flushCreates("tracing", createSpanEvents, async (events) => {
5448
+ const records = events.map((t) => (0, _mastra_core_storage.buildCreateSpanRecord)(t.exportedSpan));
5449
+ await this.#observabilityStorage.batchCreateSpans({ records });
5450
+ this.#eventBuffer.addCreatedSpans({ records });
5451
+ })
5452
+ ];
5453
+ const flushResults = [];
5454
+ if (this.#byteTracker) for (const task of createTasks) flushResults.push(await task());
5455
+ else flushResults.push(...await Promise.all(createTasks.map((task) => task())));
5456
+ const deferredUpdates = [];
5457
+ flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5458
+ flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5459
+ let deferredDropCount = 0;
5460
+ if (deferredUpdates.length > 0) {
5461
+ if (this.#unsupportedSignals.has("tracing")) {
5462
+ deferredDropCount = deferredUpdates.length;
5463
+ this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5464
+ deferredUpdates.length = 0;
5465
+ } else {
5466
+ deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5467
+ this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5468
+ }
5469
+ }
5470
+ const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5471
+ if (result.retryAttempt === void 0) return earliestAttempt;
5472
+ return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5473
+ }, void 0);
5474
+ if (retryAttempt !== void 0) {
5475
+ if (this.#byteTracker) this.#byteRetryAt = Date.now() + this.retryDelay(retryAttempt);
5476
+ this.scheduleFlush(this.retryDelay(retryAttempt));
5477
+ }
5478
+ if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5479
+ const elapsed = Date.now() - startTime;
5480
+ this.logger.debug("Batch flushed", {
5481
+ strategy: this.#resolvedStrategy,
5482
+ batchSize,
5483
+ durationMs: elapsed,
5484
+ deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5485
+ });
5486
+ }
5487
+ } finally {
5488
+ this.#eventBuffer.releaseByteBatch([...creates, ...updates]);
5302
5489
  }
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
- });
5316
- }
5490
+ }
5491
+ getByteBatchingStats() {
5492
+ return this.#byteTracker?.stats(this.#inFlightFlushes.size);
5317
5493
  }
5318
5494
  async _exportTracingEvent(event) {
5319
5495
  await this.ensureInitialized();
@@ -5369,6 +5545,21 @@ var MastraStorageExporter = class extends BaseExporter {
5369
5545
  * are exported before the runtime instance is terminated.
5370
5546
  */
5371
5547
  async flush() {
5548
+ if (this.#byteTracker) {
5549
+ if (!this.#observabilityStorage) return;
5550
+ this.#byteDrainers++;
5551
+ try {
5552
+ while (this.#eventBuffer.totalSize || this.#inFlightFlushes.size) {
5553
+ if (this.#inFlightFlushes.size) await Promise.allSettled([...this.#inFlightFlushes]);
5554
+ const delay = this.#byteRetryAt - Date.now();
5555
+ if (delay > 0 && this.#eventBuffer.totalSize) await new Promise((resolve) => setTimeout(resolve, delay));
5556
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5557
+ }
5558
+ } finally {
5559
+ this.#byteDrainers--;
5560
+ }
5561
+ return;
5562
+ }
5372
5563
  for (let round = 0; round < MAX_FLUSH_ROUNDS; round++) {
5373
5564
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5374
5565
  if (this.#eventBuffer.totalSize > 0) {
@@ -5385,10 +5576,22 @@ var MastraStorageExporter = class extends BaseExporter {
5385
5576
  clearTimeout(this.#flushTimer);
5386
5577
  this.#flushTimer = void 0;
5387
5578
  }
5388
- await this.flush();
5389
- if (this.#flushTimer) {
5390
- clearTimeout(this.#flushTimer);
5391
- this.#flushTimer = void 0;
5579
+ try {
5580
+ await this.flush();
5581
+ } catch (error) {
5582
+ const mastraError = new _mastra_core_error.MastraError({
5583
+ id: "MASTRA_STORAGE_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN",
5584
+ domain: _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY,
5585
+ category: _mastra_core_error.ErrorCategory.SYSTEM,
5586
+ details: { remainingEvents: this.#eventBuffer.totalSize }
5587
+ }, error);
5588
+ this.logger.trackException(mastraError);
5589
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
5590
+ } finally {
5591
+ if (this.#flushTimer) {
5592
+ clearTimeout(this.#flushTimer);
5593
+ this.#flushTimer = void 0;
5594
+ }
5392
5595
  }
5393
5596
  this.logger.info("MastraStorageExporter shutdown complete");
5394
5597
  }
@@ -8211,6 +8414,127 @@ var ConsoleExporter = class extends BaseExporter {
8211
8414
  this.logger.info("ConsoleExporter shutdown");
8212
8415
  }
8213
8416
  };
8417
+ // src/exporters/platform-byte-batcher.ts
8418
+ function resolveByteBatchingConfig(config) {
8419
+ const resolved = {
8420
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
8421
+ maxConcurrentUploads: config.maxConcurrentUploads ?? 2,
8422
+ uploadTimeoutMs: config.uploadTimeoutMs ?? 3e4
8423
+ };
8424
+ 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`);
8425
+ if (resolved.maxBatchBytes < 32) throw new Error("byteBatching.maxBatchBytes must be at least 32");
8426
+ if (resolved.uploadTimeoutMs > 2147483647) throw new Error("byteBatching.uploadTimeoutMs must fit in a Node.js timer");
8427
+ return resolved;
8428
+ }
8429
+ /**
8430
+ * Serialize each record once, before retaining it. The accounting includes open
8431
+ * batches, ready batches and uploads until they settle. This tracks retained
8432
+ * JSON bytes for diagnostics; queued bytes are not capped.
8433
+ */
8434
+ var PlatformByteBatcher = class {
8435
+ config;
8436
+ maxBatchSize;
8437
+ maxBatchWaitMs;
8438
+ segments;
8439
+ send;
8440
+ onError;
8441
+ open = /* @__PURE__ */ new Map();
8442
+ ready = [];
8443
+ active = /* @__PURE__ */ new Set();
8444
+ timer;
8445
+ pendingBytes = 0;
8446
+ constructor(config, maxBatchSize, maxBatchWaitMs, segments, send, onError) {
8447
+ this.config = config;
8448
+ this.maxBatchSize = maxBatchSize;
8449
+ this.maxBatchWaitMs = maxBatchWaitMs;
8450
+ this.segments = segments;
8451
+ this.send = send;
8452
+ this.onError = onError;
8453
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte batching mode");
8454
+ if (!Number.isSafeInteger(maxBatchWaitMs) || maxBatchWaitMs <= 0 || maxBatchWaitMs > 2147483647) throw new Error("maxBatchWaitMs must be a positive integer that fits in a Node.js timer");
8455
+ }
8456
+ add(signal, record) {
8457
+ const json = JSON.stringify(record);
8458
+ if (json === void 0) throw new Error("Record has no JSON representation");
8459
+ const prefix = `{"${this.segments[signal]}":[`;
8460
+ const envelopeBytes = Buffer.byteLength(prefix) + 2;
8461
+ const recordBytes = Buffer.byteLength(json);
8462
+ let batch = this.open.get(signal);
8463
+ if (batch && recordBytes + envelopeBytes > this.config.maxBatchBytes) {
8464
+ this.seal(signal);
8465
+ batch = void 0;
8466
+ }
8467
+ const extraBytes = recordBytes + (batch ? 1 : envelopeBytes);
8468
+ if (!batch) {
8469
+ batch = {
8470
+ signal,
8471
+ prefix,
8472
+ records: [],
8473
+ bytes: envelopeBytes
8474
+ };
8475
+ this.open.set(signal, batch);
8476
+ }
8477
+ batch.bytes += recordBytes + (batch.records.length ? 1 : 0);
8478
+ batch.records.push(json);
8479
+ this.pendingBytes += extraBytes;
8480
+ if (batch.records.length >= this.maxBatchSize || batch.bytes >= this.config.maxBatchBytes) this.seal(signal);
8481
+ this.pump();
8482
+ if (this.open.size && !this.timer) this.timer = setTimeout(() => {
8483
+ this.timer = void 0;
8484
+ this.sealAll();
8485
+ this.pump();
8486
+ }, this.maxBatchWaitMs);
8487
+ }
8488
+ seal(signal) {
8489
+ const batch = this.open.get(signal);
8490
+ if (batch) {
8491
+ this.open.delete(signal);
8492
+ this.ready.push(batch);
8493
+ }
8494
+ }
8495
+ sealAll() {
8496
+ if (this.timer) clearTimeout(this.timer);
8497
+ this.timer = void 0;
8498
+ for (const signal of this.open.keys()) this.seal(signal);
8499
+ }
8500
+ pump() {
8501
+ while (this.ready.length && this.active.size < this.config.maxConcurrentUploads) {
8502
+ const batch = this.ready.shift();
8503
+ const task = Promise.resolve().then(async () => {
8504
+ const count = batch.records.length;
8505
+ const body = batch.prefix + batch.records.join(",") + "]}";
8506
+ batch.records = [];
8507
+ await this.send(batch.signal, body, count);
8508
+ }).catch((error) => this.onError(error)).finally(() => {
8509
+ this.pendingBytes -= batch.bytes;
8510
+ this.active.delete(task);
8511
+ this.pump();
8512
+ });
8513
+ this.active.add(task);
8514
+ }
8515
+ }
8516
+ /** Drop unsent batches after auth/quota rejection. In-flight uploads still remain accounted for. */
8517
+ clearQueued() {
8518
+ if (this.timer) clearTimeout(this.timer);
8519
+ this.timer = void 0;
8520
+ for (const batch of [...this.open.values(), ...this.ready]) this.pendingBytes -= batch.bytes;
8521
+ this.open.clear();
8522
+ this.ready = [];
8523
+ }
8524
+ async flush() {
8525
+ do {
8526
+ this.sealAll();
8527
+ this.pump();
8528
+ await Promise.allSettled([...this.active]);
8529
+ } while (this.open.size || this.ready.length || this.active.size);
8530
+ }
8531
+ getStats() {
8532
+ return {
8533
+ pendingBytes: this.pendingBytes,
8534
+ activeUploads: this.active.size
8535
+ };
8536
+ }
8537
+ };
8214
8538
  // src/exporters/mastra-platform.ts
8215
8539
  const SIGNAL_PUBLISH_SUFFIXES = {
8216
8540
  traces: "/spans/publish",
@@ -8334,6 +8658,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8334
8658
  quotaProbeTimer = null;
8335
8659
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
8336
8660
  shuttingDown = false;
8661
+ byteBatcher;
8662
+ byteUploadTimeoutMs;
8337
8663
  constructor(config = {}) {
8338
8664
  super(config);
8339
8665
  if (config.projectId !== void 0 && !VALID_PROJECT_ID.test(config.projectId)) throw createInvalidProjectIdError(config.projectId);
@@ -8371,6 +8697,11 @@ var MastraPlatformExporter = class extends BaseExporter {
8371
8697
  feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config.feedbackEndpoint)
8372
8698
  };
8373
8699
  this.authFailureCooldown = new AuthFailureCooldown("MastraPlatformExporter", () => this.logger);
8700
+ if (config.byteBatching) {
8701
+ const byteConfig = resolveByteBatchingConfig(config.byteBatching);
8702
+ this.byteUploadTimeoutMs = byteConfig.uploadTimeoutMs;
8703
+ 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 }));
8704
+ }
8374
8705
  this.buffer = {
8375
8706
  spans: [],
8376
8707
  logs: [],
@@ -8412,27 +8743,47 @@ var MastraPlatformExporter = class extends BaseExporter {
8412
8743
  await this.handleBufferedEvent();
8413
8744
  }
8414
8745
  addToBuffer(event) {
8746
+ if (this.byteBatcher) {
8747
+ this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
8748
+ return;
8749
+ }
8415
8750
  this.markBufferStart();
8416
8751
  const spanRecord = this.formatSpan(event.exportedSpan);
8417
8752
  this.buffer.spans.push(spanRecord);
8418
8753
  this.buffer.totalSize++;
8419
8754
  }
8420
8755
  addLogToBuffer(event) {
8756
+ if (this.byteBatcher) {
8757
+ this.byteBatcher.add("logs", this.formatLog(event.log));
8758
+ return;
8759
+ }
8421
8760
  this.markBufferStart();
8422
8761
  this.buffer.logs.push(this.formatLog(event.log));
8423
8762
  this.buffer.totalSize++;
8424
8763
  }
8425
8764
  addMetricToBuffer(event) {
8765
+ if (this.byteBatcher) {
8766
+ this.byteBatcher.add("metrics", this.formatMetric(event.metric));
8767
+ return;
8768
+ }
8426
8769
  this.markBufferStart();
8427
8770
  this.buffer.metrics.push(this.formatMetric(event.metric));
8428
8771
  this.buffer.totalSize++;
8429
8772
  }
8430
8773
  addScoreToBuffer(event) {
8774
+ if (this.byteBatcher) {
8775
+ this.byteBatcher.add("scores", this.formatScore(event.score));
8776
+ return;
8777
+ }
8431
8778
  this.markBufferStart();
8432
8779
  this.buffer.scores.push(this.formatScore(event.score));
8433
8780
  this.buffer.totalSize++;
8434
8781
  }
8435
8782
  addFeedbackToBuffer(event) {
8783
+ if (this.byteBatcher) {
8784
+ this.byteBatcher.add("feedback", this.formatFeedback(event.feedback));
8785
+ return;
8786
+ }
8436
8787
  this.markBufferStart();
8437
8788
  this.buffer.feedback.push(this.formatFeedback(event.feedback));
8438
8789
  this.buffer.totalSize++;
@@ -8465,6 +8816,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8465
8816
  return { ...feedback };
8466
8817
  }
8467
8818
  async handleBufferedEvent() {
8819
+ if (this.byteBatcher) return;
8468
8820
  if (this.shouldFlush()) this.flush().catch((error) => {
8469
8821
  this.logger.error("Batch flush failed", { error: error instanceof Error ? error.message : String(error) });
8470
8822
  });
@@ -8561,6 +8913,9 @@ var MastraPlatformExporter = class extends BaseExporter {
8561
8913
  return JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records });
8562
8914
  }
8563
8915
  async batchUpload(signal, records) {
8916
+ await this.uploadBody(signal, this.buildPublishBody(signal, records));
8917
+ }
8918
+ async uploadBody(signal, body) {
8564
8919
  const endpointMap = {
8565
8920
  traces: this.platformConfig.tracesEndpoint,
8566
8921
  logs: this.platformConfig.logsEndpoint,
@@ -8571,7 +8926,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8571
8926
  const options = {
8572
8927
  method: "POST",
8573
8928
  headers: this.buildPublishHeaders(),
8574
- body: this.buildPublishBody(signal, records)
8929
+ body,
8930
+ ...this.byteUploadTimeoutMs ? { signal: AbortSignal.timeout(this.byteUploadTimeoutMs) } : {}
8575
8931
  };
8576
8932
  let quotaResponse;
8577
8933
  let response;
@@ -8591,6 +8947,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8591
8947
  throw error;
8592
8948
  }
8593
8949
  if (isObservabilityDisabled(response)) this.enterQuotaPause(parseQuotaRetryAfterSeconds(response));
8950
+ await response.body?.cancel().catch(() => {});
8594
8951
  }
8595
8952
  /**
8596
8953
  * Enter the quota-exhausted paused state: drop buffered events, stop the
@@ -8602,6 +8959,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8602
8959
  this.quotaProbeIntervalSeconds = retryAfterSeconds;
8603
8960
  if (this.quotaPaused) return;
8604
8961
  this.quotaPaused = true;
8962
+ this.byteBatcher?.clearQueued();
8605
8963
  if (this.flushTimer) {
8606
8964
  clearTimeout(this.flushTimer);
8607
8965
  this.flushTimer = null;
@@ -8650,6 +9008,30 @@ var MastraPlatformExporter = class extends BaseExporter {
8650
9008
  }
8651
9009
  this.scheduleQuotaProbe();
8652
9010
  }
9011
+ /** Current queued and active serialized JSON bytes; undefined in count mode. */
9012
+ getByteBatchingStats() {
9013
+ return this.byteBatcher?.getStats();
9014
+ }
9015
+ async flushByteBatch(signal, body, count) {
9016
+ if (this.quotaPaused || this.authFailureCooldown.dropEventsIfCoolingDown(count)) return;
9017
+ try {
9018
+ await this.uploadBody(signal, body);
9019
+ this.authFailureCooldown.reset();
9020
+ } catch (error) {
9021
+ if (isAuthFailureError(error)) {
9022
+ this.authFailureCooldown.recordFailure({
9023
+ status: error.status,
9024
+ failedSignals: [signal],
9025
+ droppedBatchSize: count
9026
+ });
9027
+ this.byteBatcher?.clearQueued();
9028
+ } else this.logger.error("Byte batch upload failed after retries, dropping batch", {
9029
+ signal,
9030
+ droppedBatchSize: count,
9031
+ error
9032
+ });
9033
+ }
9034
+ }
8653
9035
  async flushSignalBatch(signal, records) {
8654
9036
  if (records.length === 0) return {
8655
9037
  signal,
@@ -8701,6 +9083,10 @@ var MastraPlatformExporter = class extends BaseExporter {
8701
9083
  */
8702
9084
  async flush() {
8703
9085
  if (this.isDisabled) return;
9086
+ if (this.byteBatcher) {
9087
+ await this.byteBatcher.flush();
9088
+ return;
9089
+ }
8704
9090
  while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
8705
9091
  if (this.buffer.totalSize > 0) {
8706
9092
  this.logger.debug("Flushing buffered events", { bufferedEvents: this.buffer.totalSize });
@@ -8733,8 +9119,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8733
9119
  const mastraError = new _mastra_core_error.MastraError({
8734
9120
  id: `MASTRA_PLATFORM_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
8735
9121
  domain: _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY,
8736
- category: _mastra_core_error.ErrorCategory.USER,
8737
- details: { remainingEvents: this.buffer.totalSize }
9122
+ category: _mastra_core_error.ErrorCategory.SYSTEM,
9123
+ details: this.byteBatcher ? { pendingBytes: this.byteBatcher.getStats().pendingBytes } : { remainingEvents: this.buffer.totalSize }
8738
9124
  }, error);
8739
9125
  this.logger.trackException(mastraError);
8740
9126
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
@@ -10307,10 +10693,8 @@ var SensitiveDataFilter = class {
10307
10693
  const filtered = {};
10308
10694
  for (const key of Object.keys(obj)) {
10309
10695
  const normKey = this.normalizeKey(key);
10310
- if (this.isSensitive(normKey)) {
10311
- if (obj[key] && typeof obj[key] === "object") filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10312
- else filtered[key] = this.redactValue(obj[key], normKey, indexedState);
10313
- } else filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10696
+ if (this.isSensitive(normKey)) filtered[key] = obj[key] && typeof obj[key] === "object" ? this.redactionToken : this.redactValue(obj[key], normKey, indexedState);
10697
+ else filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10314
10698
  }
10315
10699
  return filtered;
10316
10700
  }