@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.
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 */
@@ -4126,7 +4126,8 @@ var DefaultSpan = class extends BaseSpan {
4126
4126
  if (options) this.applyOutcome(options);
4127
4127
  if (this.outcome === null) this.outcome = "unknown";
4128
4128
  const endTime = options?.endTime;
4129
- this.endTime = endTime instanceof Date && endTime >= this.startTime ? endTime : /* @__PURE__ */ new Date();
4129
+ const candidate = endTime instanceof Date ? endTime : /* @__PURE__ */ new Date();
4130
+ this.endTime = candidate < this.startTime ? this.startTime : candidate;
4130
4131
  this.detachFromParent();
4131
4132
  if (options?.metadata) this.metadata = {
4132
4133
  ...this.metadata,
@@ -4436,6 +4437,11 @@ var BaseExporter = class {
4436
4437
  };
4437
4438
  // src/exporters/event-buffer.ts
4438
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
+ /**
4439
4445
  * Buffers observability events (creates and updates) for batch flushing.
4440
4446
  * Handles strategy-aware routing of tracing events and tracks created spans
4441
4447
  * so updates can be deferred until their parent create has been flushed.
@@ -4444,9 +4450,13 @@ var EventBuffer = class {
4444
4450
  #preInit = [];
4445
4451
  #creates = [];
4446
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 = [];
4447
4455
  #allCreatedSpans = /* @__PURE__ */ new Set();
4448
4456
  /** Spans whose SPAN_STARTED this buffer has seen but whose create isn't confirmed yet */
4449
4457
  #pendingCreateSpans = /* @__PURE__ */ new Set();
4458
+ /** Spans whose end storage accepted, oldest first */
4459
+ #endedSpans = /* @__PURE__ */ new Set();
4450
4460
  #firstEventTime;
4451
4461
  #storageStrategy;
4452
4462
  #maxRetries;
@@ -4556,6 +4566,39 @@ var EventBuffer = class {
4556
4566
  }
4557
4567
  return dropped;
4558
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
+ }
4559
4602
  /** Alternate creates and eligible updates so either queue can make progress under load. */
4560
4603
  takeByteBatch(maxRecords) {
4561
4604
  const tracker = this.#byteTracker;
@@ -4591,11 +4634,12 @@ var EventBuffer = class {
4591
4634
  updates
4592
4635
  };
4593
4636
  }
4594
- /** 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. */
4595
4638
  releaseByteBatch(events) {
4596
4639
  if (!this.#byteTracker) return;
4640
+ const held = new Set(this.#heldRetries.map((retry) => retry.event));
4597
4641
  for (const event of events) {
4598
- if (!this.#byteTracker.releaseIfUnqueued(event)) continue;
4642
+ if (held.has(event) || !this.#byteTracker.releaseIfUnqueued(event)) continue;
4599
4643
  this.forgetDroppedCreates([event]);
4600
4644
  if (event.type === TracingEventType.SPAN_ENDED) this.endFinishedSpans({ records: [{
4601
4645
  traceId: event.exportedSpan.traceId,
@@ -4654,6 +4698,18 @@ var EventBuffer = class {
4654
4698
  isAwaitingCreate(span) {
4655
4699
  return this.#pendingCreateSpans.has(this.exportedSpanKey(span));
4656
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
+ }
4657
4713
  /** Remove completed spans from tracking after their SPAN_ENDED updates are flushed. */
4658
4714
  endFinishedSpans(args) {
4659
4715
  if (this.#storageStrategy === "event-sourced" || this.#storageStrategy === "insert-only") return;
@@ -5625,6 +5681,10 @@ function resolveTracingStorageStrategy(config, observabilityStorage, storageName
5625
5681
  }
5626
5682
  return observabilityStrategy.preferred;
5627
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
+ }
5628
5688
  const FLUSH_SUCCEEDED = { failed: false };
5629
5689
  /** Max join/write rounds a single flush() makes before it returns under continuous traffic */
5630
5690
  const MAX_FLUSH_ROUNDS = 3;
@@ -5641,10 +5701,12 @@ var MastraStorageExporter = class extends BaseExporter {
5641
5701
  #byteTracker;
5642
5702
  #byteRetryAt = 0;
5643
5703
  #byteDrainers = 0;
5704
+ #mastra;
5644
5705
  #storage;
5645
5706
  #observabilityStorage;
5646
5707
  #resolvedStrategy;
5647
5708
  #flushTimer;
5709
+ #retryTimer;
5648
5710
  /** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
5649
5711
  #inFlightFlushes = /* @__PURE__ */ new Set();
5650
5712
  #pendingAnnotations = /* @__PURE__ */ new Set();
@@ -5676,6 +5738,7 @@ var MastraStorageExporter = class extends BaseExporter {
5676
5738
  */
5677
5739
  async init(options) {
5678
5740
  this.#emitDropEvent = options.emitDropEvent;
5741
+ this.#mastra = options.mastra;
5679
5742
  this.#storage = options.mastra?.getStorage();
5680
5743
  if (!this.#storage) {
5681
5744
  this.logger.warn("MastraStorageExporter disabled: Storage not available. Traces will not be persisted.");
@@ -5756,11 +5819,26 @@ var MastraStorageExporter = class extends BaseExporter {
5756
5819
  if (this.#flushTimer) clearTimeout(this.#flushTimer);
5757
5820
  this.#flushTimer = setTimeout(() => {
5758
5821
  this.#flushTimer = void 0;
5759
- this.trackFlushBuffer().catch((error) => {
5760
- this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
5761
- });
5822
+ this.flushOnTimer();
5762
5823
  }, delayMs);
5763
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
+ }
5764
5842
  retryDelay(retryAttempt) {
5765
5843
  return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
5766
5844
  }
@@ -5852,10 +5930,11 @@ var MastraStorageExporter = class extends BaseExporter {
5852
5930
  *
5853
5931
  * When the store supports conditional updates, only spans this exporter started
5854
5932
  * and hasn't confirmed the create for are deferred. Everything else, including
5855
- * spans another exporter instance started (such as a durable agent ending spans
5856
- * it rebuilt after a crash), goes straight to storage, and updates that didn't
5857
- * apply are counted as drops. Without conditional updates, updates for spans this
5858
- * 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.
5859
5938
  *
5860
5939
  * When `isEnd` is true, successfully flushed spans are removed from tracking.
5861
5940
  */
@@ -5869,20 +5948,24 @@ var MastraStorageExporter = class extends BaseExporter {
5869
5948
  const storage = this.#observabilityStorage;
5870
5949
  const batchUpdateUnendedSpans = typeof storage.batchUpdateUnendedSpans === "function" ? storage.batchUpdateUnendedSpans.bind(storage) : void 0;
5871
5950
  const partials = [];
5951
+ const sent = [];
5872
5952
  for (const event of events) {
5873
5953
  const span = event.exportedSpan;
5874
- if (batchUpdateUnendedSpans ? !this.#eventBuffer.isAwaitingCreate(span) : this.#eventBuffer.spanExists(span)) partials.push({
5875
- traceId: span.traceId,
5876
- spanId: span.id,
5877
- updates: buildUpdateSpanRecord(span)
5878
- });
5879
- 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);
5880
5962
  }
5881
5963
  if (partials.length === 0) return FLUSH_SUCCEEDED;
5882
5964
  try {
5883
5965
  if (batchUpdateUnendedSpans) {
5884
5966
  const { updated } = await batchUpdateUnendedSpans({ records: partials });
5885
- this.emitNotApplied(partials, updated);
5967
+ if (isEnd) this.#eventBuffer.rememberEndedSpans(updated);
5968
+ this.retryNotApplied(sent, updated);
5886
5969
  } else await storage.batchUpdateSpans({ records: partials });
5887
5970
  if (isEnd) this.#eventBuffer.endFinishedSpans({ records: partials });
5888
5971
  return FLUSH_SUCCEEDED;
@@ -5907,25 +5990,34 @@ var MastraStorageExporter = class extends BaseExporter {
5907
5990
  }
5908
5991
  }
5909
5992
  /**
5910
- * Reports conditional span updates that storage didn't apply: the span wasn't
5911
- * 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.
5912
5999
  */
5913
- emitNotApplied(partials, updated) {
6000
+ retryNotApplied(events, updated) {
5914
6001
  const appliedCounts = /* @__PURE__ */ new Map();
5915
6002
  for (const span of updated) {
5916
6003
  const key = `${span.traceId}:${span.spanId}`;
5917
6004
  appliedCounts.set(key, (appliedCounts.get(key) ?? 0) + 1);
5918
6005
  }
5919
- let notApplied = 0;
5920
- for (const partial of partials) {
5921
- 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}`;
5922
6011
  const remaining = appliedCounts.get(key) ?? 0;
5923
6012
  if (remaining > 0) appliedCounts.set(key, remaining - 1);
5924
- 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);
5925
6020
  }
5926
- if (notApplied === 0) return;
5927
- this.logger.debug("Span updates not applied: span not stored or already ended", { count: notApplied });
5928
- this.emitDrop("tracing", "span-not-updatable", notApplied);
5929
6021
  }
5930
6022
  /**
5931
6023
  * Runs flushBuffer() and tracks its promise so flush() can wait for writes
@@ -5951,6 +6043,7 @@ var MastraStorageExporter = class extends BaseExporter {
5951
6043
  const delay = Math.max(0, this.#byteRetryAt - Date.now());
5952
6044
  this.scheduleFlush(delay || (this.#byteDrainers || this.shouldFlush() ? 0 : this.#config.maxBatchWaitMs));
5953
6045
  }
6046
+ this.scheduleRetry();
5954
6047
  });
5955
6048
  this.#inFlightFlushes.add(promise);
5956
6049
  return promise;
@@ -5976,6 +6069,7 @@ var MastraStorageExporter = class extends BaseExporter {
5976
6069
  clearTimeout(this.#flushTimer);
5977
6070
  this.#flushTimer = void 0;
5978
6071
  }
6072
+ this.#eventBuffer.releaseHeldRetries();
5979
6073
  if (this.#eventBuffer.totalSize === 0) return;
5980
6074
  const startTime = Date.now();
5981
6075
  const batchSize = this.#eventBuffer.totalSize;
@@ -6073,12 +6167,18 @@ var MastraStorageExporter = class extends BaseExporter {
6073
6167
  getByteBatchingStats() {
6074
6168
  return this.#byteTracker?.stats(this.#inFlightFlushes.size);
6075
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
+ }
6076
6175
  async _exportTracingEvent(event) {
6077
6176
  await this.ensureInitialized();
6078
6177
  if (!this.#observabilityStorage) {
6079
6178
  this.logger.debug("Cannot store traces. Observability storage is not initialized");
6080
6179
  return;
6081
6180
  }
6181
+ this.fallBackFromRealtimeUnderDurableExecution();
6082
6182
  this.#eventBuffer.addEvent({
6083
6183
  ...event,
6084
6184
  exportedSpan: withSpanPreviews(event.exportedSpan)
@@ -6191,10 +6291,8 @@ var MastraStorageExporter = class extends BaseExporter {
6191
6291
  this.logger.warn(`flush() stopped after ${MAX_FLUSH_ROUNDS} rounds; new writes kept starting`, { bufferedEventsLeftBehind: this.#eventBuffer.totalSize });
6192
6292
  }
6193
6293
  async shutdown() {
6194
- if (this.#flushTimer) {
6195
- clearTimeout(this.#flushTimer);
6196
- this.#flushTimer = void 0;
6197
- }
6294
+ this.clearTimers();
6295
+ this.#eventBuffer.releaseHeldRetries(Infinity);
6198
6296
  try {
6199
6297
  await this.flush();
6200
6298
  } catch (error) {
@@ -6207,11 +6305,10 @@ var MastraStorageExporter = class extends BaseExporter {
6207
6305
  this.logger.trackException(mastraError);
6208
6306
  this.logger.error("Failed to flush remaining events during shutdown", mastraError);
6209
6307
  } finally {
6210
- if (this.#flushTimer) {
6211
- clearTimeout(this.#flushTimer);
6212
- this.#flushTimer = void 0;
6213
- }
6308
+ this.clearTimers();
6214
6309
  }
6310
+ this.emitDrop("tracing", "span-not-updatable", this.#eventBuffer.takeHeldRetries().length);
6311
+ this.emitDrop("tracing", "retry-exhausted", this.#eventBuffer.updates.length);
6215
6312
  this.logger.info("MastraStorageExporter shutdown complete");
6216
6313
  }
6217
6314
  };
@@ -6554,7 +6651,7 @@ var BaseObservabilityInstance = class extends MastraBase {
6554
6651
  getLoggerContext(span) {
6555
6652
  if (this.config.logging?.enabled === false) return noOpLoggerContext;
6556
6653
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6557
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6654
+ const metadata = span?.metadata;
6558
6655
  return new LoggerContextImpl({
6559
6656
  traceId: span?.traceId,
6560
6657
  spanId: resolveExportedSpanId(span),
@@ -6571,7 +6668,7 @@ var BaseObservabilityInstance = class extends MastraBase {
6571
6668
  */
6572
6669
  getMetricsContext(span) {
6573
6670
  const correlationContext = span?.getCorrelationContext?.() ?? this.buildFallbackCorrelationContext();
6574
- const metadata = span?.metadata ? structuredClone(span.metadata) : void 0;
6671
+ const metadata = span?.metadata;
6575
6672
  return new MetricsContextImpl({
6576
6673
  traceId: span?.traceId,
6577
6674
  spanId: resolveExportedSpanId(span),
@@ -6965,14 +7062,20 @@ var BaseObservabilityInstance = class extends MastraBase {
6965
7062
  async shutdown() {
6966
7063
  this.logger.debug(`[Observability] Shutdown started [name=${this.name}]`);
6967
7064
  await this.observabilityBus.shutdown();
6968
- const shutdownPromises = [...this.exporters.map((e) => e.shutdown()), ...this.spanOutputProcessors.map((p) => p.shutdown())];
6969
- if (this.config.bridge) shutdownPromises.push(this.config.bridge.shutdown());
6970
- if (shutdownPromises.length > 0) {
6971
- const results = await Promise.allSettled(shutdownPromises);
6972
- for (const result of results) if (result.status === "rejected") this.logger.error(`[Observability] Component shutdown failed [name=${this.name}]:`, result.reason);
6973
- }
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();
6974
7073
  this.logger.info(`[Observability] Shutdown completed [name=${this.name}]`);
6975
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
+ }
6976
7079
  };
6977
7080
  // src/client/id.ts
6978
7081
  function generateClientSignalId() {
@@ -6993,6 +7096,14 @@ function generateClientSignalId() {
6993
7096
  * Using `@opentelemetry/otlp-transformer` would pull in the full proto
6994
7097
  * dependency tree (~hundreds of KB) for what amounts to a 100-line walker.
6995
7098
  */
7099
+ function hasReversedTimestamps(start, end) {
7100
+ if (typeof start !== "string" && typeof start !== "number" || typeof end !== "string" && typeof end !== "number") return false;
7101
+ try {
7102
+ return BigInt(end) < BigInt(start);
7103
+ } catch {
7104
+ return false;
7105
+ }
7106
+ }
6996
7107
  /**
6997
7108
  * Convert an OTLP nanosecond timestamp (string or number) to a JS Date.
6998
7109
  *
@@ -7001,7 +7112,7 @@ function generateClientSignalId() {
7001
7112
  * uint64 to avoid JS number precision loss) or numbers.
7002
7113
  */
7003
7114
  function nanosToDate(value) {
7004
- if (typeof value === "number") return new Date(Math.round(value / 1e6));
7115
+ if (typeof value === "number") return new Date(Math.trunc(value / 1e6));
7005
7116
  if (typeof value === "string") {
7006
7117
  if (value.length <= 6) return /* @__PURE__ */ new Date(0);
7007
7118
  const ms = Number(value.slice(0, -6));
@@ -7059,6 +7170,7 @@ function decodeResourceSpans(payload) {
7059
7170
  spanId,
7060
7171
  parentSpanId: typeof s.parentSpanId === "string" && s.parentSpanId ? s.parentSpanId : void 0,
7061
7172
  name,
7173
+ ...hasReversedTimestamps(s.startTimeUnixNano, s.endTimeUnixNano) ? { hasReversedTimestamps: true } : {},
7062
7174
  startTime: nanosToDate(s.startTimeUnixNano),
7063
7175
  endTime: s.endTimeUnixNano !== void 0 ? nanosToDate(s.endTimeUnixNano) : void 0,
7064
7176
  attributes: flattenAttributes(s.attributes)
@@ -7305,6 +7417,14 @@ var ClientObservabilityProxyImpl = class {
7305
7417
  this.#warn("Client observability payload contains spans with orphan parents; dropping.");
7306
7418
  return;
7307
7419
  }
7420
+ if (decodedSpans.some((span) => span.hasReversedTimestamps || span.endTime && span.endTime < span.startTime)) {
7421
+ this.#warn("Client observability payload contains a span whose end precedes its start; dropping.");
7422
+ return;
7423
+ }
7424
+ if (typeof payload.executionDurationMs === "number" && payload.executionDurationMs < 0) {
7425
+ this.#warn("Client observability payload contains a negative execution duration; dropping.");
7426
+ return;
7427
+ }
7308
7428
  for (const decoded of decodedSpans) {
7309
7429
  const exported = buildExportedSpan(decoded);
7310
7430
  const startedEvent = {