Skip to content

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

feat(score-configs): support mutability (#9218)

marliessophie9b8868ac9779
diff --git a/fern/apis/server/definition/score-configs.yml b/fern/apis/server/definition/score-configs.yml
index d1c021790a..bfa31ecf58 100644
--- a/fern/apis/server/definition/score-configs.yml
+++ b/fern/apis/server/definition/score-configs.yml
@@ -35,6 +35,18 @@ service:
type: string
docs: The unique langfuse identifier of a score config
response: commons.ScoreConfig
+
+ update:
+ docs: Update a score config
+ method: PATCH
+ path: /score-configs/{configId}
+ path-parameters:
+ configId:
+ type: string
+ docs: The unique langfuse identifier of a score config
+ request: UpdateScoreConfigRequest
+ response: commons.ScoreConfig
+
types:
ScoreConfigs:
properties:
@@ -56,3 +68,23 @@ types:
description:
type: optional<string>
docs: Description is shown across the Langfuse UI and can be used to e.g. explain the config categories in detail, why a numeric range was set, or provide additional context on config name or usage
+ UpdateScoreConfigRequest:
+ properties:
+ isArchived:
+ type: optional<boolean>
+ docs: The status of the score config showing if it is archived or not
+ name:
+ type: optional<string>
+ docs: The name of the score config
+ categories:
+ type: optional<list<commons.ConfigCategory>>
+ docs: Configure custom categories for categorical scores. Pass a list of objects with `label` and `value` properties. Categories are autogenerated for boolean configs and cannot be passed
+ minValue:
+ type: optional<double>
+ docs: Configure a minimum value for numerical scores. If not set, the minimum value defaults to -∞
+ maxValue:
+ type: optional<double>
+ docs: Configure a maximum value for numerical scores. If not set, the maximum value defaults to +∞
+ description:
+ type: optional<string>
+ docs: Description is shown across the Langfuse UI and can be used to e.g. explain the config categories in detail, why a numeric range was set, or provide additional context on config name or usage
diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.ts
index a1468309fe..52ae26e56b 100644
--- a/packages/shared/scripts/seeder/seed-postgres.ts
+++ b/packages/shared/scripts/seeder/seed-postgres.ts
@@ -8,6 +8,7 @@ import {
JobExecutionStatus,
PrismaClient,
type Project,
+ ScoreConfigCategoryDomain,
ScoreDataType,
} from "../../src/index";
import { getDisplaySecretKey, hashSecretKey, logger } from "../../src/server";
@@ -29,11 +30,6 @@ import {
generateEvalTraceId,
} from "./utils/seed-helpers";
-type ConfigCategory = {
- label: string;
- value: number;
-};
-
const options = {
environment: { type: "string" },
} as const;
@@ -746,7 +742,8 @@ async function generateConfigsForProject(projects: Project[]) {
{
name: string;
id: string;
- categories: ConfigCategory[] | null;
+ dataType: ScoreDataType;
+ categories: ScoreConfigCategoryDomain[] | null;
}[]
> = new Map();
@@ -795,7 +792,8 @@ async function generateConfigs(project: Project) {
const configNameAndId: {
name: string;
id: string;
- categories: ConfigCategory[] | null;
+ dataType: ScoreDataType;
+ categories: ScoreConfigCategoryDomain[] | null;
}[] = [];
const configs = [
@@ -856,6 +854,7 @@ async function generateConfigs(project: Project) {
configNameAndId.push({
name: config.name,
id: config.id,
+ dataType: config.dataType,
categories: config.categories ?? null,
});
}
@@ -870,7 +869,8 @@ async function generateQueuesForProject(
{
name: string;
id: string;
- categories: ConfigCategory[] | null;
+ dataType: ScoreDataType;
+ categories: ScoreConfigCategoryDomain[] | null;
}[]
>,
) {
@@ -893,7 +893,8 @@ async function generateQueues(
configIdsAndNames: {
name: string;
id: string;
- categories: ConfigCategory[] | null;
+ dataType: ScoreDataType;
+ categories: ScoreConfigCategoryDomain[] | null;
}[],
) {
const queue = {
diff --git a/packages/shared/src/domain/score-configs.ts b/packages/shared/src/domain/score-configs.ts
new file mode 100644
index 0000000000..48563cce67
--- /dev/null
+++ b/packages/shared/src/domain/score-configs.ts
@@ -0,0 +1,121 @@
+import { z } from "zod/v4";
+import { isPresent } from "../utils/typeChecks";
+
+// Category type, used for categorical and boolean configs
+export const ScoreConfigCategory = z.object({
+ label: z.string().min(1),
+ value: z.number(),
+});
+
+// Numeric config fields
+export const NumericConfigFields = z.object({
+ maxValue: z.number().nullish(),
+ minValue: z.number().nullish(),
+ dataType: z.literal("NUMERIC"),
+ categories: z.undefined().nullish(),
+});
+
+// Boolean config fields
+export const BooleanConfigFields = z.object({
+ dataType: z.literal("BOOLEAN"),
+ maxValue: z.number().nullish(),
+ minValue: z.number().nullish(),
+ categories: z
+ .array(ScoreConfigCategory)
+ .length(2, "Boolean data type must have exactly 2 categories.")
+ .refine((categories) => {
+ const expectedCategories = [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ];
+ return categories.every(
+ (category, index) =>
+ category.label === expectedCategories[index].label &&
+ category.value === expectedCategories[index].value,
+ );
+ }),
+});
+
+// Category config fields and types
+export const validateCategories = (
+ categories: z.infer<typeof ScoreConfigCategory>[],
+ ctx: z.RefinementCtx,
+) => {
+ const uniqueNames = new Set<string>();
+ const uniqueValues = new Set<number>();
+
+ for (const category of categories) {
+ if (uniqueNames.has(category.label)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Duplicate category label: ${category.label}, category labels must be unique`,
+ });
+ return;
+ }
+ uniqueNames.add(category.label);
+
+ if (uniqueValues.has(category.value)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Duplicate category value: ${category.value}, category values must be unique`,
+ });
+ return;
+ }
+ uniqueValues.add(category.value);
+ }
+};
+
+export const CategoricalConfigFields = z.object({
+ maxValue: z.undefined().nullish(),
+ minValue: z.undefined().nullish(),
+ dataType: z.literal("CATEGORICAL"),
+ categories: z.array(ScoreConfigCategory).superRefine(validateCategories),
+});
+
+const ScoreConfigBase = z.object({
+ id: z.string(),
+ name: z.string().min(1).max(35),
+ isArchived: z.boolean(),
+ description: z.string().nullish(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+ projectId: z.string(),
+});
+
+export const validateNumericRangeFields = (
+ data: Pick<ScoreConfigDomain, "maxValue" | "minValue" | "dataType">,
+ ctx: z.RefinementCtx,
+): void | Promise<void> => {
+ if (data.dataType === "NUMERIC") {
+ if (
+ isPresent(data.maxValue) &&
+ isPresent(data.minValue) &&
+ data.maxValue <= data.minValue
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Maximum value must be greater than Minimum value",
+ });
+ }
+ }
+};
+
+export const ScoreConfigSchema = z
+ .discriminatedUnion("dataType", [
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...NumericConfigFields.shape,
+ }),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...CategoricalConfigFields.shape,
+ }),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...BooleanConfigFields.shape,
+ }),
+ ])
+ .superRefine(validateNumericRangeFields);
+
+export type ScoreConfigDomain = z.infer<typeof ScoreConfigSchema>;
+export type ScoreConfigCategoryDomain = z.infer<typeof ScoreConfigCategory>;
diff --git a/packages/shared/src/features/scoreConfigs/index.ts b/packages/shared/src/features/scoreConfigs/index.ts
new file mode 100644
index 0000000000..99455b8180
--- /dev/null
+++ b/packages/shared/src/features/scoreConfigs/index.ts
@@ -0,0 +1 @@
+export * from "./validation";
diff --git a/packages/shared/src/features/scoreConfigs/validation.ts b/packages/shared/src/features/scoreConfigs/validation.ts
new file mode 100644
index 0000000000..7385f6e6ce
--- /dev/null
+++ b/packages/shared/src/features/scoreConfigs/validation.ts
@@ -0,0 +1,49 @@
+import { z } from "zod/v4";
+import { ScoreConfig as ScoreConfigDbType } from "@prisma/client";
+import {
+ ScoreConfigDomain,
+ ScoreConfigSchema,
+} from "../../domain/score-configs";
+
+/**
+ * Use this function when pulling a list of score configs from the database before using in the application to ensure type safety.
+ * All score configs are expected to pass the validation. If a score fails validation, it will be logged to Otel.
+ * @param scoreConfigs
+ * @returns list of validated score configs
+ */
+export const filterAndValidateDbScoreConfigList = (
+ scoreConfigs: ScoreConfigDbType[],
+ onParseError?: (error: z.ZodError) => void, // eslint-disable-line no-unused-vars
+): ScoreConfigDomain[] =>
+ scoreConfigs.reduce((acc, ts) => {
+ const result = ScoreConfigSchema.safeParse(ts);
+ if (result.success) {
+ acc.push(result.data);
+ } else {
+ onParseError?.(result.error);
+ }
+ return acc;
+ }, [] as ScoreConfigDomain[]);
+
+/**
+ * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
+ * The score is expected to pass the validation. If a score fails validation, an error will be thrown.
+ * @param scoreConfig
+ * @returns validated score config
+ * @throws error if score fails validation
+ */
+export const validateDbScoreConfig = (
+ scoreConfig: ScoreConfigDbType,
+): ScoreConfigDomain => ScoreConfigSchema.parse(scoreConfig);
+
+/**
+ * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
+ * This function will NOT throw an error by default. The score is expected to pass the validation.
+ * @param scoreConfig
+ * @returns score config validation object:
+ * - success: true if the score config passes validation
+ * - data: the validated score config if success is true
+ * - error: the error object if success is false
+ */
+export const validateDbScoreConfigSafe = (scoreConfig: ScoreConfigDbType) =>
+ ScoreConfigSchema.safeParse(scoreConfig);
diff --git a/packages/shared/src/features/scores/index.ts b/packages/shared/src/features/scores/index.ts
index fd2059c3e1..a427c734fb 100644
--- a/packages/shared/src/features/scores/index.ts
+++ b/packages/shared/src/features/scores/index.ts
@@ -1,2 +1 @@
export * from "./interfaces";
-export * from "./scoreConfigTypes";
diff --git a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
index 9ea648994b..6b785b9bb7 100644
--- a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
+++ b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
@@ -2,7 +2,7 @@ import z from "zod/v4";
import { applyScoreValidation } from "../../../../utils/scores";
import { PostScoreBodyFoundationSchema } from "../shared";
import { isPresent } from "../../../../utils/typeChecks";
-import { Category as ConfigCategory } from "../../scoreConfigTypes";
+import { ScoreConfigCategory } from "../../../../domain/score-configs";
export const ScoreBodyWithoutConfig = applyScoreValidation(
z.discriminatedUnion("dataType", [
@@ -54,7 +54,7 @@ const ScorePropsAgainstConfigNumeric = z
const ScorePropsAgainstConfigCategorical = z
.object({
value: z.string(),
- categories: z.array(ConfigCategory),
+ categories: z.array(ScoreConfigCategory),
dataType: z.literal("CATEGORICAL"),
})
.superRefine((data, ctx) => {
diff --git a/packages/shared/src/features/scores/scoreConfigTypes.ts b/packages/shared/src/features/scores/scoreConfigTypes.ts
deleted file mode 100644
index f92c40cd9d..0000000000
--- a/packages/shared/src/features/scores/scoreConfigTypes.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import { z } from "zod/v4";
-
-import { ScoreConfig as ScoreConfigDbType } from "@prisma/client";
-
-import { isPresent } from "../../utils/typeChecks";
-import {
- jsonSchema,
- paginationMetaResponseZod,
- publicApiPaginationZod,
-} from "../../utils/zod";
-
-/**
- * Types to use across codebase
- */
-export type ConfigCategory = z.infer<typeof Category>;
-export type ValidatedScoreConfig = z.infer<typeof ValidatedScoreConfigSchema>;
-
-const validateCategories = (
- categories: ConfigCategory[],
- ctx: z.RefinementCtx,
-) => {
- const uniqueNames = new Set<string>();
- const uniqueValues = new Set<number>();
-
- for (const category of categories) {
- if (uniqueNames.has(category.label)) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: `Duplicate category label: ${category.label}, category labels must be unique`,
- });
- return;
- }
- uniqueNames.add(category.label);
-
- if (uniqueValues.has(category.value)) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: `Duplicate category value: ${category.value}, category values must be unique`,
- });
- return;
- }
- uniqueValues.add(category.value);
- }
-};
-
-/**
- * Objects
- */
-export const Category = z.object({
- label: z.string().min(1),
- value: z.number(),
-});
-
-const Categories = z.array(Category);
-
-const NumericScoreConfig = z.object({
- maxValue: z.number().nullish(),
- minValue: z.number().nullish(),
- dataType: z.literal("NUMERIC"),
- categories: z.undefined().nullish(),
-});
-
-const CategoricalScoreConfig = z.object({
- maxValue: z.undefined().nullish(),
- minValue: z.undefined().nullish(),
- dataType: z.literal("CATEGORICAL"),
- categories: jsonSchema.superRefine((categories, ctx) => {
- const parseResult = Categories.safeParse(categories);
- if (!parseResult.success) {
- ctx.addIssue({
- code: "custom",
- message:
- "Category must be an array of objects with label value pairs, where labels and values are unique.",
- } as z.core.$ZodIssueCustom);
- return;
- }
-
- validateCategories(categories as ConfigCategory[], ctx);
- }),
-});
-
-const BooleanScoreConfig = z.object({
- maxValue: z.undefined().nullish(),
- minValue: z.undefined().nullish(),
- dataType: z.literal("BOOLEAN"),
- categories: z
- .array(Category)
- .length(2, "Boolean data type must have exactly 2 categories.")
- .refine((categories) => {
- const expectedCategories = [
- { label: "True", value: 1 },
- { label: "False", value: 0 },
- ];
- return categories.every(
- (category, index) =>
- category.label === expectedCategories[index].label &&
- category.value === expectedCategories[index].value,
- );
- }),
-});
-
-const ScoreConfigBase = z.object({
- id: z.string(),
- name: z.string().min(1).max(35),
- isArchived: z.boolean(),
- description: z.string().nullish(),
- createdAt: z.coerce.date(),
- updatedAt: z.coerce.date(),
- projectId: z.string(),
-});
-
-const ScoreConfigPostBase = z.object({
- name: z.string(),
- description: z.string().optional(),
-});
-
-const ValidatedScoreConfigSchema = z
- .union([
- ScoreConfigBase.merge(NumericScoreConfig),
- ScoreConfigBase.merge(
- z.object({
- maxValue: z.undefined().nullish(),
- minValue: z.undefined().nullish(),
- dataType: z.literal("CATEGORICAL"),
- categories: Categories.superRefine(validateCategories),
- }),
- ),
- ScoreConfigBase.merge(BooleanScoreConfig),
- ])
- .superRefine((data, ctx) => {
- if (data.dataType === "NUMERIC") {
- if (
- isPresent(data.maxValue) &&
- isPresent(data.minValue) &&
- data.maxValue <= data.minValue
- ) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Maximum value must be greater than Minimum value",
- });
- }
- }
- });
-
-/**
- * Use this function when pulling a list of score configs from the database before using in the application to ensure type safety.
- * All score configs are expected to pass the validation. If a score fails validation, it will be logged to Otel.
- * @param scoreConfigs
- * @returns list of validated score configs
- */
-export const filterAndValidateDbScoreConfigList = (
- scoreConfigs: ScoreConfigDbType[],
- onParseError?: (error: z.ZodError) => void, // eslint-disable-line no-unused-vars
-): ValidatedScoreConfig[] =>
- scoreConfigs.reduce((acc, ts) => {
- const result = ValidatedScoreConfigSchema.safeParse(ts);
- if (result.success) {
- acc.push(result.data);
- } else {
- onParseError?.(result.error);
- }
- return acc;
- }, [] as ValidatedScoreConfig[]);
-
-/**
- * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
- * The score is expected to pass the validation. If a score fails validation, an error will be thrown.
- * @param scoreConfig
- * @returns validated score config
- * @throws error if score fails validation
- */
-export const validateDbScoreConfig = (
- scoreConfig: ScoreConfigDbType,
-): ValidatedScoreConfig => ValidatedScoreConfigSchema.parse(scoreConfig);
-
-/**
- * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
- * This function will NOT throw an error by default. The score is expected to pass the validation.
- * @param scoreConfig
- * @returns score config validation object:
- * - success: true if the score config passes validation
- * - data: the validated score config if success is true
- * - error: the error object if success is false
- */
-export const validateDbScoreConfigSafe = (scoreConfig: ScoreConfigDbType) =>
- ValidatedScoreConfigSchema.safeParse(scoreConfig);
-
-/**
- * Endpoints
- */
-
-// GET /score-configs/{configId}
-export const GetScoreConfigQuery = z.object({
- configId: z.string(),
-});
-
-export const GetScoreConfigResponse = ValidatedScoreConfigSchema;
-
-// POST /score-configs
-export const PostScoreConfigBody = z
- .discriminatedUnion("dataType", [
- ScoreConfigPostBase.merge(CategoricalScoreConfig),
- ScoreConfigPostBase.merge(NumericScoreConfig),
- ScoreConfigPostBase.merge(
- z.object({
- dataType: z.literal("BOOLEAN"),
- categories: z.undefined().nullish(),
- }),
- ),
- ])
- .superRefine((data, ctx) => {
- if (data.dataType === "NUMERIC") {
- if (
- isPresent(data.maxValue) &&
- isPresent(data.minValue) &&
- data.maxValue <= data.minValue
- ) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Maximum value must be greater than Minimum value",
- });
- }
- }
- });
-
-export const PostScoreConfigResponse = ValidatedScoreConfigSchema;
-
-// GET /score-configs
-export const GetScoreConfigsQuery = z.object({
- ...publicApiPaginationZod,
-});
-
-export const GetScoreConfigsResponse = z.object({
- data: z.array(ValidatedScoreConfigSchema),
- meta: paginationMetaResponseZod,
-});
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 98a34d946e..c213549563 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -19,6 +19,7 @@ export * from "./interfaces/rate-limits";
export * from "./tableDefinitions/typeHelpers";
export * from "./domain/webhooks";
export * from "./domain/dataset-run-items";
+export * from "./domain/score-configs";
// llm api
export * from "./server/llm/types";
@@ -37,6 +38,9 @@ export * from "./features/annotation/types";
// scores
export * from "./features/scores";
+// score configs
+export * from "./features/scoreConfigs";
+
// comments
export * from "./features/comments/types";
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index fd439f78f9..0c3d37096b 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -1,23 +1,23 @@
import {
ScoreBodyWithoutConfig,
+ ScoreConfigDomain,
ScoreDomain,
ScorePropsAgainstConfig,
- validateDbScoreConfigSafe,
- ValidatedScoreConfig,
} from "../../../src";
import { prisma, ScoreDataType } from "../../db";
-
import { InvalidRequestError, LangfuseNotFoundError } from "../../errors";
+import { validateDbScoreConfigSafe } from "../../features/scoreConfigs/validation";
+import { ScoreEventType } from "./types";
type ValidateAndInflateScoreParams = {
projectId: string;
scoreId: string;
- body: any;
+ body: ScoreEventType["body"];
};
export async function validateAndInflateScore(
params: ValidateAndInflateScoreParams,
-): Promise<ScoreDomain> {
+) {
const { body, projectId, scoreId } = params;
if (body.configId) {
@@ -40,16 +40,17 @@ export async function validateAndInflateScore(
name: config.name,
};
- validateConfigAgainstBody(
- bodyWithConfigOverrides,
- config as ValidatedScoreConfig,
- );
+ validateConfigAgainstBody({
+ body: bodyWithConfigOverrides,
+ config: config as ScoreConfigDomain,
+ context: "INGESTION",
+ });
return inflateScoreBody({
projectId,
scoreId,
body: bodyWithConfigOverrides,
- config: config as ValidatedScoreConfig,
+ config: config as ScoreConfigDomain,
});
}
@@ -74,7 +75,7 @@ function inferDataType(value: string | number): ScoreDataType {
}
function mapStringValueToNumericValue(
- config: ValidatedScoreConfig,
+ config: ScoreConfigDomain,
label: string,
): number | null {
return (
@@ -84,12 +85,17 @@ function mapStringValueToNumericValue(
}
function inflateScoreBody(
- params: ValidateAndInflateScoreParams & { config?: ValidatedScoreConfig },
-): ScoreDomain {
+ params: ValidateAndInflateScoreParams & { config?: ScoreConfigDomain },
+) {
const { body, projectId, scoreId, config } = params;
const relevantDataType = config?.dataType ?? body.dataType;
- const scoreProps = { source: "API", ...body, id: scoreId, projectId };
+ const scoreProps = {
+ ...body,
+ source: body.source ?? "API",
+ id: scoreId,
+ projectId,
+ };
if (typeof body.value === "number") {
if (relevantDataType && relevantDataType === ScoreDataType.BOOLEAN) {
@@ -104,6 +110,7 @@ function inflateScoreBody(
return {
...scoreProps,
value: body.value,
+ stringValue: null,
dataType: ScoreDataType.NUMERIC,
};
}
@@ -116,10 +123,43 @@ function inflateScoreBody(
};
}
-function validateConfigAgainstBody(
- body: any,
- config: ValidatedScoreConfig,
-): void {
+type ScoreBodyWithContext =
+ | {
+ body: ScoreEventType["body"];
+ context: "INGESTION";
+ }
+ | {
+ body: ScoreDomain;
+ context: "ANNOTATION";
+ };
+
+function resolveScoreValueIngestion(
+ body: ScoreEventType["body"],
+): string | number | null {
+ return body.value;
+}
+
+function resolveScoreValueAnnotation(
+ body: ScoreDomain,
+): string | number | null {
+ switch (body.dataType) {
+ case ScoreDataType.NUMERIC:
+ case ScoreDataType.BOOLEAN:
+ return body.value;
+ case ScoreDataType.CATEGORICAL:
+ return body.stringValue;
+ }
+}
+
+type ValidateConfigAgainstBodyParams = {
+ config: ScoreConfigDomain;
+} & ScoreBodyWithContext;
+
+export function validateConfigAgainstBody({
+ body,
+ config,
+ context,
+}: ValidateConfigAgainstBodyParams): void {
const { maxValue, minValue, categories, dataType: configDataType } = config;
if (body.dataType && body.dataType !== configDataType) {
@@ -141,20 +181,13 @@ function validateConfigAgainstBody(
}
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 scoreValue =
+ context === "INGESTION"
+ ? resolveScoreValueIngestion(body)
+ : resolveScoreValueAnnotation(body);
const rangeValidation = ScorePropsAgainstConfig.safeParse({
- value: body.value,
+ value: scoreValue,
dataType: relevantDataType,
...(maxValue !== null && maxValue !== undefined && { maxValue }),
...(minValue !== null && minValue !== undefined && { minValue }),
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 7ef7ed4199..d0300f759f 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -3913,6 +3913,58 @@ paths:
schema: {}
security:
- BasicAuth: []
+ patch:
+ description: Update a score config
+ operationId: scoreConfigs_update
+ tags:
+ - ScoreConfigs
+ parameters:
+ - name: configId
+ in: path
+ description: The unique langfuse identifier of a score config
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ScoreConfig'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateScoreConfigRequest'
/api/public/v2/scores:
get:
description: Get a list of scores (supports both trace and session scores)
@@ -8142,6 +8194,48 @@ components:
required:
- name
- dataType
+ UpdateScoreConfigRequest:
+ title: UpdateScoreConfigRequest
+ type: object
+ properties:
+ isArchived:
+ type: boolean
+ nullable: true
+ description: The status of the score config showing if it is archived or not
+ name:
+ type: string
+ nullable: true
+ description: The name of the score config
+ categories:
+ type: array
+ items:
+ $ref: '#/components/schemas/ConfigCategory'
+ nullable: true
+ description: >-
+ Configure custom categories for categorical scores. Pass a list of
+ objects with `label` and `value` properties. Categories are
+ autogenerated for boolean configs and cannot be passed
+ minValue:
+ type: number
+ format: double
+ nullable: true
+ description: >-
+ Configure a minimum value for numerical scores. If not set, the
+ minimum value defaults to -∞
+ maxValue:
+ type: number
+ format: double
+ nullable: true
+ description: >-
+ Configure a maximum value for numerical scores. If not set, the
+ maximum value defaults to +∞
+ description:
+ type: string
+ nullable: true
+ description: >-
+ Description is shown across the Langfuse UI and can be used to e.g.
+ explain the config categories in detail, why a numeric range was
+ set, or provide additional context on config name or usage
GetScoresResponseTraceData:
title: GetScoresResponseTraceData
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 1e769ad109..1540725f4f 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -2861,6 +2861,46 @@
"body": null
},
"response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Update",
+ "request": {
+ "description": "Update a score config",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/score-configs/:configId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "score-configs",
+ ":configId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "configId",
+ "value": "",
+ "description": "The unique langfuse identifier of a score config"
+ }
+ ]
+ },
+ "header": [],
+ "method": "PATCH",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"isArchived\": true,\n \"name\": \"example\",\n \"categories\": [\n {\n \"value\": 0,\n \"label\": \"example\"\n }\n ],\n \"minValue\": 0,\n \"maxValue\": 0,\n \"description\": \"example\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
}
]
},
diff --git a/web/src/__tests__/score-configs.servertest.ts b/web/src/__tests__/score-configs.servertest.ts
index b0ad2f0f5e..6d040faed8 100644
--- a/web/src/__tests__/score-configs.servertest.ts
+++ b/web/src/__tests__/score-configs.servertest.ts
@@ -5,16 +5,17 @@ import {
makeZodVerifiedAPICall,
pruneDatabase,
} from "@/src/__tests__/test-utils";
+import {
+ GetScoreConfigResponse,
+ GetScoreConfigsResponse,
+ PostScoreConfigResponse,
+ PutScoreConfigResponse,
+} from "@/src/features/public-api/types/score-configs";
import {
type ScoreConfig,
prisma,
type ScoreDataType,
} from "@langfuse/shared/src/db";
-import {
- GetScoreConfigResponse,
- PostScoreConfigResponse,
- GetScoreConfigsResponse,
-} from "@langfuse/shared";
import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
const configOne = [
@@ -412,4 +413,341 @@ describe("/api/public/score-configs API Endpoint", () => {
],
});
});
+
+ describe("PATCH /api/public/score-configs/:configId", () => {
+ it("should successfully archive a score config", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configOne[0].name,
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeZodVerifiedAPICall(
+ PutScoreConfigResponse,
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ isArchived: true,
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(200);
+ expect(patchResponse.body.isArchived).toBe(true);
+ });
+
+ it("should fail when trying to update with invalid data type mismatch - numeric to categorical", async () => {
+ const foundConfig = await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name, // Numeric config
+ },
+ });
+ const { id: configId } = foundConfig as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ categories: [
+ { label: "Good", value: 1 },
+ { label: "Bad", value: 0 },
+ ],
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining("Invalid input"),
+ });
+ });
+
+ it("should fail when trying to update boolean with custom categories", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configOne[0].name, // Boolean config
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ categories: [
+ { label: "Custom Good", value: 1 },
+ { label: "Custom Bad", value: 0 },
+ ],
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining("Invalid input"),
+ });
+ });
+
+ it("should fail when trying to update with invalid numeric range", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name, // Numeric config
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ minValue: 100,
+ maxValue: 50,
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining(
+ "Maximum value must be greater than Minimum value",
+ ),
+ });
+ });
+
+ it("should fail when trying to update with invalid name length", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name,
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ name: "a".repeat(50), // Exceeds 35 character limit
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining("Invalid request"),
+ });
+ });
+
+ it("should fail when trying to update with empty name", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name,
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ name: "",
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining("Invalid request"),
+ });
+ });
+
+ it("should fail when trying to update non-existent config", async () => {
+ const nonExistentId = "non-existent-config-id";
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${nonExistentId}`,
+ {
+ name: "Updated Name",
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(404);
+ expect(patchResponse.body).toMatchObject({
+ message: "Score config not found within authorized project",
+ });
+ });
+
+ it("should successfully update only specific fields without affecting others", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name,
+ },
+ })) as ScoreConfig;
+
+ // Get current config state
+ const beforePatch = await makeZodVerifiedAPICall(
+ GetScoreConfigResponse,
+ "GET",
+ `/api/public/score-configs/${configId}`,
+ undefined,
+ auth,
+ );
+
+ // Update only description
+ const patchResponse = await makeZodVerifiedAPICall(
+ PutScoreConfigResponse,
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ description: "Only description updated",
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(200);
+ expect(patchResponse.body.description).toBe("Only description updated");
+ // Verify other fields remain unchanged
+ expect(patchResponse.body.name).toBe(beforePatch.body.name);
+ expect(patchResponse.body.dataType).toBe(beforePatch.body.dataType);
+ expect(patchResponse.body.minValue).toBe(beforePatch.body.minValue);
+ });
+
+ it("should fail when trying to update with empty body", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name,
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeAPICall(
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {},
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(400);
+ expect(patchResponse.body).toMatchObject({
+ message: expect.stringContaining("Invalid request"),
+ });
+ });
+
+ it("should successfully update a numeric score config", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configTwo[0].name, // "Test Numeric Config"
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeZodVerifiedAPICall(
+ PutScoreConfigResponse,
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ name: "Updated Numeric Config",
+ minValue: 5,
+ maxValue: 100,
+ description: "Updated description",
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(200);
+ expect(patchResponse.body).toMatchObject({
+ id: configId,
+ name: "Updated Numeric Config",
+ dataType: "NUMERIC",
+ minValue: 5,
+ maxValue: 100,
+ description: "Updated description",
+ });
+
+ // Verify the update persisted
+ const getResponse = await makeZodVerifiedAPICall(
+ GetScoreConfigResponse,
+ "GET",
+ `/api/public/score-configs/${configId}`,
+ undefined,
+ auth,
+ );
+
+ expect(getResponse.body.name).toBe("Updated Numeric Config");
+ expect(getResponse.body.minValue).toBe(5);
+ expect(getResponse.body.maxValue).toBe(100);
+ });
+
+ it("should successfully update a categorical score config", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configThree[0].name, // "Test Categorical Config"
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeZodVerifiedAPICall(
+ PutScoreConfigResponse,
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ name: "Updated Categorical Config",
+ categories: [
+ { label: "Excellent", value: 3 },
+ { label: "Good", value: 2 },
+ { label: "Poor", value: 1 },
+ ],
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(200);
+ expect(patchResponse.body).toMatchObject({
+ id: configId,
+ name: "Updated Categorical Config",
+ dataType: "CATEGORICAL",
+ categories: [
+ { label: "Excellent", value: 3 },
+ { label: "Good", value: 2 },
+ { label: "Poor", value: 1 },
+ ],
+ });
+ });
+
+ it("should successfully update a boolean score config", async () => {
+ const { id: configId } = (await prisma.scoreConfig.findFirst({
+ where: {
+ projectId,
+ name: configOne[0].name, // "Test Boolean Config"
+ },
+ })) as ScoreConfig;
+
+ const patchResponse = await makeZodVerifiedAPICall(
+ PutScoreConfigResponse,
+ "PATCH",
+ `/api/public/score-configs/${configId}`,
+ {
+ name: "Updated Boolean Config",
+ description: "Updated boolean description",
+ },
+ auth,
+ );
+
+ expect(patchResponse.status).toBe(200);
+ expect(patchResponse.body).toMatchObject({
+ id: configId,
+ name: "Updated Boolean Config",
+ dataType: "BOOLEAN",
+ description: "Updated boolean description",
+ categories: [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ],
+ });
+ });
+ });
});
diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsx
index 60677230be..648c1870f2 100644
--- a/web/src/components/table/use-cases/score-configs.tsx
+++ b/web/src/components/table/use-cases/score-configs.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { useState } from "react";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
import { api } from "@/src/utils/api";
@@ -8,7 +8,7 @@ import { DataTable } from "@/src/components/table/data-table";
import {
type ScoreDataType,
type Prisma,
- type ConfigCategory,
+ type ScoreConfigCategoryDomain,
} from "@langfuse/shared";
import { IOTableCell } from "../../ui/IOTableCell";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
@@ -17,19 +17,19 @@ import {
isCategoricalDataType,
isNumericDataType,
} from "@/src/features/scores/lib/helpers";
-import { Archive } from "lucide-react";
+import { Edit, MoreVertical } from "lucide-react";
import { Button } from "@/src/components/ui/button";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/src/components/ui/popover";
-import useLocalStorage from "@/src/components/useLocalStorage";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
-import { CreateScoreConfigButton } from "@/src/features/scores/components/CreateScoreConfigButton";
import { SettingsTableCard } from "@/src/components/layouts/settings-table-card";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@/src/components/ui/dropdown-menu";
+import { ArchiveScoreConfigButton } from "@/src/features/score-configs/components/ArchiveScoreConfigButton";
+import { UpsertScoreConfigDialog } from "@/src/features/score-configs/components/UpsertScoreConfigDialog";
type ScoreConfigTableRow = {
id: string;
@@ -40,7 +40,7 @@ type ScoreConfigTableRow = {
range: {
maxValue?: number | null;
minValue?: number | null;
- categories?: ConfigCategory[] | null;
+ categories?: ScoreConfigCategoryDomain[] | null;
};
description?: string | null;
isArchived: boolean;
@@ -72,32 +72,36 @@ function getConfigRange(
}
export function ScoreConfigsTable({ projectId }: { projectId: string }) {
- const utils = api.useUtils();
- const capture = usePostHogClientCapture();
- const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
- string[]
- >("emptySelectedConfigIds", []);
-
- const hasAccess = useHasProjectAccess({
- projectId: projectId,
- scope: "scoreConfigs:CUD",
- });
-
+ const [editConfigId, setEditConfigId] = useState<string | null>(null);
+ const [createConfigOpen, setCreateConfigOpen] = useState(false);
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
});
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "scoreConfigs:CUD",
+ });
+
const [rowHeight, setRowHeight] = useRowHeightLocalStorage(
"scoreConfigs",
"s",
);
- const configs = api.scoreConfigs.all.useQuery({
- projectId,
- page: paginationState.pageIndex,
- limit: paginationState.pageSize,
- });
+ const configs = api.scoreConfigs.all.useQuery(
+ {
+ projectId,
+ page: paginationState.pageIndex,
+ limit: paginationState.pageSize,
+ },
+ { enabled: hasAccess },
+ );
+
+ const configQuery = api.scoreConfigs.byId.useQuery(
+ { projectId, id: editConfigId as string },
+ { enabled: !!editConfigId && hasAccess },
+ );
const totalCount = configs.data?.totalCount ?? null;
@@ -175,54 +179,33 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {
enableHiding: true,
cell: ({ row }) => {
const { id: configId, isArchived, name } = row.original;
- const configMutation = api.scoreConfigs.update.useMutation({
- onSuccess: () => void utils.scoreConfigs.invalidate(),
- });
return (
- <Popover key={configId}>
- <PopoverTrigger asChild>
- <Button
- variant="ghost"
- size="xs"
- disabled={!hasAccess}
- onClick={() => capture("score_configs:archive_form_open")}
- >
- <Archive className="h-4 w-4"></Archive>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost">
+ <MoreVertical className="h-4 w-4" />
</Button>
- </PopoverTrigger>
- <PopoverContent>
- <h2 className="text-md mb-3 font-semibold">
- {isArchived ? "Restore config" : "Archive config"}
- </h2>
- <p className="mb-3 text-sm">
- Your config is currently{" "}
- {isArchived
- ? `archived. Restore if you want to use "${name}" in annotation again.`
- : `active. Archive if you no longer want to use "${name}" in annotation. Historic "${name}" scores will still be shown and can be deleted. You can restore your config at any point.`}
- </p>
- <div className="flex justify-end space-x-4">
- <Button
- type="button"
- variant={isArchived ? "default" : "destructive"}
- loading={configMutation.isPending}
- onClick={() => {
- void configMutation.mutateAsync({
- projectId,
- id: configId,
- isArchived: !isArchived,
- });
- setEmptySelectedConfigIds(
- emptySelectedConfigIds.filter((id) => id !== configId),
- );
- capture("score_configs:archive_form_submit");
- }}
- >
- Confirm
- </Button>
- </div>
- </PopoverContent>
- </Popover>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ key={configId}
+ aria-label="edit"
+ onClick={() => setEditConfigId(configId)}
+ >
+ <Edit className="mr-2 h-4 w-4" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild key="archive">
+ <ArchiveScoreConfigButton
+ configId={configId}
+ projectId={projectId}
+ isArchived={isArchived}
+ name={name}
+ />
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
);
},
},
@@ -249,7 +232,14 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {
setColumnOrder={setColumnOrder}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
- actionButtons={<CreateScoreConfigButton projectId={projectId} />}
+ actionButtons={
+ <UpsertScoreConfigDialog
+ key="new-config-dialog"
+ projectId={projectId}
+ open={createConfigOpen}
+ onOpenChange={setCreateConfigOpen}
+ />
+ }
className="px-0"
/>
<SettingsTableCard>
@@ -297,6 +287,33 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {
className="gap-2"
/>
</SettingsTableCard>
+
+ {!!editConfigId && configQuery.isSuccess && (
+ <UpsertScoreConfigDialog
+ key={editConfigId}
+ id={editConfigId}
+ projectId={projectId}
+ open={!!editConfigId && configQuery.isSuccess}
+ onOpenChange={(open) => {
+ if (!open) setEditConfigId(null);
+ }}
+ defaultValues={
+ configQuery.data
+ ? {
+ id: editConfigId,
+ name: configQuery.data.name,
+ dataType: configQuery.data.dataType,
+ minValue: configQuery.data.minValue ?? undefined,
+ maxValue: configQuery.data.maxValue ?? undefined,
+ description: configQuery.data.description ?? undefined,
+ categories: configQuery.data.categories?.length
+ ? configQuery.data.categories
+ : undefined,
+ }
+ : undefined
+ }
+ />
+ )}
</>
);
}
diff --git a/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx b/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
index fd42f3b70d..0ef8f94003 100644
--- a/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
+++ b/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
@@ -28,7 +28,7 @@ import { Textarea } from "@/src/components/ui/textarea";
import {
type CreateQueueWithAssignments,
CreateQueueWithAssignmentsData,
- type ValidatedScoreConfig,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import { api } from "@/src/utils/api";
import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
@@ -88,7 +88,7 @@ export const CreateOrEditAnnotationQueueButton = ({
name: queueQuery.data.name,
description: queueQuery.data.description || undefined,
scoreConfigIds: queueQuery.data.scoreConfigs.map(
- (config: ValidatedScoreConfig) => config.id,
+ (config: ScoreConfigDomain) => config.id,
),
newAssignmentUserIds: [],
});
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index c465f841d1..618cb8c08f 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -1,6 +1,6 @@
import {
type AnnotationQueueItem,
- type ValidatedScoreConfig,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import { AnnotationDrawerSection } from "../shared/AnnotationDrawerSection";
import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout";
@@ -20,7 +20,7 @@ interface SessionAnnotationProcessorProps {
lockedByUser: { name: string | null | undefined } | null;
};
data: any; // // Session data with scores
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
projectId: string;
onHasCommentDraftChange?: (hasDraft: boolean) => void;
}
diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
index 09a2c236f1..45bb216839 100644
--- a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx
@@ -4,7 +4,7 @@ import { TracePreview } from "@/src/components/trace/TracePreview";
import {
type AnnotationQueueItem,
AnnotationQueueObjectType,
- type ValidatedScoreConfig,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import { useEffect } from "react";
import { StringParam, useQueryParam } from "use-query-params";
@@ -18,7 +18,7 @@ interface TraceAnnotationProcessorProps {
};
data: any; // Trace data with observations and scores
view: "showTree" | "hideTree";
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
projectId: string;
onHasCommentDraftChange?: (hasDraft: boolean) => void;
}
diff --git a/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
index 78b010e5bd..b99922cccb 100644
--- a/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
+++ b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx
@@ -11,7 +11,7 @@ import {
type AnnotationQueueItem,
type APIScoreV2,
isPresent,
- type ValidatedScoreConfig,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import { TriangleAlertIcon } from "lucide-react";
import { useSession } from "next-auth/react";
@@ -25,7 +25,7 @@ interface AnnotationDrawerSectionProps {
};
scoreTarget: ScoreTarget;
scores: APIScoreV2[];
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
environment?: string;
onHasCommentDraftChange?: (hasDraft: boolean) => void;
}
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 62e3b38c32..830be1781d 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -57,6 +57,7 @@ const events = {
],
score_configs: [
"create_form_submit",
+ "update_form_submit",
"manage_configs_item_click",
"archive_form_open",
"archive_form_submit",
diff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.ts
new file mode 100644
index 0000000000..1d640e58ab
--- /dev/null
+++ b/web/src/features/public-api/types/score-configs.ts
@@ -0,0 +1,131 @@
+import {
+ BooleanConfigFields,
+ CategoricalConfigFields,
+ jsonSchema,
+ NumericConfigFields,
+ paginationMetaResponseZod,
+ publicApiPaginationZod,
+ ScoreConfigCategory,
+ validateCategories,
+ validateNumericRangeFields,
+} from "@langfuse/shared";
+import { z } from "zod/v4";
+
+/**
+ * Objects
+ */
+const CategoriesWithCustomError = jsonSchema.superRefine((categories, ctx) => {
+ const parseResult = z.array(ScoreConfigCategory).safeParse(categories);
+ if (!parseResult.success) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "Category must be an array of objects with label value pairs, where labels and values are unique.",
+ } as z.core.$ZodIssueCustom);
+ return;
+ }
+
+ validateCategories(parseResult.data, ctx);
+});
+
+/**
+ * Endpoints
+ */
+const ScoreConfigBase = z.object({
+ id: z.string(),
+ projectId: z.string(),
+ name: z.string(),
+ description: z.string().nullish(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+ isArchived: z.boolean(),
+});
+
+const APIScoreConfig = z
+ .discriminatedUnion("dataType", [
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...NumericConfigFields.shape,
+ }),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...CategoricalConfigFields.shape,
+ }),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...BooleanConfigFields.shape,
+ }),
+ ])
+ .superRefine(validateNumericRangeFields);
+
+// GET /score-configs/{configId}
+export const GetScoreConfigQuery = z.object({
+ configId: z.string(),
+});
+
+export const GetScoreConfigResponse = APIScoreConfig;
+
+// POST /score-configs
+const PostScoreConfigBase = z.object({
+ name: z.string(),
+ description: z.string().nullish(),
+});
+
+export const PostScoreConfigBody = z
+ .discriminatedUnion("dataType", [
+ z.object({
+ ...PostScoreConfigBase.shape,
+ ...NumericConfigFields.shape,
+ }),
+ z.object({
+ ...PostScoreConfigBase.shape,
+ ...z.object({
+ maxValue: z.undefined().nullish(),
+ minValue: z.undefined().nullish(),
+ dataType: z.literal("CATEGORICAL"),
+ categories: CategoriesWithCustomError,
+ }).shape,
+ }),
+ z.object({
+ ...PostScoreConfigBase.shape,
+ // Boolean config API POST body will always infer the categories based on data type
+ ...z.object({
+ dataType: z.literal("BOOLEAN"),
+ categories: z.undefined(),
+ }).shape,
+ }),
+ ])
+ .superRefine(validateNumericRangeFields);
+
+export const PostScoreConfigResponse = APIScoreConfig;
+
+// PUT /score-configs/{configId}
+export const PutScoreConfigQuery = z.object({
+ configId: z.string(),
+});
+
+export const PutScoreConfigBody = z
+ .object({
+ isArchived: z.boolean().optional(),
+ name: z.string().min(1).max(35).optional(),
+ minValue: z.number().optional(),
+ maxValue: z.number().optional(),
+ categories: CategoriesWithCustomError.optional(),
+ description: z.string().optional(),
+ })
+ .refine((data) => Object.keys(data).length > 0, {
+ message:
+ "Request body cannot be empty. At least one field must be provided for update.",
+ });
+
+export const PutScoreConfigResponse = APIScoreConfig;
+
+// GET /score-configs
+export const GetScoreConfigsQuery = z.object({
+ ...publicApiPaginationZod,
+});
+
+export const GetScoreConfigsResponse = z.object({
+ data: z.array(APIScoreConfig),
+ meta: paginationMetaResponseZod,
+});
diff --git a/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx b/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx
new file mode 100644
index 0000000000..9948d6f9a0
--- /dev/null
+++ b/web/src/features/score-configs/components/ArchiveScoreConfigButton.tsx
@@ -0,0 +1,92 @@
+import { Archive } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import React from "react";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import { api } from "@/src/utils/api";
+
+export const ArchiveScoreConfigButton = ({
+ configId,
+ projectId,
+ isArchived,
+ name,
+}: {
+ configId: string;
+ projectId: string;
+ isArchived: boolean;
+ name: string;
+}) => {
+ const capture = usePostHogClientCapture();
+ const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<
+ string[]
+ >("emptySelectedConfigIds", []);
+
+ const hasAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "scoreConfigs:CUD",
+ });
+
+ const utils = api.useUtils();
+ const configMutation = api.scoreConfigs.update.useMutation({
+ onSuccess: () => void utils.scoreConfigs.invalidate(),
+ });
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ className="flex w-full items-center justify-start"
+ disabled={!hasAccess}
+ onClick={(e) => {
+ e.stopPropagation();
+ capture("score_configs:archive_form_open");
+ }}
+ >
+ <Archive className="mr-2 h-4 w-4"></Archive>
+ Archive
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent
+ onClick={(e) => e.stopPropagation()}
+ className="max-w-[500px]"
+ >
+ <h2 className="text-md mb-3 font-semibold">
+ {isArchived ? "Restore config" : "Archive config"}
+ </h2>
+ <p className="mb-3 text-sm">
+ Your config is currently{" "}
+ {isArchived
+ ? `archived. Restore if you want to use "${name}" in annotation again.`
+ : `active. Archive if you no longer want to use "${name}" in annotation. Historic "${name}" scores will still be shown and can be deleted. You can restore your config at any point.`}
+ </p>
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant={isArchived ? "default" : "destructive"}
+ loading={configMutation.isPending}
+ onClick={() => {
+ void configMutation.mutateAsync({
+ projectId,
+ id: configId,
+ isArchived: !isArchived,
+ });
+ setEmptySelectedConfigIds(
+ emptySelectedConfigIds.filter((id) => id !== configId),
+ );
+ capture("score_configs:archive_form_submit");
+ }}
+ >
+ Confirm
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/web/src/features/scores/components/ScoreConfigDetails.tsx b/web/src/features/score-configs/components/ScoreConfigDetails.tsx
similarity index 81%
rename from web/src/features/scores/components/ScoreConfigDetails.tsx
rename to web/src/features/score-configs/components/ScoreConfigDetails.tsx
index 5831187185..331ff048e4 100644
--- a/web/src/features/scores/components/ScoreConfigDetails.tsx
+++ b/web/src/features/score-configs/components/ScoreConfigDetails.tsx
@@ -1,12 +1,8 @@
import { isNumericDataType } from "@/src/features/scores/lib/helpers";
-import { isPresent, type ValidatedScoreConfig } from "@langfuse/shared";
+import { isPresent, type ScoreConfigDomain } from "@langfuse/shared";
import React from "react";
-export function ScoreConfigDetails({
- config,
-}: {
- config: ValidatedScoreConfig;
-}) {
+export function ScoreConfigDetails({ config }: { config: ScoreConfigDomain }) {
const { name, description, minValue, maxValue, dataType } = config;
if (!description && !isPresent(minValue) && !isPresent(maxValue)) return null;
const isNameTruncated = name.length > 20;
diff --git a/web/src/features/scores/components/ScoreConfigSettings.tsx b/web/src/features/score-configs/components/ScoreConfigSettings.tsx
similarity index 100%
rename from web/src/features/scores/components/ScoreConfigSettings.tsx
rename to web/src/features/score-configs/components/ScoreConfigSettings.tsx
diff --git a/web/src/features/scores/components/CreateScoreConfigButton.tsx b/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
similarity index 73%
rename from web/src/features/scores/components/CreateScoreConfigButton.tsx
rename to web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
index ff7970fb71..a532360441 100644
--- a/web/src/features/scores/components/CreateScoreConfigButton.tsx
+++ b/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
@@ -22,7 +22,7 @@ import {
FormMessage,
} from "@/src/components/ui/form";
import { Input } from "@/src/components/ui/input";
-import { isPresent, ScoreDataType, availableDataTypes } from "@langfuse/shared";
+import { ScoreDataType, availableDataTypes } from "@langfuse/shared";
import {
Select,
SelectContent,
@@ -39,71 +39,28 @@ import {
} from "@/src/features/scores/lib/helpers";
import DocPopup from "@/src/components/layouts/doc-popup";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { z } from "zod/v4";
-
-const Category = z.object({
- label: z.string().min(1),
- value: z.number(),
-});
-
-const createConfigSchema = z.object({
- name: z.string().min(1).max(35),
- dataType: z.enum(availableDataTypes),
- minValue: z.coerce.number().optional(),
- maxValue: z.coerce.number().optional(),
- categories: z.array(Category).optional(),
- description: z.string().optional(),
-});
-
-type CreateConfig = z.infer<typeof createConfigSchema>;
-
-const validateScoreConfig = (values: CreateConfig): string | null => {
- const { dataType, maxValue, minValue, categories } = values;
-
- if (isNumericDataType(dataType)) {
- if (
- isPresent(maxValue) &&
- isPresent(minValue) &&
- Number(maxValue) <= Number(minValue)
- ) {
- return "Maximum value must be greater than Minimum value.";
- }
- } else if (isCategoricalDataType(dataType)) {
- if (!categories || categories.length === 0) {
- return "At least one category is required for categorical data types.";
- }
- } else if (isBooleanDataType(dataType)) {
- if (categories?.length !== 2)
- return "Boolean data type must have exactly 2 categories.";
- const isBooleanCategoryInvalid = categories?.some(
- (category) => category.value !== 0 && category.value !== 1,
- );
- if (isBooleanCategoryInvalid)
- return "Boolean data type must have categories with values 0 and 1.";
- }
-
- const uniqueNames = new Set<string>();
- const uniqueValues = new Set<number>();
-
- for (const category of categories || []) {
- if (uniqueNames.has(category.label)) {
- return "Category names must be unique.";
- }
- uniqueNames.add(category.label);
-
- if (uniqueValues.has(category.value)) {
- return "Category values must be unique.";
- }
- uniqueValues.add(category.value);
- }
-
- return null;
-};
+import {
+ createConfigSchema,
+ updateConfigSchema,
+ type CreateConfig,
+ type UpdateConfig,
+} from "@/src/features/score-configs/lib/upsertFormTypes";
+import { validateScoreConfigUpsertFormInput } from "@/src/features/score-configs/lib/validateScoreConfigUpsertFormInput";
-export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
- const [open, setOpen] = useState(false);
+export function UpsertScoreConfigDialog({
+ projectId,
+ id,
+ open,
+ onOpenChange,
+ defaultValues,
+}: {
+ projectId: string;
+ id?: string | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ defaultValues?: CreateConfig | UpdateConfig;
+}) {
const [formError, setFormError] = useState<string | null>(null);
- const [confirmOpen, setConfirmOpen] = useState(false);
const capture = usePostHogClientCapture();
const hasAccess = useHasProjectAccess({
@@ -118,15 +75,21 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
setFormError(error.message ?? "An error occurred while creating config."),
});
+ const updateScoreConfig = api.scoreConfigs.update.useMutation({
+ onSuccess: () => utils.scoreConfigs.invalidate(),
+ onError: (error) =>
+ setFormError(error.message ?? "An error occurred while updating config."),
+ });
+
const form = useForm({
- resolver: zodResolver(createConfigSchema),
- defaultValues: {
+ resolver: zodResolver(id ? updateConfigSchema : createConfigSchema),
+ defaultValues: defaultValues ?? {
dataType: ScoreDataType.NUMERIC,
minValue: undefined,
maxValue: undefined,
name: "",
},
- }) as UseFormReturn<CreateConfig>;
+ }) as UseFormReturn<CreateConfig | UpdateConfig>;
const { fields, append, remove, replace } = useFieldArray({
control: form.control,
@@ -135,59 +98,67 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
if (!hasAccess) return null;
- async function onSubmit(values: CreateConfig) {
- const error = validateScoreConfig(values);
+ async function onSubmit(values: CreateConfig | UpdateConfig) {
+ const error = validateScoreConfigUpsertFormInput(values);
setFormError(error);
const isValid = await form.trigger();
if (!isValid || error) return;
- return createScoreConfig
- .mutateAsync({
- projectId,
- ...values,
- categories: values.categories?.length ? values.categories : undefined,
- })
- .then(() => {
- capture("score_configs:create_form_submit", {
- dataType: values.dataType,
+ if (!!id) {
+ return updateScoreConfig
+ .mutateAsync({
+ ...values,
+ projectId,
+ id: id as string,
+ description: values.description ?? null,
+ categories: values.categories?.length ? values.categories : undefined,
+ })
+ .then(() => {
+ capture("score_configs:update_form_submit", {
+ dataType: values.dataType,
+ });
+ form.reset();
+ onOpenChange(false);
+ });
+ } else {
+ return createScoreConfig
+ .mutateAsync({
+ projectId,
+ ...values,
+ description: values.description ?? null,
+ categories: values.categories?.length ? values.categories : undefined,
+ })
+ .then(() => {
+ capture("score_configs:create_form_submit", {
+ dataType: values.dataType,
+ });
+ form.reset();
+ onOpenChange(false);
});
- form.reset();
- setOpen(false);
- setConfirmOpen(false);
- })
- .catch((error) => {
- console.error(error);
- });
- }
-
- const handleSubmitConfirm = async () => {
- const error = validateScoreConfig(form.getValues());
- setFormError(error);
- const isValid = await form.trigger();
- if (isValid && !error) {
- setConfirmOpen(true);
}
- };
+ }
return (
<>
<Dialog
open={open}
onOpenChange={(v) => {
- setOpen(v);
form.reset();
setFormError(null);
+ onOpenChange(v);
}}
>
<DialogTrigger asChild>
<Button variant="secondary" loading={createScoreConfig.isPending}>
<PlusIcon className="-ml-0.5 mr-1.5 h-4 w-4" aria-hidden="true" />
- Add new score config
+ {id ? "Update score config" : "Add new score config"}
</Button>
</DialogTrigger>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
- <DialogTitle>Add new score config</DialogTitle>
+ <DialogTitle>
+ {id ? "Update score config" : "Add new score config"}
+ </DialogTitle>
</DialogHeader>
<Form {...form}>
<form
@@ -222,6 +193,7 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
<FormItem>
<FormLabel>Data type</FormLabel>
<Select
+ disabled={!!id}
defaultValue={field.value}
onValueChange={(value) => {
field.onChange(
@@ -436,6 +408,7 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
<Textarea
{...field}
placeholder="Provide an optional description of the score config..."
+ value={field.value ?? undefined}
/>
</FormControl>
<FormMessage />
@@ -444,63 +417,24 @@ export function CreateScoreConfigButton({ projectId }: { projectId: string }) {
)}
/>
</DialogBody>
- </form>
- <Dialog
- open={confirmOpen}
- onOpenChange={(isOpenAction) => {
- if (!isOpenAction && !form.formState.isSubmitting)
- setConfirmOpen(false);
- }}
- >
- <DialogTrigger asChild>
- <div className="p-6 pt-0">
+ <DialogFooter>
+ <div className="flex w-full flex-col items-end gap-4">
+ {formError ? (
+ <p className="text-red w-full text-center">
+ <span className="font-bold">Error:</span> {formError}
+ </p>
+ ) : null}
<Button
- type="button"
- className="w-full"
- onClick={handleSubmitConfirm}
+ type="submit"
+ loading={
+ createScoreConfig.isPending || updateScoreConfig.isPending
+ }
>
Submit
</Button>
</div>
- </DialogTrigger>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Confirm Submission</DialogTitle>
- </DialogHeader>
- <DialogBody>
- <p className="py-4 text-sm">
- Score configs cannot be edited or deleted after they have
- been created. Are you sure you want to proceed?
- </p>
- </DialogBody>
- <DialogFooter>
- <div className="flex w-full flex-col gap-4">
- <div className="flex justify-end space-x-2">
- <Button
- type="button"
- variant="outline"
- disabled={form.formState.isSubmitting}
- onClick={() => setConfirmOpen(false)}
- >
- Continue Editing
- </Button>
- <Button
- type="submit"
- loading={form.formState.isSubmitting}
- onClick={form.handleSubmit(onSubmit)}
- >
- Confirm
- </Button>
- </div>
- {formError ? (
- <p className="text-red w-full text-center">
- <span className="font-bold">Error:</span> {formError}
- </p>
- ) : null}
- </div>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ </DialogFooter>
+ </form>
</Form>
</DialogContent>
</Dialog>
diff --git a/web/src/features/score-configs/lib/upsertFormTypes.ts b/web/src/features/score-configs/lib/upsertFormTypes.ts
new file mode 100644
index 0000000000..b4de5e1c68
--- /dev/null
+++ b/web/src/features/score-configs/lib/upsertFormTypes.ts
@@ -0,0 +1,18 @@
+import { availableDataTypes, ScoreConfigCategory } from "@langfuse/shared";
+import { z } from "zod/v4";
+
+export const createConfigSchema = z.object({
+ name: z.string().min(1).max(35),
+ description: z.string().optional(),
+ dataType: z.enum(availableDataTypes),
+ minValue: z.coerce.number().optional(),
+ maxValue: z.coerce.number().optional(),
+ categories: z.array(ScoreConfigCategory).optional(),
+});
+
+export const updateConfigSchema = createConfigSchema.extend({
+ id: z.string(),
+});
+
+export type CreateConfig = z.infer<typeof createConfigSchema>;
+export type UpdateConfig = z.infer<typeof updateConfigSchema>;
diff --git a/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts b/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts
new file mode 100644
index 0000000000..4b89fbf11c
--- /dev/null
+++ b/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts
@@ -0,0 +1,37 @@
+import {
+ NumericConfigFields,
+ CategoricalConfigFields,
+ BooleanConfigFields,
+ validateNumericRangeFields,
+} from "@langfuse/shared";
+import { z } from "zod/v4";
+import { type CreateConfig, type UpdateConfig } from "./upsertFormTypes";
+
+const ScoreConfigBaseSchema = z.object({
+ name: z.string().min(1).max(35),
+ description: z.string().optional(),
+});
+
+// Validation-only schema without metadata fields (ids, timestamps etc.)
+const ScoreConfigValidationSchema = ScoreConfigBaseSchema.and(
+ z
+ .discriminatedUnion("dataType", [
+ NumericConfigFields,
+ CategoricalConfigFields,
+ BooleanConfigFields,
+ ])
+ .superRefine(validateNumericRangeFields),
+);
+
+export const validateScoreConfigUpsertFormInput = (
+ values: CreateConfig | UpdateConfig,
+): string | null => {
+ const result = ScoreConfigValidationSchema.safeParse({
+ ...values,
+ categories: values.categories?.length ? values.categories : undefined,
+ });
+
+ return result.error
+ ? result.error?.issues.map((issue) => issue.message).join(", ")
+ : null;
+};
diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsx
index ddc1ea789c..7e9febdead 100644
--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx
+++ b/web/src/features/scores/components/AnnotateDrawerContent.tsx
@@ -29,8 +29,8 @@ import {
isPresent,
CreateAnnotationScoreData,
UpdateAnnotationScoreData,
- type ValidatedScoreConfig,
- type ConfigCategory,
+ type ScoreConfigDomain,
+ type ScoreConfigCategoryDomain,
} from "@langfuse/shared";
import { Input } from "@/src/components/ui/input";
import {
@@ -49,7 +49,6 @@ import {
import { Textarea } from "@/src/components/ui/textarea";
import { HoverCardContent } from "@radix-ui/react-hover-card";
import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";
-import { ScoreConfigDetails } from "@/src/features/scores/components/ScoreConfigDetails";
import {
formatAnnotateDescription,
isNumericDataType,
@@ -73,10 +72,11 @@ import {
import { useScoreValues } from "@/src/features/scores/hooks/useScoreValues";
import { useScoreMutations } from "@/src/features/scores/hooks/useScoreMutations";
import { AnnotateFormSchema } from "@/src/features/scores/schema";
+import { ScoreConfigDetails } from "@/src/features/score-configs/components/ScoreConfigDetails";
const CHAR_CUTOFF = 6;
-const renderSelect = (categories: ConfigCategory[]) => {
+const renderSelect = (categories: ScoreConfigCategoryDomain[]) => {
const hasMoreThanThreeCategories = categories.length > 3;
const hasLongCategoryNames = categories.some(
({ label }) => label.length > CHAR_CUTOFF,
@@ -128,6 +128,34 @@ function handleOnKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
}
}
+function enrichCategories(
+ categories: ScoreConfigCategoryDomain[],
+ currentStringValue?: string | null,
+) {
+ if (categories.length === 0) return [];
+
+ const enrichedCategories = categories.map((category) => ({
+ ...category,
+ isOutdated: false,
+ }));
+
+ if (!currentStringValue) return enrichedCategories;
+
+ // If current value exists in categories, return as-is
+ if (categories.some((category) => category.label === currentStringValue)) {
+ return enrichedCategories;
+ }
+
+ return [
+ {
+ label: currentStringValue,
+ value: 0,
+ isOutdated: true,
+ },
+ ...enrichedCategories,
+ ];
+}
+
function AnnotateHeader({
showSaving,
actionButtons,
@@ -166,7 +194,7 @@ function AnnotateHeader({
type AnnotateDrawerContentProps<Target extends ScoreTarget> =
AnnotateDrawerProps<Target> & {
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
isDrawerOpen: boolean;
showSaving: boolean;
setShowSaving: (showSaving: boolean) => void;
@@ -396,7 +424,7 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
index,
score,
}: {
- config: ValidatedScoreConfig;
+ config: ScoreConfigDomain;
field: ControllerRenderProps<
AnnotateFormSchemaType,
`scoreData.${number}.value`
@@ -496,7 +524,7 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
function handleOnValueChange(
score: AnnotationScoreSchemaType,
index: number,
- configCategories: ConfigCategory[],
+ configCategories: ScoreConfigCategoryDomain[],
): ((value: string) => void) | undefined {
return async (stringValue) => {
const selectedCategory = configCategories.find(
@@ -637,8 +665,10 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
(config) => config.id === score.configId,
);
if (!config) return null;
- const categories =
- (config.categories as ConfigCategory[]) ?? [];
+ const categories = enrichCategories(
+ config.categories ?? [],
+ score.stringValue,
+ );
return (
<div
@@ -879,8 +909,17 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
</div>
</SelectTrigger>
<SelectContent>
- {categories.map(
- (category: ConfigCategory) => (
+ {categories.map((category) =>
+ category.isOutdated ? (
+ <SelectItem
+ key={category.value}
+ value={category.label}
+ disabled
+ className="text-muted-foreground line-through"
+ >
+ {category.label}
+ </SelectItem>
+ ) : (
<SelectItem
key={category.value}
value={category.label}
@@ -908,13 +947,14 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
categories,
)}
>
- {categories.map(
- (category: ConfigCategory) => (
+ {categories.map((category) =>
+ category.isOutdated ? (
<ToggleGroupItem
key={category.value}
value={category.label}
+ disabled
variant="outline"
- className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal"
+ className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal opacity-50"
>
<span
className="truncate"
@@ -924,6 +964,20 @@ export function AnnotateDrawerContent<Target extends ScoreTarget>({
</span>
<span>{`(${category.value})`}</span>
</ToggleGroupItem>
+ ) : (
+ <ToggleGroupItem
+ key={category.value}
+ value={category.label}
+ variant="outline"
+ className="grid grid-flow-col gap-1 text-nowrap px-1 text-xs font-normal"
+ >
+ <span
+ className="truncate"
+ title={category.label}
+ >
+ {category.label}
+ </span>
+ </ToggleGroupItem>
),
)}
</ToggleGroup>
diff --git a/web/src/features/scores/hooks/useScoreMutations.ts b/web/src/features/scores/hooks/useScoreMutations.ts
index 3ed5e350db..629b5264a9 100644
--- a/web/src/features/scores/hooks/useScoreMutations.ts
+++ b/web/src/features/scores/hooks/useScoreMutations.ts
@@ -1,6 +1,6 @@
import { api } from "@/src/utils/api";
import { type AnnotateFormSchemaType, type ScoreTarget } from "../types";
-import { type ValidatedScoreConfig, type APIScoreV2 } from "@langfuse/shared";
+import { type ScoreConfigDomain, type APIScoreV2 } from "@langfuse/shared";
import {
type UseFieldArrayUpdate,
type UseFieldArrayRemove,
@@ -63,7 +63,7 @@ const onScoreSettledDelete =
utils: ReturnType<typeof api.useUtils>;
fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[];
update: UseFieldArrayUpdate<AnnotateFormSchemaType>;
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
remove: ReturnType<typeof useFieldArray>["remove"];
isDrawerOpen: boolean;
setShowSaving: (showSaving: boolean) => void;
@@ -146,7 +146,7 @@ export function useScoreMutations(
fields: FieldArrayWithId<AnnotateFormSchemaType, "scoreData", "id">[],
update: UseFieldArrayUpdate<AnnotateFormSchemaType>,
remove: UseFieldArrayRemove,
- configs: ValidatedScoreConfig[],
+ configs: ScoreConfigDomain[],
isDrawerOpen: boolean,
setShowSaving: (showSaving: boolean) => void,
) {
diff --git a/web/src/features/scores/lib/getDefaultScoreData.ts b/web/src/features/scores/lib/getDefaultScoreData.ts
index ab95ac1a7b..d2a0b0236e 100644
--- a/web/src/features/scores/lib/getDefaultScoreData.ts
+++ b/web/src/features/scores/lib/getDefaultScoreData.ts
@@ -4,7 +4,7 @@ import {
type ScoreTargetSession,
} from "@langfuse/shared";
import { ScoreSource } from "@langfuse/shared";
-import { type APIScoreV2, type ValidatedScoreConfig } from "@langfuse/shared";
+import { type APIScoreV2, type ScoreConfigDomain } from "@langfuse/shared";
import { isTraceScore } from "@/src/features/scores/lib/helpers";
import { type AnnotationScoreDataSchema } from "@/src/features/scores/schema";
import { type z } from "zod/v4";
@@ -31,7 +31,7 @@ export const getDefaultAnnotationScoreData = ({
}: {
scores: APIScoreV2[];
emptySelectedConfigIds: string[];
- configs: ValidatedScoreConfig[];
+ configs: ScoreConfigDomain[];
scoreTarget: ScoreTarget;
}): z.infer<typeof AnnotationScoreDataSchema>[] => {
const isValidScore = isTraceScore(scoreTarget)
diff --git a/web/src/pages/api/public/score-configs/[configId].ts b/web/src/pages/api/public/score-configs/[configId].ts
index f4c8849505..a0d02e9c9b 100644
--- a/web/src/pages/api/public/score-configs/[configId].ts
+++ b/web/src/pages/api/public/score-configs/[configId].ts
@@ -3,8 +3,15 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddleware
import {
GetScoreConfigQuery,
GetScoreConfigResponse,
+ PutScoreConfigBody as PatchScoreConfigBody,
+ PutScoreConfigQuery as PatchScoreConfigQuery,
+ PutScoreConfigResponse as PatchScoreConfigResponse,
+} from "@/src/features/public-api/types/score-configs";
+import {
InternalServerError,
+ InvalidRequestError,
LangfuseNotFoundError,
+ validateDbScoreConfigSafe,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { traceException } from "@langfuse/shared/src/server";
@@ -28,7 +35,7 @@ export default withMiddlewares({
);
}
- const parsedConfig = GetScoreConfigResponse.safeParse(config);
+ const parsedConfig = validateDbScoreConfigSafe(config);
if (!parsedConfig.success) {
traceException(parsedConfig.error);
throw new InternalServerError("Requested score config is corrupted");
@@ -37,4 +44,45 @@ export default withMiddlewares({
return parsedConfig.data;
},
}),
+ PATCH: createAuthedProjectAPIRoute({
+ name: "Update a Score Config",
+ querySchema: PatchScoreConfigQuery,
+ bodySchema: PatchScoreConfigBody,
+ responseSchema: PatchScoreConfigResponse,
+ fn: async ({ query, body, auth }) => {
+ const existingConfig = await prisma.scoreConfig.findUnique({
+ where: {
+ id: query.configId,
+ projectId: auth.scope.projectId,
+ },
+ });
+
+ if (!existingConfig) {
+ throw new LangfuseNotFoundError(
+ "Score config not found within authorized project",
+ );
+ }
+
+ // Merge the body with the existing config and verify schema compliance
+ const result = validateDbScoreConfigSafe({ ...existingConfig, ...body });
+
+ if (!result.success) {
+ throw new InvalidRequestError(
+ result.error.issues.map((issue) => issue.message).join(", "),
+ );
+ }
+
+ await prisma.scoreConfig.update({
+ where: {
+ id: query.configId,
+ projectId: auth.scope.projectId,
+ },
+ data: {
+ ...body,
+ },
+ });
+
+ return result.data;
+ },
+ }),
});
diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.ts
index b427694ca2..b252627e55 100644
--- a/web/src/pages/api/public/score-configs/index.ts
+++ b/web/src/pages/api/public/score-configs/index.ts
@@ -1,20 +1,21 @@
import { v4 } from "uuid";
import { type z } from "zod/v4";
-
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { isBooleanDataType } from "@/src/features/scores/lib/helpers";
import {
filterAndValidateDbScoreConfigList,
- GetScoreConfigsQuery,
- GetScoreConfigsResponse,
- PostScoreConfigBody,
- PostScoreConfigResponse,
validateDbScoreConfig,
} from "@langfuse/shared";
import { Prisma, prisma } from "@langfuse/shared/src/db";
import { traceException } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import {
+ GetScoreConfigsQuery,
+ GetScoreConfigsResponse,
+ PostScoreConfigBody,
+ PostScoreConfigResponse,
+} from "@/src/features/public-api/types/score-configs";
const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {
if (isBooleanDataType(body.dataType)) {
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index 63dddb3706..35cd869ca8 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -13,7 +13,6 @@ import { MembersTable } from "@/src/features/rbac/components/MembersTable";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { PostHogLogo } from "@/src/components/PosthogLogo";
import { Card } from "@/src/components/ui/card";
-import { ScoreConfigSettings } from "@/src/features/scores/components/ScoreConfigSettings";
import { TransferProjectButton } from "@/src/features/projects/components/TransferProjectButton";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
@@ -27,6 +26,7 @@ import ConfigureRetention from "@/src/features/projects/components/ConfigureRete
import ContainerPage from "@/src/components/layouts/container-page";
import ProtectedLabelsSettings from "@/src/features/prompts/components/ProtectedLabelsSettings";
import { Slack } from "lucide-react";
+import { ScoreConfigSettings } from "@/src/features/score-configs/components/ScoreConfigSettings";
type ProjectSettingsPage = {
title: string;
diff --git a/web/src/server/api/routers/scoreConfigs.ts b/web/src/server/api/routers/scoreConfigs.ts
index 42357de6f8..ccb68176bb 100644
--- a/web/src/server/api/routers/scoreConfigs.ts
+++ b/web/src/server/api/routers/scoreConfigs.ts
@@ -6,12 +6,15 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import {
- Category,
filterAndValidateDbScoreConfigList,
+ InvalidRequestError,
+ LangfuseNotFoundError,
optionalPaginationZod,
+ ScoreConfigCategory,
+ ScoreDataType,
validateDbScoreConfig,
+ validateDbScoreConfigSafe,
} from "@langfuse/shared";
-import { ScoreDataType } from "@langfuse/shared/src/db";
import { traceException } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
@@ -23,6 +26,28 @@ const ScoreConfigAllInputPaginated = ScoreConfigAllInput.extend({
...optionalPaginationZod,
});
+const ScoreConfigCreateInput = z.object({
+ projectId: z.string(),
+ name: z.string().min(1).max(35),
+ dataType: z.enum(ScoreDataType),
+ minValue: z.number().optional(),
+ maxValue: z.number().optional(),
+ categories: z.array(ScoreConfigCategory).optional(),
+ description: z.string().nullish(),
+});
+
+const ScoreConfigUpdateInput = z.object({
+ projectId: z.string(),
+ id: z.string(),
+ // Optional fields that may be updated
+ isArchived: z.boolean().optional(),
+ name: z.string().min(1).max(35).optional(),
+ description: z.string().nullish(),
+ minValue: z.number().optional(),
+ maxValue: z.number().optional(),
+ categories: z.array(ScoreConfigCategory).optional(),
+});
+
export const scoreConfigsRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(ScoreConfigAllInputPaginated)
@@ -58,17 +83,7 @@ export const scoreConfigsRouter = createTRPCRouter({
};
}),
create: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- name: z.string().min(1).max(35),
- dataType: z.enum(ScoreDataType),
- minValue: z.number().optional(),
- maxValue: z.number().optional(),
- categories: z.array(Category).optional(),
- description: z.string().optional(),
- }),
- )
+ .input(ScoreConfigCreateInput)
.mutation(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -93,13 +108,7 @@ export const scoreConfigsRouter = createTRPCRouter({
return validateDbScoreConfig(config);
}),
update: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- id: z.string(),
- isArchived: z.boolean(),
- }),
- )
+ .input(ScoreConfigUpdateInput)
.mutation(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -114,7 +123,18 @@ export const scoreConfigsRouter = createTRPCRouter({
},
});
if (!existingConfig) {
- throw new Error("No score config with this id in this project.");
+ throw new LangfuseNotFoundError(
+ "No score config with this id in this project.",
+ );
+ }
+
+ // Merge the input with the existing config and verify schema compliance
+ const result = validateDbScoreConfigSafe({ ...existingConfig, ...input });
+
+ if (!result.success) {
+ throw new InvalidRequestError(
+ result.error.issues.map((issue) => issue.message).join(", "),
+ );
}
const config = await ctx.prisma.scoreConfig.update({
@@ -122,9 +142,7 @@ export const scoreConfigsRouter = createTRPCRouter({
id: input.id,
projectId: input.projectId,
},
- data: {
- isArchived: input.isArchived,
- },
+ data: { ...input },
});
await auditLog({
@@ -136,6 +154,33 @@ export const scoreConfigsRouter = createTRPCRouter({
after: config,
});
+ return validateDbScoreConfig(config);
+ }),
+ byId: protectedProjectProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "scoreConfigs:read",
+ });
+
+ const config = await ctx.prisma.scoreConfig.findFirst({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!config) {
+ throw new Error("No score config with this id in this project.");
+ }
+
return validateDbScoreConfig(config);
}),
});
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 5d9cb141af..f352a7eb75 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -26,6 +26,7 @@ import {
BatchExportTableName,
type ScoreDomain,
CreateAnnotationScoreData,
+ type ScoreConfigDomain,
} from "@langfuse/shared";
import {
getScoresGroupedByNameSourceType,
@@ -45,6 +46,7 @@ import {
getScoreMetadataById,
deleteScores,
getTracesIdentifierForSession,
+ validateConfigAgainstBody,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
@@ -418,6 +420,39 @@ export const scoresRouter = createTRPCRouter({
`No annotation score with id ${input.id} in project ${input.projectId} in Clickhouse`,
);
} else {
+ // validate score against config
+ if (score.configId) {
+ const config = await ctx.prisma.scoreConfig.findFirst({
+ where: {
+ id: score.configId,
+ projectId: input.projectId,
+ },
+ });
+ if (!config) {
+ throw new LangfuseNotFoundError(
+ `No score config with id ${score.configId} in project ${input.projectId}`,
+ );
+ }
+ try {
+ validateConfigAgainstBody({
+ body: {
+ ...score,
+ value: input.value ?? null,
+ stringValue: input.stringValue ?? null,
+ comment: input.comment ?? null,
+ },
+ config: config as ScoreConfigDomain,
+ context: "ANNOTATION",
+ });
+ } catch (error) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Score does not comply with config schema. Please adjust or delete score.",
+ });
+ }
+ }
+
await upsertScore({
id: input.id,
project_id: input.projectId,
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index f93a081e2d..9a326b0cd3 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -297,37 +297,50 @@ export class IngestionService {
}),
Promise.all(
timeSortedEvents.map(async (scoreEvent) => {
- const validatedScore = await validateAndInflateScore({
- body: scoreEvent.body,
- scoreId: entityId,
- projectId,
- });
-
- return {
- id: entityId,
- project_id: projectId,
- environment: validatedScore.environment,
- timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),
- name: validatedScore.name,
- value: validatedScore.value,
- source: validatedScore.source,
- trace_id: validatedScore.traceId,
- session_id: validatedScore.sessionId,
- dataset_run_id: validatedScore.datasetRunId,
- data_type: validatedScore.dataType,
- observation_id: validatedScore.observationId,
- config_id: validatedScore.configId,
- comment: validatedScore.comment,
- metadata: scoreEvent.body.metadata
- ? convertJsonSchemaToRecord(scoreEvent.body.metadata)
- : {},
- string_value: validatedScore.stringValue,
- created_at: Date.now(),
- updated_at: Date.now(),
- event_ts: new Date(scoreEvent.timestamp).getTime(),
- is_deleted: 0,
- };
+ try {
+ const validatedScore = await validateAndInflateScore({
+ body: scoreEvent.body,
+ scoreId: entityId,
+ projectId,
+ });
+
+ return {
+ id: entityId,
+ project_id: projectId,
+ environment: validatedScore.environment,
+ timestamp: this.getMillisecondTimestamp(scoreEvent.timestamp),
+ name: validatedScore.name,
+ value: validatedScore.value,
+ source: validatedScore.source,
+ trace_id: validatedScore.traceId,
+ session_id: validatedScore.sessionId,
+ dataset_run_id: validatedScore.datasetRunId,
+ data_type: validatedScore.dataType,
+ observation_id: validatedScore.observationId,
+ config_id: validatedScore.configId,
+ comment: validatedScore.comment,
+ metadata: scoreEvent.body.metadata
+ ? convertJsonSchemaToRecord(scoreEvent.body.metadata)
+ : {},
+ string_value: validatedScore.stringValue,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: new Date(scoreEvent.timestamp).getTime(),
+ is_deleted: 0,
+ };
+ // Gracefully handle any score schema validation errors, skip the score insert and reject silently.
+ } catch (error) {
+ logger.info(
+ `Failed to validate and enrich score body for project: ${projectId} and score: ${entityId}`,
+ error,
+ );
+ return null;
+ }
}),
+ ).then((results) =>
+ results.filter(
+ (record): record is NonNullable<typeof record> => record !== null,
+ ),
),
]);
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 0469061093..1a84f9fa40 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -1114,6 +1114,169 @@ describe("Ingestion end-to-end tests", () => {
expect(score.config_id).toBe(scoreConfigId);
});
+ it("should silently reject invalid scores while processing valid ones", async () => {
+ const traceId = randomUUID();
+ const validScoreId1 = randomUUID();
+ const validScoreId2 = randomUUID();
+ const invalidScoreId1 = randomUUID(); // Will have value out of range
+ const invalidScoreId2 = randomUUID(); // Will use archived config
+
+ // Create a trace first
+ const traceEventList: TraceEventType[] = [
+ {
+ id: randomUUID(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "test-trace",
+ timestamp: new Date().toISOString(),
+ environment,
+ },
+ },
+ ];
+
+ await ingestionService.processTraceEventList({
+ projectId,
+ entityId: traceId,
+ createdAtTimestamp: new Date(),
+ traceEventList,
+ });
+
+ // Create score configs
+ const validScoreConfigId = randomUUID();
+ const archivedScoreConfigId = randomUUID();
+
+ await Promise.all([
+ // Valid numeric config with range 0-100
+ prisma.scoreConfig.create({
+ data: {
+ id: validScoreConfigId,
+ dataType: "NUMERIC",
+ name: "valid-config",
+ minValue: 0,
+ maxValue: 100,
+ projectId,
+ },
+ }),
+ // Archived config that should be rejected
+ prisma.scoreConfig.create({
+ data: {
+ id: archivedScoreConfigId,
+ dataType: "NUMERIC",
+ name: "archived-config",
+ isArchived: true,
+ projectId,
+ },
+ }),
+ ]);
+
+ // Process all scores - invalid ones should be rejected silently
+ // and valid ones should be processed
+ await Promise.all([
+ // Valid score 1
+ ingestionService.processScoreEventList({
+ projectId,
+ entityId: validScoreId1,
+ createdAtTimestamp: new Date(),
+ scoreEventList: [
+ {
+ id: validScoreId1,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: validScoreId1,
+ dataType: "NUMERIC",
+ name: "valid-config",
+ value: 85.5, // Within range 0-100
+ source: ScoreSource.API,
+ traceId: traceId,
+ environment,
+ configId: validScoreConfigId,
+ },
+ },
+ ],
+ }),
+ // One valid score, two invalid scores
+ ingestionService.processScoreEventList({
+ projectId,
+ entityId: validScoreId2,
+ createdAtTimestamp: new Date(),
+ scoreEventList: [
+ // invalid score 1
+ {
+ id: invalidScoreId1,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: invalidScoreId1,
+ dataType: "NUMERIC",
+ configId: validScoreConfigId,
+ name: "valid-config",
+ traceId: traceId,
+ source: ScoreSource.API,
+ value: 150, // Outside range 0-100, should fail validation
+ environment,
+ },
+ },
+ // valid score 2
+ {
+ id: validScoreId2,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: validScoreId2,
+ dataType: "NUMERIC",
+ configId: validScoreConfigId,
+ name: "archived-config",
+ traceId: traceId,
+ source: ScoreSource.API,
+ value: 50,
+ environment,
+ },
+ },
+ // invalid score 2
+ {
+ id: invalidScoreId2,
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: invalidScoreId2,
+ dataType: "NUMERIC",
+ configId: archivedScoreConfigId,
+ name: "archived-config",
+ traceId: traceId,
+ source: ScoreSource.API,
+ value: 50, // Valid value but config is archived
+ environment,
+ },
+ },
+ ],
+ }),
+ ]);
+
+ await clickhouseWriter.flushAll(true);
+
+ // Verify that valid scores were inserted
+ const validScore1 = await getClickhouseRecord(
+ TableName.Scores,
+ validScoreId1,
+ );
+ expect(validScore1).toBeDefined();
+ expect(validScore1.trace_id).toBe(traceId);
+ expect(validScore1.value).toBe(85.5);
+ expect(validScore1.config_id).toBe(validScoreConfigId);
+
+ // Verify that invalid scores were silently rejected (not inserted)
+ await expect(
+ getClickhouseRecord(TableName.Scores, invalidScoreId1),
+ ).rejects.toThrow();
+
+ await expect(
+ getClickhouseRecord(TableName.Scores, invalidScoreId2),
+ ).rejects.toThrow();
+ });
+
it("should upsert traces", async () => {
const traceId = randomUUID();