🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(scores): validateAndInflateScore to shared (#2903)
Hassieb Pakzad8dc6ad601ba6
diff --git a/web/src/features/public-api/types/score-configs.ts b/packages/shared/src/features/scores/scoreConfigTypes.tssimilarity index 94%rename from web/src/features/public-api/types/score-configs.tsrename to packages/shared/src/features/scores/scoreConfigTypes.tsindex 07bd269673..c26ad9a6c3 100644--- a/web/src/features/public-api/types/score-configs.ts+++ b/packages/shared/src/features/scores/scoreConfigTypes.ts@@ -1,12 +1,13 @@-import { isPresent } from "@/src/utils/typeChecks";+import { z } from "zod";++import { ScoreConfig as ScoreConfigDbType } from "@prisma/client";++import { isPresent } from "../../utils/typeChecks";import {jsonSchema,paginationMetaResponseZod,paginationZod,- type ScoreConfig as ScoreConfigDbType,-} from "@langfuse/shared";-import { z } from "zod";-import * as Sentry from "@sentry/node";+} from "../../utils/zod";/*** Types to use across codebase@@ -16,7 +17,7 @@ export type ValidatedScoreConfig = z.infer<typeof ValidatedScoreConfigSchema>;const validateCategories = (categories: ConfigCategory[],- ctx: z.RefinementCtx,+ ctx: z.RefinementCtx) => {const uniqueNames = new Set<string>();const uniqueValues = new Set<number>();@@ -93,7 +94,7 @@ const BooleanScoreConfig = z.object({return categories.every((category, index) =>category.label === expectedCategories[index].label &&- category.value === expectedCategories[index].value,+ category.value === expectedCategories[index].value);}),});@@ -122,7 +123,7 @@ const ValidatedScoreConfigSchema = zminValue: z.undefined().nullish(),dataType: z.literal("CATEGORICAL"),categories: Categories.superRefine(validateCategories),- }),+ })),ScoreConfigBase.merge(BooleanScoreConfig),])@@ -149,13 +150,14 @@ const ValidatedScoreConfigSchema = z*/export const filterAndValidateDbScoreConfigList = (scoreConfigs: ScoreConfigDbType[],+ onParseError?: (error: z.ZodError) => void): ValidatedScoreConfig[] =>scoreConfigs.reduce((acc, ts) => {const result = ValidatedScoreConfigSchema.safeParse(ts);if (result.success) {acc.push(result.data);} else {- Sentry.captureException(result.error);+ onParseError?.(result.error);}return acc;}, [] as ValidatedScoreConfig[]);@@ -168,7 +170,7 @@ export const filterAndValidateDbScoreConfigList = (* @throws error if score fails validation*/export const validateDbScoreConfig = (- scoreConfig: ScoreConfigDbType,+ scoreConfig: ScoreConfigDbType): ValidatedScoreConfig => ValidatedScoreConfigSchema.parse(scoreConfig);/**@@ -203,7 +205,7 @@ export const PostScoreConfigBody = zz.object({dataType: z.literal("BOOLEAN"),categories: z.undefined().nullish(),- }),+ })),]).superRefine((data, ctx) => {diff --git a/web/src/features/public-api/types/scores.ts b/packages/shared/src/features/scores/scoreTypes.tssimilarity index 89%rename from web/src/features/public-api/types/scores.tsrename to packages/shared/src/features/scores/scoreTypes.tsindex 8e72029212..b5f8d91599 100644--- a/web/src/features/public-api/types/scores.ts+++ b/packages/shared/src/features/scores/scoreTypes.ts@@ -1,20 +1,19 @@-import * as Sentry from "@sentry/node";+import { z } from "zod";++import { Score } from "@prisma/client";++import { isPresent, stringDateTime } from "../../utils/typeChecks";import {- paginationZod,- paginationMetaResponseZod,NonEmptyString,- type Score,-} from "@langfuse/shared";-import { stringDateTime } from "@langfuse/shared/src/server";--import { z } from "zod";-import { isPresent } from "@/src/utils/typeChecks";-import { Category as ConfigCategory } from "./score-configs";+ paginationMetaResponseZod,+ paginationZod,+} from "../../utils/zod";+import { Category as ConfigCategory } from "./scoreConfigTypes";/*** Types to use across codebase*/-export type APIScore = z.infer<typeof APIScore>;+export type APIScore = z.infer<typeof APIScoreSchema>;/*** Helpers@@ -70,7 +69,7 @@ const BaseScoreBody = z.object({* Objects*/-export const APIScore = z.discriminatedUnion("dataType", [+export const APIScoreSchema = z.discriminatedUnion("dataType", [ScoreBase.merge(NumericData),ScoreBase.merge(CategoricalData),ScoreBase.merge(BooleanData),@@ -84,13 +83,13 @@ export const ScoreBodyWithoutConfig = z.discriminatedUnion("dataType", [z.object({value: z.number(),dataType: z.literal("NUMERIC"),- }),+ })),BaseScoreBody.merge(z.object({value: z.string(),dataType: z.literal("CATEGORICAL"),- }),+ })),BaseScoreBody.merge(z.object({@@ -98,7 +97,7 @@ export const ScoreBodyWithoutConfig = z.discriminatedUnion("dataType", [message: "Value must be either 0 or 1",}),dataType: z.literal("BOOLEAN"),- }),+ })),]);@@ -160,14 +159,17 @@ export const ScorePropsAgainstConfig = z.union([* @param scores* @returns list of validated scores*/-export const filterAndValidateDbScoreList = (scores: Score[]): APIScore[] =>+export const filterAndValidateDbScoreList = (+ scores: Score[],+ onParseError?: (error: z.ZodError) => void+): APIScore[] =>scores.reduce((acc, ts) => {- const result = APIScore.safeParse(ts);+ const result = APIScoreSchema.safeParse(ts);if (result.success) {acc.push(result.data);} else {console.error("Score parsing error: ", result.error);- Sentry.captureException(result.error);+ onParseError?.(result.error);}return acc;}, [] as APIScore[]);@@ -180,7 +182,7 @@ export const filterAndValidateDbScoreList = (scores: Score[]): APIScore[] =>* @throws error if score fails validation*/export const validateDbScore = (score: Score): APIScore =>- APIScore.parse(score);+ APIScoreSchema.parse(score);/*** Endpoints@@ -196,14 +198,14 @@ export const PostScoresBody = z.discriminatedUnion("dataType", [value: z.number(),dataType: z.literal("NUMERIC"),configId: z.string().nullish(),- }),+ })),BaseScoreBody.merge(z.object({value: z.string(),dataType: z.literal("CATEGORICAL"),configId: z.string().nullish(),- }),+ })),BaseScoreBody.merge(z.object({@@ -213,14 +215,14 @@ export const PostScoresBody = z.discriminatedUnion("dataType", [}),dataType: z.literal("BOOLEAN"),configId: z.string().nullish(),- }),+ })),BaseScoreBody.merge(z.object({value: z.union([z.string(), z.number()]),dataType: z.undefined(),configId: z.string().nullish(),- }),+ })),]);@@ -249,12 +251,12 @@ export const GetScoresQuery = z.object({// LegacyGetScoreResponseDataV1 is only used for response of GET /scores list endpointconst LegacyGetScoreResponseDataV1 = z.intersection(- APIScore,+ APIScoreSchema,z.object({trace: z.object({userId: z.string().nullish(),}),- }),+ }));export const GetScoresResponse = z.object({data: z.array(LegacyGetScoreResponseDataV1),@@ -263,6 +265,7 @@ export const GetScoresResponse = z.object({export const legacyFilterAndValidateV1GetScoreList = (scores: unknown[],+ onParseError?: (error: z.ZodError) => void): z.infer<typeof LegacyGetScoreResponseDataV1>[] =>scores.reduce((acc: z.infer<typeof LegacyGetScoreResponseDataV1>[], ts) => {@@ -271,11 +274,11 @@ export const legacyFilterAndValidateV1GetScoreList = (acc.push(result.data);} else {console.error("Score parsing error: ", result.error);- Sentry.captureException(result.error);+ onParseError?.(result.error);}return acc;},- [] as z.infer<typeof LegacyGetScoreResponseDataV1>[],+ [] as z.infer<typeof LegacyGetScoreResponseDataV1>[]);// GET /scores/{scoreId}@@ -283,7 +286,7 @@ export const GetScoreQuery = z.object({scoreId: z.string(),});-export const GetScoreResponse = APIScore;+export const GetScoreResponse = APIScoreSchema;// DELETE /scores/{scoreId}export const DeleteScoreQuery = z.object({diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 1bfb04e839..ea0b2792f5 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -13,6 +13,7 @@ export * from "./observationsTable";export * from "./utils/zod";export * from "./utils/json";export * from "./utils/objects";+export * from "./utils/typeChecks";export { env } from "./env";// llm api@@ -26,6 +27,10 @@ export * from "./features/batchExport/types";// annotationexport * from "./features/annotation/types";+// scores+export * from "./features/scores/scoreConfigTypes";+export * from "./features/scores/scoreTypes";+// export db types onlyexport * from "@prisma/client";export { type DB } from "../prisma/generated/types";diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 098628cc7f..1bf9b2a946 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -13,6 +13,7 @@ export * from "../server/definitions";export * from "../server/ingestion/types";export * from "../server/ingestion/model-match";export * from "../server/ingestion/types";+export * from "../server/ingestion/validateAndInflateScore";export * from "./redis/redis";export * from "./redis/trace-upsert";export * from "./redis/batch-export";diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.tsnew file mode 100644index 0000000000..7c3acd2a78--- /dev/null+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts@@ -0,0 +1,160 @@+import {+ ScoreBodyWithoutConfig,+ ScorePropsAgainstConfig,+ validateDbScoreConfigSafe,+ ValidatedScoreConfig,+} from "../../../src";+import { prisma, Score, ScoreDataType } from "../../db";++import { InvalidRequestError, LangfuseNotFoundError } from "../../errors";++type ValidateAndInflateScoreParams = {+ projectId: string;+ scoreId: string;+ body: any;+};++export async function validateAndInflateScore(+ params: ValidateAndInflateScoreParams+): Promise<Score> {+ const { body, projectId } = params;++ if (body.configId) {+ const config = await prisma.scoreConfig.findFirst({+ where: {+ projectId,+ id: body.configId,+ },+ });++ if (!config || !validateDbScoreConfigSafe(config).success)+ throw new LangfuseNotFoundError(+ "The configId you provided does not match a valid config in this project"+ );++ validateConfigAgainstBody(body, config as ValidatedScoreConfig);++ return inflateScoreBody({+ ...params,+ config: config as ValidatedScoreConfig,+ });+ }++ const validation = ScoreBodyWithoutConfig.safeParse({+ ...body,+ dataType: body.dataType ?? inferDataType(body.value),+ });++ if (!validation.success) {+ throw new InvalidRequestError(+ `Ingested score value type not valid against provided data type. Provide numeric values for numeric and boolean scores, and string values for categorical scores.`+ );+ }++ return inflateScoreBody(params);+}++function inferDataType(value: string | number): ScoreDataType {+ return typeof value === "number"+ ? ScoreDataType.NUMERIC+ : ScoreDataType.CATEGORICAL;+}++function mapStringValueToNumericValue(+ config: ValidatedScoreConfig,+ label: string+): number | null {+ return (+ config.categories?.find((category) => category.label === label)?.value ??+ null+ );+}++function inflateScoreBody(+ params: ValidateAndInflateScoreParams & { config?: ValidatedScoreConfig }+): Score {+ const { body, projectId, scoreId, config } = params;++ const relevantDataType = config?.dataType ?? body.dataType;+ const scoreProps = { ...body, id: scoreId, projectId, source: "API" };++ if (typeof body.value === "number") {+ if (relevantDataType && relevantDataType === ScoreDataType.BOOLEAN) {+ return {+ ...scoreProps,+ value: body.value,+ stringValue: body.value === 1 ? "True" : "False",+ dataType: ScoreDataType.BOOLEAN,+ };+ }++ return {+ ...scoreProps,+ value: body.value,+ dataType: ScoreDataType.NUMERIC,+ };+ }++ return {+ ...scoreProps,+ value: config ? mapStringValueToNumericValue(config, body.value) : null,+ stringValue: body.value,+ dataType: ScoreDataType.CATEGORICAL,+ };+}++function validateConfigAgainstBody(+ body: any,+ config: ValidatedScoreConfig+): void {+ const { maxValue, minValue, categories, dataType: configDataType } = config;++ if (body.dataType && body.dataType !== configDataType) {+ throw new InvalidRequestError(+ `Data type mismatch based on config: expected ${configDataType}, got ${body.dataType}`+ );+ }++ if (config.isArchived) {+ throw new InvalidRequestError(+ "Config is archived and cannot be used to create new scores. Please restore the config first."+ );+ }++ if (config.name !== body.name) {+ throw new InvalidRequestError(+ `Name mismatch based on config: expected ${config.name}, got ${body.name}`+ );+ }++ const relevantDataType = configDataType ?? body.dataType;++ const dataTypeValidation = ScoreBodyWithoutConfig.safeParse({+ ...body,+ dataType: relevantDataType,+ });++ if (!dataTypeValidation.success) {+ throw new InvalidRequestError(+ `Ingested score body not valid against provided config data type.`+ );+ }++ const rangeValidation = ScorePropsAgainstConfig.safeParse({+ value: body.value,+ dataType: relevantDataType,+ ...(maxValue !== null && maxValue !== undefined && { maxValue }),+ ...(minValue !== null && minValue !== undefined && { minValue }),+ ...(categories && { categories }),+ });++ if (!rangeValidation.success) {+ const errorDetails = rangeValidation.error.errors+ .map((error) => `${error.path.join(".")} - ${error.message}`)+ .join(", ");++ throw new InvalidRequestError(+ `Ingested score body not valid against provided config: ${errorDetails}`+ );+ }+}diff --git a/web/src/utils/typeChecks.ts b/packages/shared/src/utils/typeChecks.tssimilarity index 55%rename from web/src/utils/typeChecks.tsrename to packages/shared/src/utils/typeChecks.tsindex 23b91e6046..c4cc71bc0b 100644--- a/web/src/utils/typeChecks.ts+++ b/packages/shared/src/utils/typeChecks.ts@@ -1,2 +1,6 @@+import { z } from "zod";+export const isPresent = <T>(value: T | null | undefined): value is T =>value !== null && value !== undefined && value !== "";++export const stringDateTime = z.string().datetime({ offset: true }).nullish();diff --git a/web/src/__tests__/aggregateScores.clienttest.ts b/web/src/__tests__/aggregateScores.clienttest.tsindex df28df76dc..ed7872f3e4 100644--- a/web/src/__tests__/aggregateScores.clienttest.ts+++ b/web/src/__tests__/aggregateScores.clienttest.ts@@ -1,5 +1,5 @@import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore } from "@langfuse/shared";describe("aggregateScores", () => {it("should return an empty object for an empty array", () => {diff --git a/web/src/__tests__/score-configs.servertest.ts b/web/src/__tests__/score-configs.servertest.tsindex fb52f46026..0660607768 100644--- a/web/src/__tests__/score-configs.servertest.ts+++ b/web/src/__tests__/score-configs.servertest.ts@@ -14,7 +14,7 @@ import {GetScoreConfigResponse,PostScoreConfigResponse,GetScoreConfigsResponse,-} from "@/src/features/public-api/types/score-configs";+} from "@langfuse/shared";const configOne = [{diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.tsindex 90e08877b2..7a15561b52 100644--- a/web/src/__tests__/scores.servertest.ts+++ b/web/src/__tests__/scores.servertest.ts@@ -11,7 +11,7 @@ import {DeleteScoreResponse,GetScoreResponse,GetScoresResponse,-} from "@/src/features/public-api/types/scores";+} from "@langfuse/shared";import { z } from "zod";import { PostTracesV1Response } from "@/src/features/public-api/types/traces";diff --git a/web/src/__tests__/traces.servertest.ts b/web/src/__tests__/traces.servertest.tsindex a0882e20ae..3c41a7ae90 100644--- a/web/src/__tests__/traces.servertest.ts+++ b/web/src/__tests__/traces.servertest.ts@@ -1,18 +1,19 @@/** @jest-environment node */+import { v4 as uuidv4 } from "uuid";+import {makeZodVerifiedAPICall,pruneDatabase,} from "@/src/__tests__/test-utils";import { PostGenerationsV1Response } from "@/src/features/public-api/types/generations";-import { PostScoresResponse } from "@/src/features/public-api/types/scores";import {- GetTraceV1Response,GetTracesV1Response,+ GetTraceV1Response,PostTracesV1Response,} from "@/src/features/public-api/types/traces";+import { PostScoresResponse } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { v4 as uuidv4 } from "uuid";describe("/api/public/traces API Endpoint", () => {beforeEach(async () => await pruneDatabase());@@ -33,7 +34,7 @@ describe("/api/public/traces API Endpoint", () => {release: "1.0.0",version: "2.0.0",},- );+ );const trace = await makeZodVerifiedAPICall(GetTraceV1Response,@@ -64,7 +65,7 @@ describe("/api/public/traces API Endpoint", () => {version: "2.0.0",public: true,},- );+ );const dbTrace1 = await prisma.trace.findFirst({where: {@@ -94,7 +95,7 @@ describe("/api/public/traces API Endpoint", () => {version: "5.0.0",public: false,},- );+ );const dbTrace2 = await prisma.trace.findFirst({where: {@@ -125,7 +126,7 @@ describe("/api/public/traces API Endpoint", () => {id: "trace-1",tags: ["tag-1", "tag-2", "tag-3"],},- );+ );await makeZodVerifiedAPICall(PostTracesV1Response,@@ -135,7 +136,7 @@ describe("/api/public/traces API Endpoint", () => {id: "trace-2",tags: ["tag-1"],},- );+ );await makeZodVerifiedAPICall(PostTracesV1Response,@@ -145,7 +146,7 @@ describe("/api/public/traces API Endpoint", () => {id: "trace-3",tags: ["tag-2", "tag-3"],},- );+ );// multiple tagsconst traces = await makeZodVerifiedAPICall(@@ -206,7 +207,7 @@ describe("/api/public/traces API Endpoint", () => {release: "1.0.0",version: "2.0.0",},- );+ );console.log(traceId);// Simulate observations with costs and latencies@@ -223,7 +224,7 @@ describe("/api/public/traces API Endpoint", () => {startTime: "2021-01-01T00:00:00.000Z",endTime: "2021-01-01T00:10:00.000Z",},- );+ );await makeZodVerifiedAPICall(PostGenerationsV1Response,"POST",@@ -234,7 +235,7 @@ describe("/api/public/traces API Endpoint", () => {startTime: "2021-01-01T00:10:00.000Z",endTime: "2021-01-01T00:20:00.000Z",},- );+ );// Simulate scores on the traceconst scoreId1 = uuidv4();@@ -249,7 +250,7 @@ describe("/api/public/traces API Endpoint", () => {traceId: traceId,comment: "First score",},- );+ );const scoreId2 = uuidv4();await makeZodVerifiedAPICall(PostScoresResponse,@@ -262,7 +263,7 @@ describe("/api/public/traces API Endpoint", () => {traceId: traceId,comment: "Second score",},- );+ );const scoreId3 = uuidv4();await makeZodVerifiedAPICall(PostScoresResponse,@@ -275,7 +276,7 @@ describe("/api/public/traces API Endpoint", () => {traceId: traceId,comment: "Third score",},- );+ );// GET traces// Retrieve the trace with totalCost and latency@@ -334,7 +335,7 @@ describe("/api/public/traces API Endpoint", () => {release: "1.0.0",version: "1.0.0",},- );+ );await makeZodVerifiedAPICall(PostTracesV1Response,@@ -350,7 +351,7 @@ describe("/api/public/traces API Endpoint", () => {release: "1.0.0",version: "1.0.0",},- );+ );// Filter by session IDconst tracesBySessionId = await makeZodVerifiedAPICall(diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex 0108fad22a..5ed92ac85d 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -6,7 +6,7 @@ import {} from "@/src/components/ui/hover-card";import { MessageCircleMore } from "lucide-react";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore } from "@langfuse/shared";import { type LastUserScore } from "@/src/features/scores/lib/types";export const GroupedScoreBadges = <T extends APIScore | LastUserScore>({diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsxindex 5ec98fa780..bcc8b22844 100644--- a/web/src/components/table/use-cases/score-configs.tsx+++ b/web/src/components/table/use-cases/score-configs.tsx@@ -6,7 +6,11 @@ import { api } from "@/src/utils/api";import { type LangfuseColumnDef } from "@/src/components/table/types";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { DataTable } from "@/src/components/table/data-table";-import { type ScoreDataType, type Prisma } from "@langfuse/shared";+import {+ type ScoreDataType,+ type Prisma,+ type ConfigCategory,+} from "@langfuse/shared";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { NumberParam, useQueryParams, withDefault } from "use-query-params";import {@@ -24,7 +28,6 @@ import {PopoverTrigger,} from "@/src/components/ui/popover";import useLocalStorage from "@/src/components/useLocalStorage";-import { type ConfigCategory } from "@/src/features/public-api/types/score-configs";type ScoreConfigTableRow = {id: string;diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex 6c558ce98e..2a1d7f1da0 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -16,9 +16,13 @@ import {scoresTableColsWithOptions,} from "@/src/server/api/definitions/scoresTable";import { api } from "@/src/utils/api";-import { isPresent } from "@/src/utils/typeChecks";+import type { RouterOutput, RouterInput } from "@/src/utils/types";-import type { FilterState, ScoreDataType } from "@langfuse/shared";+import {+ isPresent,+ type FilterState,+ type ScoreDataType,+} from "@langfuse/shared";import { useQueryParams, withDefault, NumberParam } from "use-query-params";export type ScoresTableRow = {diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex 3eb7c70cbd..60f2317f8d 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -1,5 +1,5 @@import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { type ScoreSource } from "@langfuse/shared";+import { type APIScore, type ScoreSource } from "@langfuse/shared";import {Card,CardContent,@@ -22,7 +22,6 @@ import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";-import { type APIScore } from "@/src/features/public-api/types/scores";import useLocalStorage from "@/src/components/useLocalStorage";export const ObservationPreview = (props: {diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsxindex bce0c7ef6b..a7f79e7a5c 100644--- a/web/src/components/trace/ObservationTree.tsx+++ b/web/src/components/trace/ObservationTree.tsx@@ -1,7 +1,6 @@import { type NestedObservation } from "@/src/utils/types";import { cn } from "@/src/utils/tailwind";-import { type Trace, type $Enums } from "@langfuse/shared";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore, type Trace, type $Enums } from "@langfuse/shared";import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { Fragment } from "react";import { type ObservationReturnType } from "@/src/server/api/routers/traces";diff --git a/web/src/components/trace/ScoresPreview.tsx b/web/src/components/trace/ScoresPreview.tsxindex 9b85ea73f5..a0fcf7bbbf 100644--- a/web/src/components/trace/ScoresPreview.tsx+++ b/web/src/components/trace/ScoresPreview.tsx@@ -1,5 +1,5 @@import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore } from "@langfuse/shared";export const ScoresPreview = ({itemScoresBySource,diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex 48af3b65a5..c4d528fe1d 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -1,5 +1,5 @@import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { type Trace, type ScoreSource } from "@langfuse/shared";+import { type APIScore, type Trace, type ScoreSource } from "@langfuse/shared";import {Card,CardContent,@@ -19,7 +19,6 @@ import { withDefault, StringParam, useQueryParam } from "use-query-params";import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";-import { type APIScore } from "@/src/features/public-api/types/scores";import useLocalStorage from "@/src/components/useLocalStorage";export const TracePreview = ({diff --git a/web/src/components/trace/TraceTimelineView.tsx b/web/src/components/trace/TraceTimelineView.tsxindex 92081b5495..c00012b497 100644--- a/web/src/components/trace/TraceTimelineView.tsx+++ b/web/src/components/trace/TraceTimelineView.tsx@@ -1,7 +1,6 @@import { Card } from "@/src/components/ui/card";import { type ObservationReturnType } from "@/src/server/api/routers/traces";-import { type Trace } from "@langfuse/shared";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore, type Trace } from "@langfuse/shared";import React, { useEffect, useMemo, useRef, useState } from "react";import { SimpleTreeView } from "@mui/x-tree-view/SimpleTreeView";diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsxindex b56b5f8474..c512c37a11 100644--- a/web/src/components/trace/index.tsx+++ b/web/src/components/trace/index.tsx@@ -32,7 +32,7 @@ import { DeleteButton } from "@/src/components/deleteButton";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";-import { type APIScore } from "@/src/features/public-api/types/scores";+import { type APIScore } from "@langfuse/shared";export function Trace(props: {observations: Array<ObservationReturnType>;diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex babd99bfcb..07812efcec 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -26,7 +26,7 @@ import {Minimize2,} from "lucide-react";import { api } from "@/src/utils/api";-import { isPresent } from "@/src/utils/typeChecks";+import { isPresent } from "@langfuse/shared";import { BsMarkdown } from "react-icons/bs";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { Skeleton } from "@/src/components/ui/skeleton";diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.tsindex 37610d1a59..3e9917ddbe 100644--- a/web/src/features/datasets/server/dataset-router.ts+++ b/web/src/features/datasets/server/dataset-router.ts@@ -12,10 +12,10 @@ import {import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { DB } from "@/src/server/db";-import { paginationZod } from "@langfuse/shared";-import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";+import { filterAndValidateDbScoreList, paginationZod } from "@langfuse/shared";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import { type ScoreSimplified } from "@/src/features/scores/lib/types";+import * as Sentry from "@sentry/node";export const datasetRouter = createTRPCRouter({allDatasetMeta: protectedProjectProcedure@@ -645,9 +645,14 @@ export const datasetRouter = createTRPCRouter({`,);- const validatedTraceScores = filterAndValidateDbScoreList(traceScores);- const validatedObservationScores =- filterAndValidateDbScoreList(observationScores);+ const validatedTraceScores = filterAndValidateDbScoreList(+ traceScores,+ Sentry.captureException,+ );+ const validatedObservationScores = filterAndValidateDbScoreList(+ observationScores,+ Sentry.captureException,+ );const items = runItems.map((ri) => {return {diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.tsindex 0cec317319..fe1aff12bc 100644--- a/web/src/features/public-api/server/withMiddlewares.ts+++ b/web/src/features/public-api/server/withMiddlewares.ts@@ -1,7 +1,7 @@import { isPrismaException } from "@/src/utils/exceptions";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { type NextApiRequest, type NextApiResponse } from "next";-import { z } from "zod";+import { type ZodError } from "zod";import { BaseError, MethodNotAllowedError } from "@langfuse/shared";import * as Sentry from "@sentry/node";@@ -59,7 +59,8 @@ export function withMiddlewares(handlers: Handlers) {});}- if (error instanceof z.ZodError) {+ // Instanceof check fails here as shared package zod has different instances+ if (isZodError(error)) {return res.status(400).json({message: "Invalid request data",error: error.errors,@@ -75,3 +76,7 @@ export function withMiddlewares(handlers: Handlers) {}};}++export function isZodError(error: any): error is ZodError {+ return error instanceof Object && error.constructor.name === "ZodError";+}diff --git a/web/src/features/public-api/types/traces.ts b/web/src/features/public-api/types/traces.tsindex 73568a61d3..ec1fc276b0 100644--- a/web/src/features/public-api/types/traces.ts+++ b/web/src/features/public-api/types/traces.ts@@ -1,6 +1,6 @@import { APIObservation } from "@/src/features/public-api/types/observations";-import { APIScore } from "@/src/features/public-api/types/scores";import {+ APIScoreSchema,paginationZod,paginationMetaResponseZod,orderBy,@@ -83,6 +83,6 @@ export const GetTraceV1Query = z.object({traceId: z.string(),});export const GetTraceV1Response = APIExtendedTrace.extend({- scores: z.array(APIScore),+ scores: z.array(APIScoreSchema),observations: z.array(APIObservation),}).strict();diff --git a/web/src/features/scores/components/AnnotateDrawer.tsx b/web/src/features/scores/components/AnnotateDrawer.tsxindex d12a634f91..6627cb1372 100644--- a/web/src/features/scores/components/AnnotateDrawer.tsx+++ b/web/src/features/scores/components/AnnotateDrawer.tsx@@ -30,15 +30,14 @@ import {DrawerTrigger,} from "@/src/components/ui/drawer";import {+ type APIScore,+ isPresent,ScoreDataType,CreateAnnotationScoreData,UpdateAnnotationScoreData,-} from "@langfuse/shared";-import { type APIScore } from "@/src/features/public-api/types/scores";-import {type ValidatedScoreConfig,type ConfigCategory,-} from "@/src/features/public-api/types/score-configs";+} from "@langfuse/shared";import { z } from "zod";import { Input } from "@/src/components/ui/input";import {@@ -72,7 +71,6 @@ import { useRouter } from "next/router";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { cn } from "@/src/utils/tailwind";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { isPresent } from "@/src/utils/typeChecks";import { getScoreDataTypeIcon } from "@/src/features/scores/components/ScoreDetailColumnHelpers";const AnnotationScoreDataSchema = z.object({diff --git a/web/src/features/scores/components/CreateScoreConfigButton.tsx b/web/src/features/scores/components/CreateScoreConfigButton.tsxindex a0c838540e..4c0e973652 100644--- a/web/src/features/scores/components/CreateScoreConfigButton.tsx+++ b/web/src/features/scores/components/CreateScoreConfigButton.tsx@@ -20,7 +20,7 @@ import {FormMessage,} from "@/src/components/ui/form";import { Input } from "@/src/components/ui/input";-import { ScoreDataType, availableDataTypes } from "@langfuse/shared";+import { isPresent, ScoreDataType, availableDataTypes } from "@langfuse/shared";import {Select,SelectContent,@@ -35,7 +35,6 @@ import {isCategoricalDataType,isNumericDataType,} from "@/src/features/scores/lib/helpers";-import { isPresent } from "@/src/utils/typeChecks";import DocPopup from "@/src/components/layouts/doc-popup";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { z } from "zod";diff --git a/web/src/features/scores/components/ScoreConfigDetails.tsx b/web/src/features/scores/components/ScoreConfigDetails.tsxindex b3d18aefaf..5831187185 100644--- a/web/src/features/scores/components/ScoreConfigDetails.tsx+++ b/web/src/features/scores/components/ScoreConfigDetails.tsx@@ -1,6 +1,5 @@import { isNumericDataType } from "@/src/features/scores/lib/helpers";-import { type ValidatedScoreConfig } from "@/src/features/public-api/types/score-configs";-import { isPresent } from "@/src/utils/typeChecks";+import { isPresent, type ValidatedScoreConfig } from "@langfuse/shared";import React from "react";export function ScoreConfigDetails({diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.tsindex 66619b3ef0..b83d85a70e 100644--- a/web/src/features/scores/lib/aggregateScores.ts+++ b/web/src/features/scores/lib/aggregateScores.ts@@ -2,8 +2,11 @@ import {type ScoreAggregate,type ScoreSimplified,} from "@/src/features/scores/lib/types";-import { type APIScore } from "@/src/features/public-api/types/scores";-import { type ScoreSource, type ScoreDataType } from "@langfuse/shared";+import {+ type APIScore,+ type ScoreSource,+ type ScoreDataType,+} from "@langfuse/shared";export const composeAggregateScoreKey = ({name,diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.tsindex fa5f21fe52..6f36d00fce 100644--- a/web/src/features/scores/lib/getDefaultScoreData.ts+++ b/web/src/features/scores/lib/getDefaultScoreData.ts@@ -1,6 +1,5 @@import { ScoreSource } from "@langfuse/shared";-import { type APIScore } from "@/src/features/public-api/types/scores";-import { type ValidatedScoreConfig } from "@/src/features/public-api/types/score-configs";+import { type APIScore, type ValidatedScoreConfig } from "@langfuse/shared";export const getDefaultScoreData = ({scores,diff --git a/web/src/pages/api/public/score-configs/[configId].ts b/web/src/pages/api/public/score-configs/[configId].tsindex 94425328e7..88fbd2d4be 100644--- a/web/src/pages/api/public/score-configs/[configId].ts+++ b/web/src/pages/api/public/score-configs/[configId].ts@@ -1,11 +1,12 @@-import { prisma } from "@langfuse/shared/src/db";-import { InternalServerError, LangfuseNotFoundError } from "@langfuse/shared";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {GetScoreConfigQuery,GetScoreConfigResponse,-} from "@/src/features/public-api/types/score-configs";+ InternalServerError,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";import * as Sentry from "@sentry/node";export default withMiddlewares({diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.tsindex 1ed3550999..c8ffca6e3c 100644--- a/web/src/pages/api/public/score-configs/index.ts+++ b/web/src/pages/api/public/score-configs/index.ts@@ -1,17 +1,19 @@-import { type z } from "zod";-import { Prisma, prisma } from "@langfuse/shared/src/db";-import { isBooleanDataType } from "@/src/features/scores/lib/helpers";import { v4 } from "uuid";+import { type z } from "zod";+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { isBooleanDataType } from "@/src/features/scores/lib/helpers";import {- PostScoreConfigResponse,- GetScoreConfigsResponse,+ filterAndValidateDbScoreConfigList,GetScoreConfigsQuery,+ GetScoreConfigsResponse,PostScoreConfigBody,+ PostScoreConfigResponse,validateDbScoreConfig,- filterAndValidateDbScoreConfigList,-} from "@/src/features/public-api/types/score-configs";+} from "@langfuse/shared";+import { Prisma, prisma } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {if (isBooleanDataType(body.dataType)) {@@ -63,7 +65,10 @@ export default withMiddlewares({skip: (page - 1) * limit,});- const configs = filterAndValidateDbScoreConfigList(rawConfigs);+ const configs = filterAndValidateDbScoreConfigList(+ rawConfigs,+ Sentry.captureException,+ );const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(Prisma.sql`diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].tsindex e274203010..948a056d26 100644--- a/web/src/pages/api/public/scores/[scoreId].ts+++ b/web/src/pages/api/public/scores/[scoreId].ts@@ -1,14 +1,15 @@-import { prisma } from "@langfuse/shared/src/db";-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import * as Sentry from "@sentry/node";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {DeleteScoreQuery,DeleteScoreResponse,GetScoreQuery,GetScoreResponse,-} from "@/src/features/public-api/types/scores";-import { InternalServerError, LangfuseNotFoundError } from "@langfuse/shared";+ InternalServerError,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";export default withMiddlewares({GET: createAuthedAPIRoute({diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 44e9265196..abe15251d9 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -1,20 +1,20 @@-import { prisma } from "@langfuse/shared/src/db";-import { Prisma } from "@langfuse/shared/src/db";-import { eventTypes, ingestionBatchEvent } from "@langfuse/shared/src/server";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 { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {GetScoresQuery,GetScoresResponse,+ legacyFilterAndValidateV1GetScoreList,PostScoresBody,PostScoresResponse,- legacyFilterAndValidateV1GetScoreList,-} from "@/src/features/public-api/types/scores";+} from "@langfuse/shared";+import { prisma, Prisma } from "@langfuse/shared/src/db";+import { eventTypes, ingestionBatchEvent } from "@langfuse/shared/src/server";export default withMiddlewares({POST: createAuthedAPIRoute({diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 0b901f7bd5..491cad416b 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -1,13 +1,16 @@-import { prisma } from "@langfuse/shared/src/db";+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { transformDbToApiObservation } from "@/src/features/public-api/types/observations";import {GetTraceV1Query,GetTraceV1Response,} from "@/src/features/public-api/types/traces";-import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";-import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";-import { transformDbToApiObservation } from "@/src/features/public-api/types/observations";-import { LangfuseNotFoundError } from "@langfuse/shared";+import {+ filterAndValidateDbScoreList,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";export default withMiddlewares({GET: createAuthedAPIRoute({@@ -48,7 +51,10 @@ export default withMiddlewares({]);const outObservations = observations.map(transformDbToApiObservation);- const validatedScores = filterAndValidateDbScoreList(scores);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ Sentry.captureException,+ );const { duration, ...restOfTrace } = trace;diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.tsindex ad5d15e308..92a7e36b38 100644--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts@@ -1,14 +1,15 @@+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import {datetimeFilterToPrismaSql,- tableColumnsToSqlFilterAndPrefix,+ filterAndValidateDbScoreList,observationsTableCols,+ orderByToPrismaSql,+ tableColumnsToSqlFilterAndPrefix,} from "@langfuse/shared";-import { orderByToPrismaSql } from "@langfuse/shared";-import { type ObservationView, Prisma } from "@langfuse/shared/src/db";-import { prisma } from "@langfuse/shared/src/db";+import { type ObservationView, Prisma, prisma } from "@langfuse/shared/src/db";+import { type GetAllGenerationsInput } from "../getAllQuery";-import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";-import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import * as Sentry from "@sentry/node";type AdditionalObservationFields = {traceName: string | null;@@ -150,7 +151,10 @@ export async function getAllGenerations({},},});- const validatedScores = filterAndValidateDbScoreList(scores);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ Sentry.captureException,+ );const fullGenerations = generations.map((generation) => {const filteredScores = aggregateScores(diff --git a/web/src/server/api/routers/scoreConfigs.ts b/web/src/server/api/routers/scoreConfigs.tsindex a29ce52f4c..f4b29ce0db 100644--- a/web/src/server/api/routers/scoreConfigs.ts+++ b/web/src/server/api/routers/scoreConfigs.ts@@ -1,17 +1,18 @@+import { z } from "zod";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { optionalPaginationZod } from "@langfuse/shared";--import { ScoreDataType } from "@langfuse/shared/src/db";-import { z } from "zod";import {- filterAndValidateDbScoreConfigList,Category,+ filterAndValidateDbScoreConfigList,+ optionalPaginationZod,validateDbScoreConfig,-} from "@/src/features/public-api/types/score-configs";+} from "@langfuse/shared";+import { ScoreDataType } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";const ScoreConfigAllInput = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -50,7 +51,10 @@ export const scoreConfigsRouter = createTRPCRouter({});return {- configs: filterAndValidateDbScoreConfigList(configs),+ configs: filterAndValidateDbScoreConfigList(+ configs,+ Sentry.captureException,+ ),totalCount: configsCount,};}),diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 2316b9b007..a3993aadc5 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -1,31 +1,29 @@+import { addMinutes } from "date-fns";import { z } from "zod";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";+import {+ type ScoreOptions,+ scoresTableCols,+} from "@/src/server/api/definitions/scoresTable";import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { Prisma, type Score } from "@langfuse/shared/src/db";+import { tableDateRangeAggregationSettings } from "@/src/utils/date-range-utils";import {CreateAnnotationScoreData,- UpdateAnnotationScoreData,+ orderBy,+ orderByToPrismaSql,paginationZod,-} from "@langfuse/shared";-import { singleFilter } from "@langfuse/shared";-import {+ singleFilter,tableColumnsToSqlFilterAndPrefix,- orderByToPrismaSql,+ UpdateAnnotationScoreData,+ validateDbScore,} from "@langfuse/shared";-import {- type ScoreOptions,- scoresTableCols,-} from "@/src/server/api/definitions/scoresTable";-import { orderBy } from "@langfuse/shared";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { validateDbScore } from "@/src/features/public-api/types/scores";-import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";-import { tableDateRangeAggregationSettings } from "@/src/utils/date-range-utils";-import { addMinutes } from "date-fns";+import { Prisma, type Score } from "@langfuse/shared/src/db";const ScoreFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedurediff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 7312e40b0e..d8cbad9cc4 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -1,24 +1,25 @@import { z } from "zod";++import { auditLog } from "@/src/features/audit-logs/auditLog";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,- protectedProjectProcedure,protectedGetSessionProcedure,+ protectedProjectProcedure,} from "@/src/server/api/trpc";import {- singleFilter,- type SessionOptions,+ filterAndValidateDbScoreList,getSessionTableSQL,+ orderBy,+ paginationZod,+ type SessionOptions,+ singleFilter,} from "@langfuse/shared";import { Prisma } from "@langfuse/shared/src/db";-import { paginationZod } from "@langfuse/shared";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-+import * as Sentry from "@sentry/node";import { TRPCError } from "@trpc/server";-import { orderBy } from "@langfuse/shared";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import type Decimal from "decimal.js";-import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";+import type Decimal from "decimal.js";const SessionFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedurefilter: z.array(singleFilter).nullable(),@@ -138,7 +139,10 @@ export const sessionRouter = createTRPCRouter({},});- const validatedScores = filterAndValidateDbScoreList(scores);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ Sentry.captureException,+ );const totalCostQuery = Prisma.sql`SELECTdiff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex b89c5183c9..c4ec3446ad 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -1,33 +1,36 @@import { z } from "zod";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";import {createTRPCRouter,protectedGetTraceProcedure,protectedProjectProcedure,} from "@/src/server/api/trpc";-import {- Prisma,- type Trace,- type ObservationView,- type ObservationLevel,-} from "@langfuse/shared/src/db";-import { paginationZod, timeFilter } from "@langfuse/shared";-import { type TraceOptions, singleFilter } from "@langfuse/shared";-import { tracesTableCols } from "@langfuse/shared";+import { instrumentAsync } from "@/src/utils/instrumentation";import {datetimeFilterToPrismaSql,+ filterAndValidateDbScoreList,+ orderBy,+ orderByToPrismaSql,+ paginationZod,+ singleFilter,tableColumnsToSqlFilterAndPrefix,+ timeFilter,+ type TraceOptions,+ tracesTableCols,} from "@langfuse/shared";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ type ObservationLevel,+ type ObservationView,+ Prisma,+ type Trace,+} from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";import { TRPCError } from "@trpc/server";-import { orderBy } from "@langfuse/shared";-import { orderByToPrismaSql } from "@langfuse/shared";-import { instrumentAsync } from "@/src/utils/instrumentation";-import type Decimal from "decimal.js";-import { auditLog } from "@/src/features/audit-logs/auditLog";-import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";-import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import type Decimal from "decimal.js";const TraceFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProceduresearchQuery: z.string().nullable(),@@ -163,7 +166,10 @@ export const traceRouter = createTRPCRouter({},},});- const validatedScores = filterAndValidateDbScoreList(scores);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ Sentry.captureException,+ );const totalTraceCount = totalTraces[0]?.count;return {@@ -321,7 +327,10 @@ export const traceRouter = createTRPCRouter({projectId: trace.projectId,},});- const validatedScores = filterAndValidateDbScoreList(scores);+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ Sentry.captureException,+ );const obsStartTimes = observations.map((o) => o.startTime)diff --git a/web/src/server/api/services/EventProcessor.ts b/web/src/server/api/services/EventProcessor.tsindex 4f07841571..ec93b4cf7f 100644--- a/web/src/server/api/services/EventProcessor.ts+++ b/web/src/server/api/services/EventProcessor.ts@@ -1,6 +1,5 @@import { tokenCount } from "@/src/features/ingest/usage";import { type ApiAccessScope } from "@/src/features/public-api/server/types";-import { LangfuseNotFoundError, InvalidRequestError } from "@langfuse/shared";import {type legacyObservationCreateEvent,eventTypes,@@ -8,8 +7,9 @@ import {type generationCreateEvent,type sdkLogEvent,type traceEvent,+ validateAndInflateScore,} from "@langfuse/shared/src/server";-import { ScoreDataType, prisma } from "@langfuse/shared/src/db";+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";@@ -26,14 +26,6 @@ import { jsonSchema } from "@langfuse/shared";import { ForbiddenError } from "@langfuse/shared";import { instrument } from "@/src/utils/instrumentation";import Decimal from "decimal.js";-import {- ScoreBodyWithoutConfig,- ScorePropsAgainstConfig,-} from "@/src/features/public-api/types/scores";-import {- validateDbScoreConfigSafe,- type ValidatedScoreConfig,-} from "@/src/features/public-api/types/score-configs";export interface EventProcessor {process(@@ -547,145 +539,6 @@ export class ScoreProcessor implements EventProcessor {this.event = event;}- static inferDataType(value: string | number): ScoreDataType {- return typeof value === "number"- ? ScoreDataType.NUMERIC- : ScoreDataType.CATEGORICAL;- }-- static mapStringValueToNumericValue(- config: ValidatedScoreConfig,- label: string,- ): number | null {- return (- config.categories?.find((category) => category.label === label)?.value ??- null- );- }-- static inflateScoreBody(- body: any,- id: string,- projectId: string,- config?: ValidatedScoreConfig,- ): Score {- const relevantDataType = config?.dataType ?? body.dataType;- const scoreProps = { ...body, id, projectId, source: "API" };-- if (typeof body.value === "number") {- if (relevantDataType && relevantDataType === ScoreDataType.BOOLEAN) {- return {- ...scoreProps,- value: body.value,- stringValue: body.value === 1 ? "True" : "False",- dataType: ScoreDataType.BOOLEAN,- };- }-- return {- ...scoreProps,- value: body.value,- dataType: ScoreDataType.NUMERIC,- };- }- return {- ...scoreProps,- value: config- ? ScoreProcessor.mapStringValueToNumericValue(config, body.value)- : null,- stringValue: body.value,- dataType: ScoreDataType.CATEGORICAL,- };- }-- validateConfigAgainstBody(body: any, config: ValidatedScoreConfig): void {- const { maxValue, minValue, categories, dataType: configDataType } = config;- if (body.dataType && body.dataType !== configDataType) {- throw new InvalidRequestError(- `Data type mismatch based on config: expected ${configDataType}, got ${body.dataType}`,- );- }-- if (config.isArchived) {- throw new InvalidRequestError(- "Config is archived and cannot be used to create new scores. Please restore the config first.",- );- }-- if (config.name !== body.name) {- throw new InvalidRequestError(- `Name mismatch based on config: expected ${config.name}, got ${body.name}`,- );- }-- const relevantDataType = configDataType ?? body.dataType;-- const dataTypeValidation = ScoreBodyWithoutConfig.safeParse({- ...body,- dataType: relevantDataType,- });- if (!dataTypeValidation.success) {- throw new InvalidRequestError(- `Ingested score body not valid against provided config data type.`,- );- }-- const rangeValidation = ScorePropsAgainstConfig.safeParse({- value: body.value,- dataType: relevantDataType,- ...(maxValue !== null && maxValue !== undefined && { maxValue }),- ...(minValue !== null && minValue !== undefined && { minValue }),- ...(categories && { categories }),- });- if (!rangeValidation.success) {- const errorDetails = rangeValidation.error.errors- .map((error) => `${error.path.join(".")} - ${error.message}`)- .join(", ");- throw new InvalidRequestError(- `Ingested score body not valid against provided config: ${errorDetails}`,- );- }- }-- async validateAndInflate(- body: any,- id: string,- projectId: string,- ): Promise<Score> {- if (body.configId) {- const config = await prisma.scoreConfig.findFirst({- where: {- projectId,- id: body.configId,- },- });-- if (!config || !validateDbScoreConfigSafe(config).success)- throw new LangfuseNotFoundError(- "The configId you provided does not match a valid config in this project",- );-- this.validateConfigAgainstBody(body, config as ValidatedScoreConfig);- return ScoreProcessor.inflateScoreBody(- body,- id,- projectId,- config as ValidatedScoreConfig,- );- } else {- const validation = ScoreBodyWithoutConfig.safeParse({- ...body,- dataType: body.dataType ?? ScoreProcessor.inferDataType(body.value),- });- if (!validation.success) {- throw new InvalidRequestError(- `Ingested score value type not valid against provided data type. Provide numeric values for numeric and boolean scores, and string values for categorical scores.`,- );- }- return ScoreProcessor.inflateScoreBody(body, id, projectId);- }- }-async process(apiScope: ApiAccessScope,): Promise<Trace | Observation | Score> {@@ -712,11 +565,11 @@ export class ScoreProcessor implements EventProcessor {);}- const validatedScore = await this.validateAndInflate(+ const validatedScore = await validateAndInflateScore({body,- id,- apiScope.projectId,- );+ scoreId: id,+ projectId: apiScope.projectId,+ });return await prisma.score.upsert({where: {diff --git a/worker/src/scripts/verifyClickhouseRecords.ts b/worker/src/scripts/verifyClickhouseRecords.tsindex 9503198f26..4d5636b26c 100644--- a/worker/src/scripts/verifyClickhouseRecords.ts+++ b/worker/src/scripts/verifyClickhouseRecords.ts@@ -8,20 +8,23 @@ import {// Constantsconst LIMIT = 50;-const ITERATIONS = 10;-const DATE_START = new Date("2024-08-09T08:20:00.000Z");-const DATE_END = new Date(Date.now() - 1000 * 60 * 60); // 1 hour ago+const ITERATIONS = 20;+const DATE_START = new Date("2024-08-13T10:30:00.000Z");+const DATE_END = new Date(); //new Date(Date.now() - 1000 * 60 * 60); // 1 hour ago-const TABLE_SAMPLE_RATE = 0.003;+const TABLE_SAMPLE_RATE = 10;async function main() {const failedObservationList: string[] = [];const failedTraceList: string[] = [];+ const failedScoreList: string[] = [];const checkedObservationSet = new Set<string>();const checkedTraceSet = new Set<string>();+ const checkedScoreSet = new Set<string>();let totalObservationCount = 0;let totalTraceCount = 0;+ let totalScoreCount = 0;let currentIteration = 0;while (currentIteration < ITERATIONS) {@@ -53,11 +56,7 @@ async function main() {totalObservationCount += 1;checkedObservationSet.add(id);- await verifyClickhouseObservation(obs).catch((e) => {- throw new Error(- `Failed to verify observation ${id}: ${e.message}, ${e.stack}`- );- });+ await verifyClickhouseObservation(obs);}));@@ -76,7 +75,7 @@ async function main() {// Check tracesconst randomTraces = await prisma.$queryRaw<unknown[]>(Prisma.sql`- SELECT *+ SELECT *FROM traces TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})WHEREtimestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'@@ -97,11 +96,7 @@ async function main() {totalTraceCount += 1;checkedTraceSet.add(id);- await verifyClickhouseTrace(trace).catch((e) => {- throw new Error(- `Failed to verify trace ${id}: ${e.message}, ${e.stack}`- );- });+ await verifyClickhouseTrace(trace);}));@@ -117,10 +112,53 @@ async function main() {console.error(e);}+ // Check scores+ const randomScores = await prisma.$queryRaw<unknown[]>(+ Prisma.sql`+ SELECT *+ FROM scores TABLESAMPLE SYSTEM(${TABLE_SAMPLE_RATE})+ WHERE+ timestamp > ${DATE_START}::TIMESTAMP WITH time zone at time zone 'UTC'+ AND timestamp < ${DATE_END}::TIMESTAMP WITH time zone at time zone 'UTC'+ AND source = 'API'+ LIMIT ${LIMIT}+ `+ );++ console.log(`Verifying ${randomScores.length} scores...`);++ try {+ const results = await Promise.allSettled(+ randomScores.map(async (score) => {+ const id = (score as any).id;+ if (checkedScoreSet.has(id)) {+ return;+ }+ totalScoreCount += 1;+ checkedScoreSet.add(id);++ await verifyClickhouseScore(score);+ })+ );++ results.forEach((result, i) => {+ if (result.status === "rejected") {+ const message = `[${i}] ` + result.reason;+ failedScoreList.push(message);++ console.error(message);+ }+ });+ } catch (e) {+ console.error(e);+ }+currentIteration++;}console.log(`Total observations verified: ${totalObservationCount}`);+ console.log(`Total traces verified: ${totalTraceCount}`);+ console.log(`Total scores verified: ${totalScoreCount}`);if (failedObservationList.length > 0) {await Promise.all([@@ -149,6 +187,18 @@ async function main() {} else {console.log(`All ${totalTraceCount} traces verified successfully`);}++ if (failedScoreList.length > 0) {+ writeFile(+ `src/scripts/output/${new Date().toISOString()}_failedScores.txt`,+ failedScoreList.join("\n")+ ),+ console.error(+ `Failed to verify ${failedScoreList.length} out of ${totalScoreCount} scores`+ );+ } else {+ console.log(`All ${totalScoreCount} scores verified successfully`);+ }}main().then(() => {@@ -175,7 +225,7 @@ async function verifyClickhouseObservation(postgresObservation: any) {pgValue: any;chValue: any;}) =>- `[${projectId}-observation-${observationId}] Field ${params.key} does not match between Postgres and Clickhouse: \n Postgres: ${JSON.stringify(params.pgValue)} \n Clickhouse: ${JSON.stringify(params.chValue)}`;+ `[${projectId}-observation-${observationId}] Mismatch between Postgres and Clickhouse:\n${JSON.stringify({ key: params.key, pg: params.pgValue, ch: params.chValue }, null, 2)}`;for (const key in postgresObservation) {const pgValue = postgresObservation[key];@@ -508,7 +558,7 @@ async function verifyClickhouseTrace(postgresTrace: any) {pgValue: any;chValue: any;}) =>- `[${projectId}-trace-${traceId}] Field ${params.key} does not match between Postgres and Clickhouse: \n Postgres: ${JSON.stringify(params.pgValue)} \n Clickhouse: ${JSON.stringify(params.chValue)}`;+ `[${projectId}-trace-${traceId}] Mismatch between Postgres and Clickhouse:\n${JSON.stringify({ key: params.key, pg: params.pgValue, ch: params.chValue }, null, 2)}`;for (const key of Object.keys(postgresTrace)) {const pgValue = postgresTrace[key];@@ -602,7 +652,9 @@ async function verifyClickhouseTrace(postgresTrace: any) {JSON.stringify(parsedPgValue, Object.keys(parsedPgValue).sort()) !==JSON.stringify(parsedChValue,- Object.keys(parsedChValue as any).sort()+ parsedChValue instanceof Object+ ? Object.keys(parsedChValue as any).sort()+ : undefined)) {throw new Error(@@ -622,3 +674,75 @@ async function verifyClickhouseTrace(postgresTrace: any) {}}}++async function verifyClickhouseScore(postgresScore: any) {+ const { id: scoreId, project_id: projectId } = postgresScore;++ const clickhouseResult = await clickhouseClient.query({+ query: `SELECT * FROM scores WHERE project_id = '${projectId}' AND id = '${scoreId}' ORDER BY updated_at DESC LIMIT 1`,+ format: "JSONEachRow",+ });++ const clickhouseScore = (await clickhouseResult.json())[0];+ if (!clickhouseScore) {+ throw new Error(+ `Score ${scoreId} not found in Clickhouse for project ${projectId}`+ );+ }++ const getErrorMessage = (params: {+ key: string;+ pgValue: any;+ chValue: any;+ }) =>+ `[${projectId}-score-${scoreId}] Mismatch between Postgres and Clickhouse:\n${JSON.stringify({ key: params.key, pg: params.pgValue, ch: params.chValue }, null, 2)}`;++ for (const key of Object.keys(postgresScore)) {+ const pgValue = postgresScore[key];+ const chValue = (clickhouseScore as any)[key];++ switch (key) {+ // Different by nature+ case "created_at":+ case "updated_at":+ continue;++ // Same in PG as in CH+ case "id":+ case "name":+ case "project_id":+ case "value":+ case "observation_id":+ case "trace_id":+ case "comment":+ case "source":+ case "author_user_id":+ case "config_id":+ case "string_value":+ case "data_type": {+ if (pgValue && pgValue !== chValue) {+ throw new Error(getErrorMessage({ key, pgValue, chValue }));+ }++ break;+ }++ // timestamp cannot be overwritten in CH, so they are allowed to be different+ case "timestamp": {+ if (+ pgValue &&+ chValue &&+ typeof pgValue.toISOString() !==+ typeof clickhouseStringDateSchema.parse(chValue)+ ) {+ throw new Error(getErrorMessage({ key, pgValue, chValue }));+ }++ break;+ }++ default:+ throw Error("Unhandled observation key: " + key);+ }+ }+}diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 4b2fbe310e..da4f4bd186 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -26,6 +26,7 @@ import {TraceRecordInsertType,traceRecordReadSchema,ClickhouseClientType,+ validateAndInflateScore,} from "@langfuse/shared/src/server";import { tokenCount } from "../../features/tokenisation/usage";@@ -158,12 +159,11 @@ export class IngestionService {observationEventList: eventList as ObservationEvent[],});case EntityType.Score: {- return; // TODO: refactor score validations and enable processing again- // return await this.processScoreEventList({- // projectId,- // entityId,- // scoreEventList: eventList as ScoreEventType[],- // });+ return await this.processScoreEventList({+ projectId,+ entityId,+ scoreEventList: eventList as ScoreEventType[],+ });}}}@@ -243,21 +243,30 @@ export class IngestionService {const timeSortedEvents =IngestionService.toTimeSortedEventList(scoreEventList);- const scoreRecords: ScoreRecordInsertType[] = timeSortedEvents.map(- (score) => ({- id: entityId,- project_id: projectId,- timestamp: this.getMillisecondTimestamp(score.timestamp),- name: score.body.name,- value: score.body.value,- source: "API",- trace_id: score.body.traceId,- data_type: score.body.dataType,- observation_id: score.body.observationId ?? null,- created_at: Date.now(),- updated_at: Date.now(),- })- );+ const scoreRecordPromises: Promise<ScoreRecordInsertType>[] =+ timeSortedEvents.map(async (scoreEvent) => {+ const validatedScore = await validateAndInflateScore({+ body: scoreEvent.body,+ scoreId: entityId,+ projectId,+ });++ return {+ id: entityId,+ project_id: projectId,+ timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),+ name: validatedScore.name,+ value: validatedScore.value,+ source: validatedScore.source,+ trace_id: validatedScore.traceId,+ data_type: validatedScore.dataType,+ observation_id: validatedScore.observationId,+ created_at: Date.now(),+ updated_at: Date.now(),+ };+ });++ const scoreRecords = await Promise.all(scoreRecordPromises);const finalScoreRecord: ScoreRecordInsertType =await this.mergeScoreRecords({