Skip to content

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

chore(datasets): add dataset item manager (#10576)

marliessophiec58f4a2590e5
diff --git a/packages/shared/src/server/datasets/index.ts b/packages/shared/src/server/datasets/index.ts
deleted file mode 100644
index 950aa1ed41..0000000000
--- a/packages/shared/src/server/datasets/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./schemaTypes";
-export * from "./schemaValidation";
diff --git a/packages/shared/src/server/datasets/schemaTypes.ts b/packages/shared/src/server/datasets/schemaTypes.ts
index d1848274c7..158f97a234 100644
--- a/packages/shared/src/server/datasets/schemaTypes.ts
+++ b/packages/shared/src/server/datasets/schemaTypes.ts
@@ -1,8 +1,10 @@
import { z } from "zod/v4";
+import type { Dataset } from "../../db";
import { jsonSchemaNullable } from "../../utils/zod";
-import { isValidJSONSchema } from "../../utils/jsonSchemaValidation";
-import type { Dataset } from "@prisma/client";
-import type { ValidationError } from "./schemaValidation";
+import {
+ isValidJSONSchema,
+ type FieldValidationError,
+} from "../../utils/jsonSchemaValidation";
/**
* Schema for validating JSON Schema objects
@@ -17,6 +19,16 @@ export const DatasetJSONSchema = z
export type DatasetJSONSchema = z.infer<typeof DatasetJSONSchema>;
+/**
+ * Validation error for dataset schema validation
+ * Used when validating existing items against newly added/updated schemas
+ */
+export type DatasetSchemaValidationError = {
+ datasetItemId: string;
+ field: "input" | "expectedOutput";
+ errors: FieldValidationError[];
+};
+
/**
* Result type for dataset mutations that may fail validation
* Using discriminated union for type-safe error handling
@@ -28,5 +40,5 @@ export type DatasetMutationResult =
}
| {
success: false;
- validationErrors: ValidationError[];
+ validationErrors: DatasetSchemaValidationError[];
};
diff --git a/packages/shared/src/server/datasets/schemaValidation.ts b/packages/shared/src/server/datasets/schemaValidation.ts
index ef3c73d532..02b5c58554 100644
--- a/packages/shared/src/server/datasets/schemaValidation.ts
+++ b/packages/shared/src/server/datasets/schemaValidation.ts
@@ -1,51 +1,40 @@
import type { PrismaClient } from "../../db";
-import {
- validateFieldAgainstSchema,
- DatasetSchemaValidator,
- type FieldValidationError,
- type FieldValidationResult,
-} from "../../utils/jsonSchemaValidation";
+import { DatasetSchemaValidator } from "../services/DatasetService/DatasetSchemaValidator";
+import type { DatasetSchemaValidationError } from "./schemaTypes";
-// Re-export for backward compatibility
+// Re-export for backward compatibility with tests
export { isValidJSONSchema } from "../../utils/jsonSchemaValidation";
-export type { FieldValidationError, FieldValidationResult };
-
-export type ValidationError = {
- datasetItemId: string;
- field: "input" | "expectedOutput";
- errors: FieldValidationError[];
-};
export type ValidationResult = {
isValid: boolean;
- errors: ValidationError[];
+ errors: DatasetSchemaValidationError[];
};
/**
- * Validates a single dataset item field against a JSON schema
- * Wrapper around validateFieldAgainstSchema for dataset-specific usage
- */
-export function validateDatasetItemField(params: {
- data: unknown;
- schema: Record<string, unknown>;
- itemId: string;
- field: "input" | "expectedOutput";
-}): FieldValidationResult {
- return validateFieldAgainstSchema({
- data: params.data,
- schema: params.schema,
- });
-}
-
-/**
- * Validates all dataset items against dataset schemas
- * Used when adding or updating schemas on an existing dataset
+ * Validates all existing dataset items against new/updated schemas.
+ *
+ * **When to use:**
+ * - ONLY when adding or updating schemas on a dataset that already has items
+ * - Called during dataset UPSERT operations to ensure existing items are compatible
+ * - Used to block schema changes that would make existing data invalid
+ *
+ * **When NOT to use:**
+ * - DO NOT use for validating new items during creation/update
+ * - Use DatasetItemManager methods instead, which handle per-item validation
*
- * Performance optimized with batched validation:
- * - Compiles schemas once per batch (5000 items) - provides 3800x speedup
- * - Processes items in batches to avoid memory issues
- * - Stops after collecting 10 validation errors (enough for debugging)
- * - No memory leaks: validator is scoped to each batch and garbage collected
+ * **Performance:**
+ * - Batched validation: processes 5000 items at a time
+ * - Compiles schemas once per batch (3800x+ faster than per-item compilation)
+ * - Stops after 10 errors (enough for user feedback without wasting resources)
+ *
+ * @example
+ * // User tries to add schema to dataset with existing items
+ * const result = await validateAllDatasetItems({
+ * datasetId, projectId, inputSchema, expectedOutputSchema, prisma
+ * });
+ * if (!result.isValid) {
+ * throw new Error(`Cannot add schema: ${result.errors.length} items fail validation`);
+ * }
*/
export async function validateAllDatasetItems(params: {
datasetId: string;
@@ -61,7 +50,7 @@ export async function validateAllDatasetItems(params: {
const MAX_ERRORS = 10;
let offset = 0;
- const errors: ValidationError[] = [];
+ const errors: DatasetSchemaValidationError[] = [];
while (errors.length < MAX_ERRORS) {
// Fetch batch
@@ -138,116 +127,3 @@ export async function validateAllDatasetItems(params: {
errors,
};
}
-
-/**
- * Validates a batch of dataset items (for bulk operations like CSV upload)
- * Performance optimized: compiles schemas once for entire batch
- */
-export function validateDatasetItemsBatch(params: {
- items: Array<{ id: string; input: unknown; expectedOutput: unknown }>;
- inputSchema: Record<string, unknown> | null;
- expectedOutputSchema: Record<string, unknown> | null;
-}): ValidationResult {
- const { items, inputSchema, expectedOutputSchema } = params;
- const errors: ValidationError[] = [];
-
- // Create validator once for entire batch - compiles schemas once, reuses for all items
- // Provides 3800x+ performance improvement over fresh compilation per item
- const validator = new DatasetSchemaValidator({
- inputSchema,
- expectedOutputSchema,
- });
-
- for (const item of items) {
- // Validate input if schema exists (validate even if value is null/undefined)
- if (inputSchema) {
- // For CREATE operations, undefined becomes null in DB
- const valueToValidate =
- item.input === undefined || item.input === null ? null : item.input;
-
- const result = validator.validateInput(valueToValidate);
- if (!result.isValid) {
- errors.push({
- datasetItemId: item.id,
- field: "input",
- errors: result.errors,
- });
- }
- }
-
- // Validate expected output if schema exists (validate even if value is null/undefined)
- if (expectedOutputSchema) {
- // For CREATE operations, undefined becomes null in DB
- const valueToValidate =
- item.expectedOutput === undefined || item.expectedOutput === null
- ? null
- : item.expectedOutput;
-
- const result = validator.validateOutput(valueToValidate);
- if (!result.isValid) {
- errors.push({
- datasetItemId: item.id,
- field: "expectedOutput",
- errors: result.errors,
- });
- }
- }
- }
-
- return {
- isValid: errors.length === 0,
- errors,
- };
-}
-
-export type ValidateItemResult =
- | { isValid: true }
- | {
- isValid: false;
- inputErrors?: FieldValidationError[];
- expectedOutputErrors?: FieldValidationError[];
- };
-
-/**
- * Core validation logic - validates dataset item data
- * Works with already-parsed JSON (not strings)
- * Used by both tRPC and Public API
- *
- * Performance optimized: compiles schemas once, validates both fields with reused validators
- * Provides 2x speedup even for single item validation
- *
- * @param normalizeUndefinedToNull - Set to true for CREATE operations where undefined becomes null in DB
- */
-export function validateDatasetItemData(params: {
- input: unknown;
- expectedOutput: unknown;
- inputSchema: Record<string, unknown> | null | undefined;
- expectedOutputSchema: Record<string, unknown> | null | undefined;
- normalizeUndefinedToNull?: boolean;
-}): ValidateItemResult {
- // Create validator once - compiles schemas once, validates both fields
- // Even for single item, this is 2x faster than fresh Ajv per field
- const validator = new DatasetSchemaValidator({
- inputSchema: params.inputSchema ?? null,
- expectedOutputSchema: params.expectedOutputSchema ?? null,
- });
-
- // Normalize values for validation
- const inputToValidate = params.normalizeUndefinedToNull
- ? params.input === undefined || params.input === null
- ? null
- : params.input
- : params.input;
-
- const outputToValidate = params.normalizeUndefinedToNull
- ? params.expectedOutput === undefined || params.expectedOutput === null
- ? null
- : params.expectedOutput
- : params.expectedOutput;
-
- // Use the optimized validateItem method
- return validator.validateItem({
- input: inputToValidate,
- expectedOutput: outputToValidate,
- });
-}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 0dac5bcdfb..aa24a59ed4 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -10,6 +10,9 @@ export * from "./services/PromptService";
export * from "./services/PromptService/types";
export * from "./services/traces-ui-table-service";
export * from "./services/InMemoryFilterService";
+export * from "./services/DatasetService";
+export * from "./datasets/schemaValidation";
+export * from "./datasets/schemaTypes";
export * from "./evalJobConfigCache";
export * from "./auth/apiKeys";
export * from "./auth/invalidateApiKeys";
@@ -98,7 +101,6 @@ export * from "./data-deletion/ingestionFileDeletion";
export * from "./s3";
// dataset run items
-export * from "./datasets";
export * from "./dataset-run-items/addToDeleteQueue";
// test utils
diff --git a/packages/shared/src/server/services/DatasetService/DatasetItemManager.ts b/packages/shared/src/server/services/DatasetService/DatasetItemManager.ts
new file mode 100644
index 0000000000..8106d85b95
--- /dev/null
+++ b/packages/shared/src/server/services/DatasetService/DatasetItemManager.ts
@@ -0,0 +1,421 @@
+import { v4 } from "uuid";
+import { Dataset, DatasetItem, DatasetStatus, prisma } from "../../../db";
+import { LangfuseNotFoundError } from "../../../errors/NotFoundError";
+import { DatasetItemValidator } from "./DatasetItemValidator";
+import type {
+ CreateManyItemsInsert,
+ CreateManyItemsPayload,
+ CreateManyValidationError,
+ PayloadError,
+} from "./types";
+
+type IdOrName = { datasetId: string } | { datasetName: string };
+
+/**
+ * Manager for dataset item CRUD operations.
+ *
+ * **Usage:** Use this class for all create/update/delete operations on dataset items.
+ * Each operation validates items against dataset schemas before persisting.
+ *
+ * **Performance:** Uses DatasetItemValidator which compiles schemas once per operation,
+ * providing 3800x+ speedup for batch operations compared to per-item compilation.
+ *
+ * @example
+ * // Create single item
+ * await DatasetItemManager.createItem({ projectId, datasetId, input, expectedOutput, ... });
+ *
+ * // Bulk create (CSV upload, API batch)
+ * await DatasetItemManager.createManyItems({ projectId, items: [...], ... });
+ *
+ * // Upsert by ID or name
+ * await DatasetItemManager.upsertItem({ projectId, datasetId, datasetItemId, ... });
+ */
+export class DatasetItemManager {
+ private static async getDatasets(props: {
+ projectId: string;
+ datasetIds: string[];
+ }): Promise<Pick<Dataset, "id" | "inputSchema" | "expectedOutputSchema">[]> {
+ const datasets = await prisma.dataset.findMany({
+ where: {
+ id: { in: props.datasetIds },
+ projectId: props.projectId,
+ },
+ select: {
+ id: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ },
+ });
+
+ if (datasets.length !== props.datasetIds.length)
+ throw new LangfuseNotFoundError(
+ `One or more datasets not found for project ${props.projectId}`,
+ );
+
+ return datasets;
+ }
+
+ private static async getDatasetById(props: {
+ projectId: string;
+ datasetId: string;
+ }): Promise<Pick<Dataset, "id" | "inputSchema" | "expectedOutputSchema">> {
+ const result = await this.getDatasets({
+ projectId: props.projectId,
+ datasetIds: [props.datasetId],
+ });
+ return result[0]!;
+ }
+
+ private static async getDatasetByName(props: {
+ projectId: string;
+ datasetName: string;
+ }): Promise<Pick<Dataset, "id" | "inputSchema" | "expectedOutputSchema">> {
+ const dataset = await prisma.dataset.findFirst({
+ where: {
+ name: props.datasetName,
+ projectId: props.projectId,
+ },
+ select: {
+ id: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ },
+ });
+ if (!dataset) {
+ throw new LangfuseNotFoundError(
+ `Dataset ${props.datasetName} not found for project ${props.projectId}`,
+ );
+ }
+ return dataset;
+ }
+
+ /**
+ * Creates a single dataset item with validation.
+ * Validates input/expectedOutput against dataset schemas before insertion.
+ *
+ * **Flexible input:** Accepts both JSON strings (tRPC) and objects (Public API).
+ *
+ * @returns Success with created item, or validation error with details
+ */
+ public static async createItem(props: {
+ projectId: string;
+ datasetId: string;
+ input?: string | unknown | null;
+ expectedOutput?: string | unknown | null;
+ metadata?: string | unknown | null;
+ sourceTraceId?: string;
+ sourceObservationId?: string;
+ normalizeOpts: {
+ sanitizeControlChars?: boolean;
+ };
+ validateOpts: {
+ normalizeUndefinedToNull?: boolean;
+ };
+ }): Promise<{ success: true; datasetItem: DatasetItem } | PayloadError> {
+ // Delegate to createManyItems with single item
+ const result = await this.createManyItems({
+ projectId: props.projectId,
+ items: [
+ {
+ datasetId: props.datasetId,
+ input: props.input,
+ expectedOutput: props.expectedOutput,
+ metadata: props.metadata,
+ sourceTraceId: props.sourceTraceId,
+ sourceObservationId: props.sourceObservationId,
+ },
+ ],
+ normalizeOpts: props.normalizeOpts,
+ validateOpts: props.validateOpts,
+ });
+
+ if (!result.success) {
+ // Transform validation errors to PayloadError format
+ const error = result.validationErrors[0];
+ return {
+ success: false,
+ message: error.errors.map((e) => e.message).join(", "),
+ };
+ }
+
+ const datasetItem = {
+ ...result.datasetItems[0],
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ } as DatasetItem;
+
+ return { success: true, datasetItem };
+ }
+
+ /**
+ * Upserts a dataset item (create if not exists, update if exists).
+ * Validates against dataset schemas before persisting.
+ *
+ * **Flexible input:** Accepts both JSON strings (tRPC) and objects (Public API).
+ *
+ * @param props - Can identify dataset by ID or name
+ * @returns Success with upserted item, or validation error with details
+ */
+ public static async upsertItem(
+ props: {
+ projectId: string;
+ datasetItemId?: string;
+ input?: string | unknown | null;
+ expectedOutput?: string | unknown | null;
+ metadata?: string | unknown | null;
+ sourceTraceId?: string;
+ sourceObservationId?: string;
+ status?: DatasetStatus;
+ normalizeOpts?: { sanitizeControlChars?: boolean };
+ validateOpts: { normalizeUndefinedToNull?: boolean };
+ } & IdOrName,
+ ): Promise<{ success: true; datasetItem: DatasetItem } | PayloadError> {
+ // 1. Get dataset
+ const dataset =
+ "datasetId" in props
+ ? await this.getDatasetById({
+ projectId: props.projectId,
+ datasetId: props.datasetId,
+ })
+ : await this.getDatasetByName({
+ projectId: props.projectId,
+ datasetName: props.datasetName,
+ });
+
+ // 2. Validate item payload
+ const validator = new DatasetItemValidator({
+ inputSchema: dataset.inputSchema as Record<string, unknown> | null,
+ expectedOutputSchema: dataset.expectedOutputSchema as Record<
+ string,
+ unknown
+ > | null,
+ });
+
+ const itemPayload = validator.preparePayload({
+ input: props.input,
+ expectedOutput: props.expectedOutput,
+ metadata: props.metadata,
+ normalizeOpts: props.normalizeOpts,
+ validateOpts: props.validateOpts,
+ });
+
+ if (!itemPayload.success) {
+ return itemPayload;
+ }
+
+ const itemId = props.datasetItemId ?? v4();
+
+ // 3. Update item
+ const datasetItem = await prisma.datasetItem.upsert({
+ where: {
+ id_projectId: {
+ id: itemId,
+ projectId: props.projectId,
+ },
+ datasetId: dataset.id,
+ },
+ create: {
+ id: itemId,
+ input: itemPayload.input,
+ expectedOutput: itemPayload.expectedOutput,
+ metadata: itemPayload.metadata,
+ datasetId: dataset.id,
+ sourceTraceId: props.sourceTraceId ?? undefined,
+ sourceObservationId: props.sourceObservationId ?? undefined,
+ status: props.status ?? undefined,
+ projectId: props.projectId,
+ },
+ update: {
+ input: itemPayload.input,
+ expectedOutput: itemPayload.expectedOutput,
+ metadata: itemPayload.metadata,
+ sourceTraceId: props.sourceTraceId ?? undefined,
+ sourceObservationId: props.sourceObservationId ?? undefined,
+ status: props.status ?? undefined,
+ },
+ });
+
+ return { success: true, datasetItem: datasetItem };
+ }
+
+ /**
+ * Deletes a dataset item by ID.
+ *
+ * @throws LangfuseNotFoundError if item doesn't exist
+ */
+ public static async deleteItem(props: {
+ projectId: string;
+ datasetItemId: string;
+ datasetId?: string;
+ }): Promise<{ success: true; deletedItem: DatasetItem }> {
+ const item = await prisma.datasetItem.findUnique({
+ where: {
+ id_projectId: { id: props.datasetItemId, projectId: props.projectId },
+ ...(props.datasetId ? { datasetId: props.datasetId } : {}),
+ },
+ });
+ if (!item) {
+ throw new LangfuseNotFoundError(
+ `Dataset item with id ${props.datasetItemId} not found for project ${props.projectId}`,
+ );
+ }
+
+ await prisma.datasetItem.delete({
+ where: {
+ id_projectId: { id: props.datasetItemId, projectId: props.projectId },
+ },
+ });
+ return { success: true, deletedItem: item };
+ }
+
+ /**
+ * Bulk creates multiple dataset items with validation.
+ * Validates all items before insertion - if any fail, none are inserted.
+ *
+ * **Performance:** Compiles schemas once per dataset (not per item), providing
+ * 3800x+ speedup over individual validations.
+ *
+ * **Use cases:**
+ * - CSV uploads with thousands of rows
+ * - Batch API endpoints
+ * - Multi-dataset operations (items can span multiple datasets)
+ *
+ * **Index preservation:** Validation errors include `itemIndex` to map back
+ * to original CSV rows or API payloads for user-friendly error reporting.
+ *
+ * @param props.items - Can contain items from multiple datasets
+ * @returns Success with all created items, or validation errors with indices
+ */
+ public static async createManyItems(props: {
+ projectId: string;
+ items: CreateManyItemsPayload;
+ normalizeOpts: { sanitizeControlChars?: boolean };
+ validateOpts: { normalizeUndefinedToNull?: boolean };
+ }): Promise<
+ | {
+ success: true;
+ datasetItems: CreateManyItemsInsert;
+ }
+ | {
+ success: false;
+ validationErrors: CreateManyValidationError[];
+ }
+ > {
+ // 1. Group items by datasetId and add original index (preserves CSV row mapping)
+ const itemsByDataset = props.items.reduce(
+ (acc, item, index) => {
+ if (!acc[item.datasetId]) acc[item.datasetId] = [];
+ acc[item.datasetId].push({
+ ...item,
+ originalIndex: index,
+ });
+ return acc;
+ },
+ {} as Record<
+ string,
+ Array<
+ CreateManyItemsPayload[number] & {
+ originalIndex: number;
+ }
+ >
+ >,
+ );
+ const datasetIds = Object.keys(itemsByDataset);
+
+ const result = await this.getDatasets({
+ projectId: props.projectId,
+ datasetIds,
+ });
+
+ // Create a map of dataset schemas for quick lookup
+ const datasetSchemaMap = new Map(
+ result.map((dataset) => [
+ dataset.id,
+ {
+ inputSchema: dataset.inputSchema as Record<string, unknown> | null,
+ expectedOutputSchema: dataset.expectedOutputSchema as Record<
+ string,
+ unknown
+ > | null,
+ },
+ ]),
+ );
+
+ // 3. Validate all items, collect errors with original index
+ const validationErrors: CreateManyValidationError[] = [];
+ const preparedItems: CreateManyItemsInsert = [];
+
+ for (const datasetId of datasetIds) {
+ const datasetItems = itemsByDataset[datasetId];
+ const schema = datasetSchemaMap.get(datasetId);
+
+ if (!schema) {
+ // Should never happen due to getDatasets validation
+ continue;
+ }
+
+ const validator = new DatasetItemValidator({
+ inputSchema: schema.inputSchema,
+ expectedOutputSchema: schema.expectedOutputSchema,
+ });
+
+ // Validate each item in this dataset
+ for (const item of datasetItems) {
+ const result = validator.preparePayload({
+ input: item.input,
+ expectedOutput: item.expectedOutput,
+ metadata: item.metadata,
+ normalizeOpts: props.normalizeOpts,
+ validateOpts: props.validateOpts,
+ });
+
+ if (!result.success) {
+ // Validation failed - add errors with original index
+ if (result.cause?.inputErrors) {
+ validationErrors.push({
+ itemIndex: item.originalIndex,
+ field: "input",
+ errors: result.cause.inputErrors,
+ });
+ }
+ if (result.cause?.expectedOutputErrors) {
+ validationErrors.push({
+ itemIndex: item.originalIndex,
+ field: "expectedOutput",
+ errors: result.cause.expectedOutputErrors,
+ });
+ }
+ } else {
+ // Validation passed - prepare for insert
+ preparedItems.push({
+ id: v4(),
+ projectId: props.projectId,
+ status: DatasetStatus.ACTIVE,
+ datasetId: item.datasetId,
+ input: result.input,
+ expectedOutput: result.expectedOutput,
+ metadata: result.metadata,
+ sourceTraceId: item.sourceTraceId,
+ sourceObservationId: item.sourceObservationId,
+ });
+ }
+ }
+ }
+
+ // 4. If any validation errors, return early
+ if (validationErrors.length > 0) {
+ return {
+ success: false,
+ validationErrors,
+ };
+ }
+
+ // 5. Bulk insert all valid items
+ await prisma.datasetItem.createMany({ data: preparedItems });
+
+ return {
+ success: true,
+ datasetItems: preparedItems,
+ };
+ }
+}
diff --git a/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts b/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts
new file mode 100644
index 0000000000..9e272e1b17
--- /dev/null
+++ b/packages/shared/src/server/services/DatasetService/DatasetItemValidator.ts
@@ -0,0 +1,241 @@
+import { Prisma } from "../../../db";
+import { FieldValidationError } from "../../../utils/jsonSchemaValidation";
+import { logger } from "../../logger";
+import { DatasetSchemaValidator } from "./DatasetSchemaValidator";
+import type { PreparePayloadResult } from "./types";
+
+type ValidateItemResult =
+ | { isValid: true }
+ | {
+ isValid: false;
+ inputErrors?: FieldValidationError[];
+ expectedOutputErrors?: FieldValidationError[];
+ };
+
+/**
+ * Validator for dataset item payloads (normalization + schema validation).
+ *
+ * @internal
+ * **This class is internal to DatasetService. Use DatasetItemManager methods instead.**
+ *
+ * **Purpose:**
+ * 1. JSON parsing and normalization (strings → objects, control char sanitization)
+ * 2. Schema validation against dataset's input/expectedOutput schemas
+ *
+ * **Performance:** Compiles schemas once in constructor, validates many items with
+ * reused validators. Provides 3800x+ speedup over fresh compilation per item.
+ *
+ * **Used by:** DatasetItemManager for all CRUD operations
+ *
+ * @example
+ * // Internal use only - called by DatasetItemManager
+ * const validator = new DatasetItemValidator({ inputSchema, expectedOutputSchema });
+ * for (const item of items) {
+ * const result = validator.preparePayload({ input, expectedOutput, metadata, ... });
+ * }
+ */
+export class DatasetItemValidator {
+ private validator: DatasetSchemaValidator;
+
+ constructor(params: {
+ inputSchema: Record<string, unknown> | null | undefined;
+ expectedOutputSchema: Record<string, unknown> | null | undefined;
+ }) {
+ // Create validator once - compiles schemas once, validates both fields
+ // Even for single item, this is 2x faster than fresh Ajv per field
+ this.validator = new DatasetSchemaValidator({
+ inputSchema: params.inputSchema,
+ expectedOutputSchema: params.expectedOutputSchema,
+ });
+ }
+
+ /**
+ * Remove problematic C0 and C1 control characters from string values.
+ * PostgreSQL TEXT columns cannot store NULL byte (\u0000) and other control characters.
+ * Preserves common characters like newlines and tabs.
+ */
+ private cleanControlChars(data: string): string {
+ if (!data) return data;
+
+ // Remove control characters:
+ // \u0000-\u0008: NULL through backspace
+ // \u000B: vertical tab (preserve \n=\u000A, \t=\u0009, \r=\u000D)
+ // \u000E-\u001F: shift out through unit separator
+ // \u007F-\u009F: DEL + C1 controls
+ // eslint-disable-next-line no-control-regex
+ return data.replace(/[\u0000-\u0008\u000B\u000E-\u001F\u007F-\u009F]/g, "");
+ }
+
+ /**
+ * Recursively clean control characters from all string values in a JSON structure.
+ * This handles strings within objects and arrays after JSON.parse.
+ */
+ private sanitizeJsonValue = (data: unknown): unknown => {
+ if (typeof data === "string") {
+ return this.cleanControlChars(data);
+ }
+ if (Array.isArray(data)) {
+ return data.map(this.sanitizeJsonValue);
+ }
+ if (data && typeof data === "object") {
+ return Object.fromEntries(
+ Object.entries(data).map(([k, v]) => [k, this.sanitizeJsonValue(v)]),
+ );
+ }
+ return data;
+ };
+
+ /**
+ * Converts normalized value to Prisma-safe value for database writes.
+ * - null → Prisma.DbNull (explicit NULL in DB)
+ * - undefined → undefined (skip field in updates)
+ * - other → passthrough
+ */
+ private toPrismaValue(
+ value: Prisma.InputJsonValue | null | undefined,
+ ): Prisma.InputJsonValue | Prisma.NullTypes.DbNull | undefined {
+ return value === null ? Prisma.DbNull : value;
+ }
+
+ private normalize(
+ data: string | unknown | null | undefined,
+ opts?: { sanitizeControlChars?: boolean },
+ ): Prisma.InputJsonValue | null | undefined {
+ if (data === "") return null;
+ if (data === undefined) return undefined;
+ if (data === null) return null;
+
+ try {
+ // Handle both string (tRPC) and already-parsed values (Public API)
+ // InputJsonValue accepts objects, arrays, strings, numbers, booleans, null
+ let parsed: Prisma.InputJsonValue;
+
+ if (typeof data === "string") {
+ // Try to parse as JSON first (for tRPC which sends JSON strings like '{"key":"value"}')
+ try {
+ parsed = JSON.parse(data) as Prisma.InputJsonValue;
+ } catch {
+ // If parsing fails, it's a plain string
+ // Store the string as-is
+ parsed = data;
+ }
+ } else {
+ // Public API sends already-parsed values - use directly
+ parsed = data as Prisma.InputJsonValue;
+ }
+
+ if (opts?.sanitizeControlChars) {
+ // Sanitize control characters from parsed value before sending to PostgreSQL
+ return this.sanitizeJsonValue(parsed) as Prisma.InputJsonValue;
+ } else {
+ return parsed;
+ }
+ } catch (e) {
+ logger.info(
+ "[DatasetItemValidator.normalize] failed to parse dataset item data",
+ e,
+ );
+
+ return undefined;
+ }
+ }
+
+ /**
+ * Validates dataset item data against schemas (internal use).
+ * Expects already-parsed JSON objects, not strings.
+ *
+ * @param normalizeUndefinedToNull - Set to true for CREATE operations where undefined becomes null in DB
+ */
+ public validateDatasetItemData(params: {
+ input: unknown;
+ expectedOutput: unknown;
+ normalizeUndefinedToNull?: boolean;
+ }): ValidateItemResult {
+ // 1. Normalize IO for validation
+ const inputToValidate = params.normalizeUndefinedToNull
+ ? params.input === undefined || params.input === null
+ ? null
+ : params.input
+ : params.input;
+
+ const outputToValidate = params.normalizeUndefinedToNull
+ ? params.expectedOutput === undefined || params.expectedOutput === null
+ ? null
+ : params.expectedOutput
+ : params.expectedOutput;
+
+ // 2. Validate IO against schema
+ return this.validator.validateItem({
+ input: inputToValidate,
+ expectedOutput: outputToValidate,
+ });
+ }
+
+ /**
+ * Normalizes and validates a dataset item payload for database insertion.
+ * Combines JSON parsing, control character sanitization, and schema validation.
+ *
+ * **Flexible input:** Accepts both JSON strings (from tRPC) and already-parsed
+ * objects (from Public API). Handles both seamlessly.
+ *
+ * @param params.input - JSON string, parsed object, or null
+ * @param params.expectedOutput - JSON string, parsed object, or null
+ * @param params.metadata - JSON string, parsed object, or null
+ * @returns Success with normalized data, or error with validation details
+ */
+ public preparePayload(params: {
+ input: string | unknown | null | undefined;
+ expectedOutput: string | unknown | null | undefined;
+ metadata: string | unknown | null | undefined;
+ normalizeOpts?: { sanitizeControlChars?: boolean };
+ validateOpts: { normalizeUndefinedToNull?: boolean };
+ }): PreparePayloadResult {
+ // 1. Normalize IO
+ const normalizedInput = this.normalize(params.input, params.normalizeOpts);
+ const normalizedExpectedOutput = this.normalize(
+ params.expectedOutput,
+ params.normalizeOpts,
+ );
+ const normalizedMetadata = this.normalize(
+ params.metadata,
+ params.normalizeOpts,
+ );
+
+ // 2. Validate IO against schema
+ const result = this.validateDatasetItemData({
+ input: normalizedInput,
+ expectedOutput: normalizedExpectedOutput,
+ normalizeUndefinedToNull: params.validateOpts.normalizeUndefinedToNull,
+ });
+
+ if (!result.isValid) {
+ const errorMessages: string[] = [];
+ if (result.inputErrors) {
+ errorMessages.push(
+ `Input validation failed: ${result.inputErrors.map((e) => e.message).join(", ")}`,
+ );
+ }
+ if (result.expectedOutputErrors) {
+ errorMessages.push(
+ `Expected output validation failed: ${result.expectedOutputErrors.map((e) => e.message).join(", ")}`,
+ );
+ }
+
+ return {
+ success: false,
+ message: errorMessages.join("; "),
+ cause: {
+ inputErrors: result.inputErrors,
+ expectedOutputErrors: result.expectedOutputErrors,
+ },
+ };
+ }
+
+ return {
+ success: true,
+ input: this.toPrismaValue(normalizedInput),
+ expectedOutput: this.toPrismaValue(normalizedExpectedOutput),
+ metadata: this.toPrismaValue(normalizedMetadata),
+ };
+ }
+}
diff --git a/packages/shared/src/server/services/DatasetService/DatasetSchemaValidator.ts b/packages/shared/src/server/services/DatasetService/DatasetSchemaValidator.ts
new file mode 100644
index 0000000000..e9bdf52148
--- /dev/null
+++ b/packages/shared/src/server/services/DatasetService/DatasetSchemaValidator.ts
@@ -0,0 +1,91 @@
+import { ValidateFunction } from "ajv";
+import {
+ createAjvInstanceInternal,
+ FieldValidationError,
+ FieldValidationResult,
+ validateWithCompiledSchema,
+} from "../../../utils/jsonSchemaValidation";
+
+/**
+ * Operation-scoped validator that compiles schemas once and reuses them
+ * Provides 3800x+ performance improvement over fresh compilation per validation
+ * No memory leaks: instance is scoped to the operation and garbage collected after
+ *
+ * Usage:
+ * ```typescript
+ * const validator = new DatasetSchemaValidator({ inputSchema, expectedOutputSchema });
+ * for (const item of items) {
+ * const result = validator.validateItem(item.input, item.expectedOutput);
+ * }
+ * // validator is GC'd after operation completes
+ * ```
+ */
+export class DatasetSchemaValidator {
+ private inputValidator?: ValidateFunction;
+ private outputValidator?: ValidateFunction;
+
+ constructor(params: {
+ inputSchema?: Record<string, unknown> | null;
+ expectedOutputSchema?: Record<string, unknown> | null;
+ }) {
+ const ajv = createAjvInstanceInternal();
+
+ if (params.inputSchema) {
+ this.inputValidator = ajv.compile(params.inputSchema);
+ }
+
+ if (params.expectedOutputSchema) {
+ this.outputValidator = ajv.compile(params.expectedOutputSchema);
+ }
+ }
+
+ /**
+ * Validates input field
+ */
+ validateInput(data: unknown): FieldValidationResult {
+ if (!this.inputValidator) {
+ return { isValid: true }; // No schema = always valid
+ }
+ return validateWithCompiledSchema(data, this.inputValidator);
+ }
+
+ /**
+ * Validates expectedOutput field
+ */
+ validateOutput(data: unknown): FieldValidationResult {
+ if (!this.outputValidator) {
+ return { isValid: true }; // No schema = always valid
+ }
+ return validateWithCompiledSchema(data, this.outputValidator);
+ }
+
+ /**
+ * Validates both input and expectedOutput fields
+ * Returns combined result
+ */
+ validateItem(params: { input: unknown; expectedOutput: unknown }):
+ | { isValid: true }
+ | {
+ isValid: false;
+ inputErrors?: FieldValidationError[];
+ expectedOutputErrors?: FieldValidationError[];
+ } {
+ const errors: {
+ inputErrors?: FieldValidationError[];
+ expectedOutputErrors?: FieldValidationError[];
+ } = {};
+
+ const inputResult = this.validateInput(params.input);
+ if (!inputResult.isValid) {
+ errors.inputErrors = inputResult.errors;
+ }
+
+ const outputResult = this.validateOutput(params.expectedOutput);
+ if (!outputResult.isValid) {
+ errors.expectedOutputErrors = outputResult.errors;
+ }
+
+ const isValid = !errors.inputErrors && !errors.expectedOutputErrors;
+ return isValid ? { isValid: true } : { isValid: false, ...errors };
+ }
+}
diff --git a/packages/shared/src/server/services/DatasetService/index.ts b/packages/shared/src/server/services/DatasetService/index.ts
new file mode 100644
index 0000000000..0f088bd2cc
--- /dev/null
+++ b/packages/shared/src/server/services/DatasetService/index.ts
@@ -0,0 +1,4 @@
+export * from "./DatasetItemManager";
+export * from "./types";
+export * from "./DatasetItemValidator";
+export * from "./DatasetSchemaValidator";
diff --git a/packages/shared/src/server/services/DatasetService/types.ts b/packages/shared/src/server/services/DatasetService/types.ts
new file mode 100644
index 0000000000..8c7a42cee0
--- /dev/null
+++ b/packages/shared/src/server/services/DatasetService/types.ts
@@ -0,0 +1,58 @@
+import { DatasetStatus, Prisma } from "../../../db";
+import { FieldValidationError } from "../../../utils/jsonSchemaValidation";
+
+export type PayloadError = {
+ success: false;
+ message: string;
+ cause?: {
+ inputErrors?: FieldValidationError[];
+ expectedOutputErrors?: FieldValidationError[];
+ };
+};
+
+export type PreparePayloadResult =
+ | {
+ success: true;
+ input: Prisma.NullTypes.DbNull | Prisma.InputJsonValue | undefined;
+ expectedOutput:
+ | Prisma.NullTypes.DbNull
+ | Prisma.InputJsonValue
+ | undefined;
+ metadata: Prisma.NullTypes.DbNull | Prisma.InputJsonValue | undefined;
+ }
+ | PayloadError;
+
+export type CreateManyItemsPayload = {
+ datasetId: string;
+ input?: string | unknown | null;
+ expectedOutput?: string | unknown | null;
+ metadata?: string | unknown | null;
+ sourceTraceId?: string;
+ sourceObservationId?: string;
+}[];
+
+export type CreateManyItemsInsert = {
+ id: string;
+ projectId: string;
+ datasetId: string;
+ status: DatasetStatus;
+ input: Prisma.NullTypes.DbNull | Prisma.InputJsonValue | undefined;
+ expectedOutput: Prisma.NullTypes.DbNull | Prisma.InputJsonValue | undefined;
+ metadata: Prisma.NullTypes.DbNull | Prisma.InputJsonValue | undefined;
+ sourceTraceId?: string;
+ sourceObservationId?: string;
+}[];
+
+/**
+ * Type for bulk dataset item validation errors
+ * Used when validating multiple items before creation (e.g., CSV upload)
+ */
+export type CreateManyValidationError = {
+ itemIndex: number;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ keyword?: string;
+ }>;
+};
diff --git a/packages/shared/src/utils/jsonSchemaValidation.ts b/packages/shared/src/utils/jsonSchemaValidation.ts
index 5e18c996c6..876c53accd 100644
--- a/packages/shared/src/utils/jsonSchemaValidation.ts
+++ b/packages/shared/src/utils/jsonSchemaValidation.ts
@@ -1,10 +1,25 @@
import Ajv, { AnySchema, ValidateFunction } from "ajv";
import addFormats from "ajv-formats";
+export type FieldValidationError = {
+ path: string;
+ message: string;
+ keyword?: string;
+};
+
+export type FieldValidationResult =
+ | {
+ isValid: true;
+ }
+ | {
+ isValid: false;
+ errors: FieldValidationError[];
+ };
+
/**
* Creates a fresh Ajv instance for validation
*/
-export const createAjvInstance = () => {
+export const createAjvInstanceInternal = () => {
const ajv = new Ajv({
strict: true,
allErrors: false, // Return only the first error, not all
@@ -26,7 +41,7 @@ export function isValidJSONSchema(schema: unknown): boolean {
const stringified = JSON.stringify(schema);
if (stringified.length > 1_000) return false; // Schema too large
- const ajv = createAjvInstance();
+ const ajv = createAjvInstanceInternal();
// This will throw an error if the schema is invalid
ajv.compile(schema as AnySchema);
@@ -36,26 +51,11 @@ export function isValidJSONSchema(schema: unknown): boolean {
}
}
-export type FieldValidationError = {
- path: string;
- message: string;
- keyword?: string;
-};
-
-export type FieldValidationResult =
- | {
- isValid: true;
- }
- | {
- isValid: false;
- errors: FieldValidationError[];
- };
-
/**
* Validates data against a compiled schema validator
* Optimized for reuse - compiles schema once, validates many times
*/
-function validateWithCompiledSchema(
+export function validateWithCompiledSchema(
data: unknown,
validator: ValidateFunction,
): FieldValidationResult {
@@ -85,91 +85,7 @@ export function validateFieldAgainstSchema(params: {
schema: Record<string, unknown>;
}): FieldValidationResult {
const { data, schema } = params;
- const ajv = createAjvInstance();
+ const ajv = createAjvInstanceInternal();
const validate = ajv.compile(schema);
return validateWithCompiledSchema(data, validate);
}
-
-/**
- * Operation-scoped validator that compiles schemas once and reuses them
- * Provides 3800x+ performance improvement over fresh compilation per validation
- * No memory leaks: instance is scoped to the operation and garbage collected after
- *
- * Usage:
- * ```typescript
- * const validator = new DatasetSchemaValidator({ inputSchema, expectedOutputSchema });
- * for (const item of items) {
- * const result = validator.validateItem(item.input, item.expectedOutput);
- * }
- * // validator is GC'd after operation completes
- * ```
- */
-export class DatasetSchemaValidator {
- private inputValidator?: ValidateFunction;
- private outputValidator?: ValidateFunction;
-
- constructor(params: {
- inputSchema?: Record<string, unknown> | null;
- expectedOutputSchema?: Record<string, unknown> | null;
- }) {
- const ajv = createAjvInstance();
-
- if (params.inputSchema) {
- this.inputValidator = ajv.compile(params.inputSchema);
- }
-
- if (params.expectedOutputSchema) {
- this.outputValidator = ajv.compile(params.expectedOutputSchema);
- }
- }
-
- /**
- * Validates input field
- */
- validateInput(data: unknown): FieldValidationResult {
- if (!this.inputValidator) {
- return { isValid: true }; // No schema = always valid
- }
- return validateWithCompiledSchema(data, this.inputValidator);
- }
-
- /**
- * Validates expectedOutput field
- */
- validateOutput(data: unknown): FieldValidationResult {
- if (!this.outputValidator) {
- return { isValid: true }; // No schema = always valid
- }
- return validateWithCompiledSchema(data, this.outputValidator);
- }
-
- /**
- * Validates both input and expectedOutput fields
- * Returns combined result
- */
- validateItem(params: { input: unknown; expectedOutput: unknown }):
- | { isValid: true }
- | {
- isValid: false;
- inputErrors?: FieldValidationError[];
- expectedOutputErrors?: FieldValidationError[];
- } {
- const errors: {
- inputErrors?: FieldValidationError[];
- expectedOutputErrors?: FieldValidationError[];
- } = {};
-
- const inputResult = this.validateInput(params.input);
- if (!inputResult.isValid) {
- errors.inputErrors = inputResult.errors;
- }
-
- const outputResult = this.validateOutput(params.expectedOutput);
- if (!outputResult.isValid) {
- errors.expectedOutputErrors = outputResult.errors;
- }
-
- const isValid = !errors.inputErrors && !errors.expectedOutputErrors;
- return isValid ? { isValid: true } : { isValid: false, ...errors };
- }
-}
diff --git a/web/src/__tests__/async/datasets-schema-validation.servertest.ts b/web/src/__tests__/async/datasets-schema-validation.servertest.ts
index fd3a704b78..1327678e95 100644
--- a/web/src/__tests__/async/datasets-schema-validation.servertest.ts
+++ b/web/src/__tests__/async/datasets-schema-validation.servertest.ts
@@ -11,9 +11,9 @@ import {
import {
createOrgProjectAndApiKey,
isValidJSONSchema,
- validateDatasetItemField,
- validateDatasetItemData,
+ DatasetItemValidator,
} from "@langfuse/shared/src/server";
+import { validateFieldAgainstSchema } from "@langfuse/shared";
// Test schemas
const TEST_SCHEMAS = {
@@ -127,34 +127,28 @@ describe("Unit Tests - isValidJSONSchema", () => {
});
});
-describe("Unit Tests - validateDatasetItemField", () => {
+describe("Unit Tests - validateFieldAgainstSchema", () => {
describe("Valid cases", () => {
it("should validate valid data against schema", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.validSimpleText,
schema: TEST_SCHEMAS.simpleText,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(true);
});
it("should validate null when schema allows null", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: null,
schema: TEST_SCHEMAS.allowsNull,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(true);
});
it("should validate complex nested objects", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.validChatMessages,
schema: TEST_SCHEMAS.chatMessages,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(true);
});
@@ -162,11 +156,9 @@ describe("Unit Tests - validateDatasetItemField", () => {
describe("Invalid cases", () => {
it("should return errors for invalid data", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.invalidSimpleText,
schema: TEST_SCHEMAS.simpleText,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(false);
if (!result.isValid) {
@@ -176,11 +168,9 @@ describe("Unit Tests - validateDatasetItemField", () => {
});
it("should reject null when schema doesn't allow null", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: null,
schema: TEST_SCHEMAS.requiresObject,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(false);
if (!result.isValid) {
@@ -189,11 +179,9 @@ describe("Unit Tests - validateDatasetItemField", () => {
});
it("should validate enum violations", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.invalidChatMessages,
schema: TEST_SCHEMAS.chatMessages,
- itemId: "test-id",
- field: "expectedOutput",
});
expect(result.isValid).toBe(false);
if (!result.isValid) {
@@ -202,11 +190,9 @@ describe("Unit Tests - validateDatasetItemField", () => {
});
it("should validate additionalProperties: false", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.hasExtra,
schema: TEST_SCHEMAS.simpleText,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(false);
if (!result.isValid) {
@@ -218,11 +204,9 @@ describe("Unit Tests - validateDatasetItemField", () => {
});
it("should return proper JSON paths in errors", () => {
- const result = validateDatasetItemField({
+ const result = validateFieldAgainstSchema({
data: DATA.invalidChatMessages,
schema: TEST_SCHEMAS.chatMessages,
- itemId: "test-id",
- field: "input",
});
expect(result.isValid).toBe(false);
if (!result.isValid) {
@@ -232,94 +216,110 @@ describe("Unit Tests - validateDatasetItemField", () => {
});
});
-describe("Unit Tests - validateDatasetItemData", () => {
+describe("Unit Tests - DatasetItemValidator", () => {
+ const defaultValidator = new DatasetItemValidator({
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ });
+
it("should validate both input and expectedOutput", () => {
- const result = validateDatasetItemData({
+ const result = defaultValidator.preparePayload({
input: DATA.validSimpleText,
expectedOutput: DATA.validNumber,
- inputSchema: TEST_SCHEMAS.simpleText,
- expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
});
- expect(result.isValid).toBe(true);
+
+ expect(result.success).toBe(true);
});
it("should return inputErrors when input invalid", () => {
- const result = validateDatasetItemData({
+ const result = defaultValidator.preparePayload({
input: DATA.invalidSimpleText,
expectedOutput: DATA.validNumber,
- inputSchema: TEST_SCHEMAS.simpleText,
- expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
});
- expect(result.isValid).toBe(false);
- if (!result.isValid) {
- expect(result.inputErrors).toBeDefined();
- expect(result.expectedOutputErrors).toBeUndefined();
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.cause?.inputErrors).toBeDefined();
+ expect(result.cause?.expectedOutputErrors).toBeUndefined();
}
});
it("should return expectedOutputErrors when expectedOutput invalid", () => {
- const result = validateDatasetItemData({
+ const result = defaultValidator.preparePayload({
input: DATA.validSimpleText,
expectedOutput: DATA.invalidNumber,
- inputSchema: TEST_SCHEMAS.simpleText,
- expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
});
- expect(result.isValid).toBe(false);
- if (!result.isValid) {
- expect(result.inputErrors).toBeUndefined();
- expect(result.expectedOutputErrors).toBeDefined();
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.cause?.inputErrors).toBeUndefined();
+ expect(result.cause?.expectedOutputErrors).toBeDefined();
}
});
it("should return both errors when both invalid", () => {
- const result = validateDatasetItemData({
+ const result = defaultValidator.preparePayload({
input: DATA.invalidSimpleText,
expectedOutput: DATA.invalidNumber,
- inputSchema: TEST_SCHEMAS.simpleText,
- expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
});
- expect(result.isValid).toBe(false);
- if (!result.isValid) {
- expect(result.inputErrors).toBeDefined();
- expect(result.expectedOutputErrors).toBeDefined();
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.cause?.inputErrors).toBeDefined();
+ expect(result.cause?.expectedOutputErrors).toBeDefined();
+ expect(result.cause?.inputErrors?.length).toBeGreaterThan(0);
+ expect(result.cause?.expectedOutputErrors?.length).toBeGreaterThan(0);
}
});
it("should treat undefined as null when normalizeUndefinedToNull=true", () => {
- const result = validateDatasetItemData({
- input: undefined,
- expectedOutput: undefined,
+ const validator = new DatasetItemValidator({
inputSchema: TEST_SCHEMAS.requiresObject,
expectedOutputSchema: TEST_SCHEMAS.requiresObject,
- normalizeUndefinedToNull: true,
});
- expect(result.isValid).toBe(false);
+
+ const result = validator.preparePayload({
+ input: undefined,
+ expectedOutput: undefined,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
+ });
+ expect(result.success).toBe(false);
});
it("should reject null when schema doesn't allow null", () => {
- const result = validateDatasetItemData({
+ const result = defaultValidator.preparePayload({
input: null,
expectedOutput: null,
- inputSchema: TEST_SCHEMAS.simpleText,
- expectedOutputSchema: TEST_SCHEMAS.requiresObject,
- normalizeUndefinedToNull: true,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
});
- expect(result.isValid).toBe(false);
- if (!result.isValid) {
- expect(result.inputErrors).toBeDefined();
- expect(result.expectedOutputErrors).toBeDefined();
+ expect(result.success).toBe(false);
+ if (!result.success) {
+ expect(result.cause?.inputErrors).toBeDefined();
+ expect(result.cause?.inputErrors?.length).toBeGreaterThan(0);
+ expect(result.cause?.expectedOutputErrors).toBeDefined();
+ expect(result.cause?.expectedOutputErrors?.length).toBeGreaterThan(0);
}
});
it("should pass when null is allowed in schema", () => {
- const result = validateDatasetItemData({
- input: null,
- expectedOutput: null,
+ const validator = new DatasetItemValidator({
inputSchema: TEST_SCHEMAS.allowsNull,
expectedOutputSchema: TEST_SCHEMAS.allowsNull,
- normalizeUndefinedToNull: true,
});
- expect(result.isValid).toBe(true);
+ const result = validator.preparePayload({
+ input: null,
+ expectedOutput: null,
+ metadata: undefined,
+ validateOpts: { normalizeUndefinedToNull: true },
+ });
+ expect(result.success).toBe(true);
});
});
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 90ba007ceb..1af09a96fb 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -9,7 +9,6 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";
import { DB } from "@/src/server/db";
import {
paginationZod,
- DatasetStatus,
singleFilter,
StringNoHTML,
StringNoHTMLNonEmpty,
@@ -46,79 +45,21 @@ import {
getDatasetRunItemsWithoutIOByItemIds,
getDatasetItemsWithRunDataCount,
getDatasetItemIdsWithRunData,
+ DatasetItemManager,
+ validateAllDatasetItems,
+ DatasetJSONSchema,
+ type DatasetMutationResult,
} from "@langfuse/shared/src/server";
-import { createId as createCuid } from "@paralleldrive/cuid2";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import {
updateDataset,
upsertDataset,
} from "@/src/features/datasets/server/actions/createDataset";
-import {
- validateAllDatasetItems,
- validateDatasetItemField,
- validateDatasetItemData,
- DatasetJSONSchema,
- type DatasetMutationResult,
-} from "@langfuse/shared/src/server";
import { type BulkDatasetItemValidationError } from "@langfuse/shared";
// Batch size kept small (100) as items may have large input/output/metadata JSON
const DUPLICATE_DATASET_ITEMS_BATCH_SIZE = 100;
-/**
- * Remove problematic C0 and C1 control characters from string values.
- * PostgreSQL TEXT columns cannot store NULL byte (\u0000) and other control characters.
- * Preserves common characters like newlines and tabs.
- */
-const cleanControlChars = (input: string): string => {
- if (!input) return input;
-
- // Remove control characters:
- // \u0000-\u0008: NULL through backspace
- // \u000B: vertical tab (preserve \n=\u000A, \t=\u0009, \r=\u000D)
- // \u000E-\u001F: shift out through unit separator
- // \u007F-\u009F: DEL + C1 controls
- return input.replace(/[\u0000-\u0008\u000B\u000E-\u001F\u007F-\u009F]/g, "");
-};
-
-/**
- * Recursively clean control characters from all string values in a JSON structure.
- * This handles strings within objects and arrays after JSON.parse.
- */
-const sanitizeJsonValue = (value: unknown): unknown => {
- if (typeof value === "string") {
- return cleanControlChars(value);
- }
- if (Array.isArray(value)) {
- return value.map(sanitizeJsonValue);
- }
- if (value && typeof value === "object") {
- return Object.fromEntries(
- Object.entries(value).map(([k, v]) => [k, sanitizeJsonValue(v)]),
- );
- }
- return value;
-};
-
-const formatDatasetItemData = (data: string | null | undefined) => {
- if (data === "") return Prisma.DbNull;
-
- try {
- const parsed = !!data ? JSON.parse(data) : undefined;
- // Sanitize control characters from parsed object before sending to PostgreSQL
- return parsed
- ? (sanitizeJsonValue(parsed) as Prisma.InputJsonObject)
- : undefined;
- } catch (e) {
- logger.info(
- "[trpc.datasets.formatDatasetItemData] failed to parse dataset item data",
- e,
- );
-
- return undefined;
- }
-};
-
/**
* Adds a case-insensitive search condition to a Kysely query
* @param searchQuery The search term (optional)
@@ -162,131 +103,6 @@ const resolveMetadata = (metadata: string | null | undefined) => {
}
};
-/**
- * Normalizes a value for Prisma UPDATE operations
- * - undefined = don't update field
- * - null = set to DbNull (SQL NULL)
- * - value = set to value
- */
-const normalizeForUpdate = (
- value: Prisma.InputJsonObject | null | undefined,
-) => (value === undefined ? undefined : value === null ? Prisma.DbNull : value);
-
-/**
- * Validates dataset item data (both input and expectedOutput) and throws TRPCError if invalid
- * Uses shared validation service for consistency between tRPC and Public API
- *
- * @param normalizeUndefinedToNull - Set to true for CREATE operations where undefined becomes null in DB
- */
-const validateAndThrowIfInvalid = (params: {
- input: unknown;
- expectedOutput: unknown;
- inputSchema: Record<string, unknown> | null | undefined;
- expectedOutputSchema: Record<string, unknown> | null | undefined;
- normalizeUndefinedToNull?: boolean;
-}) => {
- const result = validateDatasetItemData({
- input: params.input,
- expectedOutput: params.expectedOutput,
- inputSchema: params.inputSchema,
- expectedOutputSchema: params.expectedOutputSchema,
- normalizeUndefinedToNull: params.normalizeUndefinedToNull,
- });
-
- if (!result.isValid) {
- const errorMessages: string[] = [];
- if (result.inputErrors) {
- errorMessages.push(
- `Input validation failed: ${result.inputErrors.map((e) => e.message).join(", ")}`,
- );
- }
- if (result.expectedOutputErrors) {
- errorMessages.push(
- `Expected output validation failed: ${result.expectedOutputErrors.map((e) => e.message).join(", ")}`,
- );
- }
-
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: errorMessages.join("; "),
- cause: {
- inputErrors: result.inputErrors,
- expectedOutputErrors: result.expectedOutputErrors,
- },
- });
- }
-};
-
-/**
- * Validates bulk items and returns validation errors
- * For all-or-nothing CREATE operations - caller should block entire operation if any errors
- */
-const validateBulkDatasetItems = (params: {
- items: Array<{
- id: string;
- input: unknown;
- expectedOutput: unknown;
- datasetId: string;
- }>;
- datasetSchemas: Map<
- string,
- { inputSchema: unknown; expectedOutputSchema: unknown }
- >;
-}): BulkDatasetItemValidationError[] => {
- const validationErrors: BulkDatasetItemValidationError[] = [];
-
- for (let i = 0; i < params.items.length; i++) {
- const item = params.items[i];
- const schemas = params.datasetSchemas.get(item.datasetId);
-
- if (schemas) {
- // Validate input
- if (schemas.inputSchema) {
- const valueToValidate =
- item.input === undefined || item.input === null ? null : item.input;
-
- const result = validateDatasetItemField({
- data: valueToValidate,
- schema: schemas.inputSchema as Record<string, unknown>,
- itemId: item.id,
- field: "input",
- });
- if (!result.isValid) {
- validationErrors.push({
- itemIndex: i,
- field: "input",
- errors: result.errors,
- });
- }
- }
-
- // Validate expected output
- if (schemas.expectedOutputSchema) {
- const valueToValidate =
- item.expectedOutput === undefined || item.expectedOutput === null
- ? null
- : item.expectedOutput;
-
- const result = validateDatasetItemField({
- data: valueToValidate,
- schema: schemas.expectedOutputSchema as Record<string, unknown>,
- itemId: item.id,
- field: "expectedOutput",
- });
- if (!result.isValid) {
- validationErrors.push({
- itemIndex: i,
- field: "expectedOutput",
- errors: result.errors,
- });
- }
- }
- }
- }
-
- return validationErrors;
-};
-
type GenerateDatasetQueryInput = {
select: Prisma.Sql;
projectId: string;
@@ -877,80 +693,35 @@ export const datasetRouter = createTRPCRouter({
scope: "datasets:CUD",
});
- // Fetch dataset to check for schemas
- const dataset = await ctx.prisma.dataset.findUnique({
- where: {
- id_projectId: { id: input.datasetId, projectId: input.projectId },
- },
- select: { inputSchema: true, expectedOutputSchema: true },
+ const result = await DatasetItemManager.upsertItem({
+ projectId: input.projectId,
+ datasetId: input.datasetId,
+ datasetItemId: input.datasetItemId,
+ input: input.input,
+ expectedOutput: input.expectedOutput,
+ metadata: input.metadata,
+ sourceTraceId: input.sourceTraceId,
+ sourceObservationId: input.sourceObservationId,
+ status: input.status,
+ validateOpts: { normalizeUndefinedToNull: false }, // For UPDATE, undefined means "don't update" },
});
-
- if (!dataset) {
+ if (!result.success) {
throw new TRPCError({
- code: "NOT_FOUND",
- message: "Dataset not found",
+ code: "BAD_REQUEST",
+ message: result.message,
+ cause: result.cause,
});
}
- // Parse input and expected output
- const parsedInput: Prisma.InputJsonObject | null | undefined =
- input.input !== undefined
- ? input.input === ""
- ? null
- : (JSON.parse(input.input) as Prisma.InputJsonObject)
- : undefined;
-
- const parsedExpectedOutput: Prisma.InputJsonObject | null | undefined =
- input.expectedOutput !== undefined
- ? input.expectedOutput === ""
- ? null
- : (JSON.parse(input.expectedOutput) as Prisma.InputJsonObject)
- : undefined;
-
- // Validate both fields together (only if they're being updated)
- validateAndThrowIfInvalid({
- input: parsedInput,
- expectedOutput: parsedExpectedOutput,
- inputSchema: dataset.inputSchema as Record<string, unknown> | null,
- expectedOutputSchema: dataset.expectedOutputSchema as Record<
- string,
- unknown
- > | null,
- normalizeUndefinedToNull: false, // For UPDATE, undefined means "don't update"
- });
-
- const datasetItem = await ctx.prisma.datasetItem.update({
- where: {
- id_projectId: {
- id: input.datasetItemId,
- projectId: input.projectId,
- },
- datasetId: input.datasetId,
- },
- data: {
- input: normalizeForUpdate(parsedInput),
- expectedOutput: normalizeForUpdate(parsedExpectedOutput),
- metadata:
- input.metadata === ""
- ? Prisma.DbNull
- : input.metadata !== undefined
- ? (JSON.parse(input.metadata) as Prisma.InputJsonObject)
- : undefined,
- sourceTraceId: input.sourceTraceId,
- sourceObservationId: input.sourceObservationId,
- status: input.status,
- },
- });
-
await auditLog({
session: ctx.session,
resourceType: "datasetItem",
resourceId: input.datasetItemId,
action: "update",
- after: datasetItem,
+ after: result.datasetItem,
});
- return datasetItem;
+ return result.datasetItem;
}),
createDataset: protectedProjectProcedure
.input(
@@ -1167,44 +938,21 @@ export const datasetRouter = createTRPCRouter({
scope: "datasets:CUD",
});
- // First get the item to use in audit log
- const item = await ctx.prisma.datasetItem.findUnique({
- where: {
- id_projectId: {
- id: input.datasetItemId,
- projectId: input.projectId,
- },
- datasetId: input.datasetId,
- },
- });
-
- if (!item) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Dataset item not found",
- });
- }
-
- // Delete the dataset item
- const deletedItem = await ctx.prisma.datasetItem.delete({
- where: {
- id_projectId: {
- id: input.datasetItemId,
- projectId: input.projectId,
- },
- datasetId: input.datasetId,
- },
+ const result = await DatasetItemManager.deleteItem({
+ projectId: input.projectId,
+ datasetId: input.datasetId,
+ datasetItemId: input.datasetItemId,
});
await auditLog({
session: ctx.session,
resourceType: "datasetItem",
- resourceId: deletedItem.id,
+ resourceId: result.deletedItem.id,
action: "delete",
- before: item,
+ before: result.deletedItem,
});
- return deletedItem;
+ return result.deletedItem;
}),
duplicateDataset: protectedProjectProcedure
.input(
@@ -1340,62 +1088,38 @@ export const datasetRouter = createTRPCRouter({
projectId: input.projectId,
scope: "datasets:CUD",
});
- const dataset = await ctx.prisma.dataset.findUnique({
- where: {
- id_projectId: {
- id: input.datasetId,
- projectId: input.projectId,
- },
- },
- select: {
- id: true,
- inputSchema: true,
- expectedOutputSchema: true,
+
+ const result = await DatasetItemManager.createItem({
+ projectId: input.projectId,
+ datasetId: input.datasetId,
+ input: input.input,
+ expectedOutput: input.expectedOutput,
+ metadata: input.metadata,
+ sourceTraceId: input.sourceTraceId,
+ sourceObservationId: input.sourceObservationId,
+ normalizeOpts: { sanitizeControlChars: true },
+ validateOpts: {
+ normalizeUndefinedToNull: true, // For CREATE, undefined becomes null in DB
},
});
- if (!dataset) {
+
+ if (!result.success) {
throw new TRPCError({
- code: "NOT_FOUND",
- message: "Dataset not found",
+ code: "BAD_REQUEST",
+ message: result.message,
+ cause: result.cause,
});
}
- const parsedInput = formatDatasetItemData(input.input);
- const parsedExpectedOutput = formatDatasetItemData(input.expectedOutput);
-
- // Validate both input and expected output against schemas
- validateAndThrowIfInvalid({
- input: parsedInput,
- expectedOutput: parsedExpectedOutput,
- inputSchema: dataset.inputSchema as Record<string, unknown> | null,
- expectedOutputSchema: dataset.expectedOutputSchema as Record<
- string,
- unknown
- > | null,
- normalizeUndefinedToNull: true, // For CREATE, undefined becomes null in DB
- });
-
- const datasetItem = await ctx.prisma.datasetItem.create({
- data: {
- input: parsedInput,
- expectedOutput: parsedExpectedOutput,
- metadata: formatDatasetItemData(input.metadata),
- datasetId: input.datasetId,
- sourceTraceId: input.sourceTraceId,
- sourceObservationId: input.sourceObservationId,
- projectId: input.projectId,
- },
- });
-
await auditLog({
session: ctx.session,
resourceType: "datasetItem",
- resourceId: datasetItem.id,
+ resourceId: result.datasetItem.id,
action: "create",
- after: datasetItem,
+ after: result.datasetItem,
});
- return datasetItem;
+ return result.datasetItem;
}),
createManyDatasetItems: protectedProjectProcedure
@@ -1431,73 +1155,17 @@ export const datasetRouter = createTRPCRouter({
scope: "datasets:CUD",
});
- // Verify all datasets exist and belong to the project
- const datasetIds = [
- ...new Set(input.items.map((item) => item.datasetId)),
- ];
- const datasets = await ctx.prisma.dataset.findMany({
- where: {
- id: { in: datasetIds },
- projectId: input.projectId,
- },
- select: {
- id: true,
- inputSchema: true,
- expectedOutputSchema: true,
- },
- });
-
- if (datasets.length !== datasetIds.length) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "One or more datasets not found",
- });
- }
-
- // Create a map of dataset schemas for quick lookup
- const datasetSchemaMap = new Map(
- datasets.map((ds) => [
- ds.id,
- {
- inputSchema: ds.inputSchema,
- expectedOutputSchema: ds.expectedOutputSchema,
- },
- ]),
- );
-
- const itemsWithIds = input.items.map((item) => ({
- id: createCuid(),
- input: formatDatasetItemData(item.input),
- expectedOutput: formatDatasetItemData(item.expectedOutput),
- metadata: formatDatasetItemData(item.metadata),
- datasetId: item.datasetId,
- sourceTraceId: item.sourceTraceId,
- sourceObservationId: item.sourceObservationId,
+ const result = await DatasetItemManager.createManyItems({
projectId: input.projectId,
- status: DatasetStatus.ACTIVE,
- }));
-
- // Validate all items - all-or-nothing
- const validationErrors = validateBulkDatasetItems({
- items: itemsWithIds,
- datasetSchemas: datasetSchemaMap,
+ items: input.items,
+ normalizeOpts: { sanitizeControlChars: true },
+ validateOpts: { normalizeUndefinedToNull: true },
});
- // If any validation errors, return them instead of throwing
- if (validationErrors.length > 0) {
- return {
- success: false,
- validationErrors,
- };
- }
-
- // All items valid - create all
- await ctx.prisma.datasetItem.createMany({
- data: itemsWithIds,
- });
+ if (!result.success) return result;
await Promise.all(
- itemsWithIds.map(async (item) =>
+ result.datasetItems.map(async (item) =>
auditLog({
session: ctx.session,
resourceType: "datasetItem",
diff --git a/web/src/pages/api/public/dataset-items/[datasetItemId].ts b/web/src/pages/api/public/dataset-items/[datasetItemId].ts
index 5c93152049..da45657bae 100644
--- a/web/src/pages/api/public/dataset-items/[datasetItemId].ts
+++ b/web/src/pages/api/public/dataset-items/[datasetItemId].ts
@@ -10,6 +10,7 @@ import {
} from "@/src/features/public-api/types/datasets";
import { LangfuseNotFoundError } from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { DatasetItemManager } from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -55,28 +56,9 @@ export default withMiddlewares({
fn: async ({ query, auth }) => {
const { datasetItemId } = query;
- // First get the item to check if it exists
- const datasetItem = await prisma.datasetItem.findUnique({
- where: {
- id_projectId: {
- projectId: auth.scope.projectId,
- id: datasetItemId,
- },
- },
- });
-
- if (!datasetItem) {
- throw new LangfuseNotFoundError("Dataset item not found");
- }
-
- // Delete the dataset item
- await prisma.datasetItem.delete({
- where: {
- id_projectId: {
- projectId: auth.scope.projectId,
- id: datasetItemId,
- },
- },
+ const result = await DatasetItemManager.deleteItem({
+ projectId: auth.scope.projectId,
+ datasetItemId: datasetItemId,
});
await auditLog({
@@ -86,7 +68,7 @@ export default withMiddlewares({
projectId: auth.scope.projectId,
orgId: auth.scope.orgId,
apiKeyId: auth.scope.apiKeyId,
- before: datasetItem,
+ before: result.deletedItem,
});
return {
diff --git a/web/src/pages/api/public/dataset-items/index.ts b/web/src/pages/api/public/dataset-items/index.ts
index de1ce28776..1694016cca 100644
--- a/web/src/pages/api/public/dataset-items/index.ts
+++ b/web/src/pages/api/public/dataset-items/index.ts
@@ -1,7 +1,6 @@
import { prisma } from "@langfuse/shared/src/db";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
-import { v4 as uuidv4 } from "uuid";
import {
GetDatasetItemsV1Query,
GetDatasetItemsV1Response,
@@ -10,12 +9,11 @@ import {
transformDbDatasetItemToAPIDatasetItem,
} from "@/src/features/public-api/types/datasets";
import {
- type DatasetItem,
LangfuseNotFoundError,
InvalidRequestError,
Prisma,
} from "@langfuse/shared";
-import { logger, validateDatasetItemData } from "@langfuse/shared/src/server";
+import { logger, DatasetItemManager } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
export const config = {
@@ -44,77 +42,39 @@ export default withMiddlewares({
status,
} = body;
- const dataset = await prisma.dataset.findFirst({
- where: {
+ try {
+ const result = await DatasetItemManager.upsertItem({
projectId: auth.scope.projectId,
- name: datasetName,
- },
- select: {
- id: true,
- name: true,
- inputSchema: true,
- expectedOutputSchema: true,
- },
- });
- if (!dataset) {
- throw new LangfuseNotFoundError("Dataset not found");
- }
-
- const itemId = id ?? uuidv4();
-
- // Validate input and expectedOutput against schemas before upsert
- // For UPSERT (which handles both CREATE and UPDATE), we validate as CREATE
- // because the data is always being set (not partial update)
- const validationResult = validateDatasetItemData({
- input: input ?? undefined,
- expectedOutput: expectedOutput ?? undefined,
- inputSchema: dataset.inputSchema as Record<string, unknown> | null,
- expectedOutputSchema: dataset.expectedOutputSchema as Record<
- string,
- unknown
- > | null,
- normalizeUndefinedToNull: true, // UPSERT behaves like CREATE for validation
- });
+ datasetName: datasetName,
+ datasetItemId: id ?? undefined,
+ input: input ?? undefined,
+ expectedOutput: expectedOutput ?? undefined,
+ metadata: metadata ?? undefined,
+ sourceTraceId: sourceTraceId ?? undefined,
+ sourceObservationId: sourceObservationId ?? undefined,
+ status: status ?? undefined,
+ normalizeOpts: { sanitizeControlChars: true },
+ validateOpts: { normalizeUndefinedToNull: !!id ? false : true },
+ });
+ if (!result.success) {
+ throw new InvalidRequestError(
+ `Dataset item validation failed: ${result.message}`,
+ );
+ }
- if (!validationResult.isValid) {
- const errorDetails = {
- inputErrors: validationResult.inputErrors,
- expectedOutputErrors: validationResult.expectedOutputErrors,
- };
- throw new InvalidRequestError(
- `Dataset item validation failed: ${JSON.stringify(errorDetails)}`,
- );
- }
+ await auditLog({
+ action: "create",
+ resourceType: "datasetItem",
+ resourceId: result.datasetItem.id,
+ projectId: auth.scope.projectId,
+ orgId: auth.scope.orgId,
+ apiKeyId: auth.scope.apiKeyId,
+ after: result.datasetItem,
+ });
- let item: DatasetItem;
- try {
- item = await prisma.datasetItem.upsert({
- where: {
- datasetId: dataset.id,
- id_projectId: {
- projectId: auth.scope.projectId,
- id: itemId,
- },
- },
- create: {
- id: itemId,
- input: input ?? undefined,
- expectedOutput: expectedOutput ?? undefined,
- datasetId: dataset.id,
- metadata: metadata ?? undefined,
- sourceTraceId: sourceTraceId ?? undefined,
- sourceObservationId: sourceObservationId ?? undefined,
- status: status ?? undefined,
- projectId: auth.scope.projectId,
- },
- update: {
- input: input ?? undefined,
- expectedOutput: expectedOutput ?? undefined,
- metadata: metadata ?? undefined,
- sourceTraceId: sourceTraceId ?? undefined,
- sourceObservationId: sourceObservationId ?? undefined,
- status: status ?? undefined,
- },
+ return transformDbDatasetItemToAPIDatasetItem({
+ ...result.datasetItem,
+ datasetName: datasetName,
});
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
@@ -124,38 +84,15 @@ export default withMiddlewares({
// When this constraint is violated, the database will upsert based on (id, projectId, datasetId).
// If this record does not exist, the database will throw an error.
logger.warn(
- `Failed to upsert dataset item. Dataset item ${itemId} in project ${auth.scope.projectId} already exists for a different dataset than ${dataset.id}`,
+ `Failed to upsert dataset item. Dataset item ${id} in project ${auth.scope.projectId} already exists for a different dataset than ${datasetName}`,
);
throw new LangfuseNotFoundError(
- `The dataset item with id ${itemId} already exists in a dataset other than ${dataset.name}`,
- );
- } else if (e.code === "22P05") {
- // Input includes control characters incompatible with postgres.
- logger.warn(
- `Failed to upsert dataset item. Unsupported unicode escape sequence.`,
- );
- throw new InvalidRequestError(
- `The dataset item with id ${itemId} contains unsupported unicode escape sequences`,
+ `The dataset item with id ${id} already exists in a dataset other than ${datasetName}`,
);
}
}
throw e;
}
-
- await auditLog({
- action: "create",
- resourceType: "datasetItem",
- resourceId: item.id,
- projectId: auth.scope.projectId,
- orgId: auth.scope.orgId,
- apiKeyId: auth.scope.apiKeyId,
- after: item,
- });
-
- return transformDbDatasetItemToAPIDatasetItem({
- ...item,
- datasetName: dataset.name,
- });
},
}),
GET: createAuthedProjectAPIRoute({