@mastra/observability 1.24.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,QAAQ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AA;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;IAGtB,QA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E;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 */
@@ -4151,7 +4151,8 @@ var DefaultSpan = class extends BaseSpan {
4151
4151
  if (options) this.applyOutcome(options);
4152
4152
  if (this.outcome === null) this.outcome = "unknown";
4153
4153
  const endTime = options?.endTime;
4154
- this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
4154
+ const candidate = endTime instanceof Date ? endTime : /* @__PURE__ */ new Date();
4155
+ this.endTime = candidate < this.startTime ? this.startTime : candidate;
4155
4156
  this.detachFromParent();
4156
4157
  if (options?.metadata) this.metadata = {
4157
4158
  ...this.metadata,
@@ -4461,6 +4462,11 @@ var BaseExporter = class {
4461
4462
  };
4462
4463
  // src/exporters/event-buffer.ts
4463
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
+ /**
4464
4470
  * Buffers observability events (creates and updates) for batch flushing.
4465
4471
  * Handles strategy-aware routing of tracing events and tracks created spans
4466
4472
  * so updates can be deferred until their parent create has been flushed.
@@ -4469,9 +4475,13 @@ var EventBuffer = class {
4469
4475
  #preInit = [];
4470
4476
  #creates = [];
4471
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 = [];
4472
4480
  #allCreatedSpans = /* @__PURE__ */ new Set();
4473
4481
  /** Spans whose SPAN_STARTED this buffer has seen but whose create isn't confirmed yet */
4474
4482
  #pendingCreateSpans = /* @__PURE__ */ new Set();
4483
+ /** Spans whose end storage accepted, oldest first */
4484
+ #endedSpans = /* @__PURE__ */ new Set();
4475
4485
  #firstEventTime;
4476
4486
  #storageStrategy;
4477
4487
  #maxRetries;
@@ -4581,6 +4591,39 @@ var EventBuffer = class {
4581
4591
  }
4582
4592
  return dropped;
4583
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
+ }
4584
4627
  /** Alternate creates and eligible updates so either queue can make progress under load. */
4585
4628
  takeByteBatch(maxRecords) {
4586
4629
  const tracker = this.#byteTracker;
@@ -4616,11 +4659,12 @@ var EventBuffer = class {
4616
4659
  updates
4617
4660
  };
4618
4661
  }
4619
- /** 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. */
4620
4663
  releaseByteBatch(events) {
4621
4664
  if (!this.#byteTracker) return;
4665
+ const held = new Set(this.#heldRetries.map((retry) => retry.event));
4622
4666
  for (const event of events) {
4623
- if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4667
+ if (held.has(event) || !this.#byteTracker.releaseIfUnqueued(event)) continue;
4624
4668
  this.forgetDroppedCreates([event]);
4625
4669
  if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4626
4670
  traceId: event.exportedSpan.traceId,
@@ -4679,6 +4723,18 @@ var EventBuffer = class {
4679
4723
  isAwaitingCreate(span) {
4680
4724
  return this.#pendingCreateSpans.has(this.exportedSpanKey(span));
4681
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
+ }
4682
4738
  /** Remove completed spans from tracking after their SPAN_ENDED updates are flushed. */
4683
4739
  endFinishedSpans(args) {
4684
4740
  if (this.#storageStrategy === "event-sourced" || this.#storageStrategy === "insert-only") return;
@@ -5650,6 +5706,10 @@ function resolveTracingStorageStrategy(config, observabilityStorage, storageName
5650
5706
  }
5651
5707
  return observabilityStrategy.preferred;
5652
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
+ }
5653
5713
  const FLUSH_SUCCEEDED = { failed: false };
5654
5714
  /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5655
5715
  const MAX_FLUSH_ROUNDS = 3;
@@ -5666,10 +5726,12 @@ var MastraStorageExporter = class extends BaseExporter {
5666
5726
  #byteTracker;
5667
5727
  #byteRetryAt = 0;
5668
5728
  #byteDrainers = 0;
5729
+ #mastra;
5669
5730
  #storage;
5670
5731
  #observabilityStorage;
5671
5732
  #resolvedStrategy;
5672
5733
  #flushTimer;
5734
+ #retryTimer;
5673
5735
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5674
5736
  #inFlightFlushes = /* @__PURE__ */ new Set();
5675
5737
  #pendingAnnotations = /* @__PURE__ */ new Set();
@@ -5701,6 +5763,7 @@ var MastraStorageExporter = class extends BaseExporter {
5701
5763
  */
5702
5764
  async init(options) {
5703
5765
  this.#emitDropEvent = options.emitDropEvent;
5766
+ this.#mastra = options.mastra;
5704
5767
  this.#storage = options.mastra?.getStorage();
5705
5768
  if (!this.#storage) {
5706
5769
  this.logger.warn("MastraStorageExporter disabled: Storage not available. Traces will not be persisted.");
@@ -5781,11 +5844,26 @@ var MastraStorageExporter = class extends BaseExporter {
5781
5844
  if (this.#flushTimer) clearTimeout(this.#flushTimer);
5782
5845
  this.#flushTimer = setTimeout(() => {
5783
5846
  this.#flushTimer = void 0;
5784
- this.trackFlushBuffer().catch((error) => {
5785
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5786
- });
5847
+ this.flushOnTimer();
5787
5848
  }, delayMs);
5788
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
+ }
5789
5867
  retryDelay(retryAttempt) {
5790
5868
  return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5791
5869
  }
@@ -5877,10 +5955,11 @@ var MastraStorageExporter = class extends BaseExporter {
5877
5955
  *
5878
5956
  * When the store supports conditional updates, only spans this exporter started
5879
5957
  * and hasn't confirmed the create for are deferred. Everything else, including
5880
- * spans another exporter instance started (such as a durable agent ending spans
5881
- * it rebuilt after a crash), goes straight to storage, and updates that didn't
5882
- * apply are counted as drops. Without conditional updates, updates for spans this
5883
- * 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.
5884
5963
  *
5885
5964
  * When `isEnd` is true, successfully flushed spans are removed from tracking.
5886
5965
  */
@@ -5894,20 +5973,24 @@ var MastraStorageExporter = class extends BaseExporter {
5894
5973
  const storage = this.#observabilityStorage;
5895
5974
  const batchUpdateUnendedSpans = typeof storage.batchUpdateUnendedSpans === "function" ? storage.batchUpdateUnendedSpans.bind(storage) : void 0;
5896
5975
  const partials = [];
5976
+ const sent = [];
5897
5977
  for (const event of events) {
5898
5978
  const span = event.exportedSpan;
5899
- if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) partials.push({
5900
- traceId: span.traceId,
5901
- spanId: span.id,
5902
- updates: (0, _mastra_core_storage.buildUpdateSpanRecord)(span)
5903
- });
5904
- 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);
5905
5987
  }
5906
5988
  if (partials.length === 0) return FLUSH_SUCCEEDED;
5907
5989
  try {
5908
5990
  if (batchUpdateUnendedSpans) {
5909
5991
  const { updated } = await batchUpdateUnendedSpans({ records: partials });
5910
- this.emitNotApplied(partials, updated);
5992
+ if (isEnd) this.#eventBuffer.rememberEndedSpans(updated);
5993
+ this.retryNotApplied(sent, updated);
5911
5994
  } else await storage.batchUpdateSpans({ records: partials });
5912
5995
  if (isEnd) this.#eventBuffer.endFinishedSpans({ records: partials });
5913
5996
  return FLUSH_SUCCEEDED;
@@ -5932,25 +6015,34 @@ var MastraStorageExporter = class extends BaseExporter {
5932
6015
  }
5933
6016
  }
5934
6017
  /**
5935
- * Reports conditional span updates that storage didn't apply: the span wasn't
5936
- * 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.
5937
6024
  */
5938
- emitNotApplied(partials, updated) {
6025
+ retryNotApplied(events, updated) {
5939
6026
  const appliedCounts = /* @__PURE__ */ new Map();
5940
6027
  for (const span of updated) {
5941
6028
  const key = `${span.traceId}:${span.spanId}`;
5942
6029
  appliedCounts.set(key, (appliedCounts.get(key) ?? 0) + 1);
5943
6030
  }
5944
- let notApplied = 0;
5945
- for (const partial of partials) {
5946
- 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}`;
5947
6036
  const remaining = appliedCounts.get(key) ?? 0;
5948
6037
  if (remaining > 0) appliedCounts.set(key, remaining - 1);
5949
- 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);
5950
6045
  }
5951
- if (notApplied === 0) return;
5952
- this.logger.debug("Span updates not applied: span not stored or already ended", { count: notApplied });
5953
- this.emitDrop("tracing", "span-not-updatable", notApplied);
5954
6046
  }
5955
6047
  /**
5956
6048
  * Runs flushBuffer() and tracks its promise so flush() can wait for writes
@@ -5976,6 +6068,7 @@ var MastraStorageExporter = class extends BaseExporter {
5976
6068
  const delay = Math.max(0, this.#byteRetryAt - Date.now());
5977
6069
  this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5978
6070
  }
6071
+ this.scheduleRetry();
5979
6072
  });
5980
6073
  this.#inFlightFlushes.add(promise);
5981
6074
  return promise;
@@ -6001,6 +6094,7 @@ var MastraStorageExporter = class extends BaseExporter {
6001
6094
  clearTimeout(this.#flushTimer);
6002
6095
  this.#flushTimer = void 0;
6003
6096
  }
6097
+ this.#eventBuffer.releaseHeldRetries();
6004
6098
  if (this.#eventBuffer.totalSize === 0) return;
6005
6099
  const startTime = Date.now();
6006
6100
  const batchSize = this.#eventBuffer.totalSize;
@@ -6098,12 +6192,18 @@ var MastraStorageExporter = class extends BaseExporter {
6098
6192
  getByteBatchingStats() {
6099
6193
  return this.#byteTracker?.stats(this.#inFlightFlushes.size);
6100
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
+ }
6101
6200
  async _exportTracingEvent(event) {
6102
6201
  await this.ensureInitialized();
6103
6202
  if (!this.#observabilityStorage) {
6104
6203
  this.logger.debug("Cannot store traces. Observability storage is not initialized");
6105
6204
  return;
6106
6205
  }
6206
+ this.fallBackFromRealtimeUnderDurableExecution();
6107
6207
  this.#eventBuffer.addEvent({
6108
6208
  ...event,
6109
6209
  exportedSpan: withSpanPreviews(event.exportedSpan)
@@ -6216,10 +6316,8 @@ var MastraStorageExporter = class extends BaseExporter {
6216
6316
  this.logger.warn(`flush() stopped after ${MAX_FLUSH_ROUNDS} rounds; new writes kept starting`, { bufferedEventsLeftBehind: this.#eventBuffer.totalSize });
6217
6317
  }
6218
6318
  async shutdown() {
6219
- if (this.#flushTimer) {
6220
- clearTimeout(this.#flushTimer);
6221
- this.#flushTimer = void 0;
6222
- }
6319
+ this.clearTimers();
6320
+ this.#eventBuffer.releaseHeldRetries(Infinity);
6223
6321
  try {
6224
6322
  await this.flush();
6225
6323
  } catch (error) {
@@ -6232,11 +6330,10 @@ var MastraStorageExporter = class extends BaseExporter {
6232
6330
  this.logger.trackException(mastraError);
6233
6331
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
6234
6332
  } finally {
6235
- if (this.#flushTimer) {
6236
- clearTimeout(this.#flushTimer);
6237
- this.#flushTimer = void 0;
6238
- }
6333
+ this.clearTimers();
6239
6334
  }
6335
+ this.emitDrop("tracing", "span-not-updatable", this.#eventBuffer.takeHeldRetries().length);
6336
+ this.emitDrop("tracing", "retry-exhausted", this.#eventBuffer.updates.length);
6240
6337
  this.logger.info("MastraStorageExporter shutdown complete");
6241
6338
  }
6242
6339
  };
@@ -6579,7 +6676,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6579
6676
  getLoggerContext(span) {
6580
6677
  if (this.config.logging?.enabled === false) return _mastra_core_observability.noOpLoggerContext;
6581
6678
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6582
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6679
+ const metadata = span?.metadata;
6583
6680
  return new LoggerContextImpl({
6584
6681
  traceId: span?.traceId,
6585
6682
  spanId: resolveExportedSpanId(span),
@@ -6596,7 +6693,7 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6596
6693
  */
6597
6694
  getMetricsContext(span) {
6598
6695
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6599
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6696
+ const metadata = span?.metadata;
6600
6697
  return new MetricsContextImpl({
6601
6698
  traceId: span?.traceId,
6602
6699
  spanId: resolveExportedSpanId(span),
@@ -6990,14 +7087,20 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
6990
7087
  async shutdown() {
6991
7088
  this.logger.debug(`[Observability] Shutdown started [name=${this.name}]`);
6992
7089
  await this.observabilityBus.shutdown();
6993
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.spanOutputProcessors.map((p) => p.shutdown())];
6994
- if (this.config.bridge) shutdownPromises.push(this.config.bridge.shutdown());
6995
- if (shutdownPromises.length > 0) {
6996
- const results = await Promise.allSettled(shutdownPromises);
6997
- for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
6998
- }
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();
6999
7098
  this.logger.info(`[Observability] Shutdown completed [name=${this.name}]`);
7000
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
+ }
7001
7104
  };
7002
7105
  // src/client/id.ts
7003
7106
  function generateClientSignalId() {
@@ -7018,6 +7121,14 @@ function generateClientSignalId() {
7018
7121
  * Using `@opentelemetry/otlp-transformer` would pull in the full proto
7019
7122
  * dependency tree (~hundreds of KB) for what amounts to a 100-line walker.
7020
7123
  */
7124
+ function hasReversedTimestamps(start, end) {
7125
+ if (typeof start !== "string" && typeof start !== "number" || typeof end !== "string" && typeof end !== "number") return false;
7126
+ try {
7127
+ return BigInt(end) < BigInt(start);
7128
+ } catch {
7129
+ return false;
7130
+ }
7131
+ }
7021
7132
  /**
7022
7133
  * Convert an OTLP nanosecond timestamp (string or number) to a JS Date.
7023
7134
  *
@@ -7026,7 +7137,7 @@ function generateClientSignalId() {
7026
7137
  * uint64 to avoid JS number precision loss) or numbers.
7027
7138
  */
7028
7139
  function nanosToDate(value) {
7029
- if (typeof value === "number") return new Date(Math.round(value / 1e6));
7140
+ if (typeof value === "number") return new Date(Math.trunc(value / 1e6));
7030
7141
  if (typeof value === "string") {
7031
7142
  if (value.length <= 6) return /* @__PURE__ */ new Date(0);
7032
7143
  const ms = Number(value.slice(0, -6));
@@ -7084,6 +7195,7 @@ function decodeResourceSpans(payload) {
7084
7195
  spanId,
7085
7196
  parentSpanId: typeof s.parentSpanId === "string" && s.parentSpanId ? s.parentSpanId : void 0,
7086
7197
  name,
7198
+ ...hasReversedTimestamps(s.startTimeUnixNano, s.endTimeUnixNano) ? { hasReversedTimestamps: true } : {},
7087
7199
  startTime: nanosToDate(s.startTimeUnixNano),
7088
7200
  endTime: s.endTimeUnixNano !== void 0 ? nanosToDate(s.endTimeUnixNano) : void 0,
7089
7201
  attributes: flattenAttributes(s.attributes)
@@ -7330,6 +7442,14 @@ var ClientObservabilityProxyImpl = class {
7330
7442
  this.#warn("Client observability payload contains spans with orphan parents; dropping.");
7331
7443
  return;
7332
7444
  }
7445
+ if (decodedSpans.some((span) => span.hasReversedTimestamps || span.endTime && span.endTime < span.startTime)) {
7446
+ this.#warn("Client observability payload contains a span whose end precedes its start; dropping.");
7447
+ return;
7448
+ }
7449
+ if (typeof payload.executionDurationMs === "number" && payload.executionDurationMs < 0) {
7450
+ this.#warn("Client observability payload contains a negative execution duration; dropping.");
7451
+ return;
7452
+ }
7333
7453
  for (const decoded of decodedSpans) {
7334
7454
  const exported = buildExportedSpan(decoded);
7335
7455
  const startedEvent = {