Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix: add default timestamps for otel events (#12200)

Max Deichmannb005f4110b64
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
index 3ad1daabc5..16abfdf320 100644
--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts
+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts
@@ -75,6 +75,18 @@ interface CreateObservationEventParams {
endTimeISO: string;
}
+type NanoTimestamp =
+ | number
+ | string
+ | {
+ high: number;
+ low: number;
+ }
+ | null
+ | undefined;
+
+type TimestampField = "start_time" | "end_time" | "unknown";
+
export interface ResourceSpan {
resource?: {
attributes?: Array<{ key: string; value: any }>;
@@ -91,8 +103,8 @@ export interface ResourceSpan {
parentSpanId?: { data?: Buffer } | Buffer;
name: string;
kind: number;
- startTimeUnixNano: number | { low: number; high: number };
- endTimeUnixNano: number | { low: number; high: number };
+ startTimeUnixNano?: NanoTimestamp;
+ endTimeUnixNano?: NanoTimestamp;
attributes?: Array<{ key: string; value: any }>;
events?: any[];
status?: { code?: number; message?: string };
@@ -110,6 +122,9 @@ const observationTypeMapper = new ObservationTypeMapperRegistry();
* for converting OTEL spans to Langfuse events.
*/
export class OtelIngestionProcessor {
+ private static readonly OTEL_CONVERSION_FAILURE_METRIC =
+ "langfuse.ingestion.otel.conversion_failure";
+
private seenTraces: Set<string> = new Set();
private isInitialized = false;
private traceEventCounts = {
@@ -223,14 +238,11 @@ export class OtelIngestionProcessor {
? this.parseId(span.parentSpanId)
: null;
const name = span.name;
- const startTimeISO =
- OtelIngestionProcessor.convertNanoTimestampToISO(
- span.startTimeUnixNano,
- );
- const endTimeISO =
- OtelIngestionProcessor.convertNanoTimestampToISO(
- span.endTimeUnixNano,
- );
+ const { startTimeISO, endTimeISO } =
+ OtelIngestionProcessor.resolveSpanTimestamps({
+ startTimeUnixNano: span.startTimeUnixNano,
+ endTimeUnixNano: span.endTimeUnixNano,
+ });
// Extract metadata from different sources
const spanMetadata = this.extractMetadata(
@@ -697,12 +709,11 @@ export class OtelIngestionProcessor {
resourceAttributes,
"trace",
);
- const startTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
- span.startTimeUnixNano,
- );
- const endTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
- span.endTimeUnixNano,
- );
+ const { startTimeISO, endTimeISO } =
+ OtelIngestionProcessor.resolveSpanTimestamps({
+ startTimeUnixNano: span.startTimeUnixNano,
+ endTimeUnixNano: span.endTimeUnixNano,
+ });
const isRootSpan =
!parentObservationId ||
@@ -2345,22 +2356,54 @@ export class OtelIngestionProcessor {
* Handles various timestamp formats: string, number, or object with high/low bits.
*/
public static convertNanoTimestampToISO(
- timestamp:
- | number
- | string
- | {
- high: number;
- low: number;
- },
- ): string {
+ timestamp: NanoTimestamp,
+ field: TimestampField = "unknown",
+ ): string | undefined {
try {
+ if (timestamp == null) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_missing",
+ field,
+ );
+ return undefined;
+ }
+
if (typeof timestamp === "string") {
- return new Date(Number(BigInt(timestamp) / BigInt(1e6))).toISOString();
+ if (timestamp.trim() === "") {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_invalid_empty_string",
+ field,
+ );
+ return undefined;
+ }
+
+ const millisBigInt = BigInt(timestamp) / BigInt(1_000_000);
+ return new Date(Number(millisBigInt)).toISOString();
}
+
if (typeof timestamp === "number") {
+ if (!Number.isFinite(timestamp)) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_invalid_number",
+ field,
+ );
+ return undefined;
+ }
+
return new Date(timestamp / 1e6).toISOString();
}
+ if (
+ typeof timestamp.high !== "number" ||
+ typeof timestamp.low !== "number"
+ ) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_invalid_object",
+ field,
+ );
+ return undefined;
+ }
+
// Convert high and low to BigInt
const highBits = BigInt(timestamp.high) << BigInt(32);
const lowBits = BigInt(timestamp.low >>> 0);
@@ -2376,8 +2419,64 @@ export class OtelIngestionProcessor {
timestamp,
error: e,
});
- throw e;
+ OtelIngestionProcessor.recordConversionFailure(
+ typeof timestamp === "string"
+ ? "timestamp_invalid_string"
+ : "timestamp_conversion_exception",
+ field,
+ );
+ return undefined;
+ }
+ }
+
+ /**
+ * Ensure a stable time range for spans even if a timestamp is missing.
+ * If one edge is missing, use the other edge. If both are missing, use current time.
+ */
+ private static resolveSpanTimestamps(params: {
+ startTimeUnixNano?: NanoTimestamp;
+ endTimeUnixNano?: NanoTimestamp;
+ }): { startTimeISO: string; endTimeISO: string } {
+ const startTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
+ params.startTimeUnixNano,
+ "start_time",
+ );
+ const endTimeISO = OtelIngestionProcessor.convertNanoTimestampToISO(
+ params.endTimeUnixNano,
+ "end_time",
+ );
+ const fallbackISO = new Date().toISOString();
+
+ if (!startTimeISO && endTimeISO) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_inferred_start_from_end",
+ "start_time",
+ );
+ } else if (startTimeISO && !endTimeISO) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_inferred_end_from_start",
+ "end_time",
+ );
+ } else if (!startTimeISO && !endTimeISO) {
+ OtelIngestionProcessor.recordConversionFailure(
+ "timestamp_inferred_both_missing",
+ );
}
+
+ return {
+ startTimeISO: startTimeISO ?? endTimeISO ?? fallbackISO,
+ endTimeISO: endTimeISO ?? startTimeISO ?? fallbackISO,
+ };
+ }
+
+ private static recordConversionFailure(
+ failureType: string,
+ field: TimestampField = "unknown",
+ ): void {
+ recordIncrement(OtelIngestionProcessor.OTEL_CONVERSION_FAILURE_METRIC, 1, {
+ failure_type: failureType,
+ timestamp_field: field,
+ });
}
/**
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index fbc98fa2a7..1cb8b0c548 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -3399,6 +3399,137 @@ describe("OTel Resource Span Mapping", () => {
OtelIngestionProcessor.convertNanoTimestampToISO(zeroTimestamp),
).toBe("1970-01-01T00:00:00.000Z");
});
+
+ it("should return undefined for missing or invalid timestamps", () => {
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(undefined as any),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(null as any),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(""),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO("not-a-timestamp"),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(NaN),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(
+ Number.POSITIVE_INFINITY,
+ ),
+ ).toBeUndefined();
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO({
+ high: 1,
+ } as any),
+ ).toBeUndefined();
+ });
+ });
+
+ describe("Missing span timestamps", () => {
+ it("should process spans with no start/end times without throwing", async () => {
+ const resourceSpan = {
+ resource: {
+ attributes: [{ key: "service.name", value: { stringValue: "test" } }],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: "2cce18f7e8cd065a0b4e634eef728391",
+ spanId: "57f0255417974100",
+ name: "span-without-time",
+ kind: 1,
+ attributes: [],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+ const eventInputs = processor.processToEvent([resourceSpan]);
+ expect(eventInputs).toHaveLength(1);
+ expect(eventInputs[0].startTimeISO).toBeDefined();
+ expect(eventInputs[0].endTimeISO).toBeDefined();
+ expect(eventInputs[0].startTimeISO).toBe(eventInputs[0].endTimeISO);
+
+ const ingestionEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+
+ const trace = ingestionEvents.find((e) => e.type === "trace-create");
+ const observation = ingestionEvents.find((e) => e.type === "span-create");
+
+ expect(trace).toBeDefined();
+ expect(trace?.body.timestamp).toBeDefined();
+ expect(observation).toBeDefined();
+ expect(observation?.body.startTime).toBeDefined();
+ expect(observation?.body.endTime).toBeDefined();
+ expect(observation?.body.startTime).toBe(observation?.body.endTime);
+ });
+
+ it("should use the present timestamp as fallback when only one edge is missing", async () => {
+ const endOnlyTimestamp = {
+ low: 467248096,
+ high: 406528574,
+ unsigned: true,
+ };
+ const expectedISO =
+ OtelIngestionProcessor.convertNanoTimestampToISO(endOnlyTimestamp);
+
+ const resourceSpan = {
+ resource: {
+ attributes: [{ key: "service.name", value: { stringValue: "test" } }],
+ },
+ scopeSpans: [
+ {
+ scope: {
+ name: "test-scope",
+ version: "1.0.0",
+ },
+ spans: [
+ {
+ traceId: "2cce18f7e8cd065a0b4e634eef728391",
+ spanId: "57f0255417974100",
+ name: "span-end-only-time",
+ kind: 1,
+ endTimeUnixNano: endOnlyTimestamp,
+ attributes: [],
+ status: {},
+ },
+ ],
+ },
+ ],
+ };
+
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+ const eventInputs = processor.processToEvent([resourceSpan]);
+ expect(eventInputs).toHaveLength(1);
+ expect(eventInputs[0].startTimeISO).toBe(expectedISO);
+ expect(eventInputs[0].endTimeISO).toBe(expectedISO);
+
+ const ingestionEvents = await convertOtelSpanToIngestionEvent(
+ resourceSpan,
+ new Set(),
+ );
+ const observation = ingestionEvents.find((e) => e.type === "span-create");
+ expect(observation?.body.startTime).toBe(expectedISO);
+ expect(observation?.body.endTime).toBe(expectedISO);
+ });
});
describe("Trace seen logic", () => {