Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

perf: drop final on check trace exists (#9117)

Steffen Schmitz43e0644c64ae
diff --git a/.env.dev-redis-cluster.example b/.env.dev-redis-cluster.example
index bb0b0707fc..374f691958 100644
--- a/.env.dev-redis-cluster.example
+++ b/.env.dev-redis-cluster.example
@@ -85,9 +85,4 @@ ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
# speeds up local development by not executing init scripts on server startup
NEXT_PUBLIC_LANGFUSE_RUN_NEXT_INIT="false"
-# Use the following settings to enforce running the new AMTs during the tests
-LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES="true"
-LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE="false"
-LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT="true"
-
LANGFUSE_EXPERIMENT_USE_OTEL_INGESTION_QUEUE="true"
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 7787ad687f..14a4c74105 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -157,9 +157,6 @@ const EnvSchema = z.object({
LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT_SHORT_TERM: z
.enum(["true", "false"])
.default("false"),
- LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES: z
- .enum(["true", "false"])
- .default("false"),
LANGFUSE_EXPERIMENT_WHITELISTED_AMT_TABLES: z
.string()
.optional()
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index cf3085ad62..b6f98c4b1c 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -45,6 +45,7 @@ export const BatchExportJobSchema = z.object({
export const TraceQueueEventSchema = z.object({
projectId: z.string(),
traceId: z.string(),
+ exactTimestamp: z.date().optional(),
});
export const TracesQueueEventSchema = z.object({
projectId: z.string(),
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index eaba8564f7..2f93b9570e 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -496,128 +496,3 @@ export const convertPostgresScoreToInsert = (
is_deleted: 0,
};
};
-
-export const convertTraceToTraceNull = (
- traceRecord: TraceRecordInsertType,
-): TraceNullRecordInsertType => {
- return {
- // Identifiers
- project_id: traceRecord.project_id,
- id: traceRecord.id,
- start_time: traceRecord.timestamp,
- end_time: null, // traces don't have end_time, will be null
- name: traceRecord.name || null,
-
- // Metadata properties
- metadata: traceRecord.metadata,
- user_id: traceRecord.user_id || null,
- session_id: traceRecord.session_id || null,
- environment: traceRecord.environment,
- tags: traceRecord.tags,
- version: traceRecord.version || null,
- release: traceRecord.release || null,
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: traceRecord.bookmarked ?? null,
- public: traceRecord.public ?? null,
-
- // Aggregations - empty for now, will be populated by aggregation processes
- observation_ids: [],
- score_ids: [],
- cost_details: {},
- usage_details: {},
-
- // Input/Output
- input: traceRecord.input || "",
- output: traceRecord.output || "",
-
- created_at: traceRecord.created_at,
- updated_at: traceRecord.updated_at,
- event_ts: traceRecord.event_ts,
- };
-};
-
-export const convertObservationToTraceNull = (
- observationRecord: ObservationRecordInsertType,
-): TraceNullRecordInsertType => {
- return {
- // Identifiers
- project_id: observationRecord.project_id,
- // Use trace_id as the id in traces_null. Always set given the conditions around calling the function
- id: observationRecord.trace_id || "",
- start_time: observationRecord.start_time,
- end_time: observationRecord.end_time || null,
- name: null,
-
- // Metadata properties
- metadata: {},
- user_id: null,
- session_id: null,
- environment: observationRecord.environment,
- tags: [],
- version: null,
- release: null,
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: null,
- public: null,
-
- // Aggregations - include this observation ID
- observation_ids: [observationRecord.id],
- score_ids: [],
- // We can fill the cost details here, but we shouldn't trust them.
- // Only used for verification to estimate how big the double-counting is.
- // Actually, we don't as this will make backfills challenging.
- cost_details: {}, // observationRecord.cost_details || {},
- usage_details: {}, // observationRecord.usage_details || {},
-
- // Input/Output
- input: "",
- output: "",
-
- created_at: observationRecord.created_at,
- updated_at: observationRecord.updated_at,
- event_ts: observationRecord.event_ts,
- };
-};
-
-export const convertScoreToTraceNull = (
- scoreRecord: ScoreRecordInsertType,
-): TraceNullRecordInsertType => {
- return {
- // Identifiers
- project_id: scoreRecord.project_id,
- // Use trace_id as the id in traces_null. Always set given the conditions around calling the function
- id: scoreRecord.trace_id || "",
- start_time: scoreRecord.timestamp,
- end_time: null, // scores don't have end_time
- name: null,
-
- // Metadata properties
- metadata: {},
- user_id: null,
- session_id: null,
- environment: scoreRecord.environment,
- tags: [], // scores don't have tags
- version: null, // scores don't have version
- release: null, // scores don't have release
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: null,
- public: null,
-
- // Aggregations - include this score ID
- observation_ids: [],
- score_ids: [scoreRecord.id],
- cost_details: {},
- usage_details: {},
-
- // Input/Output
- input: "", // scores don't have input
- output: "", // scores don't have output
-
- created_at: scoreRecord.created_at,
- updated_at: scoreRecord.updated_at,
- event_ts: scoreRecord.event_ts,
- };
-};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index a5819491ec..e4e30409b7 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -15,11 +15,10 @@ import {
FilterList,
StringFilter,
} from "../queries/clickhouse-sql/clickhouse-filter";
-import { TraceRecordReadType, convertTraceToTraceNull } from "./definitions";
+import { TraceRecordReadType } from "./definitions";
import { tracesTableUiColumnDefinitions } from "../tableMappings/mapTracesTable";
import { UiColumnMappings } from "../../tableDefinitions";
import {
- clickhouseClient,
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
@@ -201,10 +200,10 @@ export const checkTraceExistsAndGetTimestamp = async ({
${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}
WHERE ${tracesFilterRes.query}
AND t.project_id = {projectId: String}
- AND timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}
- ${maxTimeStamp ? `AND timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}
- ${!maxTimeStamp ? `AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}
- ${exactTimestamp ? `AND timestamp = {exactTimestamp: DateTime64(3)}` : ""}
+ AND t.timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}
+ ${maxTimeStamp ? `AND t.timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}
+ ${!maxTimeStamp ? `AND t.timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}
+ ${exactTimestamp ? `AND toDate(t.timestamp) = toDate({exactTimestamp: DateTime64(3)})` : ""}
GROUP BY t.id, t.project_id, t.timestamp
`;
@@ -282,38 +281,6 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
projectId: trace.project_id ?? "",
},
});
-
- // Also insert into traces_null if experiment flag is enabled
- if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true") {
- // Convert trace to insert format first (since we have read format)
- const traceRecord = trace as TraceRecordReadType;
- const traceInsert = {
- ...traceRecord,
- timestamp: new Date(traceRecord.timestamp).getTime(),
- created_at: new Date(traceRecord.created_at).getTime(),
- updated_at: new Date(traceRecord.updated_at).getTime(),
- event_ts: new Date(traceRecord.event_ts).getTime(),
- is_deleted: 0,
- };
-
- // Convert to traces_null format
- const traceNull = convertTraceToTraceNull(traceInsert);
-
- // Insert directly into traces_null using clickhouse client
- await clickhouseClient().insert({
- table: "traces_null",
- format: "JSONEachRow",
- values: [traceNull],
- clickhouse_settings: {
- log_comment: JSON.stringify({
- feature: "tracing",
- type: "traces_null",
- kind: "upsert",
- experiment: "insert_into_aggregating_merge_trees",
- }),
- },
- });
- }
};
export const getTracesByIds = async (
diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
index 2968d53af3..709b01aa2c 100644
--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts
+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
@@ -4,18 +4,9 @@ import {
ObservationRecordInsertType,
ScoreRecordInsertType,
DatasetRunItemRecordInsertType,
- convertTraceToTraceNull,
} from "../repositories/definitions";
-import { env } from "../../env";
export const createTracesCh = async (trace: TraceRecordInsertType[]) => {
- if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true") {
- await clickhouseClient().insert({
- table: "traces_null",
- format: "JSONEachRow",
- values: trace.map(convertTraceToTraceNull),
- });
- }
return await clickhouseClient().insert({
table: "traces",
format: "JSONEachRow",
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 874ae5e816..308117a2e0 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -257,12 +257,6 @@ const EnvSchema = z.object({
.positive()
.default(120_000), // 2 minutes
- LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE: z
- .enum(["true", "false"])
- .default("true"),
- LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES: z
- .enum(["true", "false"])
- .default("false"),
LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z
.enum(["true", "false"])
.default("false"),
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index fadae543d2..feafd5050b 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -92,16 +92,16 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
*
* Data Flow Architecture for Evaluation Jobs
*
- * β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
- * β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
- * β”‚ TraceQueue β”‚ β”‚ DatasetRunItemUpsert β”‚ β”‚ CreateEvalQueue β”‚
- * β”‚ - Live trace data β”‚ β”‚ - Live dataset run itemβ”‚ β”‚ - Historical batch β”‚
- * β”‚ - No timestamp in body β”‚ β”‚ - No timestamp in body β”‚ β”‚ - Has timestamp in bodyβ”‚
- * β”‚ - enforcedTimeScope=NEWβ”‚ β”‚ - enforcedTimeScope=NEWβ”‚ β”‚ - No enforcedTimeScope β”‚
- * β”‚ - Always linked to β”‚ β”‚ - Always linked to β”‚ β”‚ - Always linked to β”‚
- * β”‚ traces only β”‚ β”‚ traces & sometimes β”‚ β”‚ traces & sometimes β”‚
- * β”‚ β”‚ β”‚ to observations β”‚ β”‚ to observations β”‚
- * β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
+ * β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ * β”‚ β”‚ β”‚ β”‚ β”‚ β”‚
+ * β”‚ TraceQueue β”‚ β”‚ DatasetRunItemUpsert β”‚ β”‚ CreateEvalQueue β”‚
+ * β”‚ - Live trace data β”‚ β”‚ - Live dataset run itemβ”‚ β”‚ - Historical batch β”‚
+ * β”‚ - Has timestamp in body β”‚ β”‚ - No timestamp in body β”‚ β”‚ - Has timestamp in bodyβ”‚
+ * β”‚ - enforcedTimeScope=NEW β”‚ β”‚ - enforcedTimeScope=NEWβ”‚ β”‚ - No enforcedTimeScope β”‚
+ * β”‚ - Always linked to β”‚ β”‚ - Always linked to β”‚ β”‚ - Always linked to β”‚
+ * β”‚ traces only β”‚ β”‚ traces & sometimes β”‚ β”‚ traces & sometimes β”‚
+ * β”‚ β”‚ β”‚ to observations β”‚ β”‚ to observations β”‚
+ * β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
* β”‚ β”‚ β”‚
* β”‚ β”‚ β”‚
* β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
@@ -302,6 +302,8 @@ export const createEvalJobs = async ({
let traceExists = false;
let traceTimestamp: Date | undefined = cachedTrace?.timestamp;
+ let traceExistsDecisionSource: string;
+
// Use cached trace for in-memory filtering when possible, i.e. all fields can
// be checked in-memory.
const traceFilter = config.target_object === "trace" ? validatedFilter : [];
@@ -313,6 +315,8 @@ export const createEvalJobs = async ({
mapTraceFilterColumn,
);
+ traceExistsDecisionSource = "cache";
+
recordIncrement("langfuse.evaluation-execution.trace_cache_check", 1, {
matches: traceExists ? "true" : "false",
});
@@ -323,22 +327,37 @@ export const createEvalJobs = async ({
filterCount: traceFilter.length,
});
} else {
- // Fall back to database query for complex filters or when no cached trace
- const { exists, timestamp } = await checkTraceExistsAndGetTimestamp({
- projectId: event.projectId,
- traceId: event.traceId,
- // Fallback to jobTimestamp if no payload timestamp is set to allow for successful retry attempts.
- timestamp:
- "timestamp" in event
- ? new Date(event.timestamp)
- : new Date(jobTimestamp),
- filter: traceFilter,
- maxTimeStamp,
- exactTimestamp:
+ // If the event is not a DatasetRunItemUpsertEventType and the trace has no special filters, we can already assume it's present
+ let exists: boolean = false;
+ let timestamp: Date | undefined = undefined;
+ if (!("datasetItemId" in event) && traceFilter.length === 0) {
+ exists = true;
+ timestamp =
"exactTimestamp" in event && event.exactTimestamp
? new Date(event.exactTimestamp)
- : undefined,
- });
+ : undefined;
+
+ traceExistsDecisionSource = "identifier";
+ } else {
+ // Fall back to database query for complex filters or when no cached trace
+ ({ exists, timestamp } = await checkTraceExistsAndGetTimestamp({
+ projectId: event.projectId,
+ traceId: event.traceId,
+ // Fallback to jobTimestamp if no payload timestamp is set to allow for successful retry attempts.
+ timestamp:
+ "timestamp" in event
+ ? new Date(event.timestamp)
+ : new Date(jobTimestamp),
+ filter: traceFilter,
+ maxTimeStamp,
+ exactTimestamp:
+ "exactTimestamp" in event && event.exactTimestamp
+ ? new Date(event.exactTimestamp)
+ : undefined,
+ }));
+ traceExistsDecisionSource = "lookup";
+ }
+
traceExists = exists;
traceTimestamp = timestamp;
recordIncrement("langfuse.evaluation-execution.trace_db_lookup", 1, {
@@ -349,6 +368,11 @@ export const createEvalJobs = async ({
});
}
+ recordIncrement("langfuse.evaluation-execution.trace_exists_check", 1, {
+ decisionSource: traceExistsDecisionSource,
+ exists: String(traceExists),
+ });
+
const isDatasetConfig = config.target_object === "dataset";
let datasetItem: { id: string } | undefined;
if (isDatasetConfig) {
diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.ts
index 1ffaacced4..a9d3f6de8e 100644
--- a/worker/src/queues/ingestionQueue.ts
+++ b/worker/src/queues/ingestionQueue.ts
@@ -144,10 +144,7 @@ export const ingestionQueueProcessorBuilder = (
// Check if we should skip S3 list operation
const shouldSkipS3List =
// The producer sets skipS3List to true if it's an OTel observation
- (job.data.payload.data.skipS3List && job.data.payload.data.fileKey) ||
- // If we do not insert into the traces table, we can skip the list and process single files
- (env.LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE === "false" &&
- clickhouseEntityType === "trace");
+ job.data.payload.data.skipS3List && job.data.payload.data.fileKey;
const s3Prefix = `${env.LANGFUSE_S3_EVENT_UPLOAD_PREFIX}${job.data.payload.authCheck.scope.projectId}/${clickhouseEntityType}/${job.data.payload.data.eventBodyId}/`;
let totalS3DownloadSizeBytes = 0;
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 7dbb21a496..dba7470f8c 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -32,9 +32,6 @@ import {
UsageCostType,
findModel,
validateAndInflateScore,
- convertObservationToTraceNull,
- convertTraceToTraceNull,
- convertScoreToTraceNull,
DatasetRunItemRecordInsertType,
hasNoJobConfigsCache,
} from "@langfuse/shared/src/server";
@@ -49,7 +46,6 @@ import {
overwriteObject,
} from "./utils";
import { randomUUID } from "crypto";
-import { env } from "../../env";
import { SpanKind } from "@opentelemetry/api";
import { ClickhouseReadSkipCache } from "../../utils/clickhouseReadSkipCache";
@@ -345,14 +341,6 @@ export class IngestionService {
clickhouseScoreRecord?.created_at ?? createdAtTimestamp.getTime();
this.clickHouseWriter.addToQueue(TableName.Scores, finalScoreRecord);
-
- if (
- env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
- finalScoreRecord.trace_id
- ) {
- const traceNullRecord = convertScoreToTraceNull(finalScoreRecord);
- this.clickHouseWriter.addToQueue(TableName.TracesNull, traceNullRecord);
- }
}
private async processTraceEventList(params: {
@@ -385,62 +373,45 @@ export class IngestionService {
),
};
- if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_TRACES_TABLE === "true") {
- const minTimestamp = Math.min(
- ...timeSortedEvents.flatMap((e) =>
- e.body?.timestamp ? [new Date(e.body.timestamp).getTime()] : [],
- ),
- );
- const timestamp =
- minTimestamp === Infinity
- ? undefined
- : convertDateToClickhouseDateTime(new Date(minTimestamp));
- const clickhouseTraceRecord = await this.getClickhouseRecord({
- projectId,
- entityId,
- table: TableName.Traces,
- additionalFilters: {
- whereCondition: timestamp
- ? " AND timestamp >= {timestamp: DateTime64(3)} "
- : "",
- params: { timestamp },
- },
- });
-
- if (clickhouseTraceRecord) {
- recordIncrement("langfuse.ingestion.lookup.hit", 1, {
- store: "clickhouse",
- object: "trace",
- });
- }
+ const minTimestamp = Math.min(
+ ...timeSortedEvents.flatMap((e) =>
+ e.body?.timestamp ? [new Date(e.body.timestamp).getTime()] : [],
+ ),
+ );
+ const timestamp =
+ minTimestamp === Infinity
+ ? undefined
+ : convertDateToClickhouseDateTime(new Date(minTimestamp));
+ const clickhouseTraceRecord = await this.getClickhouseRecord({
+ projectId,
+ entityId,
+ table: TableName.Traces,
+ additionalFilters: {
+ whereCondition: timestamp
+ ? " AND timestamp >= {timestamp: DateTime64(3)} "
+ : "",
+ params: { timestamp },
+ },
+ });
- const finalTraceRecord = await this.mergeTraceRecords({
- clickhouseTraceRecord,
- traceRecords,
+ if (clickhouseTraceRecord) {
+ recordIncrement("langfuse.ingestion.lookup.hit", 1, {
+ store: "clickhouse",
+ object: "trace",
});
- finalTraceRecord.created_at =
- clickhouseTraceRecord?.created_at ?? createdAtTimestamp.getTime();
+ }
- finalTraceRecord.input = finalIO.input ?? clickhouseTraceRecord?.input;
- finalTraceRecord.output = finalIO.output ?? clickhouseTraceRecord?.output;
+ const finalTraceRecord = await this.mergeTraceRecords({
+ clickhouseTraceRecord,
+ traceRecords,
+ });
+ finalTraceRecord.created_at =
+ clickhouseTraceRecord?.created_at ?? createdAtTimestamp.getTime();
- this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);
- }
+ finalTraceRecord.input = finalIO.input ?? clickhouseTraceRecord?.input;
+ finalTraceRecord.output = finalIO.output ?? clickhouseTraceRecord?.output;
- // Experimental: Also write to traces_null table if experiment flag is enabled
- // Here we use the raw events to ensure that we stop relying on the merge logic
- if (
- env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true"
- ) {
- traceRecords.map(convertTraceToTraceNull).forEach((r) =>
- this.clickHouseWriter.addToQueue(TableName.TracesNull, {
- ...r,
- // We need to re-add input and output here as they were excluded in a previous mapping step
- input: finalIO.input ?? "",
- output: finalIO.output ?? "",
- }),
- );
- }
+ this.clickHouseWriter.addToQueue(TableName.Traces, finalTraceRecord);
// If the trace has a sessionId, we upsert the corresponding session into Postgres.
const traceRecordWithSession = traceRecords
@@ -487,6 +458,7 @@ export class IngestionService {
payload: {
projectId,
traceId: entityId,
+ exactTimestamp: new Date(finalTraceRecord.timestamp),
},
id: randomUUID(),
timestamp: new Date(),
@@ -604,16 +576,6 @@ export class IngestionService {
TableName.Observations,
finalObservationRecord,
);
-
- if (
- env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
- finalObservationRecord.trace_id
- ) {
- const traceNullRecord = convertObservationToTraceNull(
- finalObservationRecord,
- );
- this.clickHouseWriter.addToQueue(TableName.TracesNull, traceNullRecord);
- }
}
private async mergeScoreRecords(params: {