Skip to content

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

perf: parse zod in ingestion pipeline async (#3253)

Max Deichmann217b92d548fc
diff --git a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
index d2d5e84aa5..6c4d8be31b 100644
--- a/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
+++ b/packages/shared/src/server/ingestion/legacy/EventProcessor.ts
@@ -24,7 +24,7 @@ export interface EventProcessor {
auth(apiScope: LegacyIngestionAccessScope): void;
process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> | undefined;
}
@@ -40,7 +40,7 @@ export class ObservationProcessor implements EventProcessor {
calculateTokenDelegate: (p: {
model: Model;
text: unknown;
- }) => number | undefined,
+ }) => number | undefined
) {
this.event = event;
this.calculateTokenDelegate = calculateTokenDelegate;
@@ -48,7 +48,7 @@ export class ObservationProcessor implements EventProcessor {
async convertToObservation(
apiScope: LegacyIngestionAccessScope,
- existingObservation: Observation | null,
+ existingObservation: Observation | null
): Promise<{
id: string;
create: Prisma.ObservationUncheckedCreateInput;
@@ -78,7 +78,7 @@ export class ObservationProcessor implements EventProcessor {
!existingObservation
) {
throw new LangfuseNotFoundError(
- `Observation with id ${this.event.id} not found`,
+ `Observation with id ${this.event.id} not found`
);
}
@@ -124,7 +124,7 @@ export class ObservationProcessor implements EventProcessor {
this.event.body,
this.calculateTokenDelegate,
internalModel ?? undefined,
- existingObservation ?? undefined,
+ existingObservation ?? undefined
)
: [undefined, undefined];
@@ -160,15 +160,15 @@ export class ObservationProcessor implements EventProcessor {
const calculatedCosts = ObservationProcessor.calculateTokenCosts(
internalModel,
userProvidedTokenCosts,
- tokenCounts,
+ tokenCounts
);
// merge metadata from existingObservation.metadata and metadata
const mergedMetadata = mergeJson(
existingObservation?.metadata
- ? jsonSchema.parse(existingObservation.metadata)
+ ? await jsonSchema.parseAsync(existingObservation.metadata)
: undefined,
- this.event.body.metadata ?? undefined,
+ this.event.body.metadata ?? undefined
);
const prompt =
@@ -320,7 +320,7 @@ export class ObservationProcessor implements EventProcessor {
text: unknown;
}) => number | undefined,
model?: Model,
- existingObservation?: Observation,
+ existingObservation?: Observation
) {
const newPromptTokens =
body.usage?.input ??
@@ -352,7 +352,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;
@@ -369,7 +369,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)
),
};
}
@@ -419,7 +419,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} `
);
}
@@ -449,7 +449,7 @@ export class TraceProcessor implements EventProcessor {
}
async process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
@@ -458,7 +458,7 @@ export class TraceProcessor implements EventProcessor {
const internalId = body.id ?? v4();
logger.debug(
- `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`,
+ `Trying to create trace, project ${apiScope.projectId}, id: ${internalId}`
);
const existingTrace = await prisma.trace.findFirst({
@@ -469,15 +469,15 @@ 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}`
);
}
const mergedMetadata = mergeJson(
existingTrace?.metadata
- ? jsonSchema.parse(existingTrace.metadata)
+ ? await jsonSchema.parseAsync(existingTrace.metadata)
: undefined,
- body.metadata ?? undefined,
+ body.metadata ?? undefined
);
const mergedTags =
@@ -555,12 +555,12 @@ export class ScoreProcessor implements EventProcessor {
auth(apiScope: LegacyIngestionAccessScope) {
if (apiScope.accessLevel !== "scores" && apiScope.accessLevel !== "all")
throw new ForbiddenError(
- `Access denied for score creation, ${apiScope.accessLevel}`,
+ `Access denied for score creation, ${apiScope.accessLevel}`
);
}
async process(
- apiScope: LegacyIngestionAccessScope,
+ apiScope: LegacyIngestionAccessScope
): Promise<Trace | Observation | Score> {
const { body } = this.event;
@@ -578,7 +578,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}`
);
}
diff --git a/packages/shared/src/server/ingestion/legacy/index.ts b/packages/shared/src/server/ingestion/legacy/index.ts
index 55c3e3fb47..d06d2796c6 100644
--- a/packages/shared/src/server/ingestion/legacy/index.ts
+++ b/packages/shared/src/server/ingestion/legacy/index.ts
@@ -50,7 +50,7 @@ type LegacyIngestionAuthHeaderVerificationResult =
export const handleBatch = async (
events: z.infer<typeof ingestionApiSchema>["batch"],
authCheck: LegacyIngestionAuthHeaderVerificationResult,
- calculateTokenDelegate: (p: TokenCountInput) => number | undefined,
+ calculateTokenDelegate: (p: TokenCountInput) => number | undefined
) => {
logger.debug(`handling ingestion ${events.length} events`);
@@ -70,7 +70,7 @@ export const handleBatch = async (
return await handleSingleEvent(
singleEvent,
authCheck.scope,
- calculateTokenDelegate,
+ calculateTokenDelegate
);
});
results.push({
@@ -123,7 +123,7 @@ const handleSingleEvent = async (
calculateTokenDelegate: (p: {
model: Model;
text: unknown;
- }) => number | undefined,
+ }) => number | undefined
) => {
const { body } = event;
let restEvent = body;
@@ -139,10 +139,10 @@ const handleSingleEvent = async (
}
logger.info(
- `handling single event ${event.id} of type ${event.type}: ${JSON.stringify({ body: restEvent })}`,
+ `handling single event ${event.id} of type ${event.type}: ${JSON.stringify({ body: restEvent })}`
);
- const cleanedEvent = ingestionEvent.parse(cleanEvent(event));
+ const cleanedEvent = await ingestionEvent.parseAsync(cleanEvent(event));
const { type } = cleanedEvent;
@@ -160,7 +160,7 @@ const handleSingleEvent = async (
case eventTypes.GENERATION_UPDATE:
processor = new ObservationProcessor(
cleanedEvent,
- calculateTokenDelegate,
+ calculateTokenDelegate
);
break;
case eventTypes.SCORE_CREATE: {
@@ -202,7 +202,7 @@ export function cleanEvent(obj: unknown): unknown {
}
export const isNotNullOrUndefined = <T>(
- val?: T | null,
+ val?: T | null
): val is Exclude<T, null | undefined> => !isUndefinedOrNull(val);
export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>
@@ -210,7 +210,7 @@ export const isUndefinedOrNull = <T>(val?: T | null): val is undefined | null =>
export const sendToWorkerIfEnvironmentConfigured = async (
batchResults: BatchResult[],
- projectId: string,
+ projectId: string
): Promise<void> => {
const traceEvents: TraceUpsertEventType[] = batchResults
.filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update.
@@ -220,7 +220,7 @@ export const sendToWorkerIfEnvironmentConfigured = async (
"id" in result.result
? // ingestion API only gets traces for one projectId
{ traceId: result.result.id as string, projectId }
- : null,
+ : null
)
.filter(isNotNullOrUndefined);
@@ -254,7 +254,7 @@ export const sendToWorkerIfEnvironmentConfigured = async (
Authorization:
"Basic " +
Buffer.from(
- "admin" + ":" + env.LANGFUSE_WORKER_PASSWORD,
+ "admin" + ":" + env.LANGFUSE_WORKER_PASSWORD
).toString("base64"),
},
body: JSON.stringify(body),
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 1d23870fbc..c44b4e7338 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -14,6 +14,7 @@ import {
recordIncrement,
getCurrentSpan,
LegacyIngestionQueue,
+ instrumentAsync,
} from "@langfuse/shared/src/server";
import {
SdkLogProcessor,
@@ -36,7 +37,6 @@ import {
import {
sendToWorkerIfEnvironmentConfigured,
QueueJobs,
- instrumentSync,
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
import { prisma } from "@langfuse/shared/src/db";
@@ -82,9 +82,9 @@ export default async function handler(
metadata: jsonSchema.nullish(),
});
- const parsedSchema = instrumentSync(
+ const parsedSchema = await instrumentAsync(
{ name: "ingestion-zod-parse-unknown-batch-event" },
- () => batchType.safeParse(req.body),
+ () => batchType.safeParseAsync(req.body),
);
recordIncrement(
@@ -123,32 +123,34 @@ export default async function handler(
const validationErrors: { id: string; error: unknown }[] = [];
const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
- parsedSchema.data.batch.map((event) => {
- const parsed = instrumentSync(
- { name: "ingestion-zod-parse-individual-event" },
- (span) => {
- const parsedBody = ingestionEvent.safeParse(event);
- if (parsedBody.data?.id !== undefined) {
- span.setAttribute("object.id", parsedBody.data.id);
- }
- return parsedBody;
- },
- );
- 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;
- }
- });
+ await Promise.all(
+ parsedSchema.data.batch.map(async (event) => {
+ const parsed = await instrumentAsync(
+ { name: "ingestion-zod-parse-individual-event" },
+ async (span) => {
+ const parsedBody = await ingestionEvent.safeParseAsync(event);
+ if (parsedBody.data?.id !== undefined) {
+ span.setAttribute("object.id", parsedBody.data.id);
+ }
+ return parsedBody;
+ },
+ );
+ 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);