🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: remove postgres from ingestion merge (#4467)
Steffen Schmitza01c27f4cc51
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 84344147f4..134b480013 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -9,9 +9,6 @@ import {convertObservationReadToInsert,convertScoreReadToInsert,convertTraceReadToInsert,- convertPostgresObservationToInsert,- convertPostgresScoreToInsert,- convertPostgresTraceToInsert,eventTypes,findModel,IngestionEventType,@@ -135,59 +132,47 @@ export class IngestionService {minTimestamp === Infinity? undefined: convertDateToClickhouseDateTime(new Date(minTimestamp));- const [postgresScoreRecord, clickhouseScoreRecord, scoreRecords] =- await Promise.all([- this.getPostgresRecord({- projectId,- entityId,- table: TableName.Scores,- }),- this.getClickhouseRecord({- projectId,- entityId,- table: TableName.Scores,- additionalFilters: {- whereCondition: timestamp- ? " AND timestamp >= {timestamp: DateTime64(3)} "- : "",- params: { timestamp },- },+ const [clickhouseScoreRecord, scoreRecords] = await Promise.all([+ this.getClickhouseRecord({+ projectId,+ entityId,+ table: TableName.Scores,+ additionalFilters: {+ whereCondition: timestamp+ ? " AND timestamp >= {timestamp: DateTime64(3)} "+ : "",+ params: { timestamp },+ },+ }),+ Promise.all(+ timeSortedEvents.map(async (scoreEvent) => {+ const validatedScore = await validateAndInflateScore({+ body: scoreEvent.body,+ scoreId: entityId,+ projectId,+ });++ return {+ id: entityId,+ project_id: projectId,+ timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),+ name: validatedScore.name,+ value: validatedScore.value,+ source: validatedScore.source,+ trace_id: validatedScore.traceId,+ data_type: validatedScore.dataType,+ observation_id: validatedScore.observationId,+ comment: validatedScore.comment,+ string_value: validatedScore.stringValue,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: new Date(scoreEvent.timestamp).getTime(),+ is_deleted: 0,+ };}),- Promise.all(- timeSortedEvents.map(async (scoreEvent) => {- const validatedScore = await validateAndInflateScore({- body: scoreEvent.body,- scoreId: entityId,- projectId,- });-- return {- id: entityId,- project_id: projectId,- timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),- name: validatedScore.name,- value: validatedScore.value,- source: validatedScore.source,- trace_id: validatedScore.traceId,- data_type: validatedScore.dataType,- observation_id: validatedScore.observationId,- comment: validatedScore.comment,- string_value: validatedScore.stringValue,- created_at: Date.now(),- updated_at: Date.now(),- event_ts: new Date(scoreEvent.timestamp).getTime(),- is_deleted: 0,- };- }),- ),- ]);+ ),+ ]);- if (postgresScoreRecord) {- recordIncrement("langfuse.ingestion.lookup.hit", 1, {- store: "postgres",- object: "score",- });- }if (clickhouseScoreRecord) {recordIncrement("langfuse.ingestion.lookup.hit", 1, {store: "clickhouse",@@ -198,7 +183,6 @@ export class IngestionService {const finalScoreRecord: ScoreRecordInsertType =await this.mergeScoreRecords({clickhouseScoreRecord,- postgresScoreRecord,scoreRecords,});@@ -231,31 +215,18 @@ export class IngestionService {minTimestamp === Infinity? undefined: convertDateToClickhouseDateTime(new Date(minTimestamp));- const [postgresTraceRecord, clickhouseTraceRecord] = await Promise.all([- this.getPostgresRecord({- projectId,- entityId,- table: TableName.Traces,- }),- this.getClickhouseRecord({- projectId,- entityId,- table: TableName.Traces,- additionalFilters: {- whereCondition: timestamp- ? " AND timestamp >= {timestamp: DateTime64(3)} "- : "",- params: { timestamp },- },- }),- ]);+ const clickhouseTraceRecord = await this.getClickhouseRecord({+ projectId,+ entityId,+ table: TableName.Traces,+ additionalFilters: {+ whereCondition: timestamp+ ? " AND timestamp >= {timestamp: DateTime64(3)} "+ : "",+ params: { timestamp },+ },+ });- if (postgresTraceRecord) {- recordIncrement("langfuse.ingestion.lookup.hit", 1, {- store: "postgres",- object: "trace",- });- }if (clickhouseTraceRecord) {recordIncrement("langfuse.ingestion.lookup.hit", 1, {store: "clickhouse",@@ -265,7 +236,6 @@ export class IngestionService {const finalTraceRecord = await this.mergeTraceRecords({clickhouseTraceRecord,- postgresTraceRecord,traceRecords,});@@ -340,34 +310,22 @@ export class IngestionService {? undefined: convertDateToClickhouseDateTime(new Date(minStartTime));- const [postgresObservationRecord, clickhouseObservationRecord, prompt] =- await Promise.all([- this.getPostgresRecord({- projectId,- entityId,- table: TableName.Observations,- }),- this.getClickhouseRecord({- projectId,- entityId,- table: TableName.Observations,- additionalFilters: {- whereCondition: `AND type = {type: String} ${startTime ? "AND start_time >= {startTime: DateTime64(3)} " : ""}`,- params: {- type,- startTime,- },+ const [clickhouseObservationRecord, prompt] = await Promise.all([+ this.getClickhouseRecord({+ projectId,+ entityId,+ table: TableName.Observations,+ additionalFilters: {+ whereCondition: `AND type = {type: String} ${startTime ? "AND start_time >= {startTime: DateTime64(3)} " : ""}`,+ params: {+ type,+ startTime,},- }),- this.getPrompt(projectId, observationEventList),- ]);+ },+ }),+ this.getPrompt(projectId, observationEventList),+ ]);- if (postgresObservationRecord) {- recordIncrement("langfuse.ingestion.lookup.hit", 1, {- store: "postgres",- object: "observation",- });- }if (clickhouseObservationRecord) {recordIncrement("langfuse.ingestion.lookup.hit", 1, {store: "clickhouse",@@ -385,7 +343,6 @@ export class IngestionService {const finalObservationRecord = await this.mergeObservationRecords({projectId,observationRecords,- postgresObservationRecord,clickhouseObservationRecord,});@@ -417,17 +374,14 @@ export class IngestionService {private async mergeScoreRecords(params: {scoreRecords: ScoreRecordInsertType[];- postgresScoreRecord?: ScoreRecordInsertType | null;clickhouseScoreRecord?: ScoreRecordInsertType | null;}): Promise<ScoreRecordInsertType> {- const { scoreRecords, postgresScoreRecord, clickhouseScoreRecord } = params;+ const { scoreRecords, clickhouseScoreRecord } = params;// Set clickhouse first as this is the baseline for immutable fields- const recordsToMerge = [- clickhouseScoreRecord,- postgresScoreRecord,- ...scoreRecords,- ].filter(Boolean) as ScoreRecordInsertType[];+ const recordsToMerge = [clickhouseScoreRecord, ...scoreRecords].filter(+ Boolean,+ ) as ScoreRecordInsertType[];const mergedRecord = this.mergeRecords(recordsToMerge,@@ -439,17 +393,14 @@ export class IngestionService {private async mergeTraceRecords(params: {traceRecords: TraceRecordInsertType[];- postgresTraceRecord?: TraceRecordInsertType | null;clickhouseTraceRecord?: TraceRecordInsertType | null;}): Promise<TraceRecordInsertType> {- const { traceRecords, postgresTraceRecord, clickhouseTraceRecord } = params;+ const { traceRecords, clickhouseTraceRecord } = params;// Set clickhouse first as this is the baseline for immutable fields- const recordsToMerge = [- clickhouseTraceRecord,- postgresTraceRecord,- ...traceRecords,- ].filter(Boolean) as TraceRecordInsertType[];+ const recordsToMerge = [clickhouseTraceRecord, ...traceRecords].filter(+ Boolean,+ ) as TraceRecordInsertType[];const mergedRecord = this.mergeRecords(recordsToMerge,@@ -462,20 +413,14 @@ export class IngestionService {private async mergeObservationRecords(params: {projectId: string;observationRecords: ObservationRecordInsertType[];- postgresObservationRecord?: ObservationRecordInsertType | null;clickhouseObservationRecord?: ObservationRecordInsertType | null;}): Promise<ObservationRecordInsertType> {- const {- projectId,- observationRecords,- postgresObservationRecord,- clickhouseObservationRecord,- } = params;+ const { projectId, observationRecords, clickhouseObservationRecord } =+ params;// Set clickhouse first as this is the baseline for immutable fieldsconst recordsToMerge = [clickhouseObservationRecord,- postgresObservationRecord,...observationRecords,].filter(Boolean) as ObservationRecordInsertType[];@@ -500,14 +445,6 @@ export class IngestionService {observationRecord: parsedObservationRecord,});- if (- "usage_details" in generationUsage &&- Object.keys(generationUsage.usage_details).length === 0- ) {- generationUsage.usage_details =- postgresObservationRecord?.usage_details ?? {};- }-return {...parsedObservationRecord,...generationUsage,@@ -844,58 +781,6 @@ export class IngestionService {);}- private async getPostgresRecord(params: {- projectId: string;- entityId: string;- table: TableName.Traces;- }): Promise<TraceRecordInsertType | null>;- private async getPostgresRecord(params: {- projectId: string;- entityId: string;- table: TableName.Scores;- }): Promise<ScoreRecordInsertType | null>;- private async getPostgresRecord(params: {- projectId: string;- entityId: string;- table: TableName.Observations;- }): Promise<ObservationRecordInsertType | null>;- private async getPostgresRecord(params: {- projectId: string;- entityId: string;- table: TableName;- }) {- const recordParser = {- traces: convertPostgresTraceToInsert,- scores: convertPostgresScoreToInsert,- observations: convertPostgresObservationToInsert,- };- const { projectId, entityId, table } = params;-- const query =- table === TableName.Observations- ? Prisma.sql`- SELECT o.*,- o."modelParameters" as model_parameters,- p.name as prompt_name,- p.version as prompt_version- FROM observations o- LEFT JOIN prompts p ON o.prompt_id = p.id- WHERE o.project_id = ${projectId}- AND o.id = ${entityId}- LIMIT 1;`- : Prisma.sql`- SELECT *- FROM ${Prisma.raw(table)}- WHERE project_id = ${projectId}- AND id = ${entityId}- LIMIT 1;`;-- const result =- await this.prisma.$queryRaw<Array<Record<string, unknown>>>(query);-- return result.length === 0 ? null : recordParser[table](result[0]);- }-private mapTraceEventsToRecords(params: {traceEventList: TraceEventType[];projectId: string;diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 0075ed99a8..7c56592483 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -1202,68 +1202,6 @@ describe("Ingestion end-to-end tests", () => {expect(score.project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");});- it("should merge observations from postgres and event list", async () => {- const traceId = randomUUID();- const observationId = randomUUID();-- const latestEvent = new Date();- const oldEvent = new Date(latestEvent).setSeconds(- latestEvent.getSeconds() - 1,- );-- await prisma.observation.create({- data: {- id: observationId,- type: "GENERATION",- traceId,- name: "generation-name",- input: { key: "value" },- output: "should be overwritten",- model: "gpt-3.5",- projectId,- startTime: new Date(oldEvent),- completionTokens: 5,- // Validates that numbers are parsed correctly. Since there is no usage, no effect on result- calculatedTotalCost: "0.273330000000000000000000000000",- modelParameters: { hello: "world" },- },- });-- const observationEventList: ObservationEvent[] = [- {- id: randomUUID(),- type: "generation-create",- timestamp: new Date().toISOString(),- body: {- id: observationId,- traceId: traceId,- output: "overwritten",- usage: undefined,- },- },- ];-- await ingestionService.processObservationEventList({- projectId,- entityId: observationId,- observationEventList,- });-- await clickhouseWriter.flushAll(true);-- const observation = await getClickhouseRecord(- TableName.Observations,- observationId,- );-- expect(observation.name).toBe("generation-name");- expect(observation.input).toBe(JSON.stringify({ key: "value" }));- expect(observation.output).toBe("overwritten");- expect(observation.model_parameters).toBe('{"hello":"world"}');- expect(observation.usage_details.output).toBe(5);- expect(observation.project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");- });-it("should merge observations and set negative tokens and cost to null", async () => {await prisma.model.create({data: {