Skip to content

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

feat(ingestion): enqueue events directly in web (#2934)

Hassieb Pakzad7af78553d1b8
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 5954e54ad8..cad90e97b2 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -28,6 +28,11 @@ const EnvSchema = z.object({
CLICKHOUSE_URL: z.string().url().optional(),
CLICKHOUSE_USER: z.string().optional(),
CLICKHOUSE_PASSWORD: z.string().optional(),
+ LANGFUSE_INGESTION_FLUSH_DELAY_MS: z.coerce
+ .number()
+ .nonnegative()
+ .default(10000),
+ LANGFUSE_INGESTION_FLUSH_ATTEMPTS: z.coerce.number().positive().default(3),
});
export const env = EnvSchema.parse(process.env);
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 1bf9b2a946..19e464749e 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -10,6 +10,7 @@ export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
export * from "./clickhouse";
export * from "../server/definitions";
+export * from "../server/ingestion/IngestionUtils";
export * from "../server/ingestion/types";
export * from "../server/ingestion/model-match";
export * from "../server/ingestion/types";
@@ -17,4 +18,5 @@ export * from "../server/ingestion/validateAndInflateScore";
export * from "./redis/redis";
export * from "./redis/trace-upsert";
export * from "./redis/batch-export";
+export * from "./redis/ingestionFlushQueue";
export * from "./clickhouse";
diff --git a/packages/shared/src/server/ingestion/IngestionUtils.ts b/packages/shared/src/server/ingestion/IngestionUtils.ts
new file mode 100644
index 0000000000..7da681ce64
--- /dev/null
+++ b/packages/shared/src/server/ingestion/IngestionUtils.ts
@@ -0,0 +1,79 @@
+import { eventTypes, IngestionEventType } from "./types";
+
+const reservedCharsEscapeMap = [
+ { reserved: ":", escape: "|%|" },
+ { reserved: "_", escape: "|#|" },
+];
+
+export enum ClickhouseEntityType {
+ Trace = "trace",
+ Score = "score",
+ Observation = "observation",
+ SDK_LOG = "sdk-log",
+}
+
+export class IngestionUtils {
+ public static getBufferKey(projectEntityKey: string): string {
+ return "ingestionBuffer:" + projectEntityKey;
+ }
+
+ public static getProjectEntityKey(params: {
+ projectId: string;
+ eventType: ClickhouseEntityType;
+ entityId: string;
+ }): string {
+ const sanitizedEntityId = IngestionUtils.escapeReservedChars(
+ params.entityId
+ );
+
+ return `${params.projectId}_${params.eventType}_${sanitizedEntityId}`;
+ }
+
+ public static parseProjectEntityKey(projectEntityKey: string) {
+ const split = projectEntityKey.split("_");
+
+ if (split.length !== 3) {
+ throw new Error(
+ `Invalid project entity key format ${projectEntityKey}, expected 3 parts`
+ );
+ }
+
+ const [projectId, eventType, escapedEntityId] = split;
+ const entityId = IngestionUtils.unescapeReservedChars(escapedEntityId);
+
+ return { projectId, eventType, entityId };
+ }
+
+ private static escapeReservedChars(string: string): string {
+ return reservedCharsEscapeMap.reduce(
+ (acc, { reserved, escape }) => acc.replaceAll(reserved, escape),
+ string
+ );
+ }
+
+ private static unescapeReservedChars(escapedString: string): string {
+ return reservedCharsEscapeMap.reduce(
+ (acc, { reserved, escape }) => acc.replaceAll(escape, reserved),
+ escapedString
+ );
+ }
+
+ public static getEventType(event: IngestionEventType): ClickhouseEntityType {
+ switch (event.type) {
+ case eventTypes.TRACE_CREATE:
+ return ClickhouseEntityType.Trace;
+ case eventTypes.OBSERVATION_CREATE:
+ case eventTypes.OBSERVATION_UPDATE:
+ case eventTypes.EVENT_CREATE:
+ case eventTypes.SPAN_CREATE:
+ case eventTypes.SPAN_UPDATE:
+ case eventTypes.GENERATION_CREATE:
+ case eventTypes.GENERATION_UPDATE:
+ return ClickhouseEntityType.Observation;
+ case eventTypes.SCORE_CREATE:
+ return ClickhouseEntityType.Score;
+ case eventTypes.SDK_LOG:
+ return ClickhouseEntityType.SDK_LOG;
+ }
+ }
+}
diff --git a/packages/shared/src/server/redis/ingestionFlushQueue.ts b/packages/shared/src/server/redis/ingestionFlushQueue.ts
new file mode 100644
index 0000000000..f36349a9c4
--- /dev/null
+++ b/packages/shared/src/server/redis/ingestionFlushQueue.ts
@@ -0,0 +1,27 @@
+import { Queue } from "bullmq";
+
+import { env } from "../../env";
+import { QueueName } from "../../queues";
+import { redis } from "../redis/redis";
+
+export type IngestionFlushQueue = Queue<null>;
+
+let ingestionFlushQueue: IngestionFlushQueue | null = null;
+
+export const getIngestionFlushQueue = () => {
+ if (ingestionFlushQueue) return ingestionFlushQueue;
+
+ ingestionFlushQueue = redis
+ ? new Queue<null>(QueueName.IngestionFlushQueue, {
+ connection: redis,
+ defaultJobOptions: {
+ removeOnComplete: true, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue
+ removeOnFail: 1000,
+ delay: env.LANGFUSE_INGESTION_FLUSH_DELAY_MS,
+ attempts: env.LANGFUSE_INGESTION_FLUSH_ATTEMPTS,
+ },
+ })
+ : null;
+
+ return ingestionFlushQueue;
+};
diff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.json
index efec50459e..e6bf29d0c4 100644
--- a/packages/shared/tsconfig.json
+++ b/packages/shared/tsconfig.json
@@ -4,7 +4,7 @@
"jsx": "react",
"moduleResolution": "NodeNext",
"module": "NodeNext",
- "lib": ["ES2020"],
+ "lib": ["ES2021"],
"outDir": "./dist",
"types": ["node"],
"target": "ES2020",
diff --git a/web/src/env.mjs b/web/src/env.mjs
index fd88a79449..df1c02fd46 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -39,7 +39,9 @@ export const env = createEnv({
}),
// Add newly signed up users to default org and/or project with role
LANGFUSE_DEFAULT_ORG_ID: z.string().optional(),
- LANGFUSE_DEFAULT_ORG_ROLE: z.enum(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE"]).optional(),
+ LANGFUSE_DEFAULT_ORG_ROLE: z
+ .enum(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE"])
+ .optional(),
LANGFUSE_DEFAULT_PROJECT_ID: z.string().optional(),
LANGFUSE_DEFAULT_PROJECT_ROLE: z
.enum(["OWNER", "ADMIN", "MEMBER", "VIEWER"])
@@ -148,14 +150,23 @@ export const env = createEnv({
LANGFUSE_ASYNC_INGESTION_PROCESSING: z
.enum(["true", "false"])
.default("false"),
- LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z.string().optional().refine((value) => {
- if (!value) return true;
+ LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z
+ .string()
+ .optional()
+ .refine((value) => {
+ if (!value) return true;
- const creators = value.split(",");
- const emailSchema = z.string().email()
- return creators.every((creator) => emailSchema.safeParse(creator).success);
- }, "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS must be a comma separated list of valid email addresses")
+ const creators = value.split(",");
+ const emailSchema = z.string().email();
+ return creators.every(
+ (creator) => emailSchema.safeParse(creator).success,
+ );
+ }, "LANGFUSE_ALLOWED_ORGANIZATION_CREATORS must be a comma separated list of valid email addresses")
.transform((v) => (v === "" || v === undefined ? undefined : v)),
+ LANGFUSE_INGESTION_BUFFER_TTL_SECONDS: z.coerce
+ .number()
+ .positive()
+ .default(60 * 10),
},
/**
@@ -297,7 +308,10 @@ export const env = createEnv({
process.env.LANGFUSE_CACHE_API_KEY_TTL_SECONDS,
LANGFUSE_ASYNC_INGESTION_PROCESSING:
process.env.LANGFUSE_ASYNC_INGESTION_PROCESSING,
- LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
+ LANGFUSE_ALLOWED_ORGANIZATION_CREATORS:
+ process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
+ LANGFUSE_INGESTION_BUFFER_TTL_SECONDS:
+ process.env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/web/src/features/ingest/enqueueIngestionEvents.ts b/web/src/features/ingest/enqueueIngestionEvents.ts
new file mode 100644
index 0000000000..17c8980a10
--- /dev/null
+++ b/web/src/features/ingest/enqueueIngestionEvents.ts
@@ -0,0 +1,62 @@
+import { env } from "@/src/env.mjs";
+import { QueueJobs } from "@langfuse/shared";
+import {
+ type IngestionEventType,
+ getIngestionFlushQueue,
+ redis,
+ IngestionUtils,
+ type IngestionFlushQueue,
+} from "@langfuse/shared/src/server";
+import { type Redis } from "ioredis";
+
+export async function enqueueIngestionEvents(
+ projectId: string,
+ events: IngestionEventType[],
+) {
+ const ingestionFlushQueue = getIngestionFlushQueue();
+
+ if (!ingestionFlushQueue) {
+ throw Error("IngestionFlushQueue not initialized");
+ }
+ if (!redis) throw Error("Redis connection not available");
+
+ const queuedEventPromises: Promise<void>[] = [];
+
+ // Use for loop as TS does not narrow redis type in map function
+ for (const event of events) {
+ queuedEventPromises.push(
+ enqueueSingleIngestionEvent(projectId, event, redis, ingestionFlushQueue),
+ );
+ }
+
+ await Promise.all(queuedEventPromises);
+}
+
+async function enqueueSingleIngestionEvent(
+ projectId: string,
+ event: IngestionEventType,
+ redis: Redis,
+ ingestionFlushQueue: IngestionFlushQueue,
+): Promise<void> {
+ if (!("id" in event.body && event.body.id)) {
+ console.warn(
+ `Received ingestion event without id: ${JSON.stringify(event)}`,
+ );
+
+ return;
+ }
+
+ const projectEntityKey = IngestionUtils.getProjectEntityKey({
+ entityId: event.body.id,
+ eventType: IngestionUtils.getEventType(event),
+ projectId,
+ });
+ const bufferKey = IngestionUtils.getBufferKey(projectEntityKey);
+ 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,
+ });
+}
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index b1e49bb31a..0ade35156e 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -19,7 +19,9 @@ import {
eventTypes,
getTraceUpsertQueue,
ingestionEvent,
+ redis,
} from "@langfuse/shared/src/server";
+import { enqueueIngestionEvents } from "@/src/features/ingest/enqueueIngestionEvents";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import { persistEventMiddleware } from "@/src/server/api/services/event-service";
import { backOff } from "exponential-backoff";
@@ -44,10 +46,8 @@ import {
ForbiddenError,
UnauthorizedError,
} from "@langfuse/shared";
-import { redis } from "@langfuse/shared/src/server";
import { isSigtermReceived } from "@/src/utils/shutdown";
-import { WorkerClient } from "@/src/server/api/services/WorkerClient";
export const config = {
api: {
@@ -283,13 +283,12 @@ export const handleBatch = async (
}
if (env.CLICKHOUSE_URL) {
- await new WorkerClient()
- .sendIngestionBatch({
- batch: events,
- metadata,
- projectId: authCheck.scope.projectId,
- })
- .catch(); // Ignore errors while testing the ingestion via worker
+ try {
+ await enqueueIngestionEvents(authCheck.scope.projectId, events);
+ console.log(`Added ${events.length} ingestion events to queue`);
+ } catch (err) {
+ console.error("Error adding ingestion events to queue", err);
+ }
}
return { results, errors };
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index d43b0e84c1..fa64a3ebf7 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -2,13 +2,10 @@ import express from "express";
import basicAuth from "express-basic-auth";
import { EventBodySchema, EventName, QueueJobs } from "@langfuse/shared";
-import { prisma } from "@langfuse/shared/src/db";
import {
clickhouseClient,
convertTraceUpsertEventsToRedisEvents,
getTraceUpsertQueue,
- ingestionApiSchemaWithProjectId,
- redis,
getBatchExportQueue,
} from "@langfuse/shared/src/server";
import * as Sentry from "@sentry/node";
@@ -16,9 +13,6 @@ import * as Sentry from "@sentry/node";
import { env } from "../env";
import { checkContainerHealth } from "../features/health";
import logger from "../logger";
-import { ingestionFlushQueue } from "../queues/ingestionFlushQueue";
-import { ClickhouseWriter } from "../services/ClickhouseWriter";
-import { IngestionService } from "../services/IngestionService";
const router = express.Router();
@@ -136,44 +130,7 @@ router
})
)
.post("/ingestion", async (req, res) => {
- try {
- if (!redis) {
- throw new Error("Redis connection not available");
- }
-
- const { body } = req;
- const events = ingestionApiSchemaWithProjectId.safeParse(body);
-
- if (!events.success) {
- logger.error(events.error, "Failed to parse ingestion event");
-
- return res.status(400).json(events.error);
- }
-
- const { batch, projectId } = events.data;
-
- if (!ingestionFlushQueue) {
- throw Error("Ingestion flush queue not available");
- }
-
- await new IngestionService(
- redis,
- prisma,
- ingestionFlushQueue,
- ClickhouseWriter.getInstance(),
- clickhouseClient,
- env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS // TODO: Make this configurable,
- ).addBatch(batch, projectId);
-
- return res.status(200).send();
- } catch (e) {
- logger.error(e, "Failed to process ingestion event");
-
- if (!res.headersSent)
- return res
- .status(500)
- .json({ message: e instanceof Error ? e.message : undefined });
- }
+ return res.status(200).send(); // Not implemented, Send 200 to acknowledge the request for web containers to not throw
});
export default router;
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 0ff4c42a72..3c1fdb989f 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -12,7 +12,7 @@ import logger from "./logger";
import { evalJobCreator, evalJobExecutor } from "./queues/evalQueue";
import { batchExportJobExecutor } from "./queues/batchExportQueue";
-import { flushIngestionQueueExecutor } from "./queues/ingestionFlushQueue";
+import { ingestionQueueExecutor } from "./queues/ingestionFlushQueueExecutor";
import { repeatQueueExecutor } from "./queues/repeatQueue";
import { logQueueWorkerError } from "./utils/logQueueWorkerError";
import { onShutdown } from "./utils/shutdown";
@@ -47,14 +47,14 @@ logger.info(
logger.info("Repeat Queue Executor started", repeatQueueExecutor?.isRunning());
logger.info(
"Flush Ingestion Queue Executor started",
- flushIngestionQueueExecutor?.isRunning()
+ ingestionQueueExecutor?.isRunning()
);
evalJobCreator?.on("failed", logQueueWorkerError);
evalJobExecutor?.on("failed", logQueueWorkerError);
batchExportJobExecutor?.on("failed", logQueueWorkerError);
repeatQueueExecutor?.on("failed", logQueueWorkerError);
-flushIngestionQueueExecutor?.on("failed", logQueueWorkerError);
+ingestionQueueExecutor?.on("failed", logQueueWorkerError);
process.on("SIGINT", () => onShutdown("SIGINT"));
process.on("SIGTERM", () => onShutdown("SIGTERM"));
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 8ae062baa8..f73647aa06 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -28,15 +28,6 @@ const EnvSchema = z.object({
EMAIL_FROM_ADDRESS: z.string().optional(),
SMTP_CONNECTION_URL: z.string().optional(),
LANGFUSE_TRACING_SAMPLE_RATE: z.coerce.number().positive().default(0.5),
- LANGFUSE_INGESTION_BUFFER_TTL_SECONDS: z.coerce
- .number()
- .positive()
- .default(60 * 10),
- LANGFUSE_INGESTION_FLUSH_DELAY_MS: z.coerce
- .number()
- .nonnegative()
- .default(10000),
- LANGFUSE_INGESTION_FLUSH_ATTEMPTS: z.coerce.number().positive().default(3),
LANGFUSE_INGESTION_FLUSH_PROCESSING_CONCURRENCY: z.coerce
.number()
.positive()
diff --git a/worker/src/queues/ingestionFlushQueue.ts b/worker/src/queues/ingestionFlushQueueExecutor.ts
similarity index 80%
rename from worker/src/queues/ingestionFlushQueue.ts
rename to worker/src/queues/ingestionFlushQueueExecutor.ts
index 43ff226e8a..37cab4a656 100644
--- a/worker/src/queues/ingestionFlushQueue.ts
+++ b/worker/src/queues/ingestionFlushQueueExecutor.ts
@@ -2,30 +2,22 @@ import { Queue, Worker } from "bullmq";
import { QueueJobs, QueueName } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { clickhouseClient, redis } from "@langfuse/shared/src/server";
+import {
+ clickhouseClient,
+ getIngestionFlushQueue,
+ redis,
+} from "@langfuse/shared/src/server";
import * as Sentry from "@sentry/node";
import { env } from "../env";
+import { instrumentAsync } from "../instrumentation";
import logger from "../logger";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
import { IngestionService } from "../services/IngestionService";
-import { instrumentAsync } from "../instrumentation";
-
-export type IngestionFlushQueue = Queue<null>;
-export const ingestionFlushQueue: IngestionFlushQueue | null = redis
- ? new Queue<null>(QueueName.IngestionFlushQueue, {
- connection: redis,
- defaultJobOptions: {
- removeOnComplete: true, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue
- removeOnFail: 1000,
- delay: env.LANGFUSE_INGESTION_FLUSH_DELAY_MS,
- attempts: env.LANGFUSE_INGESTION_FLUSH_ATTEMPTS,
- },
- })
- : null;
+const ingestionFlushQueue = getIngestionFlushQueue();
-export const flushIngestionQueueExecutor = redis
+export const ingestionQueueExecutor = redis
? new Worker(
QueueName.IngestionFlushQueue,
async (job) => {
@@ -66,10 +58,8 @@ export const flushIngestionQueueExecutor = redis
await new IngestionService(
redis,
prisma,
- ingestionFlushQueue,
ClickhouseWriter.getInstance(),
- clickhouseClient,
- env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS
+ clickhouseClient
).flush(projectEntityId);
// Log processing time
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 3f728b2e9f..d7da93ed8b 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -2,15 +2,13 @@ import { Redis } from "ioredis";
import { randomUUID } from "node:crypto";
import { v4 } from "uuid";
-import { Model, PrismaClient, Prompt, QueueJobs } from "@langfuse/shared";
+import { Model, PrismaClient, Prompt } from "@langfuse/shared";
import {
convertObservationReadToInsert,
convertScoreReadToInsert,
convertTraceReadToInsert,
eventTypes,
findModel,
- IngestionBatchEventType,
- IngestionEventType,
ingestionEventWithProjectId,
IngestionEventWithProjectIdType,
ObservationEvent,
@@ -27,22 +25,17 @@ import {
traceRecordReadSchema,
ClickhouseClientType,
validateAndInflateScore,
+ IngestionUtils,
+ ClickhouseEntityType,
+ PromptService,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
import { instrumentAsync } from "../../instrumentation";
import logger from "../../logger";
-import { IngestionFlushQueue } from "../../queues/ingestionFlushQueue";
import { ClickhouseWriter, TableName } from "../ClickhouseWriter";
import { convertJsonSchemaToRecord, overwriteObject } from "./utils";
-enum EntityType {
- Trace = "trace",
- Score = "score",
- Observation = "observation",
- SDK_LOG = "sdk-log",
-}
-
type InsertRecord =
| TraceRecordInsertType
| ScoreRecordInsertType
@@ -70,54 +63,20 @@ const immutableEntityKeys: {
],
};
-const reservedCharsEscapeMap = [
- { reserved: ":", escape: "|%|" },
- { reserved: "_", escape: "|#|" },
-];
-
export class IngestionService {
+ private promptService: PromptService;
+
constructor(
private redis: Redis,
- private prisma: PrismaClient,
- private ingestionFlushQueue: IngestionFlushQueue,
+ prisma: PrismaClient,
private clickHouseWriter: ClickhouseWriter,
- private clickhouseClient: ClickhouseClientType,
- private bufferTtlSeconds: number
- ) {}
-
- public async addBatch(
- events: IngestionBatchEventType,
- projectId: string
- ): Promise<void> {
- const ingestedEvents = events.map(async (event) => {
- if (!("id" in event.body && event.body.id)) {
- logger.warn(
- `Received ingestion event without id, ${JSON.stringify(event)}`
- );
-
- return null;
- }
-
- const projectEntityKey = this.getProjectEntityKey({
- entityId: event.body.id,
- eventType: this.getEventType(event),
- projectId,
- });
- const bufferKey = this.getBufferKey(projectEntityKey);
- const serializedEventData = JSON.stringify({ ...event, projectId });
-
- await this.redis.lpush(bufferKey, serializedEventData);
- await this.redis.expire(bufferKey, this.bufferTtlSeconds);
- await this.ingestionFlushQueue.add(QueueJobs.FlushIngestionEntity, null, {
- jobId: projectEntityKey,
- });
- });
-
- await Promise.all(ingestedEvents);
+ private clickhouseClient: ClickhouseClientType
+ ) {
+ this.promptService = new PromptService(prisma, redis);
}
public async flush(projectEntityKey: string): Promise<void> {
- const bufferKey = this.getBufferKey(projectEntityKey);
+ const bufferKey = IngestionUtils.getBufferKey(projectEntityKey);
const eventList = (await this.redis.lrange(bufferKey, 0, -1))
.map((serializedEventData) => {
const parsed = ingestionEventWithProjectId.safeParse(
@@ -143,22 +102,22 @@ export class IngestionService {
}
const { projectId, eventType, entityId } =
- this.parseProjectEntityKey(projectEntityKey);
+ IngestionUtils.parseProjectEntityKey(projectEntityKey);
switch (eventType) {
- case EntityType.Trace:
+ case ClickhouseEntityType.Trace:
return await this.processTraceEventList({
projectId,
entityId,
traceEventList: eventList as TraceEventType[],
});
- case EntityType.Observation:
+ case ClickhouseEntityType.Observation:
return await this.processObservationEventList({
projectId,
entityId,
observationEventList: eventList as ObservationEvent[],
});
- case EntityType.Score: {
+ case ClickhouseEntityType.Score: {
return await this.processScoreEventList({
projectId,
entityId,
@@ -168,70 +127,6 @@ export class IngestionService {
}
}
- private getEventType(event: IngestionEventType): EntityType {
- switch (event.type) {
- case eventTypes.TRACE_CREATE:
- return EntityType.Trace;
- case eventTypes.OBSERVATION_CREATE:
- case eventTypes.OBSERVATION_UPDATE:
- case eventTypes.EVENT_CREATE:
- case eventTypes.SPAN_CREATE:
- case eventTypes.SPAN_UPDATE:
- case eventTypes.GENERATION_CREATE:
- case eventTypes.GENERATION_UPDATE:
- return EntityType.Observation;
- case eventTypes.SCORE_CREATE:
- return EntityType.Score;
- case eventTypes.SDK_LOG:
- return EntityType.SDK_LOG;
- }
- }
-
- private getProjectEntityKey(params: {
- projectId: string;
- eventType: EntityType;
- entityId: string;
- }): string {
- const sanitizedEntityId = IngestionService.escapeReservedChars(
- params.entityId
- );
-
- return `${params.projectId}_${params.eventType}_${sanitizedEntityId}`;
- }
-
- private parseProjectEntityKey(projectEntityKey: string) {
- const split = projectEntityKey.split("_");
-
- if (split.length !== 3) {
- throw new Error(
- `Invalid project entity key format ${projectEntityKey}, expected 3 parts`
- );
- }
-
- const [projectId, eventType, escapedEntityId] = split;
- const entityId = IngestionService.unescapeReservedChars(escapedEntityId);
-
- return { projectId, eventType, entityId };
- }
-
- private getBufferKey(projectEntityKey: string): string {
- return "ingestionBuffer:" + projectEntityKey;
- }
-
- private static escapeReservedChars(string: string): string {
- return reservedCharsEscapeMap.reduce(
- (acc, { reserved, escape }) => acc.replaceAll(reserved, escape),
- string
- );
- }
-
- private static unescapeReservedChars(escapedString: string): string {
- return reservedCharsEscapeMap.reduce(
- (acc, { reserved, escape }) => acc.replaceAll(escape, reserved),
- escapedString
- );
- }
-
private async processScoreEventList(params: {
projectId: string;
entityId: string;
@@ -494,20 +389,15 @@ export class IngestionService {
if (!lastObservationWithPromptInfo) return null;
- const dbPrompt = await this.prisma.prompt.findFirst({
- where: {
- projectId,
- name: lastObservationWithPromptInfo.body.promptName,
- version: lastObservationWithPromptInfo.body.promptVersion,
- },
- select: {
- id: true,
- name: true,
- version: true,
- },
- });
+ const { promptName, promptVersion: version } =
+ lastObservationWithPromptInfo.body;
- return dbPrompt;
+ return this.promptService.getPrompt({
+ projectId,
+ promptName,
+ version,
+ label: undefined,
+ });
}
private hasPromptInformation(
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index f45e6fbcad..b2cbd9efe6 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -38,10 +38,8 @@ describe("Ingestion end-to-end tests", () => {
ingestionService = new IngestionService(
redis,
prisma,
- mockIngestionFlushQueue,
clickhouseWriter,
- clickhouseClient,
- 30
+ clickhouseClient
);
});
diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
index 6f9c7c6c23..8ee77bb30d 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
@@ -1,5 +1,6 @@
import { expect, describe, it, vi } from "vitest";
import { IngestionService } from "../../IngestionService";
+import { IngestionUtils } from "@langfuse/shared/src/server";
describe("IngestionService unit tests", () => {
it("correctly escapes user provided IDs", async () => {
@@ -7,14 +8,14 @@ describe("IngestionService unit tests", () => {
const userProvidedId = "user_provided_id_with:colon:chars";
const expectedEscapedId = "user|#|provided|#|id|#|with|%|colon|%|chars";
- expect((IngestionService as any).escapeReservedChars(userProvidedId)).toBe(
+ expect((IngestionUtils as any).escapeReservedChars(userProvidedId)).toBe(
expectedEscapedId
);
expect(
- (IngestionService as any).unescapeReservedChars(expectedEscapedId)
+ (IngestionUtils as any).unescapeReservedChars(expectedEscapedId)
).toBe(userProvidedId);
- expect((IngestionService as any).escapeReservedChars(validUuid)).toBe(
+ expect((IngestionUtils as any).escapeReservedChars(validUuid)).toBe(
validUuid
);
});
diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
index 113b1870a9..0d81efc4d4 100644
--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts
@@ -29,10 +29,8 @@ vi.mock("../../ClickhouseWriter", async (importOriginal) => {
const mockIngestionService = new IngestionService(
null as any,
prisma,
- null as any,
clickhouseWriteExports.ClickhouseWriter.getInstance() as any,
- mockClickhouseClient as any,
- 10
+ mockClickhouseClient as any
);
describe("Token Cost Calculation", () => {
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index df2f623383..1727c2256a 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -4,7 +4,7 @@ import { redis } from "@langfuse/shared/src/server";
import { evalJobCreator, evalJobExecutor } from "../queues/evalQueue";
import { batchExportJobExecutor } from "../queues/batchExportQueue";
-import { flushIngestionQueueExecutor } from "../queues/ingestionFlushQueue";
+import { ingestionQueueExecutor } from "../queues/ingestionFlushQueueExecutor";
import { repeatQueueExecutor } from "../queues/repeatQueue";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
import { setSigtermReceived } from "../features/health";
@@ -23,7 +23,7 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
evalJobCreator,
evalJobExecutor,
batchExportJobExecutor,
- flushIngestionQueueExecutor,
+ ingestionQueueExecutor,
repeatQueueExecutor,
];