@mastra/observability 1.0.0-beta.10 → 1.0.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4163,12 +4163,19 @@ var observabilityRegistryConfigSchema = external_exports.object({
4163
4163
  var BaseExporter = class {
4164
4164
  /** Mastra logger instance */
4165
4165
  logger;
4166
+ /** Base configuration (accessible by subclasses) */
4167
+ baseConfig;
4166
4168
  /** Whether this exporter is disabled */
4167
- isDisabled = false;
4169
+ #disabled = false;
4170
+ /** Public getter for disabled state */
4171
+ get isDisabled() {
4172
+ return this.#disabled;
4173
+ }
4168
4174
  /**
4169
4175
  * Initialize the base exporter with logger
4170
4176
  */
4171
4177
  constructor(config = {}) {
4178
+ this.baseConfig = config;
4172
4179
  const logLevel = this.resolveLogLevel(config.logLevel);
4173
4180
  this.logger = config.logger ?? new logger.ConsoleLogger({ level: logLevel, name: this.constructor.name });
4174
4181
  }
@@ -4203,20 +4210,50 @@ var BaseExporter = class {
4203
4210
  * @param reason - Reason why the exporter is disabled
4204
4211
  */
4205
4212
  setDisabled(reason) {
4206
- this.isDisabled = true;
4213
+ this.#disabled = true;
4207
4214
  this.logger.warn(`${this.name} disabled: ${reason}`);
4208
4215
  }
4216
+ /**
4217
+ * Apply the customSpanFormatter if configured.
4218
+ * This is called automatically by exportTracingEvent before _exportTracingEvent.
4219
+ *
4220
+ * Supports both synchronous and asynchronous formatters. If the formatter
4221
+ * returns a Promise, it will be awaited.
4222
+ *
4223
+ * @param event - The incoming tracing event
4224
+ * @returns The (possibly modified) event to process
4225
+ */
4226
+ async applySpanFormatter(event) {
4227
+ if (this.baseConfig.customSpanFormatter) {
4228
+ try {
4229
+ const formattedSpan = await this.baseConfig.customSpanFormatter(event.exportedSpan);
4230
+ return {
4231
+ ...event,
4232
+ exportedSpan: formattedSpan
4233
+ };
4234
+ } catch (error) {
4235
+ this.logger.error(`${this.name}: Error in customSpanFormatter`, {
4236
+ error,
4237
+ spanId: event.exportedSpan.id,
4238
+ traceId: event.exportedSpan.traceId
4239
+ });
4240
+ }
4241
+ }
4242
+ return event;
4243
+ }
4209
4244
  /**
4210
4245
  * Export a tracing event
4211
4246
  *
4212
- * This method checks if the exporter is disabled before calling _exportEvent.
4213
- * Subclasses should implement _exportEvent instead of overriding this method.
4247
+ * This method checks if the exporter is disabled, applies the customSpanFormatter,
4248
+ * then calls _exportTracingEvent.
4249
+ * Subclasses should implement _exportTracingEvent instead of overriding this method.
4214
4250
  */
4215
4251
  async exportTracingEvent(event) {
4216
4252
  if (this.isDisabled) {
4217
4253
  return;
4218
4254
  }
4219
- await this._exportTracingEvent(event);
4255
+ const processedEvent = await this.applySpanFormatter(event);
4256
+ await this._exportTracingEvent(processedEvent);
4220
4257
  }
4221
4258
  /**
4222
4259
  * Shutdown the exporter and clean up resources
@@ -4227,9 +4264,957 @@ var BaseExporter = class {
4227
4264
  this.logger.info(`${this.name} shutdown complete`);
4228
4265
  }
4229
4266
  };
4267
+ var TraceData = class {
4268
+ /** The vendor-specific root/trace object */
4269
+ #rootSpan;
4270
+ /** The span ID of the root span */
4271
+ #rootSpanId;
4272
+ /** Whether a span with isRootSpan=true has been successfully processed */
4273
+ #rootSpanProcessed;
4274
+ /** Maps eventId to vendor-specific event objects */
4275
+ #events;
4276
+ /** Maps spanId to vendor-specific span objects */
4277
+ #spans;
4278
+ /** Maps spanId to parentSpanId, representing the span hierarchy */
4279
+ #tree;
4280
+ /** Set of span IDs that have started but not yet ended */
4281
+ #activeSpanIds;
4282
+ /** Maps spanId to vendor-specific metadata */
4283
+ #metadata;
4284
+ /** Arbitrary key-value storage for per-trace data */
4285
+ #extraData;
4286
+ /** Events waiting for the root span to be processed */
4287
+ #waitingForRoot;
4288
+ /** Events waiting for specific parent spans, keyed by parentSpanId */
4289
+ #waitingForParent;
4290
+ /** When this trace data was created, used for cap enforcement */
4291
+ createdAt;
4292
+ constructor() {
4293
+ this.#events = /* @__PURE__ */ new Map();
4294
+ this.#spans = /* @__PURE__ */ new Map();
4295
+ this.#activeSpanIds = /* @__PURE__ */ new Set();
4296
+ this.#tree = /* @__PURE__ */ new Map();
4297
+ this.#metadata = /* @__PURE__ */ new Map();
4298
+ this.#extraData = /* @__PURE__ */ new Map();
4299
+ this.#rootSpanProcessed = false;
4300
+ this.#waitingForRoot = [];
4301
+ this.#waitingForParent = /* @__PURE__ */ new Map();
4302
+ this.createdAt = /* @__PURE__ */ new Date();
4303
+ }
4304
+ /**
4305
+ * Check if this trace has a root span registered.
4306
+ * @returns True if addRoot() has been called
4307
+ */
4308
+ hasRoot() {
4309
+ return !!this.#rootSpanId;
4310
+ }
4311
+ /**
4312
+ * Register the root span for this trace.
4313
+ * @param args.rootId - The span ID of the root span
4314
+ * @param args.rootData - The vendor-specific root object
4315
+ */
4316
+ addRoot(args) {
4317
+ this.#rootSpanId = args.rootId;
4318
+ this.#rootSpan = args.rootData;
4319
+ this.#rootSpanProcessed = true;
4320
+ }
4321
+ /**
4322
+ * Get the vendor-specific root object.
4323
+ * @returns The root object, or undefined if not yet set
4324
+ */
4325
+ getRoot() {
4326
+ return this.#rootSpan;
4327
+ }
4328
+ /**
4329
+ * Check if a span with isRootSpan=true has been successfully processed.
4330
+ * Set via addRoot() or markRootSpanProcessed().
4331
+ * @returns True if the root span has been processed
4332
+ */
4333
+ isRootProcessed() {
4334
+ return this.#rootSpanProcessed;
4335
+ }
4336
+ /**
4337
+ * Mark that the root span has been processed.
4338
+ * Used by exporters with skipBuildRootTask=true where root goes through _buildSpan
4339
+ * instead of _buildRoot.
4340
+ */
4341
+ markRootSpanProcessed() {
4342
+ this.#rootSpanProcessed = true;
4343
+ }
4344
+ /**
4345
+ * Store an arbitrary value in per-trace storage.
4346
+ * @param key - Storage key
4347
+ * @param value - Value to store
4348
+ */
4349
+ setExtraValue(key, value) {
4350
+ this.#extraData.set(key, value);
4351
+ }
4352
+ /**
4353
+ * Check if a key exists in per-trace storage.
4354
+ * @param key - Storage key
4355
+ * @returns True if the key exists
4356
+ */
4357
+ hasExtraValue(key) {
4358
+ return this.#extraData.has(key);
4359
+ }
4360
+ /**
4361
+ * Get a value from per-trace storage.
4362
+ * @param key - Storage key
4363
+ * @returns The stored value, or undefined if not found
4364
+ */
4365
+ getExtraValue(key) {
4366
+ return this.#extraData.get(key);
4367
+ }
4368
+ // ============================================================================
4369
+ // Early Queue Methods
4370
+ // ============================================================================
4371
+ /**
4372
+ * Add an event to the waiting queue.
4373
+ * @param args.event - The tracing event to queue
4374
+ * @param args.waitingFor - 'root' or a specific parentSpanId
4375
+ * @param args.attempts - Optional: preserve attempts count when re-queuing
4376
+ * @param args.queuedAt - Optional: preserve original queue time when re-queuing
4377
+ */
4378
+ addToWaitingQueue(args) {
4379
+ const queuedEvent = {
4380
+ event: args.event,
4381
+ waitingFor: args.waitingFor,
4382
+ attempts: args.attempts ?? 0,
4383
+ queuedAt: args.queuedAt ?? /* @__PURE__ */ new Date()
4384
+ };
4385
+ if (args.waitingFor === "root") {
4386
+ this.#waitingForRoot.push(queuedEvent);
4387
+ } else {
4388
+ const queue = this.#waitingForParent.get(args.waitingFor) ?? [];
4389
+ queue.push(queuedEvent);
4390
+ this.#waitingForParent.set(args.waitingFor, queue);
4391
+ }
4392
+ }
4393
+ /**
4394
+ * Get all events waiting for the root span.
4395
+ * Returns a copy of the internal array.
4396
+ */
4397
+ getEventsWaitingForRoot() {
4398
+ return [...this.#waitingForRoot];
4399
+ }
4400
+ /**
4401
+ * Get all events waiting for a specific parent span.
4402
+ * Returns a copy of the internal array.
4403
+ */
4404
+ getEventsWaitingFor(args) {
4405
+ return [...this.#waitingForParent.get(args.spanId) ?? []];
4406
+ }
4407
+ /**
4408
+ * Clear the waiting-for-root queue.
4409
+ */
4410
+ clearWaitingForRoot() {
4411
+ this.#waitingForRoot = [];
4412
+ }
4413
+ /**
4414
+ * Clear the waiting queue for a specific parent span.
4415
+ */
4416
+ clearWaitingFor(args) {
4417
+ this.#waitingForParent.delete(args.spanId);
4418
+ }
4419
+ /**
4420
+ * Get total count of events in all waiting queues.
4421
+ */
4422
+ waitingQueueSize() {
4423
+ let count = this.#waitingForRoot.length;
4424
+ for (const queue of this.#waitingForParent.values()) {
4425
+ count += queue.length;
4426
+ }
4427
+ return count;
4428
+ }
4429
+ /**
4430
+ * Get all queued events across all waiting queues.
4431
+ * Used for cleanup and logging orphaned events.
4432
+ * @returns Array of all queued events
4433
+ */
4434
+ getAllQueuedEvents() {
4435
+ const all = [...this.#waitingForRoot];
4436
+ for (const queue of this.#waitingForParent.values()) {
4437
+ all.push(...queue);
4438
+ }
4439
+ return all;
4440
+ }
4441
+ // ============================================================================
4442
+ // Span Tree Methods
4443
+ // ============================================================================
4444
+ /**
4445
+ * Record the parent-child relationship for a span.
4446
+ * @param args.spanId - The child span ID
4447
+ * @param args.parentSpanId - The parent span ID, or undefined for root spans
4448
+ */
4449
+ addBranch(args) {
4450
+ this.#tree.set(args.spanId, args.parentSpanId);
4451
+ }
4452
+ /**
4453
+ * Get the parent span ID for a given span.
4454
+ * @param args.spanId - The span ID to look up
4455
+ * @returns The parent span ID, or undefined if root or not found
4456
+ */
4457
+ getParentId(args) {
4458
+ return this.#tree.get(args.spanId);
4459
+ }
4460
+ // ============================================================================
4461
+ // Span Management Methods
4462
+ // ============================================================================
4463
+ /**
4464
+ * Register a span and mark it as active.
4465
+ * @param args.spanId - The span ID
4466
+ * @param args.spanData - The vendor-specific span object
4467
+ */
4468
+ addSpan(args) {
4469
+ this.#spans.set(args.spanId, args.spanData);
4470
+ this.#activeSpanIds.add(args.spanId);
4471
+ }
4472
+ /**
4473
+ * Check if a span exists (regardless of active state).
4474
+ * @param args.spanId - The span ID to check
4475
+ * @returns True if the span exists
4476
+ */
4477
+ hasSpan(args) {
4478
+ return this.#spans.has(args.spanId);
4479
+ }
4480
+ /**
4481
+ * Get a span by ID.
4482
+ * @param args.spanId - The span ID to look up
4483
+ * @returns The vendor-specific span object, or undefined if not found
4484
+ */
4485
+ getSpan(args) {
4486
+ return this.#spans.get(args.spanId);
4487
+ }
4488
+ /**
4489
+ * Mark a span as ended (no longer active).
4490
+ * @param args.spanId - The span ID to mark as ended
4491
+ */
4492
+ endSpan(args) {
4493
+ this.#activeSpanIds.delete(args.spanId);
4494
+ }
4495
+ /**
4496
+ * Check if a span is currently active (started but not ended).
4497
+ * @param args.spanId - The span ID to check
4498
+ * @returns True if the span is active
4499
+ */
4500
+ isActiveSpan(args) {
4501
+ return this.#activeSpanIds.has(args.spanId);
4502
+ }
4503
+ /**
4504
+ * Get the count of currently active spans.
4505
+ * @returns Number of active spans
4506
+ */
4507
+ activeSpanCount() {
4508
+ return this.#activeSpanIds.size;
4509
+ }
4510
+ /**
4511
+ * Get all active span IDs.
4512
+ * @returns Array of active span IDs
4513
+ */
4514
+ get activeSpanIds() {
4515
+ return [...this.#activeSpanIds];
4516
+ }
4517
+ // ============================================================================
4518
+ // Event Management Methods
4519
+ // ============================================================================
4520
+ /**
4521
+ * Register an event.
4522
+ * @param args.eventId - The event ID
4523
+ * @param args.eventData - The vendor-specific event object
4524
+ */
4525
+ addEvent(args) {
4526
+ this.#events.set(args.eventId, args.eventData);
4527
+ }
4528
+ // ============================================================================
4529
+ // Metadata Methods
4530
+ // ============================================================================
4531
+ /**
4532
+ * Store vendor-specific metadata for a span.
4533
+ * Note: This overwrites any existing metadata for the span.
4534
+ * @param args.spanId - The span ID
4535
+ * @param args.metadata - The vendor-specific metadata
4536
+ */
4537
+ addMetadata(args) {
4538
+ this.#metadata.set(args.spanId, args.metadata);
4539
+ }
4540
+ /**
4541
+ * Get vendor-specific metadata for a span.
4542
+ * @param args.spanId - The span ID
4543
+ * @returns The metadata, or undefined if not found
4544
+ */
4545
+ getMetadata(args) {
4546
+ return this.#metadata.get(args.spanId);
4547
+ }
4548
+ // ============================================================================
4549
+ // Parent Lookup Methods
4550
+ // ============================================================================
4551
+ /**
4552
+ * Get the parent span or event for a given span.
4553
+ * Looks up in both spans and events maps.
4554
+ * @param args.span - The span to find the parent for
4555
+ * @returns The parent span/event object, or undefined if root or not found
4556
+ */
4557
+ getParent(args) {
4558
+ const parentId = args.span.parentSpanId;
4559
+ if (parentId) {
4560
+ if (this.#spans.has(parentId)) {
4561
+ return this.#spans.get(parentId);
4562
+ }
4563
+ if (this.#events.has(parentId)) {
4564
+ return this.#events.get(parentId);
4565
+ }
4566
+ }
4567
+ return void 0;
4568
+ }
4569
+ /**
4570
+ * Get the parent span/event or fall back to the root object.
4571
+ * Useful for vendors that attach child spans to either parent spans or the trace root.
4572
+ * @param args.span - The span to find the parent for
4573
+ * @returns The parent span/event, the root object, or undefined
4574
+ */
4575
+ getParentOrRoot(args) {
4576
+ return this.getParent(args) ?? this.getRoot();
4577
+ }
4578
+ };
4579
+ var DEFAULT_EARLY_QUEUE_MAX_ATTEMPTS = 5;
4580
+ var DEFAULT_EARLY_QUEUE_TTL_MS = 3e4;
4581
+ var DEFAULT_TRACE_CLEANUP_DELAY_MS = 3e4;
4582
+ var DEFAULT_MAX_PENDING_CLEANUP_TRACES = 100;
4583
+ var DEFAULT_MAX_TOTAL_TRACES = 500;
4584
+ var TrackingExporter = class extends BaseExporter {
4585
+ /** Map of traceId to per-trace data container */
4586
+ #traceMap = /* @__PURE__ */ new Map();
4587
+ /** Flag to prevent processing during shutdown */
4588
+ #shutdownStarted = false;
4589
+ /** Flag to prevent concurrent hard cap enforcement */
4590
+ #hardCapEnforcementInProgress = false;
4591
+ /** Map of traceId to scheduled cleanup timeout */
4592
+ #pendingCleanups = /* @__PURE__ */ new Map();
4593
+ // Note: #traceMap maintains insertion order (JS Map spec), so we use
4594
+ // #traceMap.keys() to iterate traces oldest-first for cap enforcement.
4595
+ /** Subclass configuration with resolved values */
4596
+ config;
4597
+ /** Maximum attempts to process a queued event before dropping */
4598
+ #earlyQueueMaxAttempts;
4599
+ /** TTL in milliseconds for queued events */
4600
+ #earlyQueueTTLMs;
4601
+ /** Delay before cleaning up completed traces */
4602
+ #traceCleanupDelayMs;
4603
+ /** Soft cap on traces awaiting cleanup */
4604
+ #maxPendingCleanupTraces;
4605
+ /** Hard cap on total traces (will abort active spans if exceeded) */
4606
+ #maxTotalTraces;
4607
+ constructor(config) {
4608
+ super(config);
4609
+ this.config = config;
4610
+ this.#earlyQueueMaxAttempts = config.earlyQueueMaxAttempts ?? DEFAULT_EARLY_QUEUE_MAX_ATTEMPTS;
4611
+ this.#earlyQueueTTLMs = config.earlyQueueTTLMs ?? DEFAULT_EARLY_QUEUE_TTL_MS;
4612
+ this.#traceCleanupDelayMs = config.traceCleanupDelayMs ?? DEFAULT_TRACE_CLEANUP_DELAY_MS;
4613
+ this.#maxPendingCleanupTraces = config.maxPendingCleanupTraces ?? DEFAULT_MAX_PENDING_CLEANUP_TRACES;
4614
+ this.#maxTotalTraces = config.maxTotalTraces ?? DEFAULT_MAX_TOTAL_TRACES;
4615
+ }
4616
+ // ============================================================================
4617
+ // Early Queue Processing
4618
+ // ============================================================================
4619
+ /**
4620
+ * Schedule async processing of events waiting for root span.
4621
+ * Called after root span is successfully processed.
4622
+ */
4623
+ #scheduleProcessWaitingForRoot(traceId) {
4624
+ setImmediate(() => {
4625
+ this.#processWaitingForRoot(traceId).catch((error) => {
4626
+ this.logger.error(`${this.name}: Error processing waiting-for-root queue`, { error, traceId });
4627
+ });
4628
+ });
4629
+ }
4630
+ /**
4631
+ * Schedule async processing of events waiting for a specific parent span.
4632
+ * Called after a span/event is successfully created.
4633
+ */
4634
+ #scheduleProcessWaitingFor(traceId, spanId) {
4635
+ setImmediate(() => {
4636
+ this.#processWaitingFor(traceId, spanId).catch((error) => {
4637
+ this.logger.error(`${this.name}: Error processing waiting queue`, { error, traceId, spanId });
4638
+ });
4639
+ });
4640
+ }
4641
+ /**
4642
+ * Process all events waiting for root span.
4643
+ */
4644
+ async #processWaitingForRoot(traceId) {
4645
+ if (this.#shutdownStarted) return;
4646
+ const traceData = this.#traceMap.get(traceId);
4647
+ if (!traceData) return;
4648
+ const queue = traceData.getEventsWaitingForRoot();
4649
+ if (queue.length === 0) return;
4650
+ this.logger.debug(`${this.name}: Processing ${queue.length} events waiting for root`, { traceId });
4651
+ const toKeep = [];
4652
+ const now = Date.now();
4653
+ for (const queuedEvent of queue) {
4654
+ if (now - queuedEvent.queuedAt.getTime() > this.#earlyQueueTTLMs) {
4655
+ this.logger.warn(`${this.name}: Dropping event due to TTL expiry`, {
4656
+ traceId,
4657
+ spanId: queuedEvent.event.exportedSpan.id,
4658
+ waitingFor: queuedEvent.waitingFor,
4659
+ queuedAt: queuedEvent.queuedAt,
4660
+ attempts: queuedEvent.attempts
4661
+ });
4662
+ continue;
4663
+ }
4664
+ if (queuedEvent.attempts >= this.#earlyQueueMaxAttempts) {
4665
+ this.logger.warn(`${this.name}: Dropping event due to max attempts`, {
4666
+ traceId,
4667
+ spanId: queuedEvent.event.exportedSpan.id,
4668
+ waitingFor: queuedEvent.waitingFor,
4669
+ attempts: queuedEvent.attempts
4670
+ });
4671
+ continue;
4672
+ }
4673
+ queuedEvent.attempts++;
4674
+ const processed = await this.#tryProcessQueuedEvent(queuedEvent, traceData);
4675
+ if (!processed) {
4676
+ const parentId = queuedEvent.event.exportedSpan.parentSpanId;
4677
+ if (parentId && traceData.isRootProcessed()) {
4678
+ traceData.addToWaitingQueue({
4679
+ event: queuedEvent.event,
4680
+ waitingFor: parentId,
4681
+ attempts: queuedEvent.attempts,
4682
+ queuedAt: queuedEvent.queuedAt
4683
+ });
4684
+ } else {
4685
+ toKeep.push(queuedEvent);
4686
+ }
4687
+ }
4688
+ }
4689
+ traceData.clearWaitingForRoot();
4690
+ for (const event of toKeep) {
4691
+ traceData.addToWaitingQueue({
4692
+ event: event.event,
4693
+ waitingFor: "root",
4694
+ attempts: event.attempts,
4695
+ queuedAt: event.queuedAt
4696
+ });
4697
+ }
4698
+ }
4699
+ /**
4700
+ * Process events waiting for a specific parent span.
4701
+ */
4702
+ async #processWaitingFor(traceId, spanId) {
4703
+ if (this.#shutdownStarted) return;
4704
+ const traceData = this.#traceMap.get(traceId);
4705
+ if (!traceData) return;
4706
+ const queue = traceData.getEventsWaitingFor({ spanId });
4707
+ if (queue.length === 0) return;
4708
+ this.logger.debug(`${this.name}: Processing ${queue.length} events waiting for span`, { traceId, spanId });
4709
+ const toKeep = [];
4710
+ const now = Date.now();
4711
+ for (const queuedEvent of queue) {
4712
+ if (now - queuedEvent.queuedAt.getTime() > this.#earlyQueueTTLMs) {
4713
+ this.logger.warn(`${this.name}: Dropping event due to TTL expiry`, {
4714
+ traceId,
4715
+ spanId: queuedEvent.event.exportedSpan.id,
4716
+ waitingFor: queuedEvent.waitingFor,
4717
+ queuedAt: queuedEvent.queuedAt,
4718
+ attempts: queuedEvent.attempts
4719
+ });
4720
+ continue;
4721
+ }
4722
+ if (queuedEvent.attempts >= this.#earlyQueueMaxAttempts) {
4723
+ this.logger.warn(`${this.name}: Dropping event due to max attempts`, {
4724
+ traceId,
4725
+ spanId: queuedEvent.event.exportedSpan.id,
4726
+ waitingFor: queuedEvent.waitingFor,
4727
+ attempts: queuedEvent.attempts
4728
+ });
4729
+ continue;
4730
+ }
4731
+ queuedEvent.attempts++;
4732
+ const processed = await this.#tryProcessQueuedEvent(queuedEvent, traceData);
4733
+ if (!processed) {
4734
+ toKeep.push(queuedEvent);
4735
+ }
4736
+ }
4737
+ traceData.clearWaitingFor({ spanId });
4738
+ for (const event of toKeep) {
4739
+ traceData.addToWaitingQueue({
4740
+ event: event.event,
4741
+ waitingFor: spanId,
4742
+ attempts: event.attempts,
4743
+ queuedAt: event.queuedAt
4744
+ });
4745
+ }
4746
+ }
4747
+ /**
4748
+ * Try to process a queued event.
4749
+ * Returns true if successfully processed, false if still waiting for dependencies.
4750
+ */
4751
+ async #tryProcessQueuedEvent(queuedEvent, traceData) {
4752
+ const { event } = queuedEvent;
4753
+ const { exportedSpan } = event;
4754
+ const method = this.getMethod(event);
4755
+ try {
4756
+ switch (method) {
4757
+ case "handleEventSpan": {
4758
+ traceData.addBranch({ spanId: exportedSpan.id, parentSpanId: exportedSpan.parentSpanId });
4759
+ const eventData = await this._buildEvent({ span: exportedSpan, traceData });
4760
+ if (eventData) {
4761
+ if (!this.skipCachingEventSpans) {
4762
+ traceData.addEvent({ eventId: exportedSpan.id, eventData });
4763
+ }
4764
+ this.#scheduleProcessWaitingFor(exportedSpan.traceId, exportedSpan.id);
4765
+ return true;
4766
+ }
4767
+ return false;
4768
+ }
4769
+ case "handleSpanStart": {
4770
+ traceData.addBranch({ spanId: exportedSpan.id, parentSpanId: exportedSpan.parentSpanId });
4771
+ const spanData = await this._buildSpan({ span: exportedSpan, traceData });
4772
+ if (spanData) {
4773
+ traceData.addSpan({ spanId: exportedSpan.id, spanData });
4774
+ if (exportedSpan.isRootSpan) {
4775
+ traceData.markRootSpanProcessed();
4776
+ }
4777
+ this.#scheduleProcessWaitingFor(exportedSpan.traceId, exportedSpan.id);
4778
+ return true;
4779
+ }
4780
+ return false;
4781
+ }
4782
+ case "handleSpanUpdate": {
4783
+ await this._updateSpan({ span: exportedSpan, traceData });
4784
+ return true;
4785
+ }
4786
+ case "handleSpanEnd": {
4787
+ traceData.endSpan({ spanId: exportedSpan.id });
4788
+ await this._finishSpan({ span: exportedSpan, traceData });
4789
+ if (traceData.activeSpanCount() === 0) {
4790
+ this.#scheduleCleanup(exportedSpan.traceId);
4791
+ }
4792
+ return true;
4793
+ }
4794
+ default:
4795
+ return false;
4796
+ }
4797
+ } catch (error) {
4798
+ this.logger.error(`${this.name}: Error processing queued event`, { error, event, method });
4799
+ return false;
4800
+ }
4801
+ }
4802
+ // ============================================================================
4803
+ // Delayed Cleanup
4804
+ // ============================================================================
4805
+ /**
4806
+ * Schedule cleanup of trace data after a delay.
4807
+ * Allows late-arriving data to still be processed.
4808
+ */
4809
+ #scheduleCleanup(traceId) {
4810
+ this.#cancelScheduledCleanup(traceId);
4811
+ this.logger.debug(`${this.name}: Scheduling cleanup in ${this.#traceCleanupDelayMs}ms`, { traceId });
4812
+ const timeout = setTimeout(() => {
4813
+ this.#pendingCleanups.delete(traceId);
4814
+ this.#performCleanup(traceId);
4815
+ }, this.#traceCleanupDelayMs);
4816
+ this.#pendingCleanups.set(traceId, timeout);
4817
+ this.#enforcePendingCleanupCap();
4818
+ }
4819
+ /**
4820
+ * Cancel a scheduled cleanup for a trace.
4821
+ */
4822
+ #cancelScheduledCleanup(traceId) {
4823
+ const existingTimeout = this.#pendingCleanups.get(traceId);
4824
+ if (existingTimeout) {
4825
+ clearTimeout(existingTimeout);
4826
+ this.#pendingCleanups.delete(traceId);
4827
+ this.logger.debug(`${this.name}: Cancelled scheduled cleanup`, { traceId });
4828
+ }
4829
+ }
4830
+ /**
4831
+ * Perform the actual cleanup of trace data.
4832
+ */
4833
+ #performCleanup(traceId) {
4834
+ const traceData = this.#traceMap.get(traceId);
4835
+ if (!traceData) return;
4836
+ const orphanedEvents = traceData.getAllQueuedEvents();
4837
+ if (orphanedEvents.length > 0) {
4838
+ this.logger.warn(`${this.name}: Dropping ${orphanedEvents.length} orphaned events on cleanup`, {
4839
+ traceId,
4840
+ orphanedEvents: orphanedEvents.map((e) => ({
4841
+ spanId: e.event.exportedSpan.id,
4842
+ waitingFor: e.waitingFor,
4843
+ attempts: e.attempts,
4844
+ queuedAt: e.queuedAt
4845
+ }))
4846
+ });
4847
+ }
4848
+ this.#traceMap.delete(traceId);
4849
+ this.logger.debug(`${this.name}: Cleaned up trace data`, { traceId });
4850
+ }
4851
+ // ============================================================================
4852
+ // Cap Enforcement
4853
+ // ============================================================================
4854
+ /**
4855
+ * Enforce soft cap on pending cleanup traces.
4856
+ * Only removes traces with activeSpanCount == 0.
4857
+ */
4858
+ #enforcePendingCleanupCap() {
4859
+ if (this.#pendingCleanups.size <= this.#maxPendingCleanupTraces) {
4860
+ return;
4861
+ }
4862
+ const toRemove = this.#pendingCleanups.size - this.#maxPendingCleanupTraces;
4863
+ this.logger.warn(`${this.name}: Pending cleanup cap exceeded, force-cleaning ${toRemove} traces`, {
4864
+ pendingCount: this.#pendingCleanups.size,
4865
+ cap: this.#maxPendingCleanupTraces
4866
+ });
4867
+ let removed = 0;
4868
+ for (const traceId of this.#traceMap.keys()) {
4869
+ if (removed >= toRemove) break;
4870
+ if (this.#pendingCleanups.has(traceId)) {
4871
+ this.#cancelScheduledCleanup(traceId);
4872
+ this.#performCleanup(traceId);
4873
+ removed++;
4874
+ }
4875
+ }
4876
+ }
4877
+ /**
4878
+ * Enforce hard cap on total traces.
4879
+ * Will kill even active traces if necessary.
4880
+ * Uses a flag to prevent concurrent executions when called fire-and-forget.
4881
+ */
4882
+ async #enforceHardCap() {
4883
+ if (this.#traceMap.size <= this.#maxTotalTraces || this.#hardCapEnforcementInProgress) {
4884
+ return;
4885
+ }
4886
+ this.#hardCapEnforcementInProgress = true;
4887
+ try {
4888
+ if (this.#traceMap.size <= this.#maxTotalTraces) {
4889
+ return;
4890
+ }
4891
+ const toRemove = this.#traceMap.size - this.#maxTotalTraces;
4892
+ this.logger.warn(`${this.name}: Total trace cap exceeded, killing ${toRemove} oldest traces`, {
4893
+ traceCount: this.#traceMap.size,
4894
+ cap: this.#maxTotalTraces
4895
+ });
4896
+ const reason = {
4897
+ id: "TRACE_CAP_EXCEEDED",
4898
+ message: "Trace killed due to memory cap enforcement.",
4899
+ domain: "MASTRA_OBSERVABILITY",
4900
+ category: "SYSTEM"
4901
+ };
4902
+ let removed = 0;
4903
+ for (const traceId of [...this.#traceMap.keys()]) {
4904
+ if (removed >= toRemove) break;
4905
+ const traceData = this.#traceMap.get(traceId);
4906
+ if (traceData) {
4907
+ for (const spanId of traceData.activeSpanIds) {
4908
+ const span = traceData.getSpan({ spanId });
4909
+ if (span) {
4910
+ await this._abortSpan({ span, traceData, reason });
4911
+ }
4912
+ }
4913
+ this.#cancelScheduledCleanup(traceId);
4914
+ this.#performCleanup(traceId);
4915
+ removed++;
4916
+ }
4917
+ }
4918
+ } finally {
4919
+ this.#hardCapEnforcementInProgress = false;
4920
+ }
4921
+ }
4922
+ // ============================================================================
4923
+ // Lifecycle Hooks (Override in subclass)
4924
+ // ============================================================================
4925
+ /**
4926
+ * Hook called before processing each tracing event.
4927
+ * Override to transform or enrich the event before processing.
4928
+ *
4929
+ * Note: The customSpanFormatter is applied at the BaseExporter level before this hook.
4930
+ * Subclasses can override this to add additional pre-processing logic.
4931
+ *
4932
+ * @param event - The incoming tracing event
4933
+ * @returns The (possibly modified) event to process
4934
+ */
4935
+ async _preExportTracingEvent(event) {
4936
+ return event;
4937
+ }
4938
+ /**
4939
+ * Hook called after processing each tracing event.
4940
+ * Override to perform post-processing actions like flushing.
4941
+ */
4942
+ async _postExportTracingEvent() {
4943
+ }
4944
+ // ============================================================================
4945
+ // Behavior Flags (Override in subclass as needed)
4946
+ // ============================================================================
4947
+ /**
4948
+ * If true, skip calling _buildRoot and let root spans go through _buildSpan.
4949
+ * Use when the vendor doesn't have a separate trace/root concept.
4950
+ * @default false
4951
+ */
4952
+ skipBuildRootTask = false;
4953
+ /**
4954
+ * If true, skip processing span_updated events entirely.
4955
+ * Use when the vendor doesn't support incremental span updates.
4956
+ * @default false
4957
+ */
4958
+ skipSpanUpdateEvents = false;
4959
+ /**
4960
+ * If true, don't cache event spans in TraceData.
4961
+ * Use when events can't be parents of other spans.
4962
+ * @default false
4963
+ */
4964
+ skipCachingEventSpans = false;
4965
+ getMethod(event) {
4966
+ if (event.exportedSpan.isEvent) {
4967
+ return "handleEventSpan";
4968
+ }
4969
+ const eventType = event.type;
4970
+ switch (eventType) {
4971
+ case observability.TracingEventType.SPAN_STARTED:
4972
+ return "handleSpanStart";
4973
+ case observability.TracingEventType.SPAN_UPDATED:
4974
+ return "handleSpanUpdate";
4975
+ case observability.TracingEventType.SPAN_ENDED:
4976
+ return "handleSpanEnd";
4977
+ default: {
4978
+ const _exhaustiveCheck = eventType;
4979
+ throw new Error(`Unhandled event type: ${_exhaustiveCheck}`);
4980
+ }
4981
+ }
4982
+ }
4983
+ async _exportTracingEvent(event) {
4984
+ if (this.#shutdownStarted) {
4985
+ return;
4986
+ }
4987
+ const method = this.getMethod(event);
4988
+ if (method == "handleSpanUpdate" && this.skipSpanUpdateEvents) {
4989
+ return;
4990
+ }
4991
+ const traceId = event.exportedSpan.traceId;
4992
+ const traceData = this.getTraceData({ traceId, method });
4993
+ const { exportedSpan } = await this._preExportTracingEvent(event);
4994
+ if (!this.skipBuildRootTask && !traceData.hasRoot()) {
4995
+ if (exportedSpan.isRootSpan) {
4996
+ this.logger.debug(`${this.name}: Building root`, {
4997
+ traceId: exportedSpan.traceId,
4998
+ spanId: exportedSpan.id
4999
+ });
5000
+ const rootData = await this._buildRoot({ span: exportedSpan, traceData });
5001
+ if (rootData) {
5002
+ this.logger.debug(`${this.name}: Adding root`, {
5003
+ traceId: exportedSpan.traceId,
5004
+ spanId: exportedSpan.id
5005
+ });
5006
+ traceData.addRoot({ rootId: exportedSpan.id, rootData });
5007
+ this.#scheduleProcessWaitingForRoot(traceId);
5008
+ }
5009
+ } else {
5010
+ this.logger.debug(`${this.name}: Root does not exist, adding span to waiting queue.`, {
5011
+ traceId: exportedSpan.traceId,
5012
+ spanId: exportedSpan.id
5013
+ });
5014
+ traceData.addToWaitingQueue({ event, waitingFor: "root" });
5015
+ return;
5016
+ }
5017
+ }
5018
+ if (exportedSpan.metadata && this.name in exportedSpan.metadata) {
5019
+ const metadata = exportedSpan.metadata[this.name];
5020
+ this.logger.debug(`${this.name}: Found provider metadata in span`, {
5021
+ traceId: exportedSpan.traceId,
5022
+ spanId: exportedSpan.id,
5023
+ metadata
5024
+ });
5025
+ traceData.addMetadata({ spanId: exportedSpan.id, metadata });
5026
+ }
5027
+ try {
5028
+ switch (method) {
5029
+ case "handleEventSpan": {
5030
+ this.logger.debug(`${this.name}: handling event`, {
5031
+ traceId: exportedSpan.traceId,
5032
+ spanId: exportedSpan.id
5033
+ });
5034
+ traceData.addBranch({ spanId: exportedSpan.id, parentSpanId: exportedSpan.parentSpanId });
5035
+ const eventData = await this._buildEvent({ span: exportedSpan, traceData });
5036
+ if (eventData) {
5037
+ if (!this.skipCachingEventSpans) {
5038
+ this.logger.debug(`${this.name}: adding event to traceData`, {
5039
+ traceId: exportedSpan.traceId,
5040
+ spanId: exportedSpan.id
5041
+ });
5042
+ traceData.addEvent({ eventId: exportedSpan.id, eventData });
5043
+ }
5044
+ this.#scheduleProcessWaitingFor(traceId, exportedSpan.id);
5045
+ } else {
5046
+ const parentId = exportedSpan.parentSpanId;
5047
+ this.logger.debug(`${this.name}: adding event to waiting queue`, {
5048
+ traceId: exportedSpan.traceId,
5049
+ spanId: exportedSpan.id,
5050
+ waitingFor: parentId ?? "root"
5051
+ });
5052
+ traceData.addToWaitingQueue({ event, waitingFor: parentId ?? "root" });
5053
+ }
5054
+ break;
5055
+ }
5056
+ case "handleSpanStart": {
5057
+ this.logger.debug(`${this.name}: handling span start`, {
5058
+ traceId: exportedSpan.traceId,
5059
+ spanId: exportedSpan.id
5060
+ });
5061
+ traceData.addBranch({ spanId: exportedSpan.id, parentSpanId: exportedSpan.parentSpanId });
5062
+ const spanData = await this._buildSpan({ span: exportedSpan, traceData });
5063
+ if (spanData) {
5064
+ this.logger.debug(`${this.name}: adding span to traceData`, {
5065
+ traceId: exportedSpan.traceId,
5066
+ spanId: exportedSpan.id
5067
+ });
5068
+ traceData.addSpan({ spanId: exportedSpan.id, spanData });
5069
+ if (exportedSpan.isRootSpan) {
5070
+ traceData.markRootSpanProcessed();
5071
+ this.#scheduleProcessWaitingForRoot(traceId);
5072
+ }
5073
+ this.#scheduleProcessWaitingFor(traceId, exportedSpan.id);
5074
+ } else {
5075
+ const parentId = exportedSpan.parentSpanId;
5076
+ this.logger.debug(`${this.name}: adding span to waiting queue`, {
5077
+ traceId: exportedSpan.traceId,
5078
+ waitingFor: parentId ?? "root"
5079
+ });
5080
+ traceData.addToWaitingQueue({ event, waitingFor: parentId ?? "root" });
5081
+ }
5082
+ break;
5083
+ }
5084
+ case "handleSpanUpdate":
5085
+ this.logger.debug(`${this.name}: handling span update`, {
5086
+ traceId: exportedSpan.traceId,
5087
+ spanId: exportedSpan.id
5088
+ });
5089
+ await this._updateSpan({ span: exportedSpan, traceData });
5090
+ break;
5091
+ case "handleSpanEnd":
5092
+ this.logger.debug(`${this.name}: handling span end`, {
5093
+ traceId: exportedSpan.traceId,
5094
+ spanId: exportedSpan.id
5095
+ });
5096
+ traceData.endSpan({ spanId: exportedSpan.id });
5097
+ await this._finishSpan({ span: exportedSpan, traceData });
5098
+ if (traceData.activeSpanCount() === 0) {
5099
+ this.#scheduleCleanup(traceId);
5100
+ }
5101
+ break;
5102
+ }
5103
+ } catch (error) {
5104
+ this.logger.error(`${this.name}: exporter error`, { error, event, method });
5105
+ }
5106
+ if (traceData.activeSpanCount() === 0) {
5107
+ this.#scheduleCleanup(traceId);
5108
+ }
5109
+ await this._postExportTracingEvent();
5110
+ }
5111
+ // ============================================================================
5112
+ // Protected Helpers
5113
+ // ============================================================================
5114
+ /**
5115
+ * Get or create the TraceData container for a trace.
5116
+ * Also cancels any pending cleanup since new data has arrived.
5117
+ *
5118
+ * @param args.traceId - The trace ID
5119
+ * @param args.method - The calling method name (for logging)
5120
+ * @returns The TraceData container for this trace
5121
+ */
5122
+ getTraceData(args) {
5123
+ const { traceId, method } = args;
5124
+ this.#cancelScheduledCleanup(traceId);
5125
+ if (!this.#traceMap.has(traceId)) {
5126
+ this.#traceMap.set(traceId, new TraceData());
5127
+ this.logger.debug(`${this.name}: Created new trace data cache`, {
5128
+ traceId,
5129
+ method
5130
+ });
5131
+ this.#enforceHardCap().catch((error) => {
5132
+ this.logger.error(`${this.name}: Error enforcing hard cap`, { error });
5133
+ });
5134
+ }
5135
+ return this.#traceMap.get(traceId);
5136
+ }
5137
+ /**
5138
+ * Get the current number of traces being tracked.
5139
+ * @returns The trace count
5140
+ */
5141
+ traceMapSize() {
5142
+ return this.#traceMap.size;
5143
+ }
5144
+ // ============================================================================
5145
+ // Shutdown Hooks (Override in subclass as needed)
5146
+ // ============================================================================
5147
+ /**
5148
+ * Hook called at the start of shutdown, before cancelling timers and aborting spans.
5149
+ * Override to perform vendor-specific pre-shutdown tasks.
5150
+ */
5151
+ async _preShutdown() {
5152
+ }
5153
+ /**
5154
+ * Hook called at the end of shutdown, after all spans are aborted.
5155
+ * Override to perform vendor-specific cleanup (e.g., flushing).
5156
+ */
5157
+ async _postShutdown() {
5158
+ }
5159
+ /**
5160
+ * Gracefully shut down the exporter.
5161
+ * Cancels all pending cleanup timers, aborts all active spans, and clears state.
5162
+ */
5163
+ async shutdown() {
5164
+ if (this.isDisabled) {
5165
+ return;
5166
+ }
5167
+ this.#shutdownStarted = true;
5168
+ await this._preShutdown();
5169
+ for (const [traceId, timeout] of this.#pendingCleanups) {
5170
+ clearTimeout(timeout);
5171
+ this.logger.debug(`${this.name}: Cancelled pending cleanup on shutdown`, { traceId });
5172
+ }
5173
+ this.#pendingCleanups.clear();
5174
+ const reason = {
5175
+ id: "SHUTDOWN",
5176
+ message: "Observability is shutting down.",
5177
+ domain: "MASTRA_OBSERVABILITY",
5178
+ category: "SYSTEM"
5179
+ };
5180
+ for (const [traceId, traceData] of this.#traceMap) {
5181
+ const orphanedEvents = traceData.getAllQueuedEvents();
5182
+ if (orphanedEvents.length > 0) {
5183
+ this.logger.warn(`${this.name}: Dropping ${orphanedEvents.length} orphaned events on shutdown`, {
5184
+ traceId,
5185
+ orphanedEvents: orphanedEvents.map((e) => ({
5186
+ spanId: e.event.exportedSpan.id,
5187
+ waitingFor: e.waitingFor,
5188
+ attempts: e.attempts
5189
+ }))
5190
+ });
5191
+ }
5192
+ for (const spanId of traceData.activeSpanIds) {
5193
+ const span = traceData.getSpan({ spanId });
5194
+ if (span) {
5195
+ await this._abortSpan({ span, traceData, reason });
5196
+ }
5197
+ }
5198
+ }
5199
+ this.#traceMap.clear();
5200
+ await this._postShutdown();
5201
+ await super.shutdown();
5202
+ }
5203
+ };
5204
+
5205
+ // src/exporters/span-formatters.ts
5206
+ function chainFormatters(formatters) {
5207
+ return async (span) => {
5208
+ let currentSpan = span;
5209
+ for (const formatter of formatters) {
5210
+ currentSpan = await formatter(currentSpan);
5211
+ }
5212
+ return currentSpan;
5213
+ };
5214
+ }
4230
5215
  var CloudExporter = class extends BaseExporter {
4231
5216
  name = "mastra-cloud-observability-exporter";
4232
- config;
5217
+ cloudConfig;
4233
5218
  buffer;
4234
5219
  flushTimer = null;
4235
5220
  constructor(config = {}) {
@@ -4239,7 +5224,7 @@ var CloudExporter = class extends BaseExporter {
4239
5224
  this.setDisabled("MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.");
4240
5225
  }
4241
5226
  const endpoint = config.endpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
4242
- this.config = {
5227
+ this.cloudConfig = {
4243
5228
  logger: this.logger,
4244
5229
  logLevel: config.logLevel ?? logger.LogLevel.INFO,
4245
5230
  maxBatchSize: config.maxBatchSize ?? 1e3,
@@ -4297,12 +5282,12 @@ var CloudExporter = class extends BaseExporter {
4297
5282
  return spanRecord;
4298
5283
  }
4299
5284
  shouldFlush() {
4300
- if (this.buffer.totalSize >= this.config.maxBatchSize) {
5285
+ if (this.buffer.totalSize >= this.cloudConfig.maxBatchSize) {
4301
5286
  return true;
4302
5287
  }
4303
5288
  if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
4304
5289
  const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
4305
- if (elapsed >= this.config.maxBatchWaitMs) {
5290
+ if (elapsed >= this.cloudConfig.maxBatchWaitMs) {
4306
5291
  return true;
4307
5292
  }
4308
5293
  }
@@ -4325,7 +5310,7 @@ var CloudExporter = class extends BaseExporter {
4325
5310
  this.logger.trackException(mastraError);
4326
5311
  this.logger.error("Scheduled flush failed", mastraError);
4327
5312
  });
4328
- }, this.config.maxBatchWaitMs);
5313
+ }, this.cloudConfig.maxBatchWaitMs);
4329
5314
  }
4330
5315
  async flush() {
4331
5316
  if (this.flushTimer) {
@@ -4337,7 +5322,7 @@ var CloudExporter = class extends BaseExporter {
4337
5322
  }
4338
5323
  const startTime = Date.now();
4339
5324
  const spansCopy = [...this.buffer.spans];
4340
- const flushReason = this.buffer.totalSize >= this.config.maxBatchSize ? "size" : "time";
5325
+ const flushReason = this.buffer.totalSize >= this.cloudConfig.maxBatchSize ? "size" : "time";
4341
5326
  this.resetBuffer();
4342
5327
  try {
4343
5328
  await this.batchUpload(spansCopy);
@@ -4368,7 +5353,7 @@ var CloudExporter = class extends BaseExporter {
4368
5353
  */
4369
5354
  async batchUpload(spans) {
4370
5355
  const headers = {
4371
- Authorization: `Bearer ${this.config.accessToken}`,
5356
+ Authorization: `Bearer ${this.cloudConfig.accessToken}`,
4372
5357
  "Content-Type": "application/json"
4373
5358
  };
4374
5359
  const options = {
@@ -4376,7 +5361,7 @@ var CloudExporter = class extends BaseExporter {
4376
5361
  headers,
4377
5362
  body: JSON.stringify({ spans })
4378
5363
  };
4379
- await utils.fetchWithRetry(this.config.endpoint, options, this.config.maxRetries);
5364
+ await utils.fetchWithRetry(this.cloudConfig.endpoint, options, this.cloudConfig.maxRetries);
4380
5365
  }
4381
5366
  resetBuffer() {
4382
5367
  this.buffer.spans = [];
@@ -5480,10 +6465,39 @@ var ModelSpanTracker = class {
5480
6465
  case "step-finish":
5481
6466
  this.#endStepSpan(chunk.payload);
5482
6467
  break;
6468
+ // Infrastructure chunks - skip creating spans for these
6469
+ // They are either redundant, metadata-only, or error/control flow
5483
6470
  case "raw":
5484
- // Skip raw chunks as they're redundant
6471
+ // Redundant raw data
5485
6472
  case "start":
6473
+ // Stream start marker
5486
6474
  case "finish":
6475
+ // Stream finish marker (step-finish already captures this)
6476
+ case "response-metadata":
6477
+ // Response metadata (not semantic content)
6478
+ case "source":
6479
+ // Source references (metadata)
6480
+ case "file":
6481
+ // Binary file data (too large/not semantic)
6482
+ case "error":
6483
+ // Error handling
6484
+ case "abort":
6485
+ // Abort signal
6486
+ case "tripwire":
6487
+ // Processor rejection
6488
+ case "watch":
6489
+ // Internal watch event
6490
+ case "tool-error":
6491
+ // Tool error handling
6492
+ case "tool-call-approval":
6493
+ // Approval request (not content)
6494
+ case "tool-call-suspended":
6495
+ // Suspension (not content)
6496
+ case "reasoning-signature":
6497
+ // Signature metadata
6498
+ case "redacted-reasoning":
6499
+ // Redacted content metadata
6500
+ case "step-output":
5487
6501
  break;
5488
6502
  case "tool-output":
5489
6503
  this.#handleToolOutputChunk(chunk);
@@ -5498,20 +6512,6 @@ var ModelSpanTracker = class {
5498
6512
  this.#createEventSpan(chunk.type, cleanPayload);
5499
6513
  break;
5500
6514
  }
5501
- // Default: auto-create event span for all other chunk types
5502
- default: {
5503
- let outputPayload = chunk.payload;
5504
- if (outputPayload && typeof outputPayload === "object" && "data" in outputPayload) {
5505
- const typedPayload = outputPayload;
5506
- outputPayload = { ...typedPayload };
5507
- if (typedPayload.data) {
5508
- outputPayload.size = typeof typedPayload.data === "string" ? typedPayload.data.length : typedPayload.data instanceof Uint8Array ? typedPayload.data.length : void 0;
5509
- delete outputPayload.data;
5510
- }
5511
- }
5512
- this.#createEventSpan(chunk.type, outputPayload);
5513
- break;
5514
- }
5515
6515
  }
5516
6516
  }
5517
6517
  })
@@ -5712,15 +6712,15 @@ var BaseSpan = class {
5712
6712
  this.attributes = deepClean(options.attributes, this.deepCleanOptions) || {};
5713
6713
  this.metadata = deepClean(options.metadata, this.deepCleanOptions);
5714
6714
  this.parent = options.parent;
5715
- this.startTime = /* @__PURE__ */ new Date();
6715
+ this.startTime = options.startTime ?? /* @__PURE__ */ new Date();
5716
6716
  this.observabilityInstance = observabilityInstance;
5717
6717
  this.isEvent = options.isEvent ?? false;
5718
6718
  this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
5719
6719
  this.traceState = options.traceState;
5720
6720
  this.tags = !options.parent && options.tags?.length ? options.tags : void 0;
5721
- this.entityType = options.entityType;
5722
- this.entityId = options.entityId;
5723
- this.entityName = options.entityName;
6721
+ this.entityType = options.entityType ?? options.parent?.entityType;
6722
+ this.entityId = options.entityId ?? options.parent?.entityId;
6723
+ this.entityName = options.entityName ?? options.parent?.entityName;
5724
6724
  if (this.isEvent) {
5725
6725
  this.output = deepClean(options.output, this.deepCleanOptions);
5726
6726
  } else {
@@ -5769,6 +6769,8 @@ var BaseSpan = class {
5769
6769
  }
5770
6770
  /** Returns a lightweight span ready for export */
5771
6771
  exportSpan(includeInternalSpans) {
6772
+ const hideInput = this.traceState?.hideInput ?? false;
6773
+ const hideOutput = this.traceState?.hideOutput ?? false;
5772
6774
  return {
5773
6775
  id: this.id,
5774
6776
  traceId: this.traceId,
@@ -5781,8 +6783,8 @@ var BaseSpan = class {
5781
6783
  metadata: this.metadata,
5782
6784
  startTime: this.startTime,
5783
6785
  endTime: this.endTime,
5784
- input: this.input,
5785
- output: this.output,
6786
+ input: hideInput ? void 0 : this.input,
6787
+ output: hideOutput ? void 0 : this.output,
5786
6788
  errorInfo: this.errorInfo,
5787
6789
  isEvent: this.isEvent,
5788
6790
  isRootSpan: this.isRootSpan,
@@ -5822,6 +6824,14 @@ var DefaultSpan = class extends BaseSpan {
5822
6824
  traceId;
5823
6825
  constructor(options, observabilityInstance) {
5824
6826
  super(options, observabilityInstance);
6827
+ if (options.spanId && options.traceId) {
6828
+ this.id = options.spanId;
6829
+ this.traceId = options.traceId;
6830
+ if (options.parentSpanId) {
6831
+ this.parentSpanId = options.parentSpanId;
6832
+ }
6833
+ return;
6834
+ }
5825
6835
  const bridge = observabilityInstance.getBridge();
5826
6836
  if (bridge && !this.isInternal) {
5827
6837
  const bridgeIds = bridge.createSpan(options);
@@ -6066,8 +7076,12 @@ var BaseObservabilityInstance = class extends base.MastraBase {
6066
7076
  const mergedMetadata = metadata || tracingMetadata ? { ...metadata, ...tracingMetadata } : void 0;
6067
7077
  const enrichedMetadata = this.extractMetadataFromRequestContext(requestContext, mergedMetadata, traceState);
6068
7078
  const tags = !options.parent ? tracingOptions?.tags : void 0;
7079
+ const traceId = !options.parent ? options.traceId ?? tracingOptions?.traceId : options.traceId;
7080
+ const parentSpanId = !options.parent ? options.parentSpanId ?? tracingOptions?.parentSpanId : options.parentSpanId;
6069
7081
  const span = this.createSpan({
6070
7082
  ...rest,
7083
+ traceId,
7084
+ parentSpanId,
6071
7085
  metadata: enrichedMetadata,
6072
7086
  traceState,
6073
7087
  tags
@@ -6080,6 +7094,37 @@ var BaseObservabilityInstance = class extends base.MastraBase {
6080
7094
  }
6081
7095
  return span;
6082
7096
  }
7097
+ /**
7098
+ * Rebuild a span from exported data for lifecycle operations.
7099
+ * Used by durable execution engines (e.g., Inngest) to end/update spans
7100
+ * that were created in a previous durable operation.
7101
+ *
7102
+ * The rebuilt span:
7103
+ * - Does NOT emit SPAN_STARTED (assumes original span already did)
7104
+ * - Can have end(), update(), error() called on it
7105
+ * - Will emit SPAN_ENDED or SPAN_UPDATED when those methods are called
7106
+ *
7107
+ * @param cached - The exported span data to rebuild from
7108
+ * @returns A span that can have lifecycle methods called on it
7109
+ */
7110
+ rebuildSpan(cached) {
7111
+ const span = this.createSpan({
7112
+ name: cached.name,
7113
+ type: cached.type,
7114
+ traceId: cached.traceId,
7115
+ spanId: cached.id,
7116
+ parentSpanId: cached.parentSpanId,
7117
+ startTime: cached.startTime instanceof Date ? cached.startTime : new Date(cached.startTime),
7118
+ input: cached.input,
7119
+ attributes: cached.attributes,
7120
+ metadata: cached.metadata,
7121
+ entityType: cached.entityType,
7122
+ entityId: cached.entityId,
7123
+ entityName: cached.entityName
7124
+ });
7125
+ this.wireSpanLifecycle(span);
7126
+ return span;
7127
+ }
6083
7128
  // ============================================================================
6084
7129
  // Configuration Management
6085
7130
  // ============================================================================
@@ -6182,11 +7227,15 @@ var BaseObservabilityInstance = class extends base.MastraBase {
6182
7227
  const configuredKeys = this.config.requestContextKeys ?? [];
6183
7228
  const additionalKeys = tracingOptions?.requestContextKeys ?? [];
6184
7229
  const allKeys = [...configuredKeys, ...additionalKeys];
6185
- if (allKeys.length === 0) {
7230
+ const hideInput = tracingOptions?.hideInput;
7231
+ const hideOutput = tracingOptions?.hideOutput;
7232
+ if (allKeys.length === 0 && !hideInput && !hideOutput) {
6186
7233
  return void 0;
6187
7234
  }
6188
7235
  return {
6189
- requestContextKeys: allKeys
7236
+ requestContextKeys: allKeys,
7237
+ ...hideInput !== void 0 && { hideInput },
7238
+ ...hideOutput !== void 0 && { hideOutput }
6190
7239
  };
6191
7240
  }
6192
7241
  /**
@@ -6732,7 +7781,10 @@ exports.Observability = Observability;
6732
7781
  exports.SamplingStrategyType = SamplingStrategyType;
6733
7782
  exports.SensitiveDataFilter = SensitiveDataFilter;
6734
7783
  exports.TestExporter = TestExporter;
7784
+ exports.TraceData = TraceData;
7785
+ exports.TrackingExporter = TrackingExporter;
6735
7786
  exports.buildTracingOptions = buildTracingOptions;
7787
+ exports.chainFormatters = chainFormatters;
6736
7788
  exports.deepClean = deepClean;
6737
7789
  exports.getExternalParentId = getExternalParentId;
6738
7790
  exports.mergeSerializationOptions = mergeSerializationOptions;