Skip to content

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

perf: optionally move ingestion pipeline into worker (#2936)

Max Deichmann8ec44d7fdbee
diff --git a/.env.dev.example b/.env.dev.example
index deff9fefc7..10f0dab1ed 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -51,4 +51,3 @@ REDIS_AUTH="myredissecret"
LANGFUSE_WORKER_PASSWORD=mybasicauthsecret
# openssl rand -hex 32 used only here
ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
-
diff --git a/.env.prod.example b/.env.prod.example
index 2efa287136..6ac3f70d32 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -97,9 +97,6 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000
# The page size can be adjusted if needed to optimize performance
# DB_EXPORT_PAGE_SIZE=1000
-# Disable logging to `events` table in db
-# ENABLE_EVENT_LOG=false
-
### START Enterprise Edition Configuration
@@ -197,5 +194,7 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000
# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=
# LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS=
# LANGFUSE_LOG_LEVEL=
+# LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY=
+# LANGFUSE_ASYNC_INGESTION_PROCESSING="true"
## END Langfuse V3 Ingestion
\ No newline at end of file
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 82456d2782..a7dc880909 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -94,7 +94,7 @@ jobs:
- name: Load default env
run: |
cp .env.dev.example .env
- grep -v '^REDIS_HOST=' .env.dev.example > web/.env
+ grep -v -e '^REDIS_HOST=' .env.dev.example > .env
- name: Run + migrate
run: |
@@ -219,10 +219,62 @@ jobs:
- name: Run e2e tests
run: pnpm --filter=web run test:e2e
+ e2e-server-tests:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - uses: pnpm/action-setup@v3
+ with:
+ version: 9.5.0
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 20
+ cache: "pnpm"
+ cache-dependency-path: "pnpm-lock.yaml"
+
+ - name: install dependencies
+ run: |
+ pnpm install
+
+ - name: Load default env
+ run: |
+ cp .env.dev.example .env
+ echo "LANGFUSE_ASYNC_INGESTION_PROCESSING=true" >> .env
+ echo "LANGFUSE_CACHE_API_KEY_ENABLED=true" >> .env
+ echo "LANGFUSE_CACHE_PROMPT_ENABLED=true" >> .env
+
+ - name: Run + migrate
+ run: |
+ docker compose -f docker-compose.dev.yml up -d
+ docker compose ps
+ sleep 5 # Wait for PostgreSQL to accept connections
+
+ - name: Seed DB
+ run: |
+ pnpm run db:migrate
+ pnpm run db:seed:examples
+
+ - name: Build
+ run: pnpm run build
+
+ - name: Run server
+ run: (pnpm run start&)
+
+ - name: Run e2e tests
+ run: pnpm --filter=web run test:e2e:server
+
all-ci-passed:
# This allows us to have a branch protection rule for tests and deploys with matrix
runs-on: ubuntu-latest
- needs: [lint, tests-web, tests-worker, e2e-tests, test-docker-build]
+ needs:
+ [
+ lint,
+ tests-web,
+ tests-worker,
+ e2e-tests,
+ test-docker-build,
+ e2e-server-tests,
+ ]
if: always()
steps:
- name: Successful deploy
diff --git a/.github/workflows/porter_stack_worker_staging.yml b/.github/workflows/porter_stack_worker_staging.yml
index 9917467ace..ff1eaf69b5 100644
--- a/.github/workflows/porter_stack_worker_staging.yml
+++ b/.github/workflows/porter_stack_worker_staging.yml
@@ -1,7 +1,7 @@
"on":
push:
branches:
- - main
+ - staging
name: Deploy to worker (staging)
jobs:
porter-deploy:
diff --git a/packages/shared/package.json b/packages/shared/package.json
index ba77f51dfa..01afb5b7de 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -63,8 +63,9 @@
"@types/bcryptjs": "^2.4.6",
"bcryptjs": "^2.4.3",
"bullmq": "^5.4.2",
+ "decimal.js": "^10.4.3",
+ "exponential-backoff": "^3.1.1",
"ioredis": "^5.4.1",
- "js-tiktoken": "^1.0.12",
"kysely": "^0.27.3",
"langchain": "^0.2.6",
"lodash": "^4.17.21",
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index cad90e97b2..09f0502880 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -33,6 +33,10 @@ const EnvSchema = z.object({
.nonnegative()
.default(10000),
LANGFUSE_INGESTION_FLUSH_ATTEMPTS: z.coerce.number().positive().default(3),
+ LANGFUSE_INGESTION_BUFFER_TTL_SECONDS: z.coerce
+ .number()
+ .positive()
+ .default(60 * 10),
});
export const env = EnvSchema.parse(process.env);
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index ea0b2792f5..1f785c8c11 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,6 +1,5 @@
export * from "./constants";
export * from "./queries";
-export * from "./queues";
export * from "./interfaces/filters";
export * from "./interfaces/orderBy";
export * from "./tableDefinitions";
@@ -8,7 +7,7 @@ export * from "./types";
export * from "./filterToPrisma";
export * from "./orderByToPrisma";
export * from "./tracesTable";
-export * from "./server/auth";
+export * from "./server/auth/auth";
export * from "./observationsTable";
export * from "./utils/zod";
export * from "./utils/json";
diff --git a/packages/shared/src/server/auth.ts b/packages/shared/src/server/auth/auth.ts
similarity index 100%
rename from packages/shared/src/server/auth.ts
rename to packages/shared/src/server/auth/auth.ts
diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.ts
new file mode 100644
index 0000000000..2aa8cb5d66
--- /dev/null
+++ b/packages/shared/src/server/auth/types.ts
@@ -0,0 +1,16 @@
+export type AuthHeaderVerificationResult =
+ | AuthHeaderValidVerificationResult
+ | {
+ validKey: false;
+ error: string;
+ };
+
+export type AuthHeaderValidVerificationResult = {
+ validKey: true;
+ scope: ApiAccessScope;
+};
+
+export type ApiAccessScope = {
+ projectId: string;
+ accessLevel: "all" | "scores";
+};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 19e464749e..dafc2583db 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -3,7 +3,7 @@ export * from "./services/email/organizationInvitation/sendMembershipInvitationE
export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";
export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";
export * from "./services/PromptService";
-export * from "./auth";
+export * from "./auth/auth";
export * from "./llm/fetchLLMCompletion";
export * from "./llm/types";
export * from "./utils/DatabaseReadStream";
@@ -19,4 +19,8 @@ export * from "./redis/redis";
export * from "./redis/trace-upsert";
export * from "./redis/batch-export";
export * from "./redis/ingestionFlushQueue";
-export * from "./clickhouse";
+export * from "./redis/legacy-ingestion";
+export * from "./auth/types";
+export * from "./ingestion/legacy/index";
+export * from "./queues";
+export * from "./ingestion/legacy/EventProcessor";
diff --git a/web/src/server/api/services/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
similarity index 86%
rename from web/src/server/api/services/EventProcessor.ts
rename to packages/shared/src/server/ingestion/legacy/EventProcessor.ts
index ec93b4cf7f..e3e26d6413 100644
--- a/web/src/server/api/services/EventProcessor.ts
+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
@@ -1,48 +1,53 @@
-import { tokenCount } from "@/src/features/ingest/usage";
-import { type ApiAccessScope } from "@/src/features/public-api/server/types";
-import {
- type legacyObservationCreateEvent,
- eventTypes,
- type scoreEvent,
- type generationCreateEvent,
- type sdkLogEvent,
- type traceEvent,
- validateAndInflateScore,
-} from "@langfuse/shared/src/server";
-import { prisma } from "@langfuse/shared/src/db";
-import { type ObservationEvent, findModel } from "@langfuse/shared/src/server";
-import { ResourceNotFoundError } from "@/src/utils/exceptions";
-import { mergeJson } from "@langfuse/shared";
-import {
- type Trace,
- type Observation,
- type Score,
- type Prisma,
- type Model,
-} from "@langfuse/shared/src/db";
import { v4 } from "uuid";
import { type z } from "zod";
-import { jsonSchema } from "@langfuse/shared";
-import { ForbiddenError } from "@langfuse/shared";
-import { instrument } from "@/src/utils/instrumentation";
import Decimal from "decimal.js";
+import { findModel } from "../model-match";
+import {
+ ObservationEvent,
+ eventTypes,
+ legacyObservationCreateEvent,
+ generationCreateEvent,
+ traceEvent,
+ scoreEvent,
+ sdkLogEvent,
+} from "../types";
+import { validateAndInflateScore } from "../validateAndInflateScore";
+import { ApiAccessScope } from "../../auth/types";
+import { Trace, Observation, Score, Prisma, Model } from "@prisma/client";
+import { ForbiddenError, LangfuseNotFoundError } from "../../../errors";
+import { mergeJson } from "../../../utils/json";
+import { jsonSchema } from "../../../utils/zod";
+import { prisma } from "../../../db";
export interface EventProcessor {
+ auth(apiScope: ApiAccessScope): void;
+
process(
- apiScope: ApiAccessScope,
+ apiScope: ApiAccessScope
): Promise<Trace | Observation | Score> | undefined;
}
export class ObservationProcessor implements EventProcessor {
event: ObservationEvent;
-
- constructor(event: ObservationEvent) {
+ calculateTokenDelegate: (p: {
+ model: Model;
+ text: unknown;
+ }) => number | undefined;
+
+ constructor(
+ event: ObservationEvent,
+ calculateTokenDelegate: (p: {
+ model: Model;
+ text: unknown;
+ }) => number | undefined
+ ) {
this.event = event;
+ this.calculateTokenDelegate = calculateTokenDelegate;
}
async convertToObservation(
apiScope: ApiAccessScope,
- existingObservation: Observation | null,
+ existingObservation: Observation | null
): Promise<{
id: string;
create: Prisma.ObservationUncheckedCreateInput;
@@ -71,7 +76,9 @@ export class ObservationProcessor implements EventProcessor {
this.event.type === eventTypes.OBSERVATION_UPDATE &&
!existingObservation
) {
- throw new ResourceNotFoundError(this.event.id, "Observation not found");
+ throw new LangfuseNotFoundError(
+ `Observation with id ${this.event.id} not found`
+ );
}
// find matching model definition based on event and existing observation in db
@@ -114,8 +121,9 @@ export class ObservationProcessor implements EventProcessor {
"usage" in this.event.body
? this.calculateTokenCounts(
this.event.body,
+ this.calculateTokenDelegate,
internalModel ?? undefined,
- existingObservation ?? undefined,
+ existingObservation ?? undefined
)
: [undefined, undefined];
@@ -151,7 +159,7 @@ export class ObservationProcessor implements EventProcessor {
const calculatedCosts = ObservationProcessor.calculateTokenCosts(
internalModel,
userProvidedTokenCosts,
- tokenCounts,
+ tokenCounts
);
// merge metadata from existingObservation.metadata and metadata
@@ -159,7 +167,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation?.metadata
? jsonSchema.parse(existingObservation.metadata)
: undefined,
- this.event.body.metadata ?? undefined,
+ this.event.body.metadata ?? undefined
);
const prompt =
@@ -305,34 +313,34 @@ export class ObservationProcessor implements EventProcessor {
body:
| z.infer<typeof legacyObservationCreateEvent>["body"]
| z.infer<typeof generationCreateEvent>["body"],
+ calculateTokenDelegate: (p: {
+ model: Model;
+ text: unknown;
+ }) => number | undefined,
model?: Model,
- existingObservation?: Observation,
+ existingObservation?: Observation
) {
- return instrument({ name: "calculate-tokens" }, () => {
- const newPromptTokens =
- body.usage?.input ??
- ((body.input || existingObservation?.input) &&
- model &&
- model.tokenizerId
- ? tokenCount({
- model: model,
- text: body.input ?? existingObservation?.input,
- })
- : undefined);
-
- const newCompletionTokens =
- body.usage?.output ??
- ((body.output || existingObservation?.output) &&
- model &&
- model.tokenizerId
- ? tokenCount({
- model: model,
- text: body.output ?? existingObservation?.output,
- })
- : undefined);
+ const newPromptTokens =
+ body.usage?.input ??
+ ((body.input || existingObservation?.input) && model && model.tokenizerId
+ ? calculateTokenDelegate({
+ model: model,
+ text: body.input ?? existingObservation?.input,
+ })
+ : undefined);
+
+ const newCompletionTokens =
+ body.usage?.output ??
+ ((body.output || existingObservation?.output) &&
+ model &&
+ model.tokenizerId
+ ? calculateTokenDelegate({
+ model: model,
+ text: body.output ?? existingObservation?.output,
+ })
+ : undefined);
- return [newPromptTokens, newCompletionTokens];
- });
+ return [newPromptTokens, newCompletionTokens];
}
static calculateTokenCosts(
@@ -342,7 +350,7 @@ export class ObservationProcessor implements EventProcessor {
outputCost?: Decimal | null;
totalCost?: Decimal | null;
},
- tokenCounts: { input?: number; output?: number; total?: number },
+ tokenCounts: { input?: number; output?: number; total?: number }
): {
inputCost?: Decimal | null;
outputCost?: Decimal | null;
@@ -359,7 +367,7 @@ export class ObservationProcessor implements EventProcessor {
totalCost:
userProvidedCosts.totalCost ??
(userProvidedCosts.inputCost ?? new Decimal(0)).add(
- userProvidedCosts.outputCost ?? new Decimal(0),
+ userProvidedCosts.outputCost ?? new Decimal(0)
),
};
}
@@ -390,9 +398,13 @@ export class ObservationProcessor implements EventProcessor {
};
}
- async process(apiScope: ApiAccessScope): Promise<Observation> {
+ auth(apiScope: ApiAccessScope): void {
if (apiScope.accessLevel !== "all")
throw new ForbiddenError("Access denied for observation creation");
+ }
+
+ async process(apiScope: ApiAccessScope): Promise<Observation> {
+ this.auth(apiScope);
const existingObservation = this.event.body.id
? await prisma.observation.findFirst({
@@ -405,7 +417,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation.projectId !== apiScope.projectId
) {
throw new ForbiddenError(
- `Access denied for observation creation ${existingObservation.projectId} `,
+ `Access denied for observation creation ${existingObservation.projectId} `
);
}
@@ -429,15 +441,17 @@ export class TraceProcessor implements EventProcessor {
this.event = event;
}
+ auth(apiScope: ApiAccessScope): void {
+ if (apiScope.accessLevel !== "all")
+ throw new ForbiddenError("Access denied for trace creation");
+ }
+
async process(
- apiScope: ApiAccessScope,
+ apiScope: ApiAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
- if (apiScope.accessLevel !== "all")
- throw new ForbiddenError(
- `Access denied for trace creation, ${apiScope.accessLevel}`,
- );
+ this.auth(apiScope);
const internalId = body.id ?? v4();
@@ -445,7 +459,7 @@ export class TraceProcessor implements EventProcessor {
"Trying to create trace, project ",
apiScope.projectId,
", id:",
- internalId,
+ internalId
);
const existingTrace = await prisma.trace.findFirst({
@@ -456,7 +470,7 @@ export class TraceProcessor implements EventProcessor {
if (existingTrace && existingTrace.projectId !== apiScope.projectId) {
throw new ForbiddenError(
- `Access denied for trace creation ${existingTrace.projectId}`,
+ `Access denied for trace creation ${existingTrace.projectId}`
);
}
@@ -464,7 +478,7 @@ export class TraceProcessor implements EventProcessor {
existingTrace?.metadata
? jsonSchema.parse(existingTrace.metadata)
: undefined,
- body.metadata ?? undefined,
+ body.metadata ?? undefined
);
const mergedTags =
@@ -539,15 +553,19 @@ export class ScoreProcessor implements EventProcessor {
this.event = event;
}
+ auth(apiScope: ApiAccessScope) {
+ if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")
+ throw new ForbiddenError(
+ `Access denied for score creation, ${apiScope.accessLevel}`
+ );
+ }
+
async process(
- apiScope: ApiAccessScope,
+ apiScope: ApiAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
- if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")
- throw new ForbiddenError(
- `Access denied for score creation, ${apiScope.accessLevel}`,
- );
+ this.auth(apiScope);
const id = body.id ?? v4();
@@ -561,7 +579,7 @@ export class ScoreProcessor implements EventProcessor {
});
if (existingScore && existingScore.projectId !== apiScope.projectId) {
throw new ForbiddenError(
- `Access denied for score creation ${existingScore.projectId}`,
+ `Access denied for score creation ${existingScore.projectId}`
);
}
@@ -595,6 +613,10 @@ export class SdkLogProcessor implements EventProcessor {
this.event = event;
}
+ auth(apiScope: ApiAccessScope) {
+ return;
+ }
+
process() {
try {
console.log("SDK Log", this.event);
diff --git a/web/src/features/ingest/enqueueIngestionEvents.ts b/packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.ts
similarity index 80%
rename from web/src/features/ingest/enqueueIngestionEvents.ts
rename to packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.ts
index 73cc6ef11e..7d9d1d1103 100644
--- a/web/src/features/ingest/enqueueIngestionEvents.ts
+++ b/packages/shared/src/server/ingestion/legacy/enqueueIngestionEvents.ts
@@ -1,17 +1,17 @@
-import { env } from "@/src/env.mjs";
-import { QueueJobs } from "@langfuse/shared";
+import { type Redis } from "ioredis";
+import { QueueJobs } from "../../queues";
import {
- type IngestionEventType,
getIngestionFlushQueue,
- redis,
- IngestionUtils,
- type IngestionFlushQueue,
-} from "@langfuse/shared/src/server";
-import { type Redis } from "ioredis";
+ IngestionFlushQueue,
+} from "../../redis/ingestionFlushQueue";
+import { IngestionUtils } from "../IngestionUtils";
+import { IngestionEventType } from "../types";
+import { redis } from "../../redis/redis";
+import { env } from "../../../env";
export async function enqueueIngestionEvents(
projectId: string,
- events: IngestionEventType[],
+ events: IngestionEventType[]
) {
const ingestionFlushQueue = getIngestionFlushQueue();
@@ -31,8 +31,8 @@ export async function enqueueIngestionEvents(
event,
redis,
ingestionFlushQueue,
- batchTimestamp,
- ),
+ batchTimestamp
+ )
);
}
@@ -44,11 +44,11 @@ async function enqueueSingleIngestionEvent(
event: IngestionEventType,
redis: Redis,
ingestionFlushQueue: IngestionFlushQueue,
- batchTimestamp: string,
+ batchTimestamp: string
): Promise<void> {
if (!("id" in event.body && event.body.id)) {
console.warn(
- `Received ingestion event without id: ${JSON.stringify(event)}`,
+ `Received ingestion event without id: ${JSON.stringify(event)}`
);
return;
diff --git a/packages/shared/src/server/ingestion/legacy/index.ts b/packages/shared/src/server/ingestion/legacy/index.ts
new file mode 100644
index 0000000000..7a43014575
--- /dev/null
+++ b/packages/shared/src/server/ingestion/legacy/index.ts
@@ -0,0 +1,252 @@
+import { env } from "node:process";
+import z from "zod";
+import { ForbiddenError, UnauthorizedError } from "../../../errors";
+import { eventTypes, ingestionApiSchema, ingestionEvent } from "../types";
+import {
+ EventProcessor,
+ TraceProcessor,
+ ObservationProcessor,
+ ScoreProcessor,
+ SdkLogProcessor,
+} from "./EventProcessor";
+import { EventBodyType, EventName, TraceUpsertEventType } from "../../queues";
+import {
+ convertTraceUpsertEventsToRedisEvents,
+ getTraceUpsertQueue,
+} from "../../redis/trace-upsert";
+import { ApiAccessScope, AuthHeaderVerificationResult } from "../../auth/types";
+import { redis } from "../../redis/redis";
+import { backOff } from "exponential-backoff";
+import { Model } from "../../..";
+import { enqueueIngestionEvents } from "./enqueueIngestionEvents";
+
+export type BatchResult = {
+ result: unknown;
+ id: string;
+ type: string;
+};
+
+type TokenCountInput = {
+ model: Model;
+ text: unknown;
+};
+
+export const handleBatch = async (
+ events: z.infer<typeof ingestionApiSchema>["batch"],
+ authCheck: AuthHeaderVerificationResult,
+ calculateTokenDelegate: (p: TokenCountInput) => number | undefined
+) => {
+ console.log(`handling ingestion ${events.length} events`);
+
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
+
+ const results: BatchResult[] = []; // Array to store the results
+
+ const errors: {
+ error: unknown;
+ id: string;
+ type: string;
+ }[] = []; // Array to store the errors
+
+ for (const singleEvent of events) {
+ try {
+ const result = await retry(async () => {
+ return await handleSingleEvent(
+ singleEvent,
+ authCheck.scope,
+ calculateTokenDelegate
+ );
+ });
+ results.push({
+ result: result,
+ id: singleEvent.id,
+ type: singleEvent.type,
+ }); // Push each result into the array
+ } catch (error) {
+ // Handle or log the error if `handleSingleEvent` fails
+ console.error("Error handling event:", error);
+ // Decide how to handle the error: rethrow, continue, or push an error object to results
+ // For example, push an error object:
+ errors.push({
+ error: error,
+ id: singleEvent.id,
+ type: singleEvent.type,
+ });
+ }
+ }
+
+ if (env.CLICKHOUSE_URL) {
+ 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 };
+};
+
+async function retry<T>(request: () => Promise<T>): Promise<T> {
+ return await backOff(request, {
+ numOfAttempts: env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" ? 5 : 3,
+ retry: (e: Error, attemptNumber: number) => {
+ if (e instanceof UnauthorizedError || e instanceof ForbiddenError) {
+ console.log("not retrying auth error");
+ return false;
+ }
+ console.log(`retrying processing events ${attemptNumber}`);
+ return true;
+ },
+ });
+}
+
+const handleSingleEvent = async (
+ event: z.infer<typeof ingestionEvent>,
+ apiScope: ApiAccessScope,
+ calculateTokenDelegate: (p: {
+ model: Model;
+ text: unknown;
+ }) => number | undefined
+) => {
+ const { body } = event;
+ let restEvent = body;
+ if ("input" in body) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { input, ...rest } = body;
+ restEvent = rest;
+ }
+ if ("output" in restEvent) {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { output, ...rest } = restEvent;
+ restEvent = rest;
+ }
+
+ console.log(
+ `handling single event ${event.id} of type ${event.type}: ${JSON.stringify({ body: restEvent })}`
+ );
+
+ const cleanedEvent = ingestionEvent.parse(cleanEvent(event));
+
+ const { type } = cleanedEvent;
+
+ let processor: EventProcessor;
+ switch (type) {
+ case eventTypes.TRACE_CREATE:
+ processor = new TraceProcessor(cleanedEvent);
+ break;
+ 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:
+ processor = new ObservationProcessor(
+ cleanedEvent,
+ calculateTokenDelegate
+ );
+ break;
+ case eventTypes.SCORE_CREATE: {
+ processor = new ScoreProcessor(cleanedEvent);
+ break;
+ }
+ case eventTypes.SDK_LOG:
+ processor = new SdkLogProcessor(cleanedEvent);
+ }
+
+ // Deny access to non-score events if the access level is not "all"
+ // This is an additional safeguard to auth checks in EventProcessor
+ if (apiScope.accessLevel !== "all" && type !== eventTypes.SCORE_CREATE) {
+ throw new ForbiddenError("Access denied. Event type not allowed.");
+ }
+
+ return await processor.process(apiScope);
+};
+
+// cleans NULL characters from the event
+export function cleanEvent(obj: unknown): unknown {
+ if (typeof obj === "string") {
+ return obj.replace(/\u0000/g, "");
+ } else if (typeof obj === "object" && obj !== null) {
+ if (Array.isArray(obj)) {
+ return obj.map(cleanEvent);
+ } else {
+ // Here we assert that obj is a Record<string, unknown>
+ const objAsRecord = obj as Record<string, unknown>;
+ const newObj: Record<string, unknown> = {};
+ for (const key in objAsRecord) {
+ newObj[key] = cleanEvent(objAsRecord[key]);
+ }
+ return newObj;
+ }
+ } else {
+ return obj;
+ }
+}
+
+export const isNotNullOrUndefined = <T>(
+ val?: T | null
+): val is Exclude<T, null | undefined> => !isUndefinedOrNull(val);
+
+export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>
+ val === undefined || val === null;
+
+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.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && redis) {
+ console.log(`Sending ${traceEvents.length} events to worker via Redis`);
+
+ const queue = getTraceUpsertQueue();
+ if (!queue) {
+ console.error("TraceUpsertQueue not initialized");
+ return;
+ }
+
+ await queue.addBulk(convertTraceUpsertEventsToRedisEvents(traceEvents));
+ } else if (
+ env.LANGFUSE_WORKER_HOST &&
+ env.LANGFUSE_WORKER_PASSWORD &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ) {
+ console.log(`Sending ${traceEvents.length} events to worker via HTTP`);
+ const body: EventBodyType = {
+ name: EventName.TraceUpsert,
+ payload: traceEvents,
+ };
+
+ if (traceEvents.length > 0) {
+ await fetch(`${env.LANGFUSE_WORKER_HOST}/api/events`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization:
+ "Basic " +
+ Buffer.from(
+ "admin" + ":" + env.LANGFUSE_WORKER_PASSWORD
+ ).toString("base64"),
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(8 * 1000),
+ });
+ }
+ }
+ } catch (error) {
+ console.error("Error sending events to worker", error);
+ }
+};
diff --git a/packages/shared/src/queues.ts b/packages/shared/src/server/queues.ts
similarity index 76%
rename from packages/shared/src/queues.ts
rename to packages/shared/src/server/queues.ts
index 56171db195..1d43a52bda 100644
--- a/packages/shared/src/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -1,11 +1,24 @@
import { z } from "zod";
+import { ingestionBatchEvent } from ".";
export enum EventName {
TraceUpsert = "TraceUpsert",
BatchExport = "BatchExport",
EvaluationExecution = "EvaluationExecution",
+ LegacyIngestion = "LegacyIngestion",
}
+export const LegacyIngestionEvent = z.object({
+ data: ingestionBatchEvent,
+ authCheck: z.object({
+ validKey: z.literal(true),
+ scope: z.object({
+ projectId: z.string(),
+ accessLevel: z.enum(["all", "scores"]),
+ }),
+ }),
+});
+
export const BatchExportJobSchema = z.object({
projectId: z.string(),
batchExportId: z.string(),
@@ -22,6 +35,7 @@ export const EvalExecutionEvent = z.object({
export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;
export type TraceUpsertEventType = z.infer<typeof TraceUpsertEventSchema>;
export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;
+export type LegacyIngestionEventType = z.infer<typeof LegacyIngestionEvent>;
export const EventBodySchema = z.union([
z.object({
@@ -45,6 +59,7 @@ export enum QueueName {
BatchExport = "batch-export-queue",
RepeatQueue = "repeat-queue",
IngestionFlushQueue = "ingestion-flush-queue",
+ LegacyIngestionQueue = "legacy-ingestion-queue",
}
export enum QueueJobs {
@@ -53,6 +68,7 @@ export enum QueueJobs {
BatchExportJob = "batch-export-job",
EnqueueBatchExportJobs = "enqueue-batch-export-jobs",
FlushIngestionEntity = "flush-ingestion-entity",
+ LegacyIngestionJob = "legacy-ingestion-job",
}
export type TQueueJobTypes = {
@@ -74,4 +90,10 @@ export type TQueueJobTypes = {
payload: BatchExportJobType;
name: QueueJobs.BatchExportJob;
};
+ [QueueName.LegacyIngestionQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: LegacyIngestionEventType;
+ name: QueueJobs.LegacyIngestionJob;
+ };
};
diff --git a/packages/shared/src/server/redis/batch-export.ts b/packages/shared/src/server/redis/batch-export.ts
index 78cff6c0e9..31cb77fb2e 100644
--- a/packages/shared/src/server/redis/batch-export.ts
+++ b/packages/shared/src/server/redis/batch-export.ts
@@ -1,5 +1,5 @@
import { Queue } from "bullmq";
-import { QueueName, TQueueJobTypes } from "../../queues";
+import { QueueName, TQueueJobTypes } from "../queues";
import { redis } from "./redis";
let batchExportQueue: Queue<TQueueJobTypes[QueueName.BatchExport]> | null =
diff --git a/packages/shared/src/server/redis/ingestionFlushQueue.ts b/packages/shared/src/server/redis/ingestionFlushQueue.ts
index f36349a9c4..567f7ca291 100644
--- a/packages/shared/src/server/redis/ingestionFlushQueue.ts
+++ b/packages/shared/src/server/redis/ingestionFlushQueue.ts
@@ -1,8 +1,8 @@
import { Queue } from "bullmq";
import { env } from "../../env";
-import { QueueName } from "../../queues";
import { redis } from "../redis/redis";
+import { QueueName } from "../queues";
export type IngestionFlushQueue = Queue<null>;
diff --git a/packages/shared/src/server/redis/legacy-ingestion.ts b/packages/shared/src/server/redis/legacy-ingestion.ts
new file mode 100644
index 0000000000..90c1de15f1
--- /dev/null
+++ b/packages/shared/src/server/redis/legacy-ingestion.ts
@@ -0,0 +1,27 @@
+import { Queue } from "bullmq";
+import { QueueName, TQueueJobTypes } from "../queues";
+import { redis } from "./redis";
+
+let legacyIngestionQueue: Queue<
+ TQueueJobTypes[QueueName.LegacyIngestionQueue]
+> | null = null;
+
+export const getLegacyIngestionQueue = () => {
+ if (legacyIngestionQueue) return legacyIngestionQueue;
+
+ legacyIngestionQueue = redis
+ ? new Queue<TQueueJobTypes[QueueName.LegacyIngestionQueue]>(
+ QueueName.LegacyIngestionQueue,
+ {
+ connection: redis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ },
+ }
+ )
+ : null;
+
+ return legacyIngestionQueue;
+};
diff --git a/packages/shared/src/server/redis/trace-upsert.ts b/packages/shared/src/server/redis/trace-upsert.ts
index 8d3a6ebd44..b3ec2cf8fa 100644
--- a/packages/shared/src/server/redis/trace-upsert.ts
+++ b/packages/shared/src/server/redis/trace-upsert.ts
@@ -4,7 +4,7 @@ import {
QueueName,
TQueueJobTypes,
TraceUpsertEventType,
-} from "../../queues";
+} from "../queues";
import { Queue } from "bullmq";
import { redis } from "./redis";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 01305dfa9d..bb051a1ad9 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
@@ -158,12 +158,15 @@ importers:
bullmq:
specifier: ^5.4.2
version: 5.4.3
+ decimal.js:
+ specifier: ^10.4.3
+ version: 10.4.3
+ exponential-backoff:
+ specifier: ^3.1.1
+ version: 3.1.1
ioredis:
specifier: ^5.4.1
version: 5.4.1
- js-tiktoken:
- specifier: ^1.0.12
- version: 1.0.12
kysely:
specifier: ^0.27.3
version: 0.27.3
@@ -175,7 +178,7 @@ importers:
version: 4.17.21
next-auth:
specifier: ^4.24.7
nodemailer:
specifier: ^6.9.13
version: 6.9.13
@@ -459,9 +462,6 @@ importers:
dompurify:
specifier: ^3.1.5
version: 3.1.5
- exponential-backoff:
- specifier: ^3.1.1
- version: 3.1.1
graphql:
specifier: ^16.9.0
version: 16.9.0
@@ -491,7 +491,7 @@ importers:
next-auth:
specifier: ^4.24.7
next-query-params:
specifier: ^5.0.0
@@ -674,6 +674,9 @@ importers:
typescript:
specifier: ^5.4.5
version: 5.4.5
+ wait-for-expect:
+ specifier: ^3.0.2
+ version: 3.0.2
worker:
dependencies:
@@ -10379,6 +10382,9 @@ packages:
resolution: {integrity: sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==}
engines: {node: '>=14'}
+ resolution: {integrity: sha512-cfS1+DZxuav1aBYbaO/kE06EOS8yRw7qOFoD3XtjTkYvCvh3zUvNST8DXK/nPaeqIzIv3P3kL3lRJn8iwOiSag==}
+
resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==}
@@ -12717,7 +12723,7 @@ snapshots:
dependencies:
'@prisma/client': 5.16.2([email protected])
'@next/[email protected]': {}
@@ -15470,7 +15476,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])
@@ -17160,7 +17166,7 @@ snapshots:
eslint: 8.57.0
eslint-plugin-turbo: 1.13.4([email protected])
dependencies:
@@ -20039,7 +20045,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
dependencies:
'@babel/runtime': 7.24.5
'@panva/hkdf': 1.1.1
@@ -22678,6 +22684,8 @@ snapshots:
dependencies:
xml-name-validator: 4.0.0
+
dependencies:
makeerror: 1.0.12
diff --git a/web/package.json b/web/package.json
index 0b35f9a4db..28c4e70a74 100644
--- a/web/package.json
+++ b/web/package.json
@@ -14,9 +14,10 @@
"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 --detectOpenHandles --verbose",
+ "test": "dotenv -e ../.env -- jest --runInBand --detectOpenHandles --verbose --testPathIgnorePatterns='__e2e__'",
"test:watch": "dotenv -e ../.env -- jest --watch --runInBand",
"test:e2e": "dotenv -e ../.env -- playwright test",
+ "test:e2e:server": "dotenv -e ../.env -- jest --runInBand --detectOpenHandles --verbose --testPathPattern='__e2e__'",
"models:migrate": "dotenv -e ../.env -- tsx scripts/model-match.ts",
"generationCost:backfill": "dotenv -e ../.env -- tsx scripts/observations-backfill-calculated-cost.ts"
},
@@ -86,7 +87,6 @@
"date-fns": "^3.3.1",
"decimal.js": "^10.4.3",
"dompurify": "^3.1.5",
- "exponential-backoff": "^3.1.1",
"graphql": "^16.9.0",
"ioredis": "^5.4.1",
"ip-address": "^9.0.5",
@@ -157,7 +157,8 @@
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.7.2",
- "typescript": "^5.4.5"
+ "typescript": "^5.4.5",
+ "wait-for-expect": "^3.0.2"
},
"ct3aMetadata": {
"initVersion": "7.13.0"
diff --git a/web/scripts/model-match.ts b/web/scripts/model-match.ts
index e527e4bb4d..1a11987dcb 100644
--- a/web/scripts/model-match.ts
+++ b/web/scripts/model-match.ts
@@ -8,8 +8,8 @@ import "dotenv/config";
import { findModel } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import lodash from "lodash";
-import { tokenCount } from "@/src/features/ingest/usage";
import { type Prisma } from "@langfuse/shared/src/db";
+import { tokenCount } from "@/src/features/ingest/usage";
async function main() {
return await modelMatch();
diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.ts
new file mode 100644
index 0000000000..ea748d5f88
--- /dev/null
+++ b/web/src/__e2e__/api.servertest.ts
@@ -0,0 +1,203 @@
+import { v4 } from "uuid";
+import { JobExecutionStatus, prisma } from "@langfuse/shared/src/db";
+import { redis } from "@langfuse/shared/src/server";
+import waitForExpect from "wait-for-expect";
+import { ApiKeyZod } from "@/src/features/public-api/server/apiAuth";
+
+const generateAuth = (username: string, password: string) => {
+ const auth = Buffer.from(`${username}:${password}`).toString("base64");
+ return `Basic ${auth}`;
+};
+
+const workerAdminAuth = generateAuth("admin", "myworkerpassword");
+
+const userApiKeyAuth = generateAuth("pk-lf-1234567890", "sk-lf-1234567890");
+
+describe("Health endpoints", () => {
+ it("web container returns healthy", async () => {
+ // Arrange
+ const url = "http://localhost:3000/api/public/health";
+
+ // Act
+ const response = await fetch(url);
+ expect(response.status).toBe(200);
+ });
+
+ it("worker container returns healthy", async () => {
+ // Arrange
+ const url = "http://localhost:3030/api/health";
+
+ // Act
+ const response = await fetch(url, {
+ headers: {
+ Authorization: workerAdminAuth,
+ },
+ });
+ expect(response.status).toBe(200);
+ });
+});
+
+describe("Ingestion Pipeline", () => {
+ it("ingest a trace", async () => {
+ const traceId = v4();
+ const spanId = v4();
+
+ const event = {
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ name: "test trace",
+ id: traceId,
+ userId: "user-1", // triggers the eval
+ },
+ },
+ {
+ id: v4(),
+ type: "span-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: spanId,
+ traceId: traceId,
+ name: "test span",
+ },
+ },
+ ],
+ };
+ // Arrange
+ const url = "http://localhost:3000/api/public/ingestion";
+
+ // Act
+ const response = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: userApiKeyAuth,
+ },
+ body: JSON.stringify(event),
+ });
+
+ await waitForExpect(async () => {
+ // we need a second call to the public API with the API key, so that it is stored in redis
+ // first call (ingestion above) generates the new, fast API hash
+ // second call (below) stores the API key in redis
+ const traceUrl = `http://localhost:3000/api/public/traces/${traceId}`;
+
+ const traceResponse = await fetch(traceUrl, {
+ headers: {
+ Authorization: userApiKeyAuth,
+ },
+ });
+
+ expect(traceResponse.status).toBe(200);
+ expect(traceResponse.body).not.toBeNull();
+ expect((await traceResponse.json()).id).toBe(traceId);
+
+ const trace = await prisma.trace.findUnique({
+ where: {
+ id: traceId,
+ },
+ });
+ expect(trace).not.toBeNull();
+ expect(trace?.name).toBe("test trace");
+
+ const observation = await prisma.observation.findUnique({
+ where: {
+ id: spanId,
+ traceId: traceId,
+ },
+ });
+ expect(observation).not.toBeNull();
+ expect(observation?.name).toBe("test span");
+
+ expect(redis).not.toBeNull();
+
+ const redisKeys = await redis?.keys(`api-key:*`);
+ expect(redisKeys?.length).toBe(1);
+ const redisValue = await redis?.get(redisKeys![0]);
+
+ const llmApiKey = ApiKeyZod.parse(JSON.parse(redisValue!));
+ expect(llmApiKey.projectId).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ });
+
+ // check for eval
+ await waitForExpect(async () => {
+ const evalExecution = await prisma.jobExecution.findFirst({
+ where: {
+ jobInputTraceId: traceId,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ },
+ });
+
+ expect(evalExecution).not.toBeNull();
+
+ if (!evalExecution) {
+ return;
+ }
+
+ // failure due to missing openai key in the pipeline. Expected
+ expect(evalExecution.status).toBe(JobExecutionStatus.ERROR);
+ }, 20000);
+
+ expect(response.status).toBe(207);
+ }, 25000);
+});
+
+describe("Prompts endpoint", () => {
+ it("creates and returns a prompt", async () => {
+ const promptName = "prompt-name" + v4();
+ const chatMessages = [
+ { role: "system", content: "You are a bot" },
+ { role: "user", content: "What's up?" },
+ ];
+ const response = await fetch(
+ "http://localhost:3000/api/public/v2/prompts",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: userApiKeyAuth,
+ },
+ body: JSON.stringify({
+ name: promptName,
+ prompt: chatMessages,
+ type: "chat",
+ labels: ["production"],
+ }),
+ },
+ );
+
+ expect(response.status).toBe(201);
+
+ const fetchedPrompt = await fetch(
+ `http://localhost:3000/api/public/v2/prompts/${encodeURIComponent(promptName)}`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: userApiKeyAuth,
+ },
+ },
+ );
+ expect(fetchedPrompt.status).toBe(200);
+ expect(fetchedPrompt.body).not.toBeNull();
+
+ if (fetchedPrompt.body === null) {
+ return;
+ }
+
+ const validatedPrompt = await fetchedPrompt.json();
+
+ expect(validatedPrompt.name).toBe(promptName);
+
+ const redisKey = `prompt:7a88fb47-b4e2-43b8-a06c-a5ce950dc53a:${promptName}:${validatedPrompt.labels[0]}`;
+ const redisValue = await redis?.get(redisKey);
+
+ expect(redisValue).not.toBeNull();
+ if (!redisValue) {
+ return;
+ }
+ expect(JSON.parse(redisValue)).toEqual(validatedPrompt);
+ });
+});
diff --git a/web/src/__tests__/ingestion.servertest.ts b/web/src/__tests__/ingestion.servertest.ts
index 551559d016..2adabb239e 100644
--- a/web/src/__tests__/ingestion.servertest.ts
+++ b/web/src/__tests__/ingestion.servertest.ts
@@ -4,8 +4,8 @@ import { v4 } from "uuid";
import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { ModelUsageUnit } from "@langfuse/shared";
-import { cleanEvent } from "@/src/pages/api/public/ingestion";
import { prisma } from "@langfuse/shared/src/db";
+import { cleanEvent } from "@langfuse/shared/src/server";
describe("/api/public/ingestion API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -707,19 +707,6 @@ describe("/api/public/ingestion API Endpoint", () => {
expect(dbScore?.traceId).toBe(traceId);
expect(dbScore?.observationId).toBe(generationId);
expect(dbScore?.value).toBe(100.5);
-
- const logEvent = await prisma.events.findFirst({
- where: {
- data: {
- path: ["body", "log"],
- string_contains: "ERROR",
- },
- },
- });
-
- expect(logEvent).toBeDefined();
- expect(logEvent).not.toBeFalsy();
- expect(JSON.stringify(logEvent?.data)).toContain("KeyError: 'model_name'");
});
it("should upsert threats", async () => {
diff --git a/web/src/__tests__/tokenCost.servertest.ts b/web/src/__tests__/tokenCost.servertest.ts
index 7a4d637041..915e0d2a8d 100644
--- a/web/src/__tests__/tokenCost.servertest.ts
+++ b/web/src/__tests__/tokenCost.servertest.ts
@@ -3,9 +3,9 @@ import Decimal from "decimal.js";
import { v4 as uuidv4 } from "uuid";
import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
-import { ObservationProcessor } from "@/src/server/api/services/EventProcessor";
import { ModelUsageUnit } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
+import { ObservationProcessor } from "@langfuse/shared/src/server";
describe("Token Cost Calculation", () => {
const modelName = "gpt-test-" + nanoid();
diff --git a/web/src/__tests__/usage.servertest.ts b/web/src/__tests__/usage.servertest.ts
index 560d5cdd59..3b27ae4e44 100644
--- a/web/src/__tests__/usage.servertest.ts
+++ b/web/src/__tests__/usage.servertest.ts
@@ -1,5 +1,5 @@
-import { ModelUsageUnit } from "@langfuse/shared";
import { tokenCount } from "@/src/features/ingest/usage";
+import { ModelUsageUnit } from "@langfuse/shared";
describe("Token Count Functions", () => {
const generateModel = (model: string, tokenizer: string) => {
diff --git a/web/src/ee/features/evals/components/template-form.tsx b/web/src/ee/features/evals/components/template-form.tsx
index 95d382e00e..f07a870748 100644
--- a/web/src/ee/features/evals/components/template-form.tsx
+++ b/web/src/ee/features/evals/components/template-form.tsx
@@ -17,7 +17,7 @@ import { api } from "@/src/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { extractVariables, getIsCharOrUnderscore } from "@/src/utils/string";
import router from "next/router";
-import { type EvalTemplate } from "@prisma/client";
+import { type EvalTemplate } from "@langfuse/shared";
import { ModelParameters } from "@/src/components/ModelParameters";
import {
OutputSchema,
diff --git a/web/src/env.mjs b/web/src/env.mjs
index df1c02fd46..4f7440d19c 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -111,8 +111,7 @@ export const env = createEnv({
LANGFUSE_WORKER_HOST: z.string().optional(),
LANGFUSE_WORKER_PASSWORD: z.string().optional(),
TURNSTILE_SECRET_KEY: z.string().optional(),
- // DB event log
- ENABLE_EVENT_LOG: z.enum(["true", "false"]).optional().default("true"),
+
// clickhouse
CLICKHOUSE_URL: z.string().optional(),
CLICKHOUSE_USER: z.string().optional(),
@@ -283,8 +282,6 @@ export const env = createEnv({
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
// Other
NEXT_PUBLIC_CRISP_WEBSITE_ID: process.env.NEXT_PUBLIC_CRISP_WEBSITE_ID,
- // db event log
- ENABLE_EVENT_LOG: process.env.ENABLE_EVENT_LOG,
// clickhouse
CLICKHOUSE_URL: process.env.CLICKHOUSE_URL,
CLICKHOUSE_USER: process.env.CLICKHOUSE_USER,
diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.ts
index deb71188ed..f97c8d074c 100644
--- a/web/src/features/public-api/server/apiAuth.ts
+++ b/web/src/features/public-api/server/apiAuth.ts
@@ -1,24 +1,15 @@
import { env } from "@/src/env.mjs";
-import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";
-import { type ApiAccessScope } from "@/src/features/public-api/server/types";
+import {
+ createShaHash,
+ verifySecretKey,
+ type AuthHeaderVerificationResult,
+} from "@langfuse/shared/src/server";
import { type PrismaClient, type ApiKey } from "@langfuse/shared/src/db";
import { isPrismaException } from "@/src/utils/exceptions";
import * as Sentry from "@sentry/node";
import { type Redis } from "ioredis";
import { z } from "zod";
-export type AuthHeaderVerificationResult =
- | AuthHeaderValidVerificationResult
- | {
- validKey: false;
- error: string;
- };
-
-export type AuthHeaderValidVerificationResult = {
- validKey: true;
- scope: ApiAccessScope;
-};
-
export const ApiKeyZod = z.object({
id: z.string(),
note: z.string().nullable(),
diff --git a/web/src/features/public-api/server/apiScope.ts b/web/src/features/public-api/server/apiScope.ts
index 98fe70167d..667a4cbc47 100644
--- a/web/src/features/public-api/server/apiScope.ts
+++ b/web/src/features/public-api/server/apiScope.ts
@@ -1,5 +1,5 @@
-import { type ApiAccessScope } from "@/src/features/public-api/server/types";
import { prisma } from "@langfuse/shared/src/db";
+import { type ApiAccessScope } from "@langfuse/shared/src/server";
type Resource = {
type: "project" | "trace" | "observation" | "score";
diff --git a/web/src/features/public-api/server/createAuthedAPIRoute.ts b/web/src/features/public-api/server/createAuthedAPIRoute.ts
index ae5c744490..ac062c3fb1 100644
--- a/web/src/features/public-api/server/createAuthedAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedAPIRoute.ts
@@ -1,12 +1,12 @@
import { type NextApiRequest, type NextApiResponse } from "next";
import { type ZodType, type z } from "zod";
import * as Sentry from "@sentry/node";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
+import { prisma } from "@langfuse/shared/src/db";
import {
- ApiAuthService,
+ redis,
type AuthHeaderValidVerificationResult,
-} from "@/src/features/public-api/server/apiAuth";
-import { prisma } from "@langfuse/shared/src/db";
-import { redis } from "@langfuse/shared/src/server";
+} from "@langfuse/shared/src/server";
type RouteConfig<
TQuery extends ZodType<any>,
diff --git a/web/src/features/public-api/server/types.ts b/web/src/features/public-api/server/types.ts
deleted file mode 100644
index 8a863044c7..0000000000
--- a/web/src/features/public-api/server/types.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export type ApiAccessScope = {
- projectId: string;
- accessLevel: "all" | "scores";
-};
diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.ts
index 3622097e23..e526d66aa2 100644
--- a/web/src/pages/api/public/events.ts
+++ b/web/src/pages/api/public/events.ts
@@ -5,19 +5,18 @@ import {
} from "@/src/features/public-api/types/events";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
-import {
- handleBatch,
- parseSingleTypedIngestionApiResponse,
-} from "@/src/pages/api/public/ingestion";
+import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";
+import { handleBatch } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
name: "Create Event",
bodySchema: PostEventsV1Body,
responseSchema: PostEventsV1Response,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const ingestionBatch = transformEventToIngestionBatch(body);
- const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const result = await handleBatch(ingestionBatch, auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.ts
index e07b6ee50b..cd2563ebab 100644
--- a/web/src/pages/api/public/generations.ts
+++ b/web/src/pages/api/public/generations.ts
@@ -8,19 +8,18 @@ import {
} from "@/src/features/public-api/types/generations";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
-import {
- handleBatch,
- parseSingleTypedIngestionApiResponse,
-} from "@/src/pages/api/public/ingestion";
+import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";
+import { handleBatch } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
name: "Create Generation (Legacy)",
bodySchema: PostGenerationsV1Body,
responseSchema: PostGenerationsV1Response,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const ingestionBatch = transformGenerationPostToIngestionBatch(body);
- const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const result = await handleBatch(ingestionBatch, auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
@@ -33,9 +32,9 @@ export default withMiddlewares({
name: "Patch Generation (Legacy)",
bodySchema: PatchGenerationsV1Body,
responseSchema: PatchGenerationsV1Response,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const ingestionBatch = transformGenerationPatchToIngestionBatch(body);
- const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const result = await handleBatch(ingestionBatch, auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 0ade35156e..e9242aecf3 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -1,38 +1,24 @@
-import {
- type AuthHeaderVerificationResult,
- ApiAuthService,
-} from "@/src/features/public-api/server/apiAuth";
+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
-import { prisma } from "@langfuse/shared/src/db";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
+import { LangfuseNotFoundError, InternalServerError } from "@langfuse/shared";
import {
- type TraceUpsertEventType,
- type EventBodyType,
- EventName,
- LangfuseNotFoundError,
- InternalServerError,
-} from "@langfuse/shared";
-import {
- type ingestionApiSchema,
- convertTraceUpsertEventsToRedisEvents,
+ getLegacyIngestionQueue,
eventTypes,
- getTraceUpsertQueue,
ingestionEvent,
redis,
+ type AuthHeaderValidVerificationResult,
+ type ingestionBatchEvent,
+ handleBatch,
} 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";
-import { ResourceNotFoundError } from "@/src/utils/exceptions";
import {
SdkLogProcessor,
type EventProcessor,
+ ObservationProcessor,
+ ScoreProcessor,
TraceProcessor,
-} from "../../../server/api/services/EventProcessor";
-import { ObservationProcessor } from "../../../server/api/services/EventProcessor";
-import { ScoreProcessor } from "../../../server/api/services/EventProcessor";
+} from "@langfuse/shared/src/server";
import { isNotNullOrUndefined } from "@/src/utils/types";
import { telemetry } from "@/src/features/telemetry";
import { jsonSchema } from "@langfuse/shared";
@@ -43,11 +29,15 @@ import {
InvalidRequestError,
MethodNotAllowedError,
BaseError,
- ForbiddenError,
UnauthorizedError,
} from "@langfuse/shared";
-
-import { isSigtermReceived } from "@/src/utils/shutdown";
+import {
+ sendToWorkerIfEnvironmentConfigured,
+ QueueJobs,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+import { prisma } from "@langfuse/shared/src/db";
+import { tokenCount } from "@/src/features/ingest/usage";
export const config = {
api: {
@@ -57,158 +47,204 @@ export const config = {
},
};
-type BatchResult = {
- result: unknown;
- id: string;
- type: string;
-};
-
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
- return Sentry.startSpan(
- {
- name: "Ingestion-Handler",
- forceTransaction: true,
- op: "http.server",
- },
- async (span) => {
- try {
- const startTime = Date.now();
- let endTime = undefined;
- await runMiddleware(req, res, cors);
- if (req.method !== "POST") throw new MethodNotAllowedError();
-
- // CHECK AUTH FOR ALL EVENTS
- const authCheck = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
-
- if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
-
- const batchType = z.object({
- batch: z.array(z.unknown()),
- metadata: jsonSchema.nullish(),
- });
-
- const parsedSchema = batchType.safeParse(req.body);
-
- Sentry.metrics.increment(
- "ingestion_event",
- parsedSchema.success ? parsedSchema.data.batch.length : 0,
- );
+ try {
+ await runMiddleware(req, res, cors);
+ if (req.method !== "POST") throw new MethodNotAllowedError();
+
+ // CHECK AUTH FOR ALL EVENTS
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
+
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
+
+ const batchType = z.object({
+ batch: z.array(z.unknown()),
+ metadata: jsonSchema.nullish(),
+ });
+
+ const parsedSchema = batchType.safeParse(req.body);
+
+ Sentry.metrics.increment(
+ "ingestion_event",
+ parsedSchema.success ? parsedSchema.data.batch.length : 0,
+ );
- await gaugePrismaStats();
+ await gaugePrismaStats();
- if (!parsedSchema.success) {
- console.log("Invalid request data", parsedSchema.error);
- return res.status(400).json({
- message: "Invalid request data",
- errors: parsedSchema.error.issues.map((issue) => issue.message),
+ if (!parsedSchema.success) {
+ console.log("Invalid request data", parsedSchema.error);
+ return res.status(400).json({
+ message: "Invalid request data",
+ errors: parsedSchema.error.issues.map((issue) => issue.message),
+ });
+ }
+
+ const validationErrors: { id: string; error: unknown }[] = [];
+
+ const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
+ parsedSchema.data.batch.map((event) => {
+ const parsed = ingestionEvent.safeParse(event);
+ if (!parsed.success) {
+ validationErrors.push({
+ id:
+ typeof event === "object" && event && "id" in event
+ ? typeof event.id === "string"
+ ? event.id
+ : "unknown"
+ : "unknown",
+ error: new InvalidRequestError(parsed.error.message),
});
+ return undefined;
+ } else {
+ return parsed.data;
}
+ });
+ const filteredBatch: z.infer<typeof ingestionEvent>[] =
+ batch.filter(isNotNullOrUndefined);
- const validationErrors: { id: string; error: unknown }[] = [];
-
- const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
- parsedSchema.data.batch.map((event) => {
- const parsed = ingestionEvent.safeParse(event);
- if (!parsed.success) {
- validationErrors.push({
- id:
- typeof event === "object" && event && "id" in event
- ? typeof event.id === "string"
- ? event.id
- : "unknown"
- : "unknown",
- error: new InvalidRequestError(parsed.error.message),
- });
- return undefined;
- } else {
- return parsed.data;
- }
- });
- const filteredBatch: z.infer<typeof ingestionEvent>[] =
- batch.filter(isNotNullOrUndefined);
+ await telemetry();
- await telemetry();
+ const sortedBatch = sortBatch(filteredBatch);
- const sortedBatch = sortBatch(filteredBatch);
+ if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" && redis) {
+ // this function MUST NOT return but send the HTTP response directly
+ const queue = getLegacyIngestionQueue();
- if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true") {
- // this function MUST NOT return but send the HTTP response directly
- handleBatchResult(
- validationErrors, // we are not sending additional server errors to the client in case of early return
- sortedBatch.map((event) => ({ id: event.id, result: event })),
- res,
- );
- endTime = Date.now();
- }
+ if (queue) {
+ console.log("Returning http response early");
- const result = await handleBatch(
- sortedBatch,
- parsedSchema.data.metadata,
- req,
- authCheck,
- );
+ // still need to check auth scope for all events individually
- // send out REST requests to worker for all trace types
- await sendToWorkerIfEnvironmentConfigured(
- result.results,
- authCheck.scope.projectId,
+ const failedAccessScope = accessCheckPerEvent(sortedBatch, authCheck);
+
+ await queue.add(
+ QueueJobs.LegacyIngestionJob,
+ {
+ payload: { data: sortedBatch, authCheck: authCheck },
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.LegacyIngestionJob as const,
+ },
+ {
+ removeOnFail: 1_000_000,
+ removeOnComplete: true,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 1000,
+ },
+ },
+ );
+ return handleBatchResult(
+ [
+ ...validationErrors,
+ ...failedAccessScope.map((e) => ({
+ id: e.id,
+ error: "Access Scope Denied",
+ })),
+ ], // we are not sending additional server errors to the client in case of early return
+ sortedBatch.map((event) => ({ id: event.id, result: event })),
+ res,
);
+ } else {
+ console.error(
+ "Ingestion queue not initialized, falling back to sync processing",
+ );
+ }
+ }
- // in case we did not return early, we return the result here
- if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "false") {
- handleBatchResult(
- [...validationErrors, ...result.errors],
- result.results,
- res,
- );
- }
- span.setAttributes({
- duration: (endTime ?? Date.now()) - startTime,
- async_duration: Date.now() - startTime,
- });
- } catch (error: unknown) {
- if (!(error instanceof UnauthorizedError)) {
- console.error("error_handling_ingestion_event", error);
- Sentry.captureException(error);
- }
+ const result = await handleBatch(sortedBatch, authCheck, tokenCount);
+
+ // send out REST requests to worker for all trace types
+ await sendToWorkerIfEnvironmentConfigured(
+ result.results,
+ authCheck.scope.projectId,
+ );
+
+ // in case we did not return early, we return the result here
+ handleBatchResult(
+ [...validationErrors, ...result.errors],
+ result.results,
+ res,
+ );
+ } catch (error: unknown) {
+ if (!(error instanceof UnauthorizedError)) {
+ console.error("error_handling_ingestion_event", error);
+ Sentry.captureException(error);
+ }
- if (error instanceof BaseError) {
- return res.status(error.httpCode).json({
- error: error.name,
- message: error.message,
- });
- }
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({
+ error: error.name,
+ message: error.message,
+ });
+ }
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- console.log(`Zod exception`, error.errors);
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
+ if (isPrismaException(error)) {
+ return res.status(500).json({
+ error: "Internal Server Error",
+ });
+ }
+ if (error instanceof z.ZodError) {
+ console.log(`Zod exception`, error.errors);
+ return res.status(400).json({
+ message: "Invalid request data",
+ error: error.errors,
+ });
+ }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- errors: [errorMessage],
- });
- }
- },
- );
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(500).json({
+ message: "Invalid request data",
+ errors: [errorMessage],
+ });
+ }
}
+const accessCheckPerEvent = (
+ events: z.infer<typeof ingestionBatchEvent>,
+ authCheck: AuthHeaderValidVerificationResult,
+) => {
+ const unauthorizedEvents: { id: string; type: string }[] = [];
+
+ for (const event of events) {
+ try {
+ let processor: EventProcessor;
+ switch (event.type) {
+ case eventTypes.TRACE_CREATE:
+ processor = new TraceProcessor(event);
+ break;
+ 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:
+ processor = new ObservationProcessor(event, tokenCount);
+ break;
+ case eventTypes.SCORE_CREATE:
+ processor = new ScoreProcessor(event);
+ break;
+ case eventTypes.SDK_LOG:
+ processor = new SdkLogProcessor(event);
+ break;
+ }
+ processor.auth(authCheck.scope);
+ } catch (error) {
+ unauthorizedEvents.push({ id: event.id, type: event.type });
+ }
+ }
+ return unauthorizedEvents;
+};
+
/**
* Sorts a batch of ingestion events. Orders by: updating events last, sorted by timestamp asc.
*/
@@ -234,79 +270,6 @@ const sortBatch = (batch: Array<z.infer<typeof ingestionEvent>>) => {
return [...others, ...updates];
};
-export const handleBatch = async (
- events: z.infer<typeof ingestionApiSchema>["batch"],
- metadata: z.infer<typeof ingestionApiSchema>["metadata"],
- req: NextApiRequest,
- authCheck: AuthHeaderVerificationResult,
-) => {
- console.log(
- `handling ingestion ${events.length} events ${isSigtermReceived() ? "after SIGTERM" : ""}`,
- );
-
- if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
-
- const results: BatchResult[] = []; // Array to store the results
-
- const errors: {
- error: unknown;
- id: string;
- type: string;
- }[] = []; // Array to store the errors
-
- for (const singleEvent of events) {
- try {
- const result = await retry(async () => {
- return await handleSingleEvent(
- singleEvent,
- metadata,
- req,
- authCheck.scope,
- );
- });
- results.push({
- result: result,
- id: singleEvent.id,
- type: singleEvent.type,
- }); // Push each result into the array
- } catch (error) {
- // Handle or log the error if `handleSingleEvent` fails
- console.error("Error handling event:", error);
- // Decide how to handle the error: rethrow, continue, or push an error object to results
- // For example, push an error object:
- errors.push({
- error: error,
- id: singleEvent.id,
- type: singleEvent.type,
- });
- }
- }
-
- if (env.CLICKHOUSE_URL) {
- 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 };
-};
-
-async function retry<T>(request: () => Promise<T>): Promise<T> {
- return await backOff(request, {
- numOfAttempts: env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true" ? 5 : 3,
- retry: (e: Error, attemptNumber: number) => {
- if (e instanceof UnauthorizedError || e instanceof ForbiddenError) {
- console.log("not retrying auth error");
- return false;
- }
- console.log(`retrying processing events ${attemptNumber}`);
- return true;
- },
- });
-}
export const getBadRequestError = (
errors: Array<unknown>,
): InvalidRequestError[] =>
@@ -315,83 +278,17 @@ export const getBadRequestError = (
error instanceof InvalidRequestError,
);
-export const getResourceNotFoundError = (
+export const getLangfuseNotFoundError = (
errors: Array<unknown>,
-): ResourceNotFoundError[] =>
+): LangfuseNotFoundError[] =>
errors.filter(
- (error): error is ResourceNotFoundError =>
- error instanceof ResourceNotFoundError,
+ (error): error is LangfuseNotFoundError =>
+ error instanceof LangfuseNotFoundError,
);
export const hasBadRequestError = (errors: Array<unknown>) =>
errors.some((error) => error instanceof InvalidRequestError);
-const handleSingleEvent = async (
- event: z.infer<typeof ingestionEvent>,
- metadata: z.infer<typeof ingestionApiSchema>["metadata"],
- req: NextApiRequest,
- apiScope: ApiAccessScope,
-) => {
- const { body } = event;
- let restEvent = body;
- if ("input" in body) {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { input, ...rest } = body;
- restEvent = rest;
- }
- if ("output" in restEvent) {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- const { output, ...rest } = restEvent;
- restEvent = rest;
- }
-
- console.log(
- `handling single event ${event.id} of type ${event.type}: ${JSON.stringify({ body: restEvent })}`,
- );
-
- const cleanedEvent = ingestionEvent.parse(cleanEvent(event));
-
- const { type } = cleanedEvent;
-
- await persistEventMiddleware(
- prisma,
- apiScope.projectId,
- req,
- cleanedEvent,
- metadata,
- );
-
- let processor: EventProcessor;
- switch (type) {
- case eventTypes.TRACE_CREATE:
- processor = new TraceProcessor(cleanedEvent);
- break;
- 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:
- processor = new ObservationProcessor(cleanedEvent);
- break;
- case eventTypes.SCORE_CREATE: {
- processor = new ScoreProcessor(cleanedEvent);
- break;
- }
- case eventTypes.SDK_LOG:
- processor = new SdkLogProcessor(cleanedEvent);
- }
-
- // Deny access to non-score events if the access level is not "all"
- // This is an additional safeguard to auth checks in EventProcessor
- if (apiScope.accessLevel !== "all" && type !== eventTypes.SCORE_CREATE) {
- throw new ForbiddenError("Access denied. Event type not allowed.");
- }
-
- return await processor.process(apiScope);
-};
-
export const handleBatchResult = (
errors: Array<{ id: string; error: unknown }>,
results: Array<{ id: string; result: unknown }>,
@@ -424,7 +321,7 @@ export const handleBatchResult = (
message: "Authentication error",
error: error.error.message,
});
- } else if (error.error instanceof ResourceNotFoundError) {
+ } else if (error.error instanceof LangfuseNotFoundError) {
returnedErrors.push({
id: error.id,
status: 404,
@@ -507,9 +404,9 @@ export const parseSingleTypedIngestionApiResponse = <T extends z.ZodTypeAny>(
if (badRequestErrors.length > 0) {
throw new InvalidRequestError(badRequestErrors[0].message);
}
- const ResourceNotFoundError = getResourceNotFoundError(unknownErrors);
- if (ResourceNotFoundError.length > 0) {
- throw new LangfuseNotFoundError(ResourceNotFoundError[0].message);
+ const langfuseNotFoundError = getLangfuseNotFoundError(unknownErrors);
+ if (langfuseNotFoundError.length > 0) {
+ throw langfuseNotFoundError[0];
}
if (errors.length > 0) {
throw new InternalServerError("Internal Server Error");
@@ -532,94 +429,14 @@ export const parseSingleTypedIngestionApiResponse = <T extends z.ZodTypeAny>(
return results[0].result as z.infer<T>;
};
-// cleans NULL characters from the event
-export function cleanEvent(obj: unknown): unknown {
- if (typeof obj === "string") {
- return obj.replace(/\u0000/g, "");
- } else if (typeof obj === "object" && obj !== null) {
- if (Array.isArray(obj)) {
- return obj.map(cleanEvent);
- } else {
- // Here we assert that obj is a Record<string, unknown>
- const objAsRecord = obj as Record<string, unknown>;
- const newObj: Record<string, unknown> = {};
- for (const key in objAsRecord) {
- newObj[key] = cleanEvent(objAsRecord[key]);
- }
- return newObj;
- }
- } else {
- return obj;
- }
-}
-
-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.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && redis) {
- console.log(`Sending ${traceEvents.length} events to worker via Redis`);
-
- const queue = getTraceUpsertQueue();
- if (!queue) {
- console.error("TraceUpsertQueue not initialized");
- return;
- }
-
- await queue.addBulk(convertTraceUpsertEventsToRedisEvents(traceEvents));
- } else if (
- env.LANGFUSE_WORKER_HOST &&
- env.LANGFUSE_WORKER_PASSWORD &&
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
- ) {
- console.log(`Sending ${traceEvents.length} events to worker via HTTP`);
- const body: EventBodyType = {
- name: EventName.TraceUpsert,
- payload: traceEvents,
- };
-
- if (traceEvents.length > 0) {
- await fetch(`${env.LANGFUSE_WORKER_HOST}/api/events`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization:
- "Basic " +
- Buffer.from(
- "admin" + ":" + env.LANGFUSE_WORKER_PASSWORD,
- ).toString("base64"),
- },
- body: JSON.stringify(body),
- signal: AbortSignal.timeout(8 * 1000),
- });
- }
- }
- } catch (error) {
- console.error("Error sending events to worker", error);
- }
-};
-
const gaugePrismaStats = async () => {
// execute with a 50% probability
if (Math.random() > 0.5) {
return;
}
- const metrics = await prisma.$metrics.json();
+ // const metrics = await prisma.$metrics.json();
- metrics.gauges.forEach((gauge) => {
- Sentry.metrics.gauge(gauge.key, gauge.value, gauge.labels);
- });
+ // metrics.gauges.forEach((gauge) => {
+ // Sentry.metrics.gauge(gauge.key, gauge.value, gauge.labels);
+ // });
};
diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.ts
index abe15251d9..149b605c07 100644
--- a/web/src/pages/api/public/scores/index.ts
+++ b/web/src/pages/api/public/scores/index.ts
@@ -2,10 +2,7 @@ import { v4 } from "uuid";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
-import {
- handleBatch,
- parseSingleTypedIngestionApiResponse,
-} from "@/src/pages/api/public/ingestion";
+import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";
import {
GetScoresQuery,
GetScoresResponse,
@@ -14,14 +11,19 @@ import {
PostScoresResponse,
} from "@langfuse/shared";
import { prisma, Prisma } from "@langfuse/shared/src/db";
-import { eventTypes, ingestionBatchEvent } from "@langfuse/shared/src/server";
+import {
+ eventTypes,
+ handleBatch,
+ ingestionBatchEvent,
+} from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
name: "Create Score",
bodySchema: PostScoresBody,
responseSchema: PostScoresResponse,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const event = {
id: v4(),
type: eventTypes.SCORE_CREATE,
@@ -30,9 +32,8 @@ export default withMiddlewares({
};
const result = await handleBatch(
ingestionBatchEvent.parse([event]),
- {},
- req,
auth,
+ tokenCount,
);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.ts
index 5d4726077e..a455abbd1f 100644
--- a/web/src/pages/api/public/spans.ts
+++ b/web/src/pages/api/public/spans.ts
@@ -8,19 +8,18 @@ import {
} from "@/src/features/public-api/types/spans";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
-import {
- handleBatch,
- parseSingleTypedIngestionApiResponse,
-} from "@/src/pages/api/public/ingestion";
+import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";
+import { handleBatch } from "@langfuse/shared/src/server";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
name: "Create Span (Legacy)",
bodySchema: PostSpansV1Body,
responseSchema: PostSpansV1Response,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const ingestionBatch = transformLegacySpanPostToIngestionBatch(body);
- const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const result = await handleBatch(ingestionBatch, auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
@@ -33,9 +32,9 @@ export default withMiddlewares({
name: "Update Span (Legacy)",
bodySchema: PatchSpansV1Body,
responseSchema: PatchSpansV1Response,
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
const ingestionBatch = transformLegacySpanPatchToIngestionBatch(body);
- const result = await handleBatch(ingestionBatch, {}, req, auth);
+ const result = await handleBatch(ingestionBatch, auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.ts
index d01582457e..95b2298221 100644
--- a/web/src/pages/api/public/traces/index.ts
+++ b/web/src/pages/api/public/traces/index.ts
@@ -8,23 +8,21 @@ import {
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { Prisma } from "@langfuse/shared/src/db";
-import {
- handleBatch,
- parseSingleTypedIngestionApiResponse,
-} from "@/src/pages/api/public/ingestion";
+import { parseSingleTypedIngestionApiResponse } from "@/src/pages/api/public/ingestion";
import { type Trace } from "@langfuse/shared";
-import { eventTypes } from "@langfuse/shared/src/server";
+import { eventTypes, handleBatch } from "@langfuse/shared/src/server";
import { v4 } from "uuid";
import { telemetry } from "@/src/features/telemetry";
import { tracesTableCols, orderByToPrismaSql } from "@langfuse/shared";
+import { tokenCount } from "@/src/features/ingest/usage";
export default withMiddlewares({
POST: createAuthedAPIRoute({
name: "Create Trace",
bodySchema: PostTracesV1Body,
responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schema
- fn: async ({ body, auth, req }) => {
+ fn: async ({ body, auth }) => {
await telemetry();
const event = {
@@ -34,7 +32,7 @@ export default withMiddlewares({
body: body,
};
- const result = await handleBatch([event], {}, req, auth);
+ const result = await handleBatch([event], auth, tokenCount);
const response = parseSingleTypedIngestionApiResponse(
result.errors,
result.results,
diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.ts
index 403784602e..67ad16cb65 100644
--- a/web/src/server/api/routers/batchExport.ts
+++ b/web/src/server/api/routers/batchExport.ts
@@ -6,14 +6,13 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
+import { BatchExportStatus, CreateBatchExportSchema } from "@langfuse/shared";
import {
- BatchExportStatus,
+ getBatchExportQueue,
type EventBodyType,
EventName,
- CreateBatchExportSchema,
QueueJobs,
-} from "@langfuse/shared";
-import { getBatchExportQueue } from "@langfuse/shared/src/server";
+} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { redis } from "@langfuse/shared/src/server";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
diff --git a/web/src/server/api/services/WorkerClient.ts b/web/src/server/api/services/WorkerClient.ts
index a812169fbf..635c671f20 100644
--- a/web/src/server/api/services/WorkerClient.ts
+++ b/web/src/server/api/services/WorkerClient.ts
@@ -1,6 +1,8 @@
import { env } from "@/src/env.mjs";
-import { type EventBodyType } from "@langfuse/shared";
-import { type IngestionApiSchemaWithProjectId } from "@langfuse/shared/src/server";
+import {
+ type EventBodyType,
+ type IngestionApiSchemaWithProjectId,
+} from "@langfuse/shared/src/server";
import { instrumentAsync } from "@/src/utils/instrumentation";
export class WorkerClient {
diff --git a/web/src/server/api/services/event-service.ts b/web/src/server/api/services/event-service.ts
deleted file mode 100644
index 5c06f39d4e..0000000000
--- a/web/src/server/api/services/event-service.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { type Prisma, type PrismaClient } from "@langfuse/shared/src/db";
-import { type NextApiRequest } from "next";
-import { type jsonSchema } from "@langfuse/shared";
-import lodash from "lodash";
-import { env } from "@/src/env.mjs";
-import { randomUUID } from "crypto";
-
-// This function persists raw events to the database which came via API
-// It relates each event to a project
-// It checks that the event is valid JSON to avoid DB errors
-// It persists over which URL and Method the event came in
-// It does not extract more data to avoid any early errors such as schema parsing errors
-// this table eventually becomes very large. Old data can be archived then in blob storage
-export const persistEventMiddleware = async (
- prisma: PrismaClient,
- projectId: string,
- req: NextApiRequest,
- data: Prisma.JsonObject,
- metadata?: Zod.infer<typeof jsonSchema> | null,
-) => {
- // If event logging is disabled, do nothing
- if (env.ENABLE_EVENT_LOG === "false") return;
-
- const langfuseHeadersObject = Object.fromEntries(
- Object.entries(req.headers).filter(([key]) => key.startsWith("x-langfuse")),
- );
-
- // combine metadata from the request and langfuseHeadersObject
- const combinedMetadata = lodash.merge(metadata, langfuseHeadersObject);
-
- await prisma.$queryRaw`
- INSERT INTO events (id, project_id, url, method, data, headers)
- VALUES (
- ${randomUUID()},
- ${projectId},
- ${req.url},
- ${req.method},
- ${data},
- ${combinedMetadata}
- );
- `;
-};
diff --git a/web/src/utils/exceptions.ts b/web/src/utils/exceptions.ts
index 4542c79cda..0e0f53db8f 100644
--- a/web/src/utils/exceptions.ts
+++ b/web/src/utils/exceptions.ts
@@ -1,14 +1,5 @@
import { Prisma } from "@langfuse/shared/src/db";
-export class ResourceNotFoundError extends Error {
- id: string;
- constructor(type: string, id: string) {
- super(`${type} with ${id} not found}`);
- this.name = "ResourceNotFoundError";
- this.id = id;
- }
-}
-
export function isPrismaException(e: unknown) {
return (
e instanceof Prisma.PrismaClientKnownRequestError ||
diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.ts
index ffdc90adee..b184ce6036 100644
--- a/worker/src/__tests__/redis-consumer.test.ts
+++ b/worker/src/__tests__/redis-consumer.test.ts
@@ -1,10 +1,13 @@
import { expect, test, describe, vi } from "vitest";
-import { QueueJobs, TraceUpsertEventSchema } from "@langfuse/shared";
import { randomUUID } from "crypto";
import { z } from "zod";
import logger from "../logger";
import { evalJobCreator } from "../queues/evalQueue";
-import { getTraceUpsertQueue } from "@langfuse/shared/src/server";
+import {
+ getTraceUpsertQueue,
+ QueueJobs,
+ TraceUpsertEventSchema,
+} from "@langfuse/shared/src/server";
describe.sequential("handle redis events", () => {
test("handle redis job succeeding", async () => {
diff --git a/worker/src/api/index.ts b/worker/src/api/index.ts
index fa64a3ebf7..7317f740e2 100644
--- a/worker/src/api/index.ts
+++ b/worker/src/api/index.ts
@@ -1,12 +1,13 @@
import express from "express";
import basicAuth from "express-basic-auth";
-
-import { EventBodySchema, EventName, QueueJobs } from "@langfuse/shared";
import {
clickhouseClient,
convertTraceUpsertEventsToRedisEvents,
getTraceUpsertQueue,
getBatchExportQueue,
+ EventBodySchema,
+ EventName,
+ QueueJobs,
} from "@langfuse/shared/src/server";
import * as Sentry from "@sentry/node";
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 3c1fdb989f..ba26374705 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -18,6 +18,7 @@ import { logQueueWorkerError } from "./utils/logQueueWorkerError";
import { onShutdown } from "./utils/shutdown";
import helmet from "helmet";
+import { legacyIngestionExecutor } from "./queues/legacyIngestionQueue";
const app = express();
@@ -49,12 +50,17 @@ logger.info(
"Flush Ingestion Queue Executor started",
ingestionQueueExecutor?.isRunning()
);
+logger.info(
+ "Legacy Ingestion Executor started",
+ legacyIngestionExecutor?.isRunning()
+);
evalJobCreator?.on("failed", logQueueWorkerError);
evalJobExecutor?.on("failed", logQueueWorkerError);
batchExportJobExecutor?.on("failed", logQueueWorkerError);
repeatQueueExecutor?.on("failed", logQueueWorkerError);
ingestionQueueExecutor?.on("failed", logQueueWorkerError);
+legacyIngestionExecutor?.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 f73647aa06..ac93970a94 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -63,6 +63,10 @@ const EnvSchema = z.object({
CLICKHOUSE_USER: z.string().optional(),
CLICKHOUSE_PASSWORD: z.string().optional(),
LANGFUSE_WORKER_BETTERSTACK_TOKEN: z.string().optional(),
+ LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY: z.coerce
+ .number()
+ .positive()
+ .default(25),
});
export const env = EnvSchema.parse(process.env);
diff --git a/worker/src/features/batchExport/enqueueBatchExportJobs.ts b/worker/src/features/batchExport/enqueueBatchExportJobs.ts
index c1f1adca0f..c9b2f9569a 100644
--- a/worker/src/features/batchExport/enqueueBatchExportJobs.ts
+++ b/worker/src/features/batchExport/enqueueBatchExportJobs.ts
@@ -1,9 +1,9 @@
-import { BatchExportStatus, QueueJobs } from "@langfuse/shared";
+import { BatchExportStatus } from "@langfuse/shared";
import { kyselyPrisma } from "@langfuse/shared/src/db";
import * as Sentry from "@sentry/node";
import logger from "../../logger";
-import { getBatchExportQueue } from "@langfuse/shared/src/server";
+import { getBatchExportQueue, QueueJobs } from "@langfuse/shared/src/server";
/**
* Enqueues batch export jobs from the database to the job queue.
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index 397b9cf1f6..9517eadd46 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -2,7 +2,6 @@ import { pipeline } from "stream";
import {
BatchExportFileFormat,
- BatchExportJobType,
BatchExportQuerySchema,
BatchExportStatus,
exportOptions,
@@ -15,6 +14,7 @@ import {
S3StorageService,
sendBatchExportSuccessEmail,
streamTransformations,
+ BatchExportJobType,
} from "@langfuse/shared/src/server";
import { env } from "../../env";
diff --git a/worker/src/features/evaluation/eval-service.ts b/worker/src/features/evaluation/eval-service.ts
index a9ac95d75b..f1f4b24e87 100644
--- a/worker/src/features/evaluation/eval-service.ts
+++ b/worker/src/features/evaluation/eval-service.ts
@@ -2,23 +2,24 @@ import { randomUUID } from "crypto";
import Handlebars from "handlebars";
import { sql } from "kysely";
import { z } from "zod";
-
+import {
+ QueueJobs,
+ QueueName,
+ EvalExecutionEvent,
+ TraceUpsertEventSchema,
+} from "@langfuse/shared/src/server";
import {
ApiError,
availableEvalVariables,
ChatMessageRole,
- EvalExecutionEvent,
evalTableCols,
fetchLLMCompletion,
ForbiddenError,
LangfuseNotFoundError,
LLMApiKeySchema,
Prisma,
- QueueJobs,
- QueueName,
singleFilter,
tableColumnsToSqlFilterAndPrefix,
- TraceUpsertEventSchema,
InvalidRequestError,
variableMappingList,
ZodModelConfig,
diff --git a/worker/src/features/tokenisation/usage.ts b/worker/src/features/tokenisation/usage.ts
index 178b431847..24c1542219 100644
--- a/worker/src/features/tokenisation/usage.ts
+++ b/worker/src/features/tokenisation/usage.ts
@@ -1,7 +1,6 @@
-import { parseJsonPrioritised } from "@langfuse/shared";
+import { Model, parseJsonPrioritised } from "@langfuse/shared";
import { isChatModel, isTiktokenModel } from "./types";
import { countTokens } from "@anthropic-ai/tokenizer";
-import { Model } from "@prisma/client";
import {
type TiktokenModel,
diff --git a/worker/src/queues/batchExportQueue.ts b/worker/src/queues/batchExportQueue.ts
index 4a306d6198..97a438139e 100644
--- a/worker/src/queues/batchExportQueue.ts
+++ b/worker/src/queues/batchExportQueue.ts
@@ -1,17 +1,12 @@
import { Job, Worker } from "bullmq";
-import {
- BaseError,
- BatchExportStatus,
- QueueName,
- TQueueJobTypes,
-} from "@langfuse/shared";
+import { BaseError, BatchExportStatus } from "@langfuse/shared";
import { kyselyPrisma } from "@langfuse/shared/src/db";
import * as Sentry from "@sentry/node";
import { instrumentAsync } from "../instrumentation";
import logger from "../logger";
-import { redis } from "@langfuse/shared/src/server";
+import { redis, QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
import { handleBatchExportJob } from "../features/batchExport/handleBatchExportJob";
export const batchExportJobExecutor = redis
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 78448e3044..45a8f47b24 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -1,15 +1,10 @@
import { Job, Queue, Worker } from "bullmq";
-import {
- ApiError,
- BaseError,
- QueueName,
- TQueueJobTypes,
-} from "@langfuse/shared";
+import { ApiError, BaseError } from "@langfuse/shared";
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 "@langfuse/shared/src/server";
+import { redis, QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";
import { instrumentAsync } from "../instrumentation";
import * as Sentry from "@sentry/node";
diff --git a/worker/src/queues/ingestionFlushQueueExecutor.ts b/worker/src/queues/ingestionFlushQueueExecutor.ts
index bdbc168e74..20e6902797 100644
--- a/worker/src/queues/ingestionFlushQueueExecutor.ts
+++ b/worker/src/queues/ingestionFlushQueueExecutor.ts
@@ -1,6 +1,6 @@
import { Queue, Worker } from "bullmq";
-import { QueueJobs, QueueName } from "@langfuse/shared";
+import { QueueJobs, QueueName } from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import {
clickhouseClient,
diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.ts
new file mode 100644
index 0000000000..b1b3036ac5
--- /dev/null
+++ b/worker/src/queues/legacyIngestionQueue.ts
@@ -0,0 +1,91 @@
+import { Job, Worker } from "bullmq";
+import {
+ getLegacyIngestionQueue,
+ QueueName,
+ TQueueJobTypes,
+} from "@langfuse/shared/src/server";
+import logger from "../logger";
+
+import {
+ handleBatch,
+ redis,
+ sendToWorkerIfEnvironmentConfigured,
+} from "@langfuse/shared/src/server";
+import { instrumentAsync } from "../instrumentation";
+import * as Sentry from "@sentry/node";
+import { tokenCount } from "../features/tokenisation/usage";
+import { env } from "../env";
+
+export const legacyIngestionExecutor = redis
+ ? new Worker<TQueueJobTypes[QueueName.LegacyIngestionQueue]>(
+ QueueName.LegacyIngestionQueue,
+ async (job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>) => {
+ return instrumentAsync({ name: "legacyIngestion" }, async () => {
+ try {
+ logger.info(
+ `Processing legacy ingestion for payload ${JSON.stringify(job.data.payload)}`
+ );
+
+ // Log wait time
+ const waitTime = Date.now() - job.timestamp;
+ logger.debug(
+ `Received flush request after ${waitTime} ms for ${job.data.payload.authCheck.scope.projectId}`
+ );
+
+ Sentry.metrics.increment("legacy_ingestion_processing_request");
+ Sentry.metrics.distribution(
+ "legacy_ingestion_flush_wait_time",
+ waitTime,
+ {
+ unit: "milliseconds",
+ }
+ );
+
+ const result = await handleBatch(
+ job.data.payload.data,
+ job.data.payload.authCheck,
+ tokenCount
+ );
+
+ // send out REDIS requests to worker for all trace types
+ await sendToWorkerIfEnvironmentConfigured(
+ result.results,
+ job.data.payload.authCheck.scope.projectId
+ );
+
+ // Log queue size
+ await getLegacyIngestionQueue()
+ ?.count()
+ .then((count) => {
+ logger.info(`Legacy Ingestion flush queue length: ${count}`);
+ Sentry.metrics.gauge(
+ "legacy_ingestion_flush_queue_length",
+ count,
+ {
+ unit: "records",
+ }
+ );
+ return count;
+ })
+ .catch();
+ } catch (e) {
+ logger.error(
+ e,
+ `Failed job Evaluation for traceId ${job.data.payload} ${e}`
+ );
+ Sentry.captureException(e);
+ throw e;
+ }
+ });
+ },
+ {
+ connection: redis,
+ concurrency: env.LANGFUSE_LEGACY_INGESTION_WORKER_CONCURRENCY, // n ingestion batches at a time
+ limiter: {
+ // per second, process max n batches
+ max: 20,
+ duration: 1000,
+ },
+ }
+ )
+ : null;
diff --git a/worker/src/queues/repeatQueue.ts b/worker/src/queues/repeatQueue.ts
index d49bde3f17..012ee6aa2a 100644
--- a/worker/src/queues/repeatQueue.ts
+++ b/worker/src/queues/repeatQueue.ts
@@ -1,8 +1,7 @@
import { Queue, Worker } from "bullmq";
-import { redis } from "@langfuse/shared/src/server";
+import { redis, QueueJobs, QueueName } from "@langfuse/shared/src/server";
import { enqueueBatchExportJobs } from "../features/batchExport/enqueueBatchExportJobs";
-import { QueueJobs, QueueName } from "@langfuse/shared";
export const repeatQueue = redis
? new Queue(QueueName.RepeatQueue, {
diff --git a/worker/src/sentry.ts b/worker/src/sentry.ts
index ddf0bc35d1..fb15777c99 100644
--- a/worker/src/sentry.ts
+++ b/worker/src/sentry.ts
@@ -9,6 +9,7 @@ require("dd-trace").init({
Sentry.init({
dsn: String(env.SENTRY_DSN),
+
integrations: [
Sentry.httpIntegration(),
Sentry.expressIntegration(),
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 4d9cb333c7..4c28dc2e21 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -28,6 +28,7 @@ import {
IngestionUtils,
ClickhouseEntityType,
PromptService,
+ QueueJobs,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index 1727c2256a..8c45cd8199 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -9,6 +9,7 @@ import { repeatQueueExecutor } from "../queues/repeatQueue";
import { ClickhouseWriter } from "../services/ClickhouseWriter";
import { setSigtermReceived } from "../features/health";
import { server } from "../index";
+import { legacyIngestionExecutor } from "../queues/legacyIngestionQueue";
export const onShutdown: NodeJS.SignalsListener = async (signal) => {
logger.info(`Received ${signal}, closing server...`);
@@ -25,6 +26,7 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
batchExportJobExecutor,
ingestionQueueExecutor,
repeatQueueExecutor,
+ legacyIngestionExecutor,
];
await Promise.all(workers.map((worker) => worker?.close()));