@mastra/observability 1.24.1-alpha.0 → 1.24.1-alpha.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"event-buffer.d.ts","sourceRoot":"","sources":["../../src/exporters/event-buffer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,KAAK,EAAE,gBAAgB,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7G,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAEjE,oFAAoF;AACpF,MAAM,WAAW,UAAU;IACzB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,+DAA+D;AAC/D,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACpC;AAED,2EAA2E;AAC3E,MAAM,MAAM,eAAe,GAAG,OAAO,CAAC,kBAAkB,EAAE;IAAE,IAAI,EAAE,sBAAsB,GAAG,wBAAwB,CAAA;CAAE,CAAC,CAAC;AACvH,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG,UAAU,CAAC;AAEzD;;;;GAIG;AACH,qBAAa,WAAW;;IAatB,YAAY,IAAI,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,kBAAkB,CAAA;KAAE,EAGzE;IAED,yEAAyE;IACzE,IAAI,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,4BAA4B,CAAA;KAAE,GAAG,IAAI,CAQ3D;IAED,qEAAqE;IACrE,KAAK,SAIJ;IAED,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,UAAU;IAMlB,OAAO,CAAC,UAAU;IAMlB,gGAAgG;IAChG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AAM,CAAA;KAAE,EAAE,GAAG,IAAI,CAQrE;IAED,0EAA0E;IAC1E,QAAQ,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAEvC;IAED,uFAAuF;IACvF,gBAAgB,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,iBAAiB,EAAE,CAAA;KAAE,GAAG,IAAI,CAU7D;CACF"}
@@ -37,6 +37,10 @@ export declare class MastraStorageExporter extends BaseExporter {
37
37
  * Schedules a flush using setTimeout
38
38
  */
39
39
  private scheduleFlush;
40
+ /** Wakes a flush at the earliest held retry's time. A timer of its own, so a new batch can't push the retry back. */
41
+ private scheduleRetry;
42
+ private flushOnTimer;
43
+ private clearTimers;
40
44
  private retryDelay;
41
45
  private retryAttempt;
42
46
  private logStorageFailure;
@@ -59,19 +63,24 @@ export declare class MastraStorageExporter extends BaseExporter {
59
63
  *
60
64
  * When the store supports conditional updates, only spans this exporter started
61
65
  * and hasn't confirmed the create for are deferred. Everything else, including
62
- * spans another exporter instance started (such as a durable agent ending spans
63
- * it rebuilt after a crash), goes straight to storage, and updates that didn't
64
- * apply are counted as drops. Without conditional updates, updates for spans this
65
- * exporter hasn't created are deferred until their create is flushed.
66
+ * spans another exporter instance started (a durable agent ending spans it rebuilt
67
+ * after a crash, or a worker finishing a run the API process started), goes straight
68
+ * to storage, and updates that didn't apply go to `retryNotApplied`. Without conditional
69
+ * updates, updates for spans this exporter hasn't created are deferred until their
70
+ * create is flushed.
66
71
  *
67
72
  * When `isEnd` is true, successfully flushed spans are removed from tracking.
68
73
  */
69
74
  private flushSpanUpdates;
70
75
  /**
71
- * Reports conditional span updates that storage didn't apply: the span wasn't
72
- * stored, or it had already ended. Ended spans are immutable, so these are dropped.
76
+ * Handles conditional span updates that storage didn't apply. The store can't say whether
77
+ * the row is missing or already ended. A span this exporter created and still tracks, or
78
+ * whose end it stored, can't be missing, so its update is dropped. Any other span may belong
79
+ * to a process whose create hasn't landed yet, so its end is held for a retry. Only ends retry:
80
+ * an end carries the span's full state, and a retried update could overwrite a newer one.
81
+ * `realtime` assumes one process owns a span, so it drops the end right away.
73
82
  */
74
- private emitNotApplied;
83
+ private retryNotApplied;
75
84
  /**
76
85
  * Runs flushBuffer() and tracks its promise so flush() can wait for writes
77
86
  * that a timer or size trigger started on their own.
@@ -87,6 +96,7 @@ export declare class MastraStorageExporter extends BaseExporter {
87
96
  */
88
97
  private flushBuffer;
89
98
  getByteBatchingStats(): StorageByteBatchingStats | undefined;
99
+ private fallBackFromRealtimeUnderDurableExecution;
90
100
  _exportTracingEvent(event: TracingEvent): Promise<void>;
91
101
  /**
92
102
  * Handle metric events — buffer for batch flush.
@@ -1 +1 @@
1
- {"version":3,"file":"mastra-storage.d.ts","sourceRoot":"","sources":["../../src/exporters/mastra-storage.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EACnB,WAAW,EACX,QAAQ,EACR,UAAU,EACV,aAAa,EACb,wBAAwB,EACxB,yBAAyB,EAI1B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAwB,sBAAsB,EAAwB,MAAM,sBAAsB,CAAC;AAS/G,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAOtC,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAElG,YAAY,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAElG,4FAA4F;AAC5F,MAAM,WAAW,2BAA4B,SAAQ,kBAAkB;IACrE,YAAY,CAAC,EAAE,yBAAyB,CAAC;IACzC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IA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C,CAEzE;IAED,eAAe,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnD;IAED,OAAO,CAAC,iBAAiB;YAeX,eAAe;IAyC7B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAG3B;YAEa,mBAAmB;IA4C3B,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA2B9B;CACF"}
package/dist/index.cjs CHANGED
@@ -3666,7 +3666,7 @@ var BaseSpan = class BaseSpan {
3666
3666
  *
3667
3667
  * Note: metadata is still attached and deepCleaned because it is read in
3668
3668
  * process by getCorrelationContext() and by getLoggerContext() /
3669
- * getMetricsContext() (which structuredClone it).
3669
+ * getMetricsContext() (which hand it to a context that snapshots it).
3670
3670
  */
3671
3671
  isExcluded;
3672
3672
  /** Cached canonical correlation context for this live span */
@@ -4462,6 +4462,11 @@ var BaseExporter = class {
4462
4462
  };
4463
4463
  // src/exporters/event-buffer.ts
4464
4464
  /**
4465
+ * How many ended spans a buffer remembers, so a long-lived worker doesn't grow the set forever.
4466
+ * A second end of a forgotten span looks like a span that isn't stored yet, so it's retried before it's dropped.
4467
+ */
4468
+ const MAX_ENDED_SPANS = 1e4;
4469
+ /**
4465
4470
  * Buffers observability events (creates and updates) for batch flushing.
4466
4471
  * Handles strategy-aware routing of tracing events and tracks created spans
4467
4472
  * so updates can be deferred until their parent create has been flushed.
@@ -4470,9 +4475,13 @@ var EventBuffer = class {
4470
4475
  #preInit = [];
4471
4476
  #creates = [];
4472
4477
  #updates = [];
4478
+ /** Span ends storage didn't apply, each held until its retry time. Outside `totalSize`, so they can't trigger a flush. */
4479
+ #heldRetries = [];
4473
4480
  #allCreatedSpans = /* @__PURE__ */ new Set();
4474
4481
  /** Spans whose SPAN_STARTED this buffer has seen but whose create isn't confirmed yet */
4475
4482
  #pendingCreateSpans = /* @__PURE__ */ new Set();
4483
+ /** Spans whose end storage accepted, oldest first */
4484
+ #endedSpans = /* @__PURE__ */ new Set();
4476
4485
  #firstEventTime;
4477
4486
  #storageStrategy;
4478
4487
  #maxRetries;
@@ -4582,6 +4591,39 @@ var EventBuffer = class {
4582
4591
  }
4583
4592
  return dropped;
4584
4593
  }
4594
+ /** Hold span ends storage didn't apply until their retry time, returning events that exceed max retries. */
4595
+ holdForRetry(events, retryDelay) {
4596
+ const now = Date.now();
4597
+ const dropped = [];
4598
+ for (const event of events) if (++event.retryCount <= this.#maxRetries) this.#heldRetries.push({
4599
+ event,
4600
+ retryAt: now + retryDelay(event.retryCount)
4601
+ });
4602
+ else dropped.push(event);
4603
+ return dropped;
4604
+ }
4605
+ /** Move held ends whose retry time is at or before `until` into the update buffer. */
4606
+ releaseHeldRetries(until = Date.now()) {
4607
+ const due = this.#heldRetries.filter((held) => held.retryAt <= until);
4608
+ if (due.length === 0) return;
4609
+ this.#heldRetries = this.#heldRetries.filter((held) => held.retryAt > until);
4610
+ this.setFirstEventTime();
4611
+ for (const { event } of due) {
4612
+ this.#byteTracker?.enqueue(event);
4613
+ this.#updates.push(event);
4614
+ }
4615
+ }
4616
+ /** Remove and return every held end. */
4617
+ takeHeldRetries() {
4618
+ const events = this.#heldRetries.map((held) => held.event);
4619
+ this.#heldRetries = [];
4620
+ this.releaseByteBatch(events);
4621
+ return events;
4622
+ }
4623
+ /** Epoch milliseconds of the earliest held retry. */
4624
+ get nextRetryAt() {
4625
+ return this.#heldRetries.reduce((earliest, { retryAt }) => earliest === void 0 ? retryAt : Math.min(earliest, retryAt), void 0);
4626
+ }
4585
4627
  /** Alternate creates and eligible updates so either queue can make progress under load. */
4586
4628
  takeByteBatch(maxRecords) {
4587
4629
  const tracker = this.#byteTracker;
@@ -4617,11 +4659,12 @@ var EventBuffer = class {
4617
4659
  updates
4618
4660
  };
4619
4661
  }
4620
- /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4662
+ /** Retries, deferred updates and held ends remain reserved; everything else has finished or been dropped. */
4621
4663
  releaseByteBatch(events) {
4622
4664
  if (!this.#byteTracker) return;
4665
+ const held = new Set(this.#heldRetries.map((retry) => retry.event));
4623
4666
  for (const event of events) {
4624
- if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4667
+ if (held.has(event) || !this.#byteTracker.releaseIfUnqueued(event)) continue;
4625
4668
  this.forgetDroppedCreates([event]);
4626
4669
  if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4627
4670
  traceId: event.exportedSpan.traceId,
@@ -4680,6 +4723,18 @@ var EventBuffer = class {
4680
4723
  isAwaitingCreate(span) {
4681
4724
  return this.#pendingCreateSpans.has(this.exportedSpanKey(span));
4682
4725
  }
4726
+ /** Remember spans whose end storage accepted, forgetting the oldest once the set is full. */
4727
+ rememberEndedSpans(spans) {
4728
+ for (const span of spans) this.#endedSpans.add(this.buildSpanKey(span));
4729
+ for (const key of this.#endedSpans) {
4730
+ if (this.#endedSpans.size <= MAX_ENDED_SPANS) break;
4731
+ this.#endedSpans.delete(key);
4732
+ }
4733
+ }
4734
+ /** Check whether storage accepted this span's end through this buffer. */
4735
+ wasEnded(span) {
4736
+ return this.#endedSpans.has(this.exportedSpanKey(span));
4737
+ }
4683
4738
  /** Remove completed spans from tracking after their SPAN_ENDED updates are flushed. */
4684
4739
  endFinishedSpans(args) {
4685
4740
  if (this.#storageStrategy === "event-sourced" || this.#storageStrategy === "insert-only") return;
@@ -5651,6 +5706,10 @@ function resolveTracingStorageStrategy(config, observabilityStorage, storageName
5651
5706
  }
5652
5707
  return observabilityStrategy.preferred;
5653
5708
  }
5709
+ const isDurableAgent = (agent) => "agent" in agent && Boolean(agent.agent);
5710
+ function usesDurableExecution(mastra) {
5711
+ return Object.values(mastra.listAgents()).some(isDurableAgent) || Object.values(mastra.listWorkflows()).some((workflow) => workflow.engineType !== "default");
5712
+ }
5654
5713
  const FLUSH_SUCCEEDED = { failed: false };
5655
5714
  /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5656
5715
  const MAX_FLUSH_ROUNDS = 3;
@@ -5667,10 +5726,12 @@ var MastraStorageExporter = class extends BaseExporter {
5667
5726
  #byteTracker;
5668
5727
  #byteRetryAt = 0;
5669
5728
  #byteDrainers = 0;
5729
+ #mastra;
5670
5730
  #storage;
5671
5731
  #observabilityStorage;
5672
5732
  #resolvedStrategy;
5673
5733
  #flushTimer;
5734
+ #retryTimer;
5674
5735
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5675
5736
  #inFlightFlushes = /* @__PURE__ */ new Set();
5676
5737
  #pendingAnnotations = /* @__PURE__ */ new Set();
@@ -5702,6 +5763,7 @@ var MastraStorageExporter = class extends BaseExporter {
5702
5763
  */
5703
5764
  async init(options) {
5704
5765
  this.#emitDropEvent = options.emitDropEvent;
5766
+ this.#mastra = options.mastra;
5705
5767
  this.#storage = options.mastra?.getStorage();
5706
5768
  if (!this.#storage) {
5707
5769
  this.logger.warn("MastraStorageExporter disabled: Storage not available. Traces will not be persisted.");
@@ -5782,11 +5844,26 @@ var MastraStorageExporter = class extends BaseExporter {
5782
5844
  if (this.#flushTimer) clearTimeout(this.#flushTimer);
5783
5845
  this.#flushTimer = setTimeout(() => {
5784
5846
  this.#flushTimer = void 0;
5785
- this.trackFlushBuffer().catch((error) => {
5786
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5787
- });
5847
+ this.flushOnTimer();
5788
5848
  }, delayMs);
5789
5849
  }
5850
+ /** Wakes a flush at the earliest held retry's time. A timer of its own, so a new batch can't push the retry back. */
5851
+ scheduleRetry() {
5852
+ clearTimeout(this.#retryTimer);
5853
+ const retryAt = this.#eventBuffer.nextRetryAt;
5854
+ this.#retryTimer = retryAt === void 0 ? void 0 : setTimeout(() => this.flushOnTimer(), Math.max(0, retryAt - Date.now()));
5855
+ }
5856
+ flushOnTimer() {
5857
+ this.trackFlushBuffer().catch((error) => {
5858
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5859
+ });
5860
+ }
5861
+ clearTimers() {
5862
+ clearTimeout(this.#flushTimer);
5863
+ clearTimeout(this.#retryTimer);
5864
+ this.#flushTimer = void 0;
5865
+ this.#retryTimer = void 0;
5866
+ }
5790
5867
  retryDelay(retryAttempt) {
5791
5868
  return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5792
5869
  }
@@ -5878,10 +5955,11 @@ var MastraStorageExporter = class extends BaseExporter {
5878
5955
  *
5879
5956
  * When the store supports conditional updates, only spans this exporter started
5880
5957
  * and hasn't confirmed the create for are deferred. Everything else, including
5881
- * spans another exporter instance started (such as a durable agent ending spans
5882
- * it rebuilt after a crash), goes straight to storage, and updates that didn't
5883
- * apply are counted as drops. Without conditional updates, updates for spans this
5884
- * exporter hasn't created are deferred until their create is flushed.
5958
+ * spans another exporter instance started (a durable agent ending spans it rebuilt
5959
+ * after a crash, or a worker finishing a run the API process started), goes straight
5960
+ * to storage, and updates that didn't apply go to `retryNotApplied`. Without conditional
5961
+ * updates, updates for spans this exporter hasn't created are deferred until their
5962
+ * create is flushed.
5885
5963
  *
5886
5964
  * When `isEnd` is true, successfully flushed spans are removed from tracking.
5887
5965
  */
@@ -5895,20 +5973,24 @@ var MastraStorageExporter = class extends BaseExporter {
5895
5973
  const storage = this.#observabilityStorage;
5896
5974
  const batchUpdateUnendedSpans = typeof storage.batchUpdateUnendedSpans === "function" ? storage.batchUpdateUnendedSpans.bind(storage) : void 0;
5897
5975
  const partials = [];
5976
+ const sent = [];
5898
5977
  for (const event of events) {
5899
5978
  const span = event.exportedSpan;
5900
- if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) partials.push({
5901
- traceId: span.traceId,
5902
- spanId: span.id,
5903
- updates: (0, _mastra_core_storage.buildUpdateSpanRecord)(span)
5904
- });
5905
- else deferredUpdates.push(event);
5979
+ if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) {
5980
+ partials.push({
5981
+ traceId: span.traceId,
5982
+ spanId: span.id,
5983
+ updates: (0, _mastra_core_storage.buildUpdateSpanRecord)(span)
5984
+ });
5985
+ sent.push(event);
5986
+ } else deferredUpdates.push(event);
5906
5987
  }
5907
5988
  if (partials.length === 0) return FLUSH_SUCCEEDED;
5908
5989
  try {
5909
5990
  if (batchUpdateUnendedSpans) {
5910
5991
  const { updated } = await batchUpdateUnendedSpans({ records: partials });
5911
- this.emitNotApplied(partials, updated);
5992
+ if (isEnd) this.#eventBuffer.rememberEndedSpans(updated);
5993
+ this.retryNotApplied(sent, updated);
5912
5994
  } else await storage.batchUpdateSpans({ records: partials });
5913
5995
  if (isEnd) this.#eventBuffer.endFinishedSpans({ records: partials });
5914
5996
  return FLUSH_SUCCEEDED;
@@ -5933,25 +6015,34 @@ var MastraStorageExporter = class extends BaseExporter {
5933
6015
  }
5934
6016
  }
5935
6017
  /**
5936
- * Reports conditional span updates that storage didn't apply: the span wasn't
5937
- * stored, or it had already ended. Ended spans are immutable, so these are dropped.
6018
+ * Handles conditional span updates that storage didn't apply. The store can't say whether
6019
+ * the row is missing or already ended. A span this exporter created and still tracks, or
6020
+ * whose end it stored, can't be missing, so its update is dropped. Any other span may belong
6021
+ * to a process whose create hasn't landed yet, so its end is held for a retry. Only ends retry:
6022
+ * an end carries the span's full state, and a retried update could overwrite a newer one.
6023
+ * `realtime` assumes one process owns a span, so it drops the end right away.
5938
6024
  */
5939
- emitNotApplied(partials, updated) {
6025
+ retryNotApplied(events, updated) {
5940
6026
  const appliedCounts = /* @__PURE__ */ new Map();
5941
6027
  for (const span of updated) {
5942
6028
  const key = `${span.traceId}:${span.spanId}`;
5943
6029
  appliedCounts.set(key, (appliedCounts.get(key) ?? 0) + 1);
5944
6030
  }
5945
- let notApplied = 0;
5946
- for (const partial of partials) {
5947
- const key = `${partial.traceId}:${partial.spanId}`;
6031
+ const retryable = [];
6032
+ let notUpdatable = 0;
6033
+ for (const event of events) {
6034
+ const span = event.exportedSpan;
6035
+ const key = `${span.traceId}:${span.id}`;
5948
6036
  const remaining = appliedCounts.get(key) ?? 0;
5949
6037
  if (remaining > 0) appliedCounts.set(key, remaining - 1);
5950
- else notApplied++;
6038
+ else if (event.type !== _mastra_core_observability.TracingEventType.SPAN_ENDED || this.#resolvedStrategy === "realtime" || this.#eventBuffer.spanExists(span) || this.#eventBuffer.wasEnded(span)) notUpdatable++;
6039
+ else retryable.push(event);
6040
+ }
6041
+ notUpdatable += this.#eventBuffer.holdForRetry(retryable, (attempt) => this.retryDelay(attempt)).length;
6042
+ if (notUpdatable > 0) {
6043
+ this.logger.debug("Span updates not applied: span not stored or already ended", { count: notUpdatable });
6044
+ this.emitDrop("tracing", "span-not-updatable", notUpdatable);
5951
6045
  }
5952
- if (notApplied === 0) return;
5953
- this.logger.debug("Span updates not applied: span not stored or already ended", { count: notApplied });
5954
- this.emitDrop("tracing", "span-not-updatable", notApplied);
5955
6046
  }
5956
6047
  /**
5957
6048
  * Runs flushBuffer() and tracks its promise so flush() can wait for writes
@@ -5977,6 +6068,7 @@ var MastraStorageExporter = class extends BaseExporter {
5977
6068
  const delay = Math.max(0, this.#byteRetryAt - Date.now());
5978
6069
  this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5979
6070
  }
6071
+ this.scheduleRetry();
5980
6072
  });
5981
6073
  this.#inFlightFlushes.add(promise);
5982
6074
  return promise;
@@ -6002,6 +6094,7 @@ var MastraStorageExporter = class extends BaseExporter {
6002
6094
  clearTimeout(this.#flushTimer);
6003
6095
  this.#flushTimer = void 0;
6004
6096
  }
6097
+ this.#eventBuffer.releaseHeldRetries();
6005
6098
  if (this.#eventBuffer.totalSize === 0) return;
6006
6099
  const startTime = Date.now();
6007
6100
  const batchSize = this.#eventBuffer.totalSize;
@@ -6099,12 +6192,18 @@ var MastraStorageExporter = class extends BaseExporter {
6099
6192
  getByteBatchingStats() {
6100
6193
  return this.#byteTracker?.stats(this.#inFlightFlushes.size);
6101
6194
  }
6195
+ fallBackFromRealtimeUnderDurableExecution() {
6196
+ if (this.#resolvedStrategy !== "realtime" || !this.#mastra || !usesDurableExecution(this.#mastra)) return;
6197
+ this.logger.warn("Tracing strategy realtime is not supported with durable execution, using batch-with-updates", { storageAdapter: this.#storage?.constructor.name });
6198
+ this.#resolvedStrategy = "batch-with-updates";
6199
+ }
6102
6200
  async _exportTracingEvent(event) {
6103
6201
  await this.ensureInitialized();
6104
6202
  if (!this.#observabilityStorage) {
6105
6203
  this.logger.debug("Cannot store traces. Observability storage is not initialized");
6106
6204
  return;
6107
6205
  }
6206
+ this.fallBackFromRealtimeUnderDurableExecution();
6108
6207
  this.#eventBuffer.addEvent({
6109
6208
  ...event,
6110
6209
  exportedSpan: withSpanPreviews(event.exportedSpan)
@@ -6217,10 +6316,8 @@ var MastraStorageExporter = class extends BaseExporter {
6217
6316
  this.logger.warn(`flush() stopped after ${MAX_FLUSH_ROUNDS} rounds; new writes kept starting`, { bufferedEventsLeftBehind: this.#eventBuffer.totalSize });
6218
6317
  }
6219
6318
  async shutdown() {
6220
- if (this.#flushTimer) {
6221
- clearTimeout(this.#flushTimer);
6222
- this.#flushTimer = void 0;
6223
- }
6319
+ this.clearTimers();
6320
+ this.#eventBuffer.releaseHeldRetries(Infinity);
6224
6321
  try {
6225
6322
  await this.flush();
6226
6323
  } catch (error) {
@@ -6233,11 +6330,10 @@ var MastraStorageExporter = class extends BaseExporter {
6233
6330
  this.logger.trackException(mastraError);
6234
6331
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
6235
6332
  } finally {
6236
- if (this.#flushTimer) {
6237
- clearTimeout(this.#flushTimer);
6238
- this.#flushTimer = void 0;
6239
- }
6333
+ this.clearTimers();
6240
6334
  }
6335
+ this.emitDrop("tracing", "span-not-updatable", this.#eventBuffer.takeHeldRetries().length);
6336
+ this.emitDrop("tracing", "retry-exhausted", this.#eventBuffer.updates.length);
6241
6337
  this.logger.info("MastraStorageExporter shutdown complete");
6242
6338
  }
6243
6339
  };
@@ -6580,7 +6676,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6580
6676
  getLoggerContext(span) {
6581
6677
  if (this.config.logging?.enabled === false) return _mastra_core_observability.noOpLoggerContext;
6582
6678
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6583
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6679
+ const metadata = span?.metadata;
6584
6680
  return new LoggerContextImpl({
6585
6681
  traceId: span?.traceId,
6586
6682
  spanId: resolveExportedSpanId(span),
@@ -6597,7 +6693,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6597
6693
  */
6598
6694
  getMetricsContext(span) {
6599
6695
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6600
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6696
+ const metadata = span?.metadata;
6601
6697
  return new MetricsContextImpl({
6602
6698
  traceId: span?.traceId,
6603
6699
  spanId: resolveExportedSpanId(span),
@@ -6991,14 +7087,20 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6991
7087
  async shutdown() {
6992
7088
  this.logger.debug(`[Observability] Shutdown started [name=${this.name}]`);
6993
7089
  await this.observabilityBus.shutdown();
6994
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.spanOutputProcessors.map((p) => p.shutdown())];
6995
- if (this.config.bridge) shutdownPromises.push(this.config.bridge.shutdown());
6996
- if (shutdownPromises.length > 0) {
6997
- const results = await Promise.allSettled(shutdownPromises);
6998
- for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
6999
- }
7090
+ const handlers = [...this.exporters, ...this.config.bridge ? [this.config.bridge] : []];
7091
+ const dropHandlers = handlers.filter((h) => h.onDroppedEvent);
7092
+ const others = [...handlers.filter((h) => !h.onDroppedEvent), ...this.spanOutputProcessors];
7093
+ await this.settleShutdownSteps(others.map((c) => c.shutdown()));
7094
+ await this.observabilityBus.drainPendingHandlers();
7095
+ await this.settleShutdownSteps(dropHandlers.map((h) => h.flush()));
7096
+ await this.settleShutdownSteps(dropHandlers.map((h) => h.shutdown()));
7097
+ await this.observabilityBus.drainPendingHandlers();
7000
7098
  this.logger.info(`[Observability] Shutdown completed [name=${this.name}]`);
7001
7099
  }
7100
+ async settleShutdownSteps(steps) {
7101
+ const results = await Promise.allSettled(steps);
7102
+ for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
7103
+ }
7002
7104
  };
7003
7105
  // src/client/id.ts
7004
7106
  function generateClientSignalId() {