🪢 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
fix(ingestion): race condition on events 10s apart (#2950)
Hassieb Pakzad9358f21b2b71
diff --git a/packages/shared/src/server/ingestion/IngestionUtils.ts b/packages/shared/src/server/ingestion/IngestionUtils.tsindex 7da681ce64..e4cbbd1125 100644--- a/packages/shared/src/server/ingestion/IngestionUtils.ts+++ b/packages/shared/src/server/ingestion/IngestionUtils.ts@@ -13,35 +13,42 @@ export enum ClickhouseEntityType {}export class IngestionUtils {- public static getBufferKey(projectEntityKey: string): string {- return "ingestionBuffer:" + projectEntityKey;+ public static getBufferKey(flushKey: string): string {+ const { projectId, eventType, entityId } =+ IngestionUtils.parseFlushKey(flushKey);++ const sanitizedEntityId = IngestionUtils.escapeReservedChars(entityId);++ return (+ "ingestionBuffer:" + `${projectId}_${eventType}_${sanitizedEntityId}`+ );}- public static getProjectEntityKey(params: {+ public static getFlushKey(params: {projectId: string;eventType: ClickhouseEntityType;entityId: string;+ batchTimestamp: string;}): string {- const sanitizedEntityId = IngestionUtils.escapeReservedChars(- params.entityId- );+ const { projectId, eventType, entityId, batchTimestamp } = params;+ const sanitizedEntityId = IngestionUtils.escapeReservedChars(entityId);- return `${params.projectId}_${params.eventType}_${sanitizedEntityId}`;+ return `${projectId}_${eventType}_${sanitizedEntityId}_${batchTimestamp}`;}- public static parseProjectEntityKey(projectEntityKey: string) {+ public static parseFlushKey(projectEntityKey: string) {const split = projectEntityKey.split("_");- if (split.length !== 3) {+ if (split.length < 3) {throw new Error(- `Invalid project entity key format ${projectEntityKey}, expected 3 parts`+ `Invalid project entity key format ${projectEntityKey}, expected 3 or 4 parts`);}- const [projectId, eventType, escapedEntityId] = split;+ const [projectId, eventType, escapedEntityId, batchTimestamp] = split;const entityId = IngestionUtils.unescapeReservedChars(escapedEntityId);- return { projectId, eventType, entityId };+ return { projectId, eventType, entityId, batchTimestamp };}private static escapeReservedChars(string: string): string {diff --git a/web/src/features/ingest/enqueueIngestionEvents.ts b/web/src/features/ingest/enqueueIngestionEvents.tsindex 17c8980a10..73cc6ef11e 100644--- a/web/src/features/ingest/enqueueIngestionEvents.ts+++ b/web/src/features/ingest/enqueueIngestionEvents.ts@@ -21,11 +21,18 @@ export async function enqueueIngestionEvents(if (!redis) throw Error("Redis connection not available");const queuedEventPromises: Promise<void>[] = [];+ const batchTimestamp = Date.now().toString();// Use for loop as TS does not narrow redis type in map functionfor (const event of events) {queuedEventPromises.push(- enqueueSingleIngestionEvent(projectId, event, redis, ingestionFlushQueue),+ enqueueSingleIngestionEvent(+ projectId,+ event,+ redis,+ ingestionFlushQueue,+ batchTimestamp,+ ),);}@@ -37,6 +44,7 @@ async function enqueueSingleIngestionEvent(event: IngestionEventType,redis: Redis,ingestionFlushQueue: IngestionFlushQueue,+ batchTimestamp: string,): Promise<void> {if (!("id" in event.body && event.body.id)) {console.warn(@@ -46,17 +54,18 @@ async function enqueueSingleIngestionEvent(return;}- const projectEntityKey = IngestionUtils.getProjectEntityKey({+ const flushKey = IngestionUtils.getFlushKey({entityId: event.body.id,eventType: IngestionUtils.getEventType(event),projectId,+ batchTimestamp,});- const bufferKey = IngestionUtils.getBufferKey(projectEntityKey);+ const bufferKey = IngestionUtils.getBufferKey(flushKey);const serializedEventData = JSON.stringify({ ...event, projectId });await redis.lpush(bufferKey, serializedEventData);await redis.expire(bufferKey, env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS);await ingestionFlushQueue.add(QueueJobs.FlushIngestionEntity, null, {- jobId: projectEntityKey,+ jobId: flushKey,});}diff --git a/worker/src/queues/ingestionFlushQueueExecutor.ts b/worker/src/queues/ingestionFlushQueueExecutor.tsindex 37cab4a656..bdbc168e74 100644--- a/worker/src/queues/ingestionFlushQueueExecutor.ts+++ b/worker/src/queues/ingestionFlushQueueExecutor.ts@@ -25,15 +25,15 @@ export const ingestionQueueExecutor = redis{ name: "flush-ingestion-consumer" },async () => {if (job.name === QueueJobs.FlushIngestionEntity) {- const projectEntityId = job.id;- if (!projectEntityId) {- throw new Error("ProjectEntity ID not provided");+ const flushKey = job.id;+ if (!flushKey) {+ throw new Error("Flushkey not provided");}// Log wait timeconst waitTime = Date.now() - job.timestamp;logger.debug(- `Received flush request after ${waitTime} ms for ${projectEntityId}`+ `Received flush request after ${waitTime} ms for ${flushKey}`);Sentry.metrics.increment("ingestion_processing_request");@@ -60,12 +60,12 @@ export const ingestionQueueExecutor = redisprisma,ClickhouseWriter.getInstance(),clickhouseClient- ).flush(projectEntityId);+ ).flush(flushKey);// Log processing timeconst processingTime = Date.now() - processingStartTime;logger.debug(- `Prepared and scheduled CH-write in ${processingTime} ms for ${projectEntityId}`+ `Prepared and scheduled CH-write in ${processingTime} ms for ${flushKey}`);Sentry.metrics.distribution("ingestion_flush_processing_time",@@ -90,7 +90,7 @@ export const ingestionQueueExecutor = redis.catch();} catch (err) {console.error(- `Error processing flush request for ${projectEntityId}`,+ `Error processing flush request for ${flushKey}`,err);diff --git a/worker/src/scripts/verifyClickhouseRecords.ts b/worker/src/scripts/verifyClickhouseRecords.tsindex 4d5636b26c..a670ba48a8 100644--- a/worker/src/scripts/verifyClickhouseRecords.ts+++ b/worker/src/scripts/verifyClickhouseRecords.ts@@ -7,14 +7,39 @@ import {} from "@langfuse/shared/src/server";// Constants-const LIMIT = 50;-const ITERATIONS = 20;-const DATE_START = new Date("2024-08-13T10:30:00.000Z");-const DATE_END = new Date(); //new Date(Date.now() - 1000 * 60 * 60); // 1 hour ago+const LIMIT = 100;+const ITERATIONS = 10;+const DATE_START = new Date("2024-08-15T00:00:00.000Z");+const DATE_END = new Date(Date.now() - 1000 * 60 * 15); // 15 minutes ago++const TABLE_SAMPLE_RATE = 0.05;++// Execution+main({+ overwriteObservationIds: [],+ overwriteTraceIds: [],+ overwriteScoreIds: [],+}).then(() => {+ console.log("done");+ process.exit(0);+});++type MainParams = {+ overwriteObservationIds: string[];+ overwriteTraceIds: string[];+ overwriteScoreIds: string[];+};-const TABLE_SAMPLE_RATE = 10;+async function main(params: MainParams) {+ const { overwriteObservationIds, overwriteTraceIds, overwriteScoreIds } =+ params;++ const hasOverwrite = [+ overwriteObservationIds,+ overwriteTraceIds,+ overwriteScoreIds,+ ].some((o) => o.length > 0);-async function main() {const failedObservationList: string[] = [];const failedTraceList: string[] = [];const failedScoreList: string[] = [];@@ -31,24 +56,41 @@ async function main() {console.log(`Iteration ${currentIteration + 1}/${ITERATIONS}`);// Check observations- const randomObservations = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT- *- FROM- observations TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})- WHERE- start_time > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'- AND start_time < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'- LIMIT ${LIMIT}- `- );+ let observations: unknown[] = [];++ if (overwriteObservationIds.length > 0) {+ observations = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT+ *+ FROM+ observations+ WHERE+ id IN (${Prisma.join(overwriteObservationIds, ", ")})+ `+ );+ } else if (!hasOverwrite) {+ const randomObservations = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT+ *+ FROM+ observations TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})+ WHERE+ start_time > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'+ AND start_time < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'+ LIMIT ${LIMIT}+ `+ );++ observations = randomObservations;+ }- console.log(`Verifying ${randomObservations.length} observations...`);+ console.log(`Verifying ${observations.length} observations...`);try {const results = await Promise.allSettled(- randomObservations.map(async (obs) => {+ observations.map(async (obs) => {const id = (obs as any).id;if (checkedObservationSet.has(id)) {return;@@ -73,8 +115,19 @@ async function main() {}// Check traces- const randomTraces = await prisma.$queryRaw<unknown[]>(- Prisma.sql`+ let traces: unknown[] = [];+ if (overwriteTraceIds.length > 0) {+ const traces = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT *+ FROM traces+ WHERE+ id IN (${Prisma.join(overwriteTraceIds, ", ")})+ `+ );+ } else if (!hasOverwrite) {+ const randomTraces = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`SELECT *FROM traces TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})WHERE@@ -82,13 +135,16 @@ async function main() {AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'LIMIT ${LIMIT}`- );+ );- console.log(`Verifying ${randomTraces.length} traces...`);+ traces = randomTraces;+ }++ console.log(`Verifying ${traces.length} traces...`);try {const results = await Promise.allSettled(- randomTraces.map(async (trace) => {+ traces.map(async (trace) => {const id = (trace as any).id;if (checkedTraceSet.has(id)) {return;@@ -113,23 +169,37 @@ async function main() {}// Check scores- const randomScores = await prisma.$queryRaw<unknown[]>(- Prisma.sql`- SELECT *- FROM scores TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})- WHERE- timestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'- AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'- AND source = 'API'- LIMIT ${LIMIT}- `- );+ let scores: unknown[] = [];+ if (overwriteScoreIds.length > 0) {+ scores = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT *+ FROM scores+ WHERE+ id IN (${Prisma.join(overwriteScoreIds, ", ")})+ `+ );+ } else if (!hasOverwrite) {+ const randomScores = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT *+ FROM scores TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})+ WHERE+ timestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'+ AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'+ AND source = 'API'+ LIMIT ${LIMIT}+ `+ );- console.log(`Verifying ${randomScores.length} scores...`);+ scores = randomScores;+ }++ console.log(`Verifying ${scores.length} scores...`);try {const results = await Promise.allSettled(- randomScores.map(async (score) => {+ scores.map(async (score) => {const id = (score as any).id;if (checkedScoreSet.has(id)) {return;@@ -154,6 +224,7 @@ async function main() {}currentIteration++;+ if (hasOverwrite) break;}console.log(`Total observations verified: ${totalObservationCount}`);@@ -161,15 +232,13 @@ async function main() {console.log(`Total scores verified: ${totalScoreCount}`);if (failedObservationList.length > 0) {- await Promise.all([- writeFile(- `src/scripts/output/${new Date().toISOString()}_failedObservations.txt`,- failedObservationList.join("\n")- ),- ]);- console.error(- `Failed to verify ${failedObservationList.length} out of ${totalObservationCount} observations`- );+ await writeFile(+ `src/scripts/output/${new Date().toISOString()}_failedObservations.txt`,+ failedObservationList.join("\n")+ ),+ console.error(+ `Failed to verify ${failedObservationList.length} out of ${totalObservationCount} observations`+ );} else {console.log(`All ${totalObservationCount} observations verified successfully`@@ -177,35 +246,32 @@ async function main() {}if (failedTraceList.length > 0) {- writeFile(+ await writeFile(`src/scripts/output/${new Date().toISOString()}_failedTraces.txt`,failedTraceList.join("\n")- ),- console.error(- `Failed to verify ${failedTraceList.length} out of ${totalTraceCount} traces`- );+ );++ console.error(+ `Failed to verify ${failedTraceList.length} out of ${totalTraceCount} traces`+ );} else {console.log(`All ${totalTraceCount} traces verified successfully`);}if (failedScoreList.length > 0) {- writeFile(+ await writeFile(`src/scripts/output/${new Date().toISOString()}_failedScores.txt`,failedScoreList.join("\n")- ),- console.error(- `Failed to verify ${failedScoreList.length} out of ${totalScoreCount} scores`- );+ );++ console.error(+ `Failed to verify ${failedScoreList.length} out of ${totalScoreCount} scores`+ );} else {console.log(`All ${totalScoreCount} scores verified successfully`);}}-main().then(() => {- console.log("done");- process.exit(0);-});-async function verifyClickhouseObservation(postgresObservation: any) {const { id: observationId, project_id: projectId } = postgresObservation;const clickhouseResult = await clickhouseClient.query({diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 9b5c4744ba..4d9cb333c7 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -75,8 +75,8 @@ export class IngestionService {this.promptService = new PromptService(prisma, redis);}- public async flush(projectEntityKey: string): Promise<void> {- const bufferKey = IngestionUtils.getBufferKey(projectEntityKey);+ public async flush(flushKey: string): Promise<void> {+ const bufferKey = IngestionUtils.getBufferKey(flushKey);const eventList = (await this.redis.lrange(bufferKey, 0, -1)).map((serializedEventData) => {const parsed = ingestionEventWithProjectId.safeParse(@@ -97,12 +97,12 @@ export class IngestionService {if (eventList.length === 0) {throw new Error(- `No valid events found in buffer for project entity ${projectEntityKey}`+ `No valid events found in buffer for flushKey ${flushKey}`);}const { projectId, eventType, entityId } =- IngestionUtils.parseProjectEntityKey(projectEntityKey);+ IngestionUtils.parseFlushKey(flushKey);switch (eventType) {case ClickhouseEntityType.Trace: