@mastra/observability 1.24.1-alpha.0 → 1.24.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.
package/dist/index.js CHANGED
@@ -3641,7 +3641,7 @@ var BaseSpan = class BaseSpan {
3641
3641
  *
3642
3642
  * Note: metadata is still attached and deepCleaned because it is read in
3643
3643
  * process by getCorrelationContext() and by getLoggerContext() /
3644
- * getMetricsContext() (which structuredClone it).
3644
+ * getMetricsContext() (which hand it to a context that snapshots it).
3645
3645
  */
3646
3646
  isExcluded;
3647
3647
  /** Cached canonical correlation context for this live span */
@@ -4437,6 +4437,11 @@ var BaseExporter = class {
4437
4437
  };
4438
4438
  // src/exporters/event-buffer.ts
4439
4439
  /**
4440
+ * How many ended spans a buffer remembers, so a long-lived worker doesn't grow the set forever.
4441
+ * A second end of a forgotten span looks like a span that isn't stored yet, so it's retried before it's dropped.
4442
+ */
4443
+ const MAX_ENDED_SPANS = 1e4;
4444
+ /**
4440
4445
  * Buffers observability events (creates and updates) for batch flushing.
4441
4446
  * Handles strategy-aware routing of tracing events and tracks created spans
4442
4447
  * so updates can be deferred until their parent create has been flushed.
@@ -4445,9 +4450,13 @@ var EventBuffer = class {
4445
4450
  #preInit = [];
4446
4451
  #creates = [];
4447
4452
  #updates = [];
4453
+ /** Span ends storage didn't apply, each held until its retry time. Outside `totalSize`, so they can't trigger a flush. */
4454
+ #heldRetries = [];
4448
4455
  #allCreatedSpans = /* @__PURE__ */ new Set();
4449
4456
  /** Spans whose SPAN_STARTED this buffer has seen but whose create isn't confirmed yet */
4450
4457
  #pendingCreateSpans = /* @__PURE__ */ new Set();
4458
+ /** Spans whose end storage accepted, oldest first */
4459
+ #endedSpans = /* @__PURE__ */ new Set();
4451
4460
  #firstEventTime;
4452
4461
  #storageStrategy;
4453
4462
  #maxRetries;
@@ -4557,6 +4566,39 @@ var EventBuffer = class {
4557
4566
  }
4558
4567
  return dropped;
4559
4568
  }
4569
+ /** Hold span ends storage didn't apply until their retry time, returning events that exceed max retries. */
4570
+ holdForRetry(events, retryDelay) {
4571
+ const now = Date.now();
4572
+ const dropped = [];
4573
+ for (const event of events) if (++event.retryCount <= this.#maxRetries) this.#heldRetries.push({
4574
+ event,
4575
+ retryAt: now + retryDelay(event.retryCount)
4576
+ });
4577
+ else dropped.push(event);
4578
+ return dropped;
4579
+ }
4580
+ /** Move held ends whose retry time is at or before `until` into the update buffer. */
4581
+ releaseHeldRetries(until = Date.now()) {
4582
+ const due = this.#heldRetries.filter((held) => held.retryAt <= until);
4583
+ if (due.length === 0) return;
4584
+ this.#heldRetries = this.#heldRetries.filter((held) => held.retryAt > until);
4585
+ this.setFirstEventTime();
4586
+ for (const { event } of due) {
4587
+ this.#byteTracker?.enqueue(event);
4588
+ this.#updates.push(event);
4589
+ }
4590
+ }
4591
+ /** Remove and return every held end. */
4592
+ takeHeldRetries() {
4593
+ const events = this.#heldRetries.map((held) => held.event);
4594
+ this.#heldRetries = [];
4595
+ this.releaseByteBatch(events);
4596
+ return events;
4597
+ }
4598
+ /** Epoch milliseconds of the earliest held retry. */
4599
+ get nextRetryAt() {
4600
+ return this.#heldRetries.reduce((earliest, { retryAt }) => earliest === void 0 ? retryAt : Math.min(earliest, retryAt), void 0);
4601
+ }
4560
4602
  /** Alternate creates and eligible updates so either queue can make progress under load. */
4561
4603
  takeByteBatch(maxRecords) {
4562
4604
  const tracker = this.#byteTracker;
@@ -4592,11 +4634,12 @@ var EventBuffer = class {
4592
4634
  updates
4593
4635
  };
4594
4636
  }
4595
- /** Retries/deferred updates remain reserved; everything else has finished or been dropped. */
4637
+ /** Retries, deferred updates and held ends remain reserved; everything else has finished or been dropped. */
4596
4638
  releaseByteBatch(events) {
4597
4639
  if (!this.#byteTracker) return;
4640
+ const held = new Set(this.#heldRetries.map((retry) => retry.event));
4598
4641
  for (const event of events) {
4599
- if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4642
+ if (held.has(event) || !this.#byteTracker.releaseIfUnqueued(event)) continue;
4600
4643
  this.forgetDroppedCreates([event]);
4601
4644
  if (event.type === TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4602
4645
  traceId: event.exportedSpan.traceId,
@@ -4655,6 +4698,18 @@ var EventBuffer = class {
4655
4698
  isAwaitingCreate(span) {
4656
4699
  return this.#pendingCreateSpans.has(this.exportedSpanKey(span));
4657
4700
  }
4701
+ /** Remember spans whose end storage accepted, forgetting the oldest once the set is full. */
4702
+ rememberEndedSpans(spans) {
4703
+ for (const span of spans) this.#endedSpans.add(this.buildSpanKey(span));
4704
+ for (const key of this.#endedSpans) {
4705
+ if (this.#endedSpans.size <= MAX_ENDED_SPANS) break;
4706
+ this.#endedSpans.delete(key);
4707
+ }
4708
+ }
4709
+ /** Check whether storage accepted this span's end through this buffer. */
4710
+ wasEnded(span) {
4711
+ return this.#endedSpans.has(this.exportedSpanKey(span));
4712
+ }
4658
4713
  /** Remove completed spans from tracking after their SPAN_ENDED updates are flushed. */
4659
4714
  endFinishedSpans(args) {
4660
4715
  if (this.#storageStrategy === "event-sourced" || this.#storageStrategy === "insert-only") return;
@@ -5626,6 +5681,10 @@ function resolveTracingStorageStrategy(config, observabilityStorage, storageName
5626
5681
  }
5627
5682
  return observabilityStrategy.preferred;
5628
5683
  }
5684
+ const isDurableAgent = (agent) => "agent" in agent && Boolean(agent.agent);
5685
+ function usesDurableExecution(mastra) {
5686
+ return Object.values(mastra.listAgents()).some(isDurableAgent) || Object.values(mastra.listWorkflows()).some((workflow) => workflow.engineType !== "default");
5687
+ }
5629
5688
  const FLUSH_SUCCEEDED = { failed: false };
5630
5689
  /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5631
5690
  const MAX_FLUSH_ROUNDS = 3;
@@ -5642,10 +5701,12 @@ var MastraStorageExporter = class extends BaseExporter {
5642
5701
  #byteTracker;
5643
5702
  #byteRetryAt = 0;
5644
5703
  #byteDrainers = 0;
5704
+ #mastra;
5645
5705
  #storage;
5646
5706
  #observabilityStorage;
5647
5707
  #resolvedStrategy;
5648
5708
  #flushTimer;
5709
+ #retryTimer;
5649
5710
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5650
5711
  #inFlightFlushes = /* @__PURE__ */ new Set();
5651
5712
  #pendingAnnotations = /* @__PURE__ */ new Set();
@@ -5677,6 +5738,7 @@ var MastraStorageExporter = class extends BaseExporter {
5677
5738
  */
5678
5739
  async init(options) {
5679
5740
  this.#emitDropEvent = options.emitDropEvent;
5741
+ this.#mastra = options.mastra;
5680
5742
  this.#storage = options.mastra?.getStorage();
5681
5743
  if (!this.#storage) {
5682
5744
  this.logger.warn("MastraStorageExporter disabled: Storage not available. Traces will not be persisted.");
@@ -5757,11 +5819,26 @@ var MastraStorageExporter = class extends BaseExporter {
5757
5819
  if (this.#flushTimer) clearTimeout(this.#flushTimer);
5758
5820
  this.#flushTimer = setTimeout(() => {
5759
5821
  this.#flushTimer = void 0;
5760
- this.trackFlushBuffer().catch((error) => {
5761
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5762
- });
5822
+ this.flushOnTimer();
5763
5823
  }, delayMs);
5764
5824
  }
5825
+ /** 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. */
5826
+ scheduleRetry() {
5827
+ clearTimeout(this.#retryTimer);
5828
+ const retryAt = this.#eventBuffer.nextRetryAt;
5829
+ this.#retryTimer = retryAt === void 0 ? void 0 : setTimeout(() => this.flushOnTimer(), Math.max(0, retryAt - Date.now()));
5830
+ }
5831
+ flushOnTimer() {
5832
+ this.trackFlushBuffer().catch((error) => {
5833
+ this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5834
+ });
5835
+ }
5836
+ clearTimers() {
5837
+ clearTimeout(this.#flushTimer);
5838
+ clearTimeout(this.#retryTimer);
5839
+ this.#flushTimer = void 0;
5840
+ this.#retryTimer = void 0;
5841
+ }
5765
5842
  retryDelay(retryAttempt) {
5766
5843
  return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5767
5844
  }
@@ -5853,10 +5930,11 @@ var MastraStorageExporter = class extends BaseExporter {
5853
5930
  *
5854
5931
  * When the store supports conditional updates, only spans this exporter started
5855
5932
  * and hasn't confirmed the create for are deferred. Everything else, including
5856
- * spans another exporter instance started (such as a durable agent ending spans
5857
- * it rebuilt after a crash), goes straight to storage, and updates that didn't
5858
- * apply are counted as drops. Without conditional updates, updates for spans this
5859
- * exporter hasn't created are deferred until their create is flushed.
5933
+ * spans another exporter instance started (a durable agent ending spans it rebuilt
5934
+ * after a crash, or a worker finishing a run the API process started), goes straight
5935
+ * to storage, and updates that didn't apply go to `retryNotApplied`. Without conditional
5936
+ * updates, updates for spans this exporter hasn't created are deferred until their
5937
+ * create is flushed.
5860
5938
  *
5861
5939
  * When `isEnd` is true, successfully flushed spans are removed from tracking.
5862
5940
  */
@@ -5870,20 +5948,24 @@ var MastraStorageExporter = class extends BaseExporter {
5870
5948
  const storage = this.#observabilityStorage;
5871
5949
  const batchUpdateUnendedSpans = typeof storage.batchUpdateUnendedSpans === "function" ? storage.batchUpdateUnendedSpans.bind(storage) : void 0;
5872
5950
  const partials = [];
5951
+ const sent = [];
5873
5952
  for (const event of events) {
5874
5953
  const span = event.exportedSpan;
5875
- if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) partials.push({
5876
- traceId: span.traceId,
5877
- spanId: span.id,
5878
- updates: buildUpdateSpanRecord(span)
5879
- });
5880
- else deferredUpdates.push(event);
5954
+ if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) {
5955
+ partials.push({
5956
+ traceId: span.traceId,
5957
+ spanId: span.id,
5958
+ updates: buildUpdateSpanRecord(span)
5959
+ });
5960
+ sent.push(event);
5961
+ } else deferredUpdates.push(event);
5881
5962
  }
5882
5963
  if (partials.length === 0) return FLUSH_SUCCEEDED;
5883
5964
  try {
5884
5965
  if (batchUpdateUnendedSpans) {
5885
5966
  const { updated } = await batchUpdateUnendedSpans({ records: partials });
5886
- this.emitNotApplied(partials, updated);
5967
+ if (isEnd) this.#eventBuffer.rememberEndedSpans(updated);
5968
+ this.retryNotApplied(sent, updated);
5887
5969
  } else await storage.batchUpdateSpans({ records: partials });
5888
5970
  if (isEnd) this.#eventBuffer.endFinishedSpans({ records: partials });
5889
5971
  return FLUSH_SUCCEEDED;
@@ -5908,25 +5990,34 @@ var MastraStorageExporter = class extends BaseExporter {
5908
5990
  }
5909
5991
  }
5910
5992
  /**
5911
- * Reports conditional span updates that storage didn't apply: the span wasn't
5912
- * stored, or it had already ended. Ended spans are immutable, so these are dropped.
5993
+ * Handles conditional span updates that storage didn't apply. The store can't say whether
5994
+ * the row is missing or already ended. A span this exporter created and still tracks, or
5995
+ * whose end it stored, can't be missing, so its update is dropped. Any other span may belong
5996
+ * to a process whose create hasn't landed yet, so its end is held for a retry. Only ends retry:
5997
+ * an end carries the span's full state, and a retried update could overwrite a newer one.
5998
+ * `realtime` assumes one process owns a span, so it drops the end right away.
5913
5999
  */
5914
- emitNotApplied(partials, updated) {
6000
+ retryNotApplied(events, updated) {
5915
6001
  const appliedCounts = /* @__PURE__ */ new Map();
5916
6002
  for (const span of updated) {
5917
6003
  const key = `${span.traceId}:${span.spanId}`;
5918
6004
  appliedCounts.set(key, (appliedCounts.get(key) ?? 0) + 1);
5919
6005
  }
5920
- let notApplied = 0;
5921
- for (const partial of partials) {
5922
- const key = `${partial.traceId}:${partial.spanId}`;
6006
+ const retryable = [];
6007
+ let notUpdatable = 0;
6008
+ for (const event of events) {
6009
+ const span = event.exportedSpan;
6010
+ const key = `${span.traceId}:${span.id}`;
5923
6011
  const remaining = appliedCounts.get(key) ?? 0;
5924
6012
  if (remaining > 0) appliedCounts.set(key, remaining - 1);
5925
- else notApplied++;
6013
+ else if (event.type !== TracingEventType.SPAN_ENDED || this.#resolvedStrategy === "realtime" || this.#eventBuffer.spanExists(span) || this.#eventBuffer.wasEnded(span)) notUpdatable++;
6014
+ else retryable.push(event);
6015
+ }
6016
+ notUpdatable += this.#eventBuffer.holdForRetry(retryable, (attempt) => this.retryDelay(attempt)).length;
6017
+ if (notUpdatable > 0) {
6018
+ this.logger.debug("Span updates not applied: span not stored or already ended", { count: notUpdatable });
6019
+ this.emitDrop("tracing", "span-not-updatable", notUpdatable);
5926
6020
  }
5927
- if (notApplied === 0) return;
5928
- this.logger.debug("Span updates not applied: span not stored or already ended", { count: notApplied });
5929
- this.emitDrop("tracing", "span-not-updatable", notApplied);
5930
6021
  }
5931
6022
  /**
5932
6023
  * Runs flushBuffer() and tracks its promise so flush() can wait for writes
@@ -5952,6 +6043,7 @@ var MastraStorageExporter = class extends BaseExporter {
5952
6043
  const delay = Math.max(0, this.#byteRetryAt - Date.now());
5953
6044
  this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5954
6045
  }
6046
+ this.scheduleRetry();
5955
6047
  });
5956
6048
  this.#inFlightFlushes.add(promise);
5957
6049
  return promise;
@@ -5977,6 +6069,7 @@ var MastraStorageExporter = class extends BaseExporter {
5977
6069
  clearTimeout(this.#flushTimer);
5978
6070
  this.#flushTimer = void 0;
5979
6071
  }
6072
+ this.#eventBuffer.releaseHeldRetries();
5980
6073
  if (this.#eventBuffer.totalSize === 0) return;
5981
6074
  const startTime = Date.now();
5982
6075
  const batchSize = this.#eventBuffer.totalSize;
@@ -6074,12 +6167,18 @@ var MastraStorageExporter = class extends BaseExporter {
6074
6167
  getByteBatchingStats() {
6075
6168
  return this.#byteTracker?.stats(this.#inFlightFlushes.size);
6076
6169
  }
6170
+ fallBackFromRealtimeUnderDurableExecution() {
6171
+ if (this.#resolvedStrategy !== "realtime" || !this.#mastra || !usesDurableExecution(this.#mastra)) return;
6172
+ this.logger.warn("Tracing strategy realtime is not supported with durable execution, using batch-with-updates", { storageAdapter: this.#storage?.constructor.name });
6173
+ this.#resolvedStrategy = "batch-with-updates";
6174
+ }
6077
6175
  async _exportTracingEvent(event) {
6078
6176
  await this.ensureInitialized();
6079
6177
  if (!this.#observabilityStorage) {
6080
6178
  this.logger.debug("Cannot store traces. Observability storage is not initialized");
6081
6179
  return;
6082
6180
  }
6181
+ this.fallBackFromRealtimeUnderDurableExecution();
6083
6182
  this.#eventBuffer.addEvent({
6084
6183
  ...event,
6085
6184
  exportedSpan: withSpanPreviews(event.exportedSpan)
@@ -6192,10 +6291,8 @@ var MastraStorageExporter = class extends BaseExporter {
6192
6291
  this.logger.warn(`flush() stopped after ${MAX_FLUSH_ROUNDS} rounds; new writes kept starting`, { bufferedEventsLeftBehind: this.#eventBuffer.totalSize });
6193
6292
  }
6194
6293
  async shutdown() {
6195
- if (this.#flushTimer) {
6196
- clearTimeout(this.#flushTimer);
6197
- this.#flushTimer = void 0;
6198
- }
6294
+ this.clearTimers();
6295
+ this.#eventBuffer.releaseHeldRetries(Infinity);
6199
6296
  try {
6200
6297
  await this.flush();
6201
6298
  } catch (error) {
@@ -6208,11 +6305,10 @@ var MastraStorageExporter = class extends BaseExporter {
6208
6305
  this.logger.trackException(mastraError);
6209
6306
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
6210
6307
  } finally {
6211
- if (this.#flushTimer) {
6212
- clearTimeout(this.#flushTimer);
6213
- this.#flushTimer = void 0;
6214
- }
6308
+ this.clearTimers();
6215
6309
  }
6310
+ this.emitDrop("tracing", "span-not-updatable", this.#eventBuffer.takeHeldRetries().length);
6311
+ this.emitDrop("tracing", "retry-exhausted", this.#eventBuffer.updates.length);
6216
6312
  this.logger.info("MastraStorageExporter shutdown complete");
6217
6313
  }
6218
6314
  };
@@ -6555,7 +6651,7 @@ var BaseObservabilityInstance = class extends MastraBase {
6555
6651
  getLoggerContext(span) {
6556
6652
  if (this.config.logging?.enabled === false) return noOpLoggerContext;
6557
6653
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6558
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6654
+ const metadata = span?.metadata;
6559
6655
  return new LoggerContextImpl({
6560
6656
  traceId: span?.traceId,
6561
6657
  spanId: resolveExportedSpanId(span),
@@ -6572,7 +6668,7 @@ var BaseObservabilityInstance = class extends MastraBase {
6572
6668
  */
6573
6669
  getMetricsContext(span) {
6574
6670
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6575
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6671
+ const metadata = span?.metadata;
6576
6672
  return new MetricsContextImpl({
6577
6673
  traceId: span?.traceId,
6578
6674
  spanId: resolveExportedSpanId(span),
@@ -6966,14 +7062,20 @@ var BaseObservabilityInstance = class extends MastraBase {
6966
7062
  async shutdown() {
6967
7063
  this.logger.debug(`[Observability] Shutdown started [name=${this.name}]`);
6968
7064
  await this.observabilityBus.shutdown();
6969
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.spanOutputProcessors.map((p) => p.shutdown())];
6970
- if (this.config.bridge) shutdownPromises.push(this.config.bridge.shutdown());
6971
- if (shutdownPromises.length > 0) {
6972
- const results = await Promise.allSettled(shutdownPromises);
6973
- for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
6974
- }
7065
+ const handlers = [...this.exporters, ...this.config.bridge ? [this.config.bridge] : []];
7066
+ const dropHandlers = handlers.filter((h) => h.onDroppedEvent);
7067
+ const others = [...handlers.filter((h) => !h.onDroppedEvent), ...this.spanOutputProcessors];
7068
+ await this.settleShutdownSteps(others.map((c) => c.shutdown()));
7069
+ await this.observabilityBus.drainPendingHandlers();
7070
+ await this.settleShutdownSteps(dropHandlers.map((h) => h.flush()));
7071
+ await this.settleShutdownSteps(dropHandlers.map((h) => h.shutdown()));
7072
+ await this.observabilityBus.drainPendingHandlers();
6975
7073
  this.logger.info(`[Observability] Shutdown completed [name=${this.name}]`);
6976
7074
  }
7075
+ async settleShutdownSteps(steps) {
7076
+ const results = await Promise.allSettled(steps);
7077
+ for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
7078
+ }
6977
7079
  };
6978
7080
  // src/client/id.ts
6979
7081
  function generateClientSignalId() {