Skip to content

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

feat(web): send trace events via Redis instead of Rest (#2579)

Max Deichmann6554c5ee8820
diff --git a/.env.prod.example b/.env.prod.example
index fab73c2e52..cdf7143970 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -151,5 +151,11 @@ LANGFUSE_CSP_ENFORCE_HTTPS="true"
# Admin API
# ADMIN_API_KEY=
+# Redis
+# REDIS_HOST=
+# REDIS_PORT=
+# REDIS_AUTH=
+# REDIS_CONNECTION_STRING=
+
### END Langfuse Cloud Config
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 3bcdd1dd0c..adc35cf350 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -63,6 +63,7 @@ jobs:
fi
tests-web:
+ timeout-minutes: 20
runs-on: ubuntu-latest
name: tests-web (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }})
strategy:
@@ -93,7 +94,7 @@ jobs:
- name: Load default env
run: |
cp .env.dev.example .env
- cp .env.dev.example web/.env
+ grep -v '^REDIS_HOST=' .env.dev.example > web/.env
- name: Run + migrate
run: |
@@ -118,6 +119,7 @@ jobs:
run: pnpm --filter=web run test
tests-worker:
+ timeout-minutes: 20
runs-on: ubuntu-latest
name: tests-worker (node${{ matrix.node-version }}, pg${{ matrix.postgres-version }})
strategy:
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 9417b99496..08a5dae1b7 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -55,6 +55,8 @@
"@react-email/render": "^0.0.15",
"@types/bcryptjs": "^2.4.6",
"bcryptjs": "^2.4.3",
+ "bullmq": "^5.4.2",
+ "ioredis": "^5.4.1",
"kysely": "^0.27.3",
"langchain": "^0.2.6",
"lodash": "^4.17.21",
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index 2b4e64a4a2..bbad2bf36a 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -14,6 +14,7 @@ import { v4 } from "uuid";
import { ModelUsageUnit } from "../src";
import { getDisplaySecretKey, hashSecretKey } from "../src/server";
import { encrypt } from "../src/encryption";
+import { redis } from "../src/server/redis/redis";
const LOAD_TRACE_VOLUME = 10_000;
@@ -354,10 +355,14 @@ async function main() {
main()
.then(async () => {
await prisma.$disconnect();
+ redis?.disconnect();
+ console.log("Disconnected from postgres and redis");
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
+ redis?.disconnect();
+ console.log("Disconnected from postgres and redis");
process.exit(1);
});
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 0049d632d5..ca24787754 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -1,6 +1,21 @@
import { z } from "zod";
const EnvSchema = z.object({
+ NODE_ENV: z
+ .enum(["development", "test", "production"])
+ .default("development"),
+ REDIS_HOST: z.string().nullish(),
+ REDIS_PORT: z.coerce
+ .number({
+ description:
+ ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ })
+ .positive()
+ .max(65536, `options.port should be >= 0 and < 65536`)
+ .default(6379)
+ .nullable(),
+ REDIS_AUTH: z.string().nullish(),
+ REDIS_CONNECTION_STRING: z.string().nullish(),
ENCRYPTION_KEY: z
.string()
.length(
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 4eea486810..a0a164d540 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -7,3 +7,5 @@ export * from "./llm/fetchLLMCompletion";
export * from "./llm/types";
export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
+export * from "./redis/redis";
+export * from "./redis/trace-upsert";
diff --git a/worker/src/redis.ts b/packages/shared/src/server/redis/redis.ts
similarity index 56%
rename from worker/src/redis.ts
rename to packages/shared/src/server/redis/redis.ts
index f64b59d187..c88325d818 100644
--- a/worker/src/redis.ts
+++ b/packages/shared/src/server/redis/redis.ts
@@ -1,23 +1,23 @@
import Redis from "ioredis";
-import { env } from "./env";
-import logger from "./logger";
+import { env } from "../../env";
const createRedisClient = () => {
try {
return env.REDIS_CONNECTION_STRING
? new Redis(env.REDIS_CONNECTION_STRING, { maxRetriesPerRequest: null })
- : new Redis({
- host: String(env.REDIS_HOST),
- port: Number(env.REDIS_PORT),
- password: String(env.REDIS_AUTH),
- maxRetriesPerRequest: null, // Set to `null` to disable retrying
- });
+ : env.REDIS_HOST
+ ? new Redis({
+ host: String(env.REDIS_HOST),
+ port: Number(env.REDIS_PORT),
+ password: String(env.REDIS_AUTH),
+ maxRetriesPerRequest: null, // Set to `null` to disable retrying
+ })
+ : null;
} catch (e) {
- logger.error(e, "Failed to connect to redis");
+ console.error(e, "Failed to connect to redis");
return null;
}
};
-
declare global {
// eslint-disable-next-line no-var
var redis: undefined | ReturnType<typeof createRedisClient>;
diff --git a/packages/shared/src/server/redis/trace-upsert.ts b/packages/shared/src/server/redis/trace-upsert.ts
new file mode 100644
index 0000000000..807c8c53ac
--- /dev/null
+++ b/packages/shared/src/server/redis/trace-upsert.ts
@@ -0,0 +1,56 @@
+import { randomUUID } from "crypto";
+import {
+ QueueJobs,
+ QueueName,
+ TQueueJobTypes,
+ TraceUpsertEventType,
+} from "../../queues";
+import { Queue } from "bullmq";
+import { redis } from "./redis";
+
+export const traceUpsertQueue = redis
+ ? new Queue<TQueueJobTypes[QueueName.TraceUpsert]>(QueueName.TraceUpsert, {
+ connection: redis,
+ })
+ : null;
+
+export function convertTraceUpsertEventsToRedisEvents(
+ events: TraceUpsertEventType[]
+) {
+ const uniqueTracesPerProject = events.reduce((acc, event) => {
+ if (!acc.get(event.projectId)) {
+ acc.set(event.projectId, new Set());
+ }
+ acc.get(event.projectId)?.add(event.traceId);
+ return acc;
+ }, new Map<string, Set<string>>());
+
+ const jobs = [...uniqueTracesPerProject.entries()]
+ .map((tracesPerProject) => {
+ const [projectId, traceIds] = tracesPerProject;
+
+ return [...traceIds].map((traceId) => ({
+ name: QueueJobs.TraceUpsert,
+ data: {
+ payload: {
+ projectId,
+ traceId,
+ },
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.TraceUpsert as const,
+ },
+ opts: {
+ removeOnFail: 10000,
+ removeOnComplete: true,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 1000,
+ },
+ },
+ }));
+ })
+ .flat();
+ return jobs;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 24a9b092f8..c73a1049c0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -40,7 +40,7 @@ importers:
next-auth:
specifier: ^4.24.7
zod:
specifier: ^3.23.8
version: 3.23.8
@@ -149,6 +149,12 @@ importers:
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
+ bullmq:
+ specifier: ^5.4.2
+ version: 5.4.3
+ ioredis:
+ specifier: ^5.4.1
+ version: 5.4.1
kysely:
specifier: ^0.27.3
version: 0.27.3
@@ -470,7 +476,7 @@ importers:
next-auth:
specifier: ^4.24.7
next-query-params:
specifier: ^5.0.0
@@ -15290,7 +15296,7 @@ snapshots:
'@typescript-eslint/eslint-plugin': 7.3.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
'@typescript-eslint/parser': 7.12.0([email protected])([email protected])
eslint-config-prettier: 9.1.0([email protected])
- eslint-import-resolver-alias: 1.1.2([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected]))
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])
eslint-plugin-eslint-comments: 3.2.0([email protected])
@@ -16999,7 +17005,7 @@ snapshots:
eslint: 8.57.0
eslint-plugin-turbo: 1.13.4([email protected])
dependencies:
@@ -18134,7 +18140,7 @@ snapshots:
dependencies:
'@ioredis/commands': 1.2.0
cluster-key-slot: 1.1.2
- debug: 4.3.4
+ debug: 4.3.5([email protected])
denque: 2.1.0
lodash.defaults: 4.2.0
lodash.isarguments: 3.1.0
@@ -19808,23 +19814,6 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.13
- dependencies:
- '@babel/runtime': 7.24.5
- '@panva/hkdf': 1.1.1
- cookie: 0.5.0
- jose: 4.15.5
- oauth: 0.9.15
- openid-client: 5.6.5
- preact: 10.19.7
- preact-render-to-string: 5.2.6([email protected])
- react: 18.2.0
- react-dom: 18.2.0([email protected])
- uuid: 8.3.2
- optionalDependencies:
- nodemailer: 6.9.13
-
dependencies:
'@babel/runtime': 7.24.5
diff --git a/web/jest.config.mjs b/web/jest.config.mjs
index 7147a999c4..bf6c6b646c 100644
--- a/web/jest.config.mjs
+++ b/web/jest.config.mjs
@@ -10,12 +10,16 @@ const clientTestConfig = {
displayName: "client",
testMatch: ["/**/*.clienttest.[jt]s?(x)"],
testEnvironment: "jest-environment-jsdom",
+ // setupFilesAfterEnv: ["<rootDir>/src/__tests__/after-teardown.ts"],
+ // globalTeardown: "<rootDir>/src/__tests__/teardown.ts",
};
const serverTestConfig = {
displayName: "server",
testMatch: ["/**/*.servertest.[jt]s?(x)"],
testEnvironment: "jest-environment-node",
+ setupFilesAfterEnv: ["<rootDir>/src/__tests__/after-teardown.ts"],
+ globalTeardown: "<rootDir>/src/__tests__/teardown.ts",
};
// To avoid the "Cannot use import statement outside a module" errors while transforming ESM.
diff --git a/web/package.json b/web/package.json
index 701db6856b..b07790da1a 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,7 +14,7 @@
"prettier": "prettier --write ./src *.{ts,js}",
"clean": "rm -rf node_modules",
"start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",
- "test": "dotenv -e ../.env -- jest --runInBand",
+ "test": "dotenv -e ../.env -- jest --runInBand --detectOpenHandles",
"test:watch": "dotenv -e ../.env -- jest --watch --runInBand",
"test:e2e": "dotenv -e ../.env -- playwright test",
"models:migrate": "dotenv -e ../.env -- tsx scripts/model-match.ts",
diff --git a/web/src/__tests__/after-teardown.ts b/web/src/__tests__/after-teardown.ts
new file mode 100644
index 0000000000..007235af15
--- /dev/null
+++ b/web/src/__tests__/after-teardown.ts
@@ -0,0 +1,5 @@
+import teardown from "@/src/__tests__/teardown";
+
+afterAll(async () => {
+ await teardown();
+});
diff --git a/web/src/__tests__/teardown.ts b/web/src/__tests__/teardown.ts
new file mode 100644
index 0000000000..e19329f2d3
--- /dev/null
+++ b/web/src/__tests__/teardown.ts
@@ -0,0 +1,13 @@
+export default async function teardown() {
+ const { redis } = await import("@langfuse/shared/src/server");
+ console.log(`Redis status ${redis?.status}`);
+ if (!redis) {
+ return;
+ }
+ if (redis.status === "end") {
+ console.log("Redis connection already closed");
+ return;
+ }
+ redis?.disconnect();
+ console.log("Teardown complete");
+}
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 4268692b54..b18d5a2132 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -117,9 +117,21 @@ export const env = createEnv({
.string()
.length(
64,
- "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32"
+ "ENCRYPTION_KEY must be 256 bits, 64 string characters in hex format, generate via: openssl rand -hex 32",
)
.optional(),
+ REDIS_HOST: z.string().nullish(),
+ REDIS_PORT: z.coerce
+ .number({
+ description:
+ ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ })
+ .positive()
+ .max(65536, `options.port should be >= 0 and < 65536`)
+ .default(6379)
+ .nullable(),
+ REDIS_AUTH: z.string().nullish(),
+ REDIS_CONNECTION_STRING: z.string().nullish(),
},
/**
@@ -239,6 +251,10 @@ export const env = createEnv({
LANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,
ADMIN_API_KEY: process.env.ADMIN_API_KEY,
ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,
+ REDIS_HOST: process.env.REDIS_HOST,
+ REDIS_PORT: process.env.REDIS_PORT,
+ REDIS_AUTH: process.env.REDIS_AUTH,
+ REDIS_CONNECTION_STRING: process.env.REDIS_CONNECTION_STRING,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/web/src/instrumentation.ts b/web/src/instrumentation.ts
index 9d0b69e8b6..4bd68736f9 100644
--- a/web/src/instrumentation.ts
+++ b/web/src/instrumentation.ts
@@ -1,17 +1,8 @@
// See: https://vercel.com/docs/observability/otel-overview
-import { shutdown } from "@/src/utils/shutdown";
-import prexit from "prexit";
-
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./sentry.server.config");
- if (process.env.NEXT_MANUAL_SIG_HANDLE) {
- prexit(async (signal) => {
- console.log("Signal: ", signal);
- return await shutdown(signal);
- });
- }
}
if (process.env.NEXT_RUNTIME === "edge") {
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 98e394d902..ba46864a60 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -40,6 +40,7 @@ import {
ForbiddenError,
UnauthorizedError,
} from "@langfuse/shared";
+
import { isSigtermReceived } from "@/src/utils/shutdown";
export const config = {
@@ -509,24 +510,34 @@ export const sendToWorkerIfEnvironmentConfigured = async (
batchResults: BatchResult[],
projectId: string,
): Promise<void> => {
+ const traceEvents: TraceUpsertEventType[] = batchResults
+ .filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update.
+ .map((result) =>
+ result.result &&
+ typeof result.result === "object" &&
+ "id" in result.result
+ ? // ingestion API only gets traces for one projectId
+ { traceId: result.result.id as string, projectId }
+ : null,
+ )
+ .filter(isNotNullOrUndefined);
+
try {
if (
+ (env.REDIS_CONNECTION_STRING || env.REDIS_HOST) &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ) {
+ const { convertTraceUpsertEventsToRedisEvents, traceUpsertQueue } =
+ await import("@langfuse/shared/src/server");
+ console.log("Sending events to worker via redis", traceEvents);
+ const jobs = convertTraceUpsertEventsToRedisEvents(traceEvents);
+ await traceUpsertQueue?.addBulk(jobs);
+ } else if (
env.LANGFUSE_WORKER_HOST &&
env.LANGFUSE_WORKER_PASSWORD &&
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
) {
- const traceEvents: TraceUpsertEventType[] = batchResults
- .filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update.
- .map((result) =>
- result.result &&
- typeof result.result === "object" &&
- "id" in result.result
- ? // ingestion API only gets traces for one projectId
- { traceId: result.result.id as string, projectId }
- : null,
- )
- .filter(isNotNullOrUndefined);
-
+ console.log("Sending events to worker via HTTP", traceEvents);
const body: EventBodyType = {
name: EventName.TraceUpsert,
payload: traceEvents,
diff --git a/web/src/utils/shutdown.ts b/web/src/utils/shutdown.ts
index 5708e067ef..50e02099e4 100644
--- a/web/src/utils/shutdown.ts
+++ b/web/src/utils/shutdown.ts
@@ -4,7 +4,7 @@
// NEVER call process.exit() in this process. Kubernetes should kill the container: https://kostasbariotis.com/why-you-should-not-use-process-exit/
// We wait for 20 seconds to allow the app to finish processing requests. There is no native way to do this in Next.js.
-const TIMEOUT = 240_000;
+const TIMEOUT = 60_000;
declare global {
// eslint-disable-next-line no-var
@@ -22,6 +22,8 @@ export const isSigtermReceived = () =>
Boolean(process.env.NEXT_MANUAL_SIG_HANDLE) && globalThis.sigtermReceived;
export const shutdown = async (signal: PrexitSignal) => {
+ // import redis at runtime
+
if (signal === "SIGTERM" || signal === "SIGINT") {
console.log(
`SIGTERM / SIGINT received. Shutting down in ${TIMEOUT / 1000} seconds.`,
@@ -29,7 +31,19 @@ export const shutdown = async (signal: PrexitSignal) => {
setSigtermReceived();
return await new Promise<void>((resolve) => {
- setTimeout(() => {
+ setTimeout(async () => {
+ if (typeof window === "undefined") {
+ const { redis } = await import("@langfuse/shared/src/server");
+ console.log(`Redis status ${redis?.status}`);
+ if (!redis) {
+ return;
+ }
+ if (redis.status === "end") {
+ console.log("Redis connection already closed");
+ return;
+ }
+ redis?.disconnect();
+ }
console.log("Shutdown complete");
resolve();
}, TIMEOUT);
diff --git a/worker/src/__tests__/evnets-api.test.ts b/worker/src/__tests__/evnets-api.test.ts
index d9bebed0b7..9877a98ca1 100644
--- a/worker/src/__tests__/evnets-api.test.ts
+++ b/worker/src/__tests__/evnets-api.test.ts
@@ -1,5 +1,5 @@
import { expect, test, describe } from "vitest";
-import { createRedisEvents } from "../api";
+import { convertTraceUpsertEventsToRedisEvents } from "@langfuse/shared/src/server";
describe.sequential("create redis events", () => {
test("deduplicate events from the same project id", async () => {
@@ -11,7 +11,7 @@ describe.sequential("create redis events", () => {
{ traceId: "trace3", projectId: "project2" },
];
- const jobs = createRedisEvents(events);
+ const jobs = convertTraceUpsertEventsToRedisEvents(events);
expect(jobs).toBeDefined();
expect(jobs.length).toBe(4);
diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.ts
index e21f25078d..a25f471d03 100644
--- a/worker/src/__tests__/redis-consumer.test.ts
+++ b/worker/src/__tests__/redis-consumer.test.ts
@@ -1,10 +1,10 @@
import { expect, test, describe, vi } from "vitest";
-import { evalQueue } from "../api";
import { QueueJobs, TraceUpsertEventSchema } from "@langfuse/shared";
import { randomUUID } from "crypto";
import { z } from "zod";
import logger from "../logger";
import { evalJobCreator } from "../queues/evalQueue";
+import { traceUpsertQueue } from "@langfuse/shared/src/server";
describe.sequential("handle redis events", () => {
test("handle redis job succeeding", async () => {
@@ -23,9 +23,9 @@ describe.sequential("handle redis events", () => {
logger.info(`Eval Job with id ${job?.id} completed`);
});
- expect(evalQueue).toBeDefined();
+ expect(traceUpsertQueue).toBeDefined();
- const job = await evalQueue?.add(QueueJobs.TraceUpsert, {
+ const job = await traceUpsertQueue?.add(QueueJobs.TraceUpsert, {
id: randomUUID(),
timestamp: new Date(),
payload: {
@@ -37,7 +37,7 @@ describe.sequential("handle redis events", () => {
await vi.waitFor(
async () => {
- const jobState = await evalQueue?.getJobState(job!.id!);
+ const jobState = await traceUpsertQueue?.getJobState(job!.id!);
expect(jobState).toEqual("completed");
},
{
diff --git a/worker/src/api/emojis.ts b/worker/src/api/emojis.ts
deleted file mode 100644
index 0618ae7ee5..0000000000
--- a/worker/src/api/emojis.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { Router } from "express";
-
-const router = Router();
-
-type EmojiResponse = string[];
-
-router.get<{}, EmojiResponse>("/", (req, res) => {
- res.json(["😀"]);
-});
-
-export default router;
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index dd69a1acc2..70c7171d6d 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -1,33 +1,18 @@
-import { Queue } from "bullmq";
-import { randomUUID } from "crypto";
import express from "express";
import basicAuth from "express-basic-auth";
import * as Sentry from "@sentry/node";
-
+import { EventBodySchema, EventName, QueueJobs } from "@langfuse/shared";
import {
- EventBodySchema,
- EventName,
- QueueJobs,
- QueueName,
- TQueueJobTypes,
- TraceUpsertEventType,
-} from "@langfuse/shared";
-
+ convertTraceUpsertEventsToRedisEvents,
+ traceUpsertQueue,
+} from "@langfuse/shared/src/server";
import { env } from "../env";
import logger from "../logger";
import { batchExportQueue } from "../queues/batchExportQueue";
-import { redis } from "../redis";
-import emojis from "./emojis";
import { checkContainerHealth } from "../features/health";
const router = express.Router();
-export const evalQueue = redis
- ? new Queue<TQueueJobTypes[QueueName.TraceUpsert]>(QueueName.TraceUpsert, {
- connection: redis,
- })
- : null;
-
type EventsResponse = {
status: "success" | "error";
};
@@ -66,8 +51,8 @@ router
if (event.data.name === EventName.TraceUpsert) {
// Find set of traces per project. There might be two events for the same trace in one API call.
// If we don't deduplicate, we will end up processing the same trace twice on two different workers in parallel.
- const jobs = createRedisEvents(event.data.payload);
- await evalQueue?.addBulk(jobs); // add all jobs as bulk
+ const jobs = convertTraceUpsertEventsToRedisEvents(event.data.payload);
+ await traceUpsertQueue?.addBulk(jobs); // add all jobs as bulk
return res.json({
status: "success",
@@ -97,45 +82,4 @@ router
}
});
-router.use("/emojis", emojis);
-
export default router;
-
-export function createRedisEvents(events: TraceUpsertEventType[]) {
- const uniqueTracesPerProject = events.reduce((acc, event) => {
- if (!acc.get(event.projectId)) {
- acc.set(event.projectId, new Set());
- }
- acc.get(event.projectId)?.add(event.traceId);
- return acc;
- }, new Map<string, Set<string>>());
-
- const jobs = [...uniqueTracesPerProject.entries()]
- .map((tracesPerProject) => {
- const [projectId, traceIds] = tracesPerProject;
-
- return [...traceIds].map((traceId) => ({
- name: QueueJobs.TraceUpsert,
- data: {
- payload: {
- projectId,
- traceId,
- },
- id: randomUUID(),
- timestamp: new Date(),
- name: QueueJobs.TraceUpsert as const,
- },
- opts: {
- removeOnFail: 10000,
- removeOnComplete: true,
- attempts: 5,
- backoff: {
- type: "exponential",
- delay: 1000,
- },
- },
- }));
- })
- .flat();
- return jobs;
-}
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 381afe49ae..f145760001 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -14,18 +14,6 @@ const EnvSchema = z.object({
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
.default(3030),
- REDIS_HOST: z.string().nullish(),
- REDIS_PORT: z.coerce
- .number({
- description:
- ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
- })
- .positive()
- .max(65536, `options.port should be >= 0 and < 65536`)
- .default(6379)
- .nullable(),
- REDIS_AUTH: z.string().nullish(),
- REDIS_CONNECTION_STRING: z.string().nullish(),
LANGFUSE_WORKER_PASSWORD: z.string(),
S3_ACCESS_KEY_ID: z.string().optional(),
S3_SECRET_ACCESS_KEY: z.string().optional(),
@@ -40,6 +28,18 @@ 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),
+ REDIS_HOST: z.string().nullish(),
+ REDIS_PORT: z.coerce
+ .number({
+ description:
+ ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",
+ })
+ .positive()
+ .max(65536, `options.port should be >= 0 and < 65536`)
+ .default(6379)
+ .nullable(),
+ REDIS_AUTH: z.string().nullish(),
+ REDIS_CONNECTION_STRING: z.string().nullish(),
});
export const env = EnvSchema.parse(process.env);
diff --git a/worker/src/features/evaluation/eval-service.ts b/worker/src/features/evaluation/eval-service.ts
index 5d741c3233..a9ac95d75b 100644
--- a/worker/src/features/evaluation/eval-service.ts
+++ b/worker/src/features/evaluation/eval-service.ts
@@ -36,6 +36,9 @@ export const createEvalJobs = async ({
}: {
event: z.infer<typeof TraceUpsertEventSchema>;
}) => {
+ logger.info(
+ `Creating eval jobs for trace ${event.traceId} on project ${event.projectId}`
+ );
const configs = await kyselyPrisma.$kysely
.selectFrom("job_configurations")
.selectAll()
@@ -47,7 +50,9 @@ export const createEvalJobs = async ({
logger.debug("No evaluation jobs found for project", event.projectId);
return;
}
- logger.info("Creating eval jobs for trace", event.traceId);
+ logger.info(
+ `Creating eval jobs for trace ${event.traceId} on project ${event.projectId}`
+ );
for (const config of configs) {
if (config.status === "INACTIVE") {
@@ -115,17 +120,16 @@ export const createEvalJobs = async ({
`Creating eval job for config ${config.id} and trace ${event.traceId}`
);
- await kyselyPrisma.$kysely
- .insertInto("job_executions")
- .values({
+ await prisma.jobExecution.create({
+ data: {
id: jobExecutionId,
- project_id: event.projectId,
- job_configuration_id: config.id,
- job_input_trace_id: event.traceId,
- status: sql`'PENDING'::"JobExecutionStatus"`,
- start_time: new Date(),
- })
- .execute();
+ projectId: event.projectId,
+ jobConfigurationId: config.id,
+ jobInputTraceId: event.traceId,
+ status: "PENDING",
+ startTime: new Date(),
+ },
+ });
// add the job to the next queue so that eval can be executed
evalQueue?.add(
@@ -153,7 +157,7 @@ export const createEvalJobs = async ({
} else {
// if we do not have a match, and execution exists, we mark the job as cancelled
// we do this, because a second trace event might 'deselect' a trace
- logger.debug(`Eval job for config ${config.id} did not match trace`);
+ logger.info(`Eval job for config ${config.id} did not match trace`);
if (existingJob.length > 0) {
logger.info(
`Cancelling eval job for config ${config.id} and trace ${event.traceId}`
@@ -275,6 +279,10 @@ export const evaluate = async ({
if (!parsedKey.success) {
// this will fail the eval execution if a user deletes the API key.
+ logger.error(
+ `API key for provider ${template.provider} and project ${event.projectId} not
+ found. Eval will fail. ${parsedKey.error}`
+ );
throw new LangfuseNotFoundError(
`API key for provider ${template.provider} and project ${event.projectId} not found.`
);
diff --git a/worker/src/features/health/index.ts b/worker/src/features/health/index.ts
index 13ce9af17b..a74f17c648 100644
--- a/worker/src/features/health/index.ts
+++ b/worker/src/features/health/index.ts
@@ -1,5 +1,5 @@
import { prisma } from "@langfuse/shared/src/db";
-import { redis } from "../../redis";
+import { redis } from "@langfuse/shared/src/server";
import { Response } from "express";
import logger from "../../logger";
diff --git a/worker/src/index.ts b/worker/src/index.ts
index 638ef39c45..b2bbd1c0cc 100644
--- a/worker/src/index.ts
+++ b/worker/src/index.ts
@@ -6,6 +6,7 @@ import logger from "./logger";
import { evalJobCreator, evalJobExecutor } from "./queues/evalQueue";
import { batchExportJobExecutor } from "./queues/batchExportQueue";
import { setSigtermReceived } from "./features/health";
+import { redis } from "@langfuse/shared/src/server";
const server = app.listen(env.PORT, () => {
logger.info(`Listening: http://localhost:${env.PORT}`);
@@ -26,6 +27,7 @@ async function onShutdown() {
evalJobExecutor?.close(),
batchExportJobExecutor?.close(),
]);
+ redis?.shutdown();
logger.info("Http server and Redis jobs have been closed.");
}
diff --git a/worker/src/queues/batchExportQueue.ts b/worker/src/queues/batchExportQueue.ts
index d2868dee2d..f99be3b615 100644
--- a/worker/src/queues/batchExportQueue.ts
+++ b/worker/src/queues/batchExportQueue.ts
@@ -11,7 +11,7 @@ import * as Sentry from "@sentry/node";
import { instrumentAsync } from "../instrumentation";
import logger from "../logger";
-import { redis } from "../redis";
+import { redis } from "@langfuse/shared/src/server";
import { handleBatchExportJob } from "../features/batchExport/handleBatchExportJob";
export const batchExportQueue = redis
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index ed88897ed7..78448e3044 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -9,7 +9,7 @@ import { evaluate, createEvalJobs } from "../features/evaluation/eval-service";
import { kyselyPrisma } from "@langfuse/shared/src/db";
import logger from "../logger";
import { sql } from "kysely";
-import { redis } from "../redis";
+import { redis } from "@langfuse/shared/src/server";
import { instrumentAsync } from "../instrumentation";
import * as Sentry from "@sentry/node";
diff --git a/worker/src/queues/repeatQueue.ts b/worker/src/queues/repeatQueue.ts
index 33d2b83884..e3e3fd2cbb 100644
--- a/worker/src/queues/repeatQueue.ts
+++ b/worker/src/queues/repeatQueue.ts
@@ -1,6 +1,6 @@
import { Queue, Worker } from "bullmq";
-import { redis } from "../redis";
+import { redis } from "@langfuse/shared/src/server";
import { enqueueBatchExportJobs } from "../features/batchExport/enqueueBatchExportJobs";
import { QueueJobs, QueueName } from "@langfuse/shared";