@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.js CHANGED
@@ -4283,8 +4283,11 @@ var EventBuffer = class {
4283
4283
  #firstEventTime;
4284
4284
  #storageStrategy;
4285
4285
  #maxRetries;
4286
+ #byteTracker;
4287
+ #preferUpdates = false;
4286
4288
  constructor(args) {
4287
4289
  this.#maxRetries = args.maxRetries;
4290
+ this.#byteTracker = args.byteTracker;
4288
4291
  }
4289
4292
  /** Initialize with a storage strategy and replay any pre-init events. */
4290
4293
  init(args) {
@@ -4304,18 +4307,20 @@ var EventBuffer = class {
4304
4307
  if (!this.#firstEventTime) this.#firstEventTime = /* @__PURE__ */ new Date();
4305
4308
  }
4306
4309
  pushCreate(event) {
4307
- this.setFirstEventTime();
4308
- this.#creates.push({
4310
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4309
4311
  ...event,
4310
4312
  retryCount: 0
4311
- });
4313
+ };
4314
+ this.setFirstEventTime();
4315
+ this.#creates.push(buffered);
4312
4316
  }
4313
4317
  pushUpdate(event) {
4314
- this.setFirstEventTime();
4315
- this.#updates.push({
4318
+ const buffered = this.#byteTracker ? this.#byteTracker.capture(event) : {
4316
4319
  ...event,
4317
4320
  retryCount: 0
4318
- });
4321
+ };
4322
+ this.setFirstEventTime();
4323
+ this.#updates.push(buffered);
4319
4324
  }
4320
4325
  /** Route an event to the create or update buffer based on its type and the storage strategy. */
4321
4326
  addEvent(event) {
@@ -4331,8 +4336,8 @@ var EventBuffer = class {
4331
4336
  switch (this.#storageStrategy) {
4332
4337
  case "realtime":
4333
4338
  case "batch-with-updates":
4334
- if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4335
4339
  this.pushCreate(event);
4340
+ if (!event.exportedSpan.isEvent) this.#pendingCreateSpans.add(this.exportedSpanKey(event.exportedSpan));
4336
4341
  break;
4337
4342
  case "event-sourced": this.pushCreate(event);
4338
4343
  }
@@ -4360,8 +4365,10 @@ var EventBuffer = class {
4360
4365
  reAddCreates(events) {
4361
4366
  const retryable = [];
4362
4367
  const dropped = [];
4363
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4364
- else dropped.push(e);
4368
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4369
+ retryable.push(e);
4370
+ this.#byteTracker?.enqueue(e);
4371
+ } else dropped.push(e);
4365
4372
  if (retryable.length > 0) {
4366
4373
  this.setFirstEventTime();
4367
4374
  this.#creates.push(...retryable);
@@ -4372,14 +4379,64 @@ var EventBuffer = class {
4372
4379
  reAddUpdates(events) {
4373
4380
  const retryable = [];
4374
4381
  const dropped = [];
4375
- for (const e of events) if (++e.retryCount <= this.#maxRetries) retryable.push(e);
4376
- else dropped.push(e);
4382
+ for (const e of events) if (++e.retryCount <= this.#maxRetries) {
4383
+ retryable.push(e);
4384
+ this.#byteTracker?.enqueue(e);
4385
+ } else dropped.push(e);
4377
4386
  if (retryable.length > 0) {
4378
4387
  this.setFirstEventTime();
4379
4388
  this.#updates.push(...retryable);
4380
4389
  }
4381
4390
  return dropped;
4382
4391
  }
4392
+ /** Alternate creates and eligible updates so either queue can make progress under load. */
4393
+ takeByteBatch(maxRecords) {
4394
+ const tracker = this.#byteTracker;
4395
+ const creates = [];
4396
+ const updates = [];
4397
+ const selectedUpdates = /* @__PURE__ */ new Set();
4398
+ let updateIndex = 0;
4399
+ let bytes = 0;
4400
+ while (creates.length + updates.length < maxRecords && bytes < tracker.config.maxBatchBytes) {
4401
+ while (updateIndex < this.#updates.length) {
4402
+ const event = this.#updates[updateIndex];
4403
+ if (!("exportedSpan" in event) || !this.isAwaitingCreate(event.exportedSpan)) break;
4404
+ updateIndex++;
4405
+ }
4406
+ const create = this.#creates[creates.length];
4407
+ const update = this.#updates[updateIndex];
4408
+ if (!create && !update) break;
4409
+ const takeUpdate = !!update && (!create || this.#preferUpdates);
4410
+ const event = takeUpdate ? update : create;
4411
+ if (takeUpdate) {
4412
+ updates.push(event);
4413
+ selectedUpdates.add(updateIndex++);
4414
+ } else creates.push(event);
4415
+ this.#preferUpdates = !takeUpdate;
4416
+ tracker.dequeue(event);
4417
+ bytes += tracker.size(event);
4418
+ }
4419
+ this.#creates.splice(0, creates.length);
4420
+ this.#updates = this.#updates.filter((_, index) => !selectedUpdates.has(index));
4421
+ if (this.totalSize === 0) this.#firstEventTime = void 0;
4422
+ return {
4423
+ creates,
4424
+ updates
4425
+ };
4426
+ }
4427
+ /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4428
+ releaseByteBatch(events) {
4429
+ if (!this.#byteTracker) return;
4430
+ for (const event of events) {
4431
+ if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4432
+ this.forgetDroppedCreates([event]);
4433
+ if (event.type === TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4434
+ traceId: event.exportedSpan.traceId,
4435
+ spanId: event.exportedSpan.id,
4436
+ updates: {}
4437
+ }] });
4438
+ }
4439
+ }
4383
4440
  /** Snapshot of buffered create events. */
4384
4441
  get creates() {
4385
4442
  return [...this.#creates];
@@ -4893,6 +4950,67 @@ function withSpanPreviews(span) {
4893
4950
  return span;
4894
4951
  }
4895
4952
  }
4953
+ // src/exporters/storage-byte-tracker.ts
4954
+ function resolveStorageByteBatching(config) {
4955
+ const resolved = {
4956
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
4957
+ maxConcurrentWrites: config.maxConcurrentWrites ?? 1
4958
+ };
4959
+ 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`);
4960
+ return resolved;
4961
+ }
4962
+ /** Counts each admitted event once until persistence or a definitive drop, even across retries. */
4963
+ var StorageByteTracker = class {
4964
+ config;
4965
+ sizes = /* @__PURE__ */ new WeakMap();
4966
+ queued = /* @__PURE__ */ new WeakSet();
4967
+ pendingBytes = 0;
4968
+ pendingRecords = 0;
4969
+ queuedBytes = 0;
4970
+ constructor(config) {
4971
+ this.config = config;
4972
+ }
4973
+ capture(event) {
4974
+ const snapshot = {
4975
+ ...structuredClone(event),
4976
+ retryCount: 0
4977
+ };
4978
+ const bytes = Buffer.byteLength(JSON.stringify(snapshot)) + 1;
4979
+ this.sizes.set(snapshot, bytes);
4980
+ this.pendingBytes += bytes;
4981
+ this.pendingRecords++;
4982
+ this.enqueue(snapshot);
4983
+ return snapshot;
4984
+ }
4985
+ size(event) {
4986
+ return this.sizes.get(event) ?? 0;
4987
+ }
4988
+ enqueue(event) {
4989
+ if (!this.queued.has(event)) {
4990
+ this.queued.add(event);
4991
+ this.queuedBytes += this.size(event);
4992
+ }
4993
+ }
4994
+ dequeue(event) {
4995
+ if (this.queued.delete(event)) this.queuedBytes -= this.size(event);
4996
+ }
4997
+ releaseIfUnqueued(event) {
4998
+ if (this.queued.has(event)) return false;
4999
+ const bytes = this.sizes.get(event);
5000
+ if (bytes === void 0) return false;
5001
+ this.sizes.delete(event);
5002
+ this.pendingBytes -= bytes;
5003
+ this.pendingRecords--;
5004
+ return true;
5005
+ }
5006
+ stats(activeWrites) {
5007
+ return {
5008
+ pendingBytes: this.pendingBytes,
5009
+ pendingRecords: this.pendingRecords,
5010
+ activeWrites
5011
+ };
5012
+ }
5013
+ };
4896
5014
  // src/exporters/mastra-storage.ts
4897
5015
  /**
4898
5016
  * Resolves the final tracing storage strategy based on config and observability store hints
@@ -4923,6 +5041,9 @@ var MastraStorageExporter = class extends BaseExporter {
4923
5041
  #initializationPromise;
4924
5042
  #wasUnavailable = false;
4925
5043
  #eventBuffer;
5044
+ #byteTracker;
5045
+ #byteRetryAt = 0;
5046
+ #byteDrainers = 0;
4926
5047
  #storage;
4927
5048
  #observabilityStorage;
4928
5049
  #resolvedStrategy;
@@ -4942,7 +5063,14 @@ var MastraStorageExporter = class extends BaseExporter {
4942
5063
  retryDelayMs: config.retryDelayMs ?? 500,
4943
5064
  strategy: config.strategy ?? "auto"
4944
5065
  };
4945
- this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
5066
+ if (config.byteBatching) {
5067
+ if (!Number.isSafeInteger(this.#config.maxBatchSize) || this.#config.maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte mode");
5068
+ this.#byteTracker = new StorageByteTracker(resolveStorageByteBatching(config.byteBatching));
5069
+ }
5070
+ this.#eventBuffer = new EventBuffer({
5071
+ maxRetries: this.#config.maxRetries ?? 4,
5072
+ byteTracker: this.#byteTracker
5073
+ });
4946
5074
  }
4947
5075
  /**
4948
5076
  * Initialize the exporter (called after all dependencies are ready)
@@ -4979,6 +5107,11 @@ var MastraStorageExporter = class extends BaseExporter {
4979
5107
  return;
4980
5108
  }
4981
5109
  this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, this.#observabilityStorage, storage.constructor.name, this.logger);
5110
+ if (this.#resolvedStrategy === "realtime" && this.#byteTracker) {
5111
+ this.logger.warn("MastraStorageExporter: byteBatching is ignored for the realtime strategy.");
5112
+ this.#byteTracker = void 0;
5113
+ this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries });
5114
+ }
4982
5115
  this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
4983
5116
  this.logger.debug("tracing storage exporter initialized", {
4984
5117
  strategy: this.#resolvedStrategy,
@@ -5003,6 +5136,7 @@ var MastraStorageExporter = class extends BaseExporter {
5003
5136
  * Checks if buffer should be flushed based on size or time triggers
5004
5137
  */
5005
5138
  shouldFlush() {
5139
+ if (this.#byteTracker && this.#byteTracker.queuedBytes >= this.#byteTracker.config.maxBatchBytes) return true;
5006
5140
  if (this.#resolvedStrategy === "realtime") return true;
5007
5141
  if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
5008
5142
  if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
@@ -5048,8 +5182,11 @@ var MastraStorageExporter = class extends BaseExporter {
5048
5182
  * Returns the flush promise when flushing so callers can await it.
5049
5183
  */
5050
5184
  async handleBatchedFlush() {
5051
- if (this.shouldFlush()) await this.trackFlushBuffer();
5052
- else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5185
+ if (this.shouldFlush()) {
5186
+ const writing = this.trackFlushBuffer();
5187
+ if (this.#byteTracker) writing.catch((error) => this.logger.error("Byte batch flush failed", { error }));
5188
+ else await writing;
5189
+ } else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
5053
5190
  }
5054
5191
  sanitizeDropError(error) {
5055
5192
  if (error instanceof MastraError) return {
@@ -5191,7 +5328,26 @@ var MastraStorageExporter = class extends BaseExporter {
5191
5328
  * that a timer or size trigger started on their own.
5192
5329
  */
5193
5330
  trackFlushBuffer() {
5194
- const promise = this.flushBuffer().finally(() => this.#inFlightFlushes.delete(promise));
5331
+ if (this.#byteTracker) {
5332
+ const concurrency = this.#resolvedStrategy === "insert-only" || this.#resolvedStrategy === "event-sourced" ? this.#byteTracker.config.maxConcurrentWrites : 1;
5333
+ if (this.#inFlightFlushes.size >= concurrency) return Promise.resolve();
5334
+ const delay = this.#byteRetryAt - Date.now();
5335
+ if (delay > 0) {
5336
+ this.scheduleFlush(delay);
5337
+ return Promise.resolve();
5338
+ }
5339
+ }
5340
+ let reschedule = true;
5341
+ const promise = this.flushBuffer().catch((error) => {
5342
+ reschedule = false;
5343
+ throw error;
5344
+ }).finally(() => {
5345
+ this.#inFlightFlushes.delete(promise);
5346
+ if (reschedule && this.#byteTracker && this.#eventBuffer.totalSize > 0) {
5347
+ const delay = Math.max(0, this.#byteRetryAt - Date.now());
5348
+ this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5349
+ }
5350
+ });
5195
5351
  this.#inFlightFlushes.add(promise);
5196
5352
  return promise;
5197
5353
  }
@@ -5219,76 +5375,96 @@ var MastraStorageExporter = class extends BaseExporter {
5219
5375
  if (this.#eventBuffer.totalSize === 0) return;
5220
5376
  const startTime = Date.now();
5221
5377
  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);
5378
+ const { creates, updates } = this.#byteTracker ? this.#eventBuffer.takeByteBatch(this.#config.maxBatchSize) : {
5379
+ creates: this.#eventBuffer.creates,
5380
+ updates: this.#eventBuffer.updates
5381
+ };
5382
+ if (this.#byteTracker && creates.length === 0 && updates.length === 0 && this.#inFlightFlushes.size === 0) {
5383
+ const message = "MastraStorageExporter flush made no progress: queued events have no eligible batch.";
5384
+ this.logger.error(message, { bufferedEvents: this.#eventBuffer.totalSize });
5385
+ throw new Error(message);
5252
5386
  }
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);
5387
+ if (!this.#byteTracker) this.#eventBuffer.reset();
5388
+ try {
5389
+ const createFeedbackEvents = [];
5390
+ const createLogEvents = [];
5391
+ const createMetricEvents = [];
5392
+ const createScoreEvents = [];
5393
+ const createSpanEvents = [];
5394
+ const updateSpanEvents = [];
5395
+ const endSpanEvents = [];
5396
+ for (const createEvent of creates) switch (createEvent.type) {
5397
+ case "feedback":
5398
+ createFeedbackEvents.push(createEvent);
5399
+ break;
5400
+ case "log":
5401
+ createLogEvents.push(createEvent);
5402
+ break;
5403
+ case "metric":
5404
+ createMetricEvents.push(createEvent);
5405
+ break;
5406
+ case "score":
5407
+ createScoreEvents.push(createEvent);
5408
+ break;
5409
+ default: createSpanEvents.push(createEvent);
5276
5410
  }
5411
+ for (const updateEvent of updates) switch (updateEvent.type) {
5412
+ case TracingEventType.SPAN_UPDATED:
5413
+ updateSpanEvents.push(updateEvent);
5414
+ break;
5415
+ case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
5416
+ }
5417
+ const createTasks = [
5418
+ () => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({ feedbacks: events.map((f) => buildFeedbackRecord(f)) })),
5419
+ () => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
5420
+ () => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
5421
+ () => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
5422
+ () => this.flushCreates("tracing", createSpanEvents, async (events) => {
5423
+ const records = events.map((t) => buildCreateSpanRecord(t.exportedSpan));
5424
+ await this.#observabilityStorage.batchCreateSpans({ records });
5425
+ this.#eventBuffer.addCreatedSpans({ records });
5426
+ })
5427
+ ];
5428
+ const flushResults = [];
5429
+ if (this.#byteTracker) for (const task of createTasks) flushResults.push(await task());
5430
+ else flushResults.push(...await Promise.all(createTasks.map((task) => task())));
5431
+ const deferredUpdates = [];
5432
+ flushResults.push(await this.flushSpanUpdates(updateSpanEvents, deferredUpdates, false));
5433
+ flushResults.push(await this.flushSpanUpdates(endSpanEvents, deferredUpdates, true));
5434
+ let deferredDropCount = 0;
5435
+ if (deferredUpdates.length > 0) {
5436
+ if (this.#unsupportedSignals.has("tracing")) {
5437
+ deferredDropCount = deferredUpdates.length;
5438
+ this.emitDrop("tracing", "unsupported-storage", deferredDropCount);
5439
+ deferredUpdates.length = 0;
5440
+ } else {
5441
+ deferredDropCount = this.#eventBuffer.reAddUpdates(deferredUpdates).length;
5442
+ this.emitDrop("tracing", "retry-exhausted", deferredDropCount);
5443
+ }
5444
+ }
5445
+ const retryAttempt = flushResults.reduce((earliestAttempt, result) => {
5446
+ if (result.retryAttempt === void 0) return earliestAttempt;
5447
+ return earliestAttempt === void 0 ? result.retryAttempt : Math.min(earliestAttempt, result.retryAttempt);
5448
+ }, void 0);
5449
+ if (retryAttempt !== void 0) {
5450
+ if (this.#byteTracker) this.#byteRetryAt = Date.now() + this.retryDelay(retryAttempt);
5451
+ this.scheduleFlush(this.retryDelay(retryAttempt));
5452
+ }
5453
+ if (!flushResults.some((result) => result.failed) && deferredDropCount === 0) {
5454
+ const elapsed = Date.now() - startTime;
5455
+ this.logger.debug("Batch flushed", {
5456
+ strategy: this.#resolvedStrategy,
5457
+ batchSize,
5458
+ durationMs: elapsed,
5459
+ deferredUpdates: deferredUpdates.length > 0 ? deferredUpdates.length : void 0
5460
+ });
5461
+ }
5462
+ } finally {
5463
+ this.#eventBuffer.releaseByteBatch([...creates, ...updates]);
5277
5464
  }
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
- });
5291
- }
5465
+ }
5466
+ getByteBatchingStats() {
5467
+ return this.#byteTracker?.stats(this.#inFlightFlushes.size);
5292
5468
  }
5293
5469
  async _exportTracingEvent(event) {
5294
5470
  await this.ensureInitialized();
@@ -5344,6 +5520,21 @@ var MastraStorageExporter = class extends BaseExporter {
5344
5520
  * are exported before the runtime instance is terminated.
5345
5521
  */
5346
5522
  async flush() {
5523
+ if (this.#byteTracker) {
5524
+ if (!this.#observabilityStorage) return;
5525
+ this.#byteDrainers++;
5526
+ try {
5527
+ while (this.#eventBuffer.totalSize || this.#inFlightFlushes.size) {
5528
+ if (this.#inFlightFlushes.size) await Promise.allSettled([...this.#inFlightFlushes]);
5529
+ const delay = this.#byteRetryAt - Date.now();
5530
+ if (delay > 0 && this.#eventBuffer.totalSize) await new Promise((resolve) => setTimeout(resolve, delay));
5531
+ if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
5532
+ }
5533
+ } finally {
5534
+ this.#byteDrainers--;
5535
+ }
5536
+ return;
5537
+ }
5347
5538
  for (let round = 0; round < MAX_FLUSH_ROUNDS; round++) {
5348
5539
  if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
5349
5540
  if (this.#eventBuffer.totalSize > 0) {
@@ -5360,10 +5551,22 @@ var MastraStorageExporter = class extends BaseExporter {
5360
5551
  clearTimeout(this.#flushTimer);
5361
5552
  this.#flushTimer = void 0;
5362
5553
  }
5363
- await this.flush();
5364
- if (this.#flushTimer) {
5365
- clearTimeout(this.#flushTimer);
5366
- this.#flushTimer = void 0;
5554
+ try {
5555
+ await this.flush();
5556
+ } catch (error) {
5557
+ const mastraError = new MastraError({
5558
+ id: "MASTRA_STORAGE_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN",
5559
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
5560
+ category: ErrorCategory.SYSTEM,
5561
+ details: { remainingEvents: this.#eventBuffer.totalSize }
5562
+ }, error);
5563
+ this.logger.trackException(mastraError);
5564
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
5565
+ } finally {
5566
+ if (this.#flushTimer) {
5567
+ clearTimeout(this.#flushTimer);
5568
+ this.#flushTimer = void 0;
5569
+ }
5367
5570
  }
5368
5571
  this.logger.info("MastraStorageExporter shutdown complete");
5369
5572
  }
@@ -8186,6 +8389,127 @@ var ConsoleExporter = class extends BaseExporter {
8186
8389
  this.logger.info("ConsoleExporter shutdown");
8187
8390
  }
8188
8391
  };
8392
+ // src/exporters/platform-byte-batcher.ts
8393
+ function resolveByteBatchingConfig(config) {
8394
+ const resolved = {
8395
+ maxBatchBytes: config.maxBatchBytes ?? 8388608,
8396
+ maxConcurrentUploads: config.maxConcurrentUploads ?? 2,
8397
+ uploadTimeoutMs: config.uploadTimeoutMs ?? 3e4
8398
+ };
8399
+ 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`);
8400
+ if (resolved.maxBatchBytes < 32) throw new Error("byteBatching.maxBatchBytes must be at least 32");
8401
+ if (resolved.uploadTimeoutMs > 2147483647) throw new Error("byteBatching.uploadTimeoutMs must fit in a Node.js timer");
8402
+ return resolved;
8403
+ }
8404
+ /**
8405
+ * Serialize each record once, before retaining it. The accounting includes open
8406
+ * batches, ready batches and uploads until they settle. This tracks retained
8407
+ * JSON bytes for diagnostics; queued bytes are not capped.
8408
+ */
8409
+ var PlatformByteBatcher = class {
8410
+ config;
8411
+ maxBatchSize;
8412
+ maxBatchWaitMs;
8413
+ segments;
8414
+ send;
8415
+ onError;
8416
+ open = /* @__PURE__ */ new Map();
8417
+ ready = [];
8418
+ active = /* @__PURE__ */ new Set();
8419
+ timer;
8420
+ pendingBytes = 0;
8421
+ constructor(config, maxBatchSize, maxBatchWaitMs, segments, send, onError) {
8422
+ this.config = config;
8423
+ this.maxBatchSize = maxBatchSize;
8424
+ this.maxBatchWaitMs = maxBatchWaitMs;
8425
+ this.segments = segments;
8426
+ this.send = send;
8427
+ this.onError = onError;
8428
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize <= 0) throw new Error("maxBatchSize must be a positive safe integer in byte batching mode");
8429
+ if (!Number.isSafeInteger(maxBatchWaitMs) || maxBatchWaitMs <= 0 || maxBatchWaitMs > 2147483647) throw new Error("maxBatchWaitMs must be a positive integer that fits in a Node.js timer");
8430
+ }
8431
+ add(signal, record) {
8432
+ const json = JSON.stringify(record);
8433
+ if (json === void 0) throw new Error("Record has no JSON representation");
8434
+ const prefix = `{"${this.segments[signal]}":[`;
8435
+ const envelopeBytes = Buffer.byteLength(prefix) + 2;
8436
+ const recordBytes = Buffer.byteLength(json);
8437
+ let batch = this.open.get(signal);
8438
+ if (batch && recordBytes + envelopeBytes > this.config.maxBatchBytes) {
8439
+ this.seal(signal);
8440
+ batch = void 0;
8441
+ }
8442
+ const extraBytes = recordBytes + (batch ? 1 : envelopeBytes);
8443
+ if (!batch) {
8444
+ batch = {
8445
+ signal,
8446
+ prefix,
8447
+ records: [],
8448
+ bytes: envelopeBytes
8449
+ };
8450
+ this.open.set(signal, batch);
8451
+ }
8452
+ batch.bytes += recordBytes + (batch.records.length ? 1 : 0);
8453
+ batch.records.push(json);
8454
+ this.pendingBytes += extraBytes;
8455
+ if (batch.records.length >= this.maxBatchSize || batch.bytes >= this.config.maxBatchBytes) this.seal(signal);
8456
+ this.pump();
8457
+ if (this.open.size && !this.timer) this.timer = setTimeout(() => {
8458
+ this.timer = void 0;
8459
+ this.sealAll();
8460
+ this.pump();
8461
+ }, this.maxBatchWaitMs);
8462
+ }
8463
+ seal(signal) {
8464
+ const batch = this.open.get(signal);
8465
+ if (batch) {
8466
+ this.open.delete(signal);
8467
+ this.ready.push(batch);
8468
+ }
8469
+ }
8470
+ sealAll() {
8471
+ if (this.timer) clearTimeout(this.timer);
8472
+ this.timer = void 0;
8473
+ for (const signal of this.open.keys()) this.seal(signal);
8474
+ }
8475
+ pump() {
8476
+ while (this.ready.length && this.active.size < this.config.maxConcurrentUploads) {
8477
+ const batch = this.ready.shift();
8478
+ const task = Promise.resolve().then(async () => {
8479
+ const count = batch.records.length;
8480
+ const body = batch.prefix + batch.records.join(",") + "]}";
8481
+ batch.records = [];
8482
+ await this.send(batch.signal, body, count);
8483
+ }).catch((error) => this.onError(error)).finally(() => {
8484
+ this.pendingBytes -= batch.bytes;
8485
+ this.active.delete(task);
8486
+ this.pump();
8487
+ });
8488
+ this.active.add(task);
8489
+ }
8490
+ }
8491
+ /** Drop unsent batches after auth/quota rejection. In-flight uploads still remain accounted for. */
8492
+ clearQueued() {
8493
+ if (this.timer) clearTimeout(this.timer);
8494
+ this.timer = void 0;
8495
+ for (const batch of [...this.open.values(), ...this.ready]) this.pendingBytes -= batch.bytes;
8496
+ this.open.clear();
8497
+ this.ready = [];
8498
+ }
8499
+ async flush() {
8500
+ do {
8501
+ this.sealAll();
8502
+ this.pump();
8503
+ await Promise.allSettled([...this.active]);
8504
+ } while (this.open.size || this.ready.length || this.active.size);
8505
+ }
8506
+ getStats() {
8507
+ return {
8508
+ pendingBytes: this.pendingBytes,
8509
+ activeUploads: this.active.size
8510
+ };
8511
+ }
8512
+ };
8189
8513
  // src/exporters/mastra-platform.ts
8190
8514
  const SIGNAL_PUBLISH_SUFFIXES = {
8191
8515
  traces: "/spans/publish",
@@ -8309,6 +8633,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8309
8633
  quotaProbeTimer = null;
8310
8634
  quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
8311
8635
  shuttingDown = false;
8636
+ byteBatcher;
8637
+ byteUploadTimeoutMs;
8312
8638
  constructor(config = {}) {
8313
8639
  super(config);
8314
8640
  if (config.projectId !== void 0 && !VALID_PROJECT_ID.test(config.projectId)) throw createInvalidProjectIdError(config.projectId);
@@ -8346,6 +8672,11 @@ var MastraPlatformExporter = class extends BaseExporter {
8346
8672
  feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config.feedbackEndpoint)
8347
8673
  };
8348
8674
  this.authFailureCooldown = new AuthFailureCooldown("MastraPlatformExporter", () => this.logger);
8675
+ if (config.byteBatching) {
8676
+ const byteConfig = resolveByteBatchingConfig(config.byteBatching);
8677
+ this.byteUploadTimeoutMs = byteConfig.uploadTimeoutMs;
8678
+ 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 }));
8679
+ }
8349
8680
  this.buffer = {
8350
8681
  spans: [],
8351
8682
  logs: [],
@@ -8387,27 +8718,47 @@ var MastraPlatformExporter = class extends BaseExporter {
8387
8718
  await this.handleBufferedEvent();
8388
8719
  }
8389
8720
  addToBuffer(event) {
8721
+ if (this.byteBatcher) {
8722
+ this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
8723
+ return;
8724
+ }
8390
8725
  this.markBufferStart();
8391
8726
  const spanRecord = this.formatSpan(event.exportedSpan);
8392
8727
  this.buffer.spans.push(spanRecord);
8393
8728
  this.buffer.totalSize++;
8394
8729
  }
8395
8730
  addLogToBuffer(event) {
8731
+ if (this.byteBatcher) {
8732
+ this.byteBatcher.add("logs", this.formatLog(event.log));
8733
+ return;
8734
+ }
8396
8735
  this.markBufferStart();
8397
8736
  this.buffer.logs.push(this.formatLog(event.log));
8398
8737
  this.buffer.totalSize++;
8399
8738
  }
8400
8739
  addMetricToBuffer(event) {
8740
+ if (this.byteBatcher) {
8741
+ this.byteBatcher.add("metrics", this.formatMetric(event.metric));
8742
+ return;
8743
+ }
8401
8744
  this.markBufferStart();
8402
8745
  this.buffer.metrics.push(this.formatMetric(event.metric));
8403
8746
  this.buffer.totalSize++;
8404
8747
  }
8405
8748
  addScoreToBuffer(event) {
8749
+ if (this.byteBatcher) {
8750
+ this.byteBatcher.add("scores", this.formatScore(event.score));
8751
+ return;
8752
+ }
8406
8753
  this.markBufferStart();
8407
8754
  this.buffer.scores.push(this.formatScore(event.score));
8408
8755
  this.buffer.totalSize++;
8409
8756
  }
8410
8757
  addFeedbackToBuffer(event) {
8758
+ if (this.byteBatcher) {
8759
+ this.byteBatcher.add("feedback", this.formatFeedback(event.feedback));
8760
+ return;
8761
+ }
8411
8762
  this.markBufferStart();
8412
8763
  this.buffer.feedback.push(this.formatFeedback(event.feedback));
8413
8764
  this.buffer.totalSize++;
@@ -8440,6 +8791,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8440
8791
  return { ...feedback };
8441
8792
  }
8442
8793
  async handleBufferedEvent() {
8794
+ if (this.byteBatcher) return;
8443
8795
  if (this.shouldFlush()) this.flush().catch((error) => {
8444
8796
  this.logger.error("Batch flush failed", { error: error instanceof Error ? error.message : String(error) });
8445
8797
  });
@@ -8536,6 +8888,9 @@ var MastraPlatformExporter = class extends BaseExporter {
8536
8888
  return JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records });
8537
8889
  }
8538
8890
  async batchUpload(signal, records) {
8891
+ await this.uploadBody(signal, this.buildPublishBody(signal, records));
8892
+ }
8893
+ async uploadBody(signal, body) {
8539
8894
  const endpointMap = {
8540
8895
  traces: this.platformConfig.tracesEndpoint,
8541
8896
  logs: this.platformConfig.logsEndpoint,
@@ -8546,7 +8901,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8546
8901
  const options = {
8547
8902
  method: "POST",
8548
8903
  headers: this.buildPublishHeaders(),
8549
- body: this.buildPublishBody(signal, records)
8904
+ body,
8905
+ ...this.byteUploadTimeoutMs ? { signal: AbortSignal.timeout(this.byteUploadTimeoutMs) } : {}
8550
8906
  };
8551
8907
  let quotaResponse;
8552
8908
  let response;
@@ -8566,6 +8922,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8566
8922
  throw error;
8567
8923
  }
8568
8924
  if (isObservabilityDisabled(response)) this.enterQuotaPause(parseQuotaRetryAfterSeconds(response));
8925
+ await response.body?.cancel().catch(() => {});
8569
8926
  }
8570
8927
  /**
8571
8928
  * Enter the quota-exhausted paused state: drop buffered events, stop the
@@ -8577,6 +8934,7 @@ var MastraPlatformExporter = class extends BaseExporter {
8577
8934
  this.quotaProbeIntervalSeconds = retryAfterSeconds;
8578
8935
  if (this.quotaPaused) return;
8579
8936
  this.quotaPaused = true;
8937
+ this.byteBatcher?.clearQueued();
8580
8938
  if (this.flushTimer) {
8581
8939
  clearTimeout(this.flushTimer);
8582
8940
  this.flushTimer = null;
@@ -8625,6 +8983,30 @@ var MastraPlatformExporter = class extends BaseExporter {
8625
8983
  }
8626
8984
  this.scheduleQuotaProbe();
8627
8985
  }
8986
+ /** Current queued and active serialized JSON bytes; undefined in count mode. */
8987
+ getByteBatchingStats() {
8988
+ return this.byteBatcher?.getStats();
8989
+ }
8990
+ async flushByteBatch(signal, body, count) {
8991
+ if (this.quotaPaused || this.authFailureCooldown.dropEventsIfCoolingDown(count)) return;
8992
+ try {
8993
+ await this.uploadBody(signal, body);
8994
+ this.authFailureCooldown.reset();
8995
+ } catch (error) {
8996
+ if (isAuthFailureError(error)) {
8997
+ this.authFailureCooldown.recordFailure({
8998
+ status: error.status,
8999
+ failedSignals: [signal],
9000
+ droppedBatchSize: count
9001
+ });
9002
+ this.byteBatcher?.clearQueued();
9003
+ } else this.logger.error("Byte batch upload failed after retries, dropping batch", {
9004
+ signal,
9005
+ droppedBatchSize: count,
9006
+ error
9007
+ });
9008
+ }
9009
+ }
8628
9010
  async flushSignalBatch(signal, records) {
8629
9011
  if (records.length === 0) return {
8630
9012
  signal,
@@ -8676,6 +9058,10 @@ var MastraPlatformExporter = class extends BaseExporter {
8676
9058
  */
8677
9059
  async flush() {
8678
9060
  if (this.isDisabled) return;
9061
+ if (this.byteBatcher) {
9062
+ await this.byteBatcher.flush();
9063
+ return;
9064
+ }
8679
9065
  while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
8680
9066
  if (this.buffer.totalSize > 0) {
8681
9067
  this.logger.debug("Flushing buffered events", { bufferedEvents: this.buffer.totalSize });
@@ -8708,8 +9094,8 @@ var MastraPlatformExporter = class extends BaseExporter {
8708
9094
  const mastraError = new MastraError({
8709
9095
  id: `MASTRA_PLATFORM_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
8710
9096
  domain: ErrorDomain.MASTRA_OBSERVABILITY,
8711
- category: ErrorCategory.USER,
8712
- details: { remainingEvents: this.buffer.totalSize }
9097
+ category: ErrorCategory.SYSTEM,
9098
+ details: this.byteBatcher ? { pendingBytes: this.byteBatcher.getStats().pendingBytes } : { remainingEvents: this.buffer.totalSize }
8713
9099
  }, error);
8714
9100
  this.logger.trackException(mastraError);
8715
9101
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
@@ -10282,10 +10668,8 @@ var SensitiveDataFilter = class {
10282
10668
  const filtered = {};
10283
10669
  for (const key of Object.keys(obj)) {
10284
10670
  const normKey = this.normalizeKey(key);
10285
- if (this.isSensitive(normKey)) {
10286
- if (obj[key] && typeof obj[key] === "object") filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10287
- else filtered[key] = this.redactValue(obj[key], normKey, indexedState);
10288
- } else filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10671
+ if (this.isSensitive(normKey)) filtered[key] = obj[key] && typeof obj[key] === "object" ? this.redactionToken : this.redactValue(obj[key], normKey, indexedState);
10672
+ else filtered[key] = this.deepFilter(obj[key], seen, indexedState);
10289
10673
  }
10290
10674
  return filtered;
10291
10675
  }