Skip to content

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

feat(datasets): add schema enforcement on dataset items (#10180)

Hassieb Pakzad25e6ad94d3de
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 1e8af52f95..d46ea9ce6f 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -384,6 +384,12 @@ types:
name: string
description: optional<string>
metadata: optional<unknown>
+ inputSchema:
+ type: optional<unknown>
+ docs: JSON Schema for validating dataset item inputs
+ expectedOutputSchema:
+ type: optional<unknown>
+ docs: JSON Schema for validating dataset item expected outputs
projectId: string
createdAt: datetime
updatedAt: datetime
diff --git a/fern/apis/server/definition/datasets.yml b/fern/apis/server/definition/datasets.yml
index 5b68674c7e..f1fc001da7 100644
--- a/fern/apis/server/definition/datasets.yml
+++ b/fern/apis/server/definition/datasets.yml
@@ -76,6 +76,12 @@ types:
name: string
description: optional<string>
metadata: optional<unknown>
+ inputSchema:
+ type: optional<unknown>
+ docs: JSON Schema for validating dataset item inputs. When set, all new and existing dataset items will be validated against this schema.
+ expectedOutputSchema:
+ type: optional<unknown>
+ docs: JSON Schema for validating dataset item expected outputs. When set, all new and existing dataset items will be validated against this schema.
PaginatedDatasetRuns:
properties:
data: list<commons.DatasetRun>
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 173366a8c4..06bc913ebf 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -77,6 +77,8 @@
"@slack/oauth": "^3.0.4",
"@slack/web-api": "^7.10.0",
"@types/bcryptjs": "^2.4.6",
+ "ajv": "^8.17.1",
+ "ajv-formats": "^3.0.1",
"bcryptjs": "^2.4.3",
"bullmq": "^5.34.10",
"date-fns": "^3.3.1",
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index a0cd0d1810..a81b2845aa 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -412,6 +412,8 @@ export type Dataset = {
metadata: unknown | null;
remote_experiment_url: string | null;
remote_experiment_payload: unknown | null;
+ input_schema: unknown | null;
+ expected_output_schema: unknown | null;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
diff --git a/packages/shared/prisma/migrations/20251104091248_add_dataset_schema_enforcement/migration.sql b/packages/shared/prisma/migrations/20251104091248_add_dataset_schema_enforcement/migration.sql
new file mode 100644
index 0000000000..50d4a44045
--- /dev/null
+++ b/packages/shared/prisma/migrations/20251104091248_add_dataset_schema_enforcement/migration.sql
@@ -0,0 +1,4 @@
+-- AlterTable
+ALTER TABLE "datasets"
+ADD COLUMN "expected_output_schema" JSON,
+ADD COLUMN "input_schema" JSON;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 373617862f..7322260399 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -598,6 +598,8 @@ model Dataset {
metadata Json?
remoteExperimentUrl String? @map("remote_experiment_url")
remoteExperimentPayload Json? @map("remote_experiment_payload")
+ inputSchema Json? @map("input_schema")
+ expectedOutputSchema Json? @map("expected_output_schema")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
diff --git a/packages/shared/src/features/datasets/validation.ts b/packages/shared/src/features/datasets/validation.ts
index 09a10ecb22..e2f1eda61d 100644
--- a/packages/shared/src/features/datasets/validation.ts
+++ b/packages/shared/src/features/datasets/validation.ts
@@ -5,3 +5,17 @@ import { withFolderPathValidation } from "../folders/validation";
* Dataset name validation schema for API, tRPC and client
*/
export const DatasetNameSchema = withFolderPathValidation(StringNoHTMLNonEmpty);
+
+/**
+ * Type for bulk dataset item validation errors
+ * Used when validating multiple items before creation (e.g., CSV upload)
+ */
+export type BulkDatasetItemValidationError = {
+ itemIndex: number;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ keyword?: string;
+ }>;
+};
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index bc9695d100..49f1406ced 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -14,6 +14,7 @@ export * from "./utils/stringChecks";
export * from "./utils/objects";
export * from "./utils/typeChecks";
export * from "./utils/prompts";
+export * from "./utils/jsonSchemaValidation";
export * from "./features/entitlements/plans";
export * from "./interfaces/rate-limits";
export * from "./tableDefinitions/typeHelpers";
diff --git a/packages/shared/src/server/datasets/index.ts b/packages/shared/src/server/datasets/index.ts
new file mode 100644
index 0000000000..950aa1ed41
--- /dev/null
+++ b/packages/shared/src/server/datasets/index.ts
@@ -0,0 +1,2 @@
+export * from "./schemaTypes";
+export * from "./schemaValidation";
diff --git a/packages/shared/src/server/datasets/schemaTypes.ts b/packages/shared/src/server/datasets/schemaTypes.ts
new file mode 100644
index 0000000000..d1848274c7
--- /dev/null
+++ b/packages/shared/src/server/datasets/schemaTypes.ts
@@ -0,0 +1,32 @@
+import { z } from "zod/v4";
+import { jsonSchemaNullable } from "../../utils/zod";
+import { isValidJSONSchema } from "../../utils/jsonSchemaValidation";
+import type { Dataset } from "@prisma/client";
+import type { ValidationError } from "./schemaValidation";
+
+/**
+ * Schema for validating JSON Schema objects
+ * Supports JSON Schema Draft 2020-12
+ * Uses Ajv to validate that the input is a valid JSON Schema
+ */
+export const DatasetJSONSchema = z
+ .record(z.string(), jsonSchemaNullable)
+ .refine(isValidJSONSchema, {
+ message: "Must be a valid JSON Schema",
+ });
+
+export type DatasetJSONSchema = z.infer<typeof DatasetJSONSchema>;
+
+/**
+ * Result type for dataset mutations that may fail validation
+ * Using discriminated union for type-safe error handling
+ */
+export type DatasetMutationResult =
+ | {
+ success: true;
+ dataset: Dataset;
+ }
+ | {
+ success: false;
+ validationErrors: ValidationError[];
+ };
diff --git a/packages/shared/src/server/datasets/schemaValidation.ts b/packages/shared/src/server/datasets/schemaValidation.ts
new file mode 100644
index 0000000000..ef3c73d532
--- /dev/null
+++ b/packages/shared/src/server/datasets/schemaValidation.ts
@@ -0,0 +1,253 @@
+import type { PrismaClient } from "../../db";
+import {
+ validateFieldAgainstSchema,
+ DatasetSchemaValidator,
+ type FieldValidationError,
+ type FieldValidationResult,
+} from "../../utils/jsonSchemaValidation";
+
+// Re-export for backward compatibility
+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[];
+};
+
+/**
+ * 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
+ *
+ * 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
+ */
+export async function validateAllDatasetItems(params: {
+ datasetId: string;
+ projectId: string;
+ inputSchema: Record<string, unknown> | null;
+ expectedOutputSchema: Record<string, unknown> | null;
+ prisma: PrismaClient;
+}): Promise<ValidationResult> {
+ const { datasetId, projectId, inputSchema, expectedOutputSchema, prisma } =
+ params;
+
+ const BATCH_SIZE = 5_000;
+ const MAX_ERRORS = 10;
+
+ let offset = 0;
+ const errors: ValidationError[] = [];
+
+ while (errors.length < MAX_ERRORS) {
+ // Fetch batch
+ const items = await prisma.datasetItem.findMany({
+ where: {
+ datasetId,
+ projectId,
+ },
+ select: {
+ id: true,
+ input: true,
+ expectedOutput: true,
+ },
+ skip: offset,
+ take: BATCH_SIZE,
+ orderBy: { id: "asc" }, // Consistent ordering for pagination
+ });
+
+ // No more items
+ if (items.length === 0) break;
+
+ // Create validator once per batch - compiles schemas once, reuses for all items
+ // This provides 3800x+ performance improvement over fresh compilation per item
+ // Validator is scoped to this batch and garbage collected after
+ const validator = new DatasetSchemaValidator({
+ inputSchema,
+ expectedOutputSchema,
+ });
+
+ // Validate batch with reused compiled schemas
+ for (const item of items) {
+ // Validate input if schema exists (validate even if value is null)
+ if (inputSchema) {
+ const result = validator.validateInput(item.input);
+ if (!result.isValid) {
+ errors.push({
+ datasetItemId: item.id,
+ field: "input",
+ errors: result.errors,
+ });
+ if (errors.length >= MAX_ERRORS) break;
+ }
+ }
+
+ // Validate expected output if schema exists (validate even if value is null)
+ if (expectedOutputSchema && errors.length < MAX_ERRORS) {
+ const result = validator.validateOutput(item.expectedOutput);
+ if (!result.isValid) {
+ errors.push({
+ datasetItemId: item.id,
+ field: "expectedOutput",
+ errors: result.errors,
+ });
+ if (errors.length >= MAX_ERRORS) break;
+ }
+ }
+
+ // Early exit if we have enough errors
+ if (errors.length >= MAX_ERRORS) break;
+ }
+
+ // Move to next batch
+ offset += BATCH_SIZE;
+
+ // Last batch was incomplete - we've processed all items
+ if (items.length < BATCH_SIZE) break;
+
+ // Early exit if we have enough errors
+ if (errors.length >= MAX_ERRORS) break;
+ }
+
+ return {
+ isValid: errors.length === 0,
+ 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 9dc3ea8f8a..6685caa419 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -95,6 +95,7 @@ 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/utils/jsonSchemaValidation.ts b/packages/shared/src/utils/jsonSchemaValidation.ts
new file mode 100644
index 0000000000..5e18c996c6
--- /dev/null
+++ b/packages/shared/src/utils/jsonSchemaValidation.ts
@@ -0,0 +1,175 @@
+import Ajv, { AnySchema, ValidateFunction } from "ajv";
+import addFormats from "ajv-formats";
+
+/**
+ * Creates a fresh Ajv instance for validation
+ */
+export const createAjvInstance = () => {
+ const ajv = new Ajv({
+ strict: true,
+ allErrors: false, // Return only the first error, not all
+ code: { optimize: true }, // Enable code optimization to improve performance and reduce DoS risk
+ validateFormats: false, // Prevent ReDoS via format validators
+ });
+ addFormats(ajv); // Formats added but not validated
+
+ return ajv;
+};
+
+/**
+ * Validates if a given object is a valid JSON Schema
+ * Used by Zod schema validation
+ * Can be used in both client and server contexts
+ */
+export function isValidJSONSchema(schema: unknown): boolean {
+ try {
+ const stringified = JSON.stringify(schema);
+ if (stringified.length > 1_000) return false; // Schema too large
+
+ const ajv = createAjvInstance();
+ // This will throw an error if the schema is invalid
+ ajv.compile(schema as AnySchema);
+
+ return true;
+ } catch (e) {
+ return false;
+ }
+}
+
+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(
+ data: unknown,
+ validator: ValidateFunction,
+): FieldValidationResult {
+ const isValid = validator(data);
+
+ if (!isValid && validator.errors) {
+ return {
+ isValid: false,
+ errors: validator.errors.map((err) => ({
+ path: err.instancePath || "/",
+ message: err.message || "Validation failed",
+ keyword: err.keyword,
+ })),
+ };
+ }
+
+ return { isValid: true };
+}
+
+/**
+ * Validates a single field against a JSON schema
+ * Creates a fresh Ajv instance for each validation
+ * Use this for one-off validations (e.g., single item create/update)
+ */
+export function validateFieldAgainstSchema(params: {
+ data: unknown;
+ schema: Record<string, unknown>;
+}): FieldValidationResult {
+ const { data, schema } = params;
+ const ajv = createAjvInstance();
+ 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/pnpm-lock.yaml b/pnpm-lock.yaml
index 025b433b07..0b626566da 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -189,6 +189,12 @@ importers:
'@types/bcryptjs':
specifier: ^2.4.6
version: 2.4.6
+ ajv:
+ specifier: ^8.17.1
+ version: 8.17.1
+ ajv-formats:
+ specifier: ^3.0.1
+ version: 3.0.1([email protected])
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
@@ -610,6 +616,9 @@ importers:
ip-address:
specifier: ^9.0.5
version: 9.0.5
+ json-schema-faker:
+ specifier: ^0.5.9
+ version: 0.5.9
kysely:
specifier: ^0.27.4
version: 0.27.4
@@ -6583,6 +6592,14 @@ packages:
ajv:
optional: true
+ resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}
+ peerDependencies:
+ ajv: ^8.0.0
+ peerDependenciesMeta:
+ ajv:
+ optional: true
+
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
peerDependencies:
@@ -6993,6 +7010,9 @@ packages:
resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==}
+
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
@@ -8706,6 +8726,9 @@ packages:
resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-varLbTj0e0yVyRpqQhuWV+8hlePAgaoFRhNFj50BNjEIrw1/DphHSObtqwskVCPWNgzwPoQrZAbfa/SBiicNeg==}
+
resolution: {integrity: sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==}
engines: {node: '>= 12.20'}
@@ -9788,6 +9811,14 @@ packages:
resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}
+ resolution: {integrity: sha512-fNKLHgDvfGNNTX1zqIjqFMJjCLzJ2kvnJ831x4aqkAoeE4jE2TxvpJdhOnk3JU3s42vFzmXvkpbYzH5H3ncAzg==}
+ hasBin: true
+
+ resolution: {integrity: sha512-pXe9H1m6IgIpXmE5JSb8epilNTGsmTb2iPohAXpOdhqGFbQjNeHHsZxU+C8w6T81GZxSPFLeUoqDJmzxx5IGuw==}
+ deprecated: Please switch to @apidevtools/json-schema-ref-parser
+
resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}
engines: {node: '>=16'}
@@ -10970,6 +11001,9 @@ packages:
resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-jQ31cORBFE6td25deYeD80wxKBMj+zBmHTrVxnc6CKhx8gho6ipmWM5zj/oeoqioZ99yqBls9Z/9Nss7J26G2g==}
+
resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
engines: {node: '>=18'}
@@ -21770,6 +21804,10 @@ snapshots:
optionalDependencies:
ajv: 8.17.1
+ optionalDependencies:
+ ajv: 8.17.1
+
dependencies:
ajv: 6.12.6
@@ -22324,6 +22362,8 @@ snapshots:
call-bind-apply-helpers: 1.0.2
get-intrinsic: 1.3.0
+
@@ -24459,6 +24499,8 @@ snapshots:
hasown: 2.0.2
mime-types: 2.1.35
+
dependencies:
node-domexception: 1.0.0
@@ -25884,6 +25926,17 @@ snapshots:
+ dependencies:
+ json-schema-ref-parser: 6.1.0
+ jsonpath-plus: 10.3.0
+
+ dependencies:
+ call-me-maybe: 1.0.2
+ js-yaml: 3.14.1
+ ono: 4.0.11
+
dependencies:
'@babel/runtime': 7.28.4
@@ -27374,6 +27427,10 @@ snapshots:
dependencies:
mimic-function: 5.0.1
+ dependencies:
+ format-util: 1.0.5
+
dependencies:
default-browser: 5.2.1
diff --git a/web/package.json b/web/package.json
index e9d5b7a740..75f06554e0 100644
--- a/web/package.json
+++ b/web/package.json
@@ -118,6 +118,7 @@
"https-proxy-agent": "^7.0.6",
"ioredis": "^5.4.1",
"ip-address": "^9.0.5",
+ "json-schema-faker": "^0.5.9",
"kysely": "^0.27.4",
"langchain": "^0.3.30",
"langfuse": "3.38.4",
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 86ee438ad0..a22bbba1ac 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -6405,6 +6405,12 @@ components:
nullable: true
metadata:
nullable: true
+ inputSchema:
+ nullable: true
+ description: JSON Schema for validating dataset item inputs
+ expectedOutputSchema:
+ nullable: true
+ description: JSON Schema for validating dataset item expected outputs
projectId:
type: string
createdAt:
@@ -6794,6 +6800,17 @@ components:
nullable: true
metadata:
nullable: true
+ inputSchema:
+ nullable: true
+ description: >-
+ JSON Schema for validating dataset item inputs. When set, all new
+ and existing dataset items will be validated against this schema.
+ expectedOutputSchema:
+ nullable: true
+ description: >-
+ JSON Schema for validating dataset item expected outputs. When set,
+ all new and existing dataset items will be validated against this
+ schema.
required:
- name
PaginatedDatasetRuns:
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 0dba1de742..4c2c5986ca 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1005,7 +1005,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"name\": \"example\",\n \"description\": \"example\",\n \"metadata\": \"UNKNOWN\"\n}",
+ "raw": "{\n \"name\": \"example\",\n \"description\": \"example\",\n \"metadata\": \"UNKNOWN\",\n \"inputSchema\": \"UNKNOWN\",\n \"expectedOutputSchema\": \"UNKNOWN\"\n}",
"options": {
"raw": {
"language": "json"
diff --git a/web/src/__tests__/async/datasets-schema-validation.servertest.ts b/web/src/__tests__/async/datasets-schema-validation.servertest.ts
new file mode 100644
index 0000000000..fd3a704b78
--- /dev/null
+++ b/web/src/__tests__/async/datasets-schema-validation.servertest.ts
@@ -0,0 +1,1107 @@
+/** @jest-environment node */
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+} from "@/src/__tests__/test-utils";
+import {
+ PostDatasetsV2Response,
+ PostDatasetItemsV1Response,
+} from "@/src/features/public-api/types/datasets";
+import {
+ createOrgProjectAndApiKey,
+ isValidJSONSchema,
+ validateDatasetItemField,
+ validateDatasetItemData,
+} from "@langfuse/shared/src/server";
+
+// Test schemas
+const TEST_SCHEMAS = {
+ simpleText: {
+ type: "object",
+ properties: { text: { type: "string" } },
+ required: ["text"],
+ additionalProperties: false,
+ },
+
+ chatMessages: {
+ type: "object",
+ properties: {
+ messages: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ role: { type: "string", enum: ["user", "assistant", "system"] },
+ content: { type: "string" },
+ },
+ required: ["role", "content"],
+ },
+ },
+ },
+ required: ["messages"],
+ additionalProperties: false,
+ },
+
+ allowsNull: {
+ anyOf: [
+ { type: "null" },
+ { type: "object", properties: { text: { type: "string" } } },
+ ],
+ },
+
+ requiresObject: {
+ type: "object",
+ properties: { value: { type: "number" } },
+ required: ["value"],
+ additionalProperties: false,
+ },
+
+ invalid: {
+ type: "invalid-type", // Invalid JSON Schema
+ },
+};
+
+// Test data
+const DATA = {
+ validSimpleText: { text: "hello" },
+ invalidSimpleText: { text: 123 },
+ missingRequired: {},
+ hasExtra: { text: "hello", extra: "field" },
+
+ validChatMessages: {
+ messages: [
+ { role: "user", content: "hello" },
+ { role: "assistant", content: "hi" },
+ ],
+ },
+ invalidChatMessages: {
+ messages: [{ role: "invalid", content: "hello" }],
+ },
+
+ validNumber: { value: 42 },
+ invalidNumber: { value: "not a number" },
+};
+
+// ============================================================================
+// UNIT TESTS - Validation Functions
+// ============================================================================
+
+describe("Unit Tests - isValidJSONSchema", () => {
+ it("should return true for valid JSON Schema", () => {
+ expect(isValidJSONSchema(TEST_SCHEMAS.simpleText)).toBe(true);
+ expect(isValidJSONSchema(TEST_SCHEMAS.chatMessages)).toBe(true);
+ expect(isValidJSONSchema(TEST_SCHEMAS.allowsNull)).toBe(true);
+ });
+
+ it("should return false for invalid JSON Schema", () => {
+ expect(isValidJSONSchema(TEST_SCHEMAS.invalid)).toBe(false);
+ });
+
+ it("should return false for null", () => {
+ expect(isValidJSONSchema(null)).toBe(false);
+ });
+
+ it("should return false for non-object values", () => {
+ expect(isValidJSONSchema("string")).toBe(false);
+ expect(isValidJSONSchema(123)).toBe(false);
+ expect(isValidJSONSchema([])).toBe(false);
+ });
+
+ it("should accept complex nested schemas", () => {
+ const complexSchema = {
+ type: "object",
+ properties: {
+ nested: {
+ type: "object",
+ properties: {
+ deep: {
+ type: "array",
+ items: { type: "string" },
+ },
+ },
+ },
+ },
+ };
+ expect(isValidJSONSchema(complexSchema)).toBe(true);
+ });
+});
+
+describe("Unit Tests - validateDatasetItemField", () => {
+ describe("Valid cases", () => {
+ it("should validate valid data against schema", () => {
+ const result = validateDatasetItemField({
+ 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({
+ 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({
+ data: DATA.validChatMessages,
+ schema: TEST_SCHEMAS.chatMessages,
+ itemId: "test-id",
+ field: "input",
+ });
+ expect(result.isValid).toBe(true);
+ });
+ });
+
+ describe("Invalid cases", () => {
+ it("should return errors for invalid data", () => {
+ const result = validateDatasetItemField({
+ data: DATA.invalidSimpleText,
+ schema: TEST_SCHEMAS.simpleText,
+ itemId: "test-id",
+ field: "input",
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.errors.length).toBeGreaterThan(0);
+ expect(result.errors[0].message).toBeDefined();
+ }
+ });
+
+ it("should reject null when schema doesn't allow null", () => {
+ const result = validateDatasetItemField({
+ data: null,
+ schema: TEST_SCHEMAS.requiresObject,
+ itemId: "test-id",
+ field: "input",
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.errors.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("should validate enum violations", () => {
+ const result = validateDatasetItemField({
+ data: DATA.invalidChatMessages,
+ schema: TEST_SCHEMAS.chatMessages,
+ itemId: "test-id",
+ field: "expectedOutput",
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.errors.some((e) => e.keyword === "enum")).toBe(true);
+ }
+ });
+
+ it("should validate additionalProperties: false", () => {
+ const result = validateDatasetItemField({
+ data: DATA.hasExtra,
+ schema: TEST_SCHEMAS.simpleText,
+ itemId: "test-id",
+ field: "input",
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(
+ result.errors.some((e) => e.keyword === "additionalProperties"),
+ ).toBe(true);
+ }
+ });
+ });
+
+ it("should return proper JSON paths in errors", () => {
+ const result = validateDatasetItemField({
+ data: DATA.invalidChatMessages,
+ schema: TEST_SCHEMAS.chatMessages,
+ itemId: "test-id",
+ field: "input",
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.errors[0].path).toBeDefined();
+ expect(typeof result.errors[0].path).toBe("string");
+ }
+ });
+});
+
+describe("Unit Tests - validateDatasetItemData", () => {
+ it("should validate both input and expectedOutput", () => {
+ const result = validateDatasetItemData({
+ input: DATA.validSimpleText,
+ expectedOutput: DATA.validNumber,
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ });
+ expect(result.isValid).toBe(true);
+ });
+
+ it("should return inputErrors when input invalid", () => {
+ const result = validateDatasetItemData({
+ input: DATA.invalidSimpleText,
+ expectedOutput: DATA.validNumber,
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.inputErrors).toBeDefined();
+ expect(result.expectedOutputErrors).toBeUndefined();
+ }
+ });
+
+ it("should return expectedOutputErrors when expectedOutput invalid", () => {
+ const result = validateDatasetItemData({
+ input: DATA.validSimpleText,
+ expectedOutput: DATA.invalidNumber,
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.inputErrors).toBeUndefined();
+ expect(result.expectedOutputErrors).toBeDefined();
+ }
+ });
+
+ it("should return both errors when both invalid", () => {
+ const result = validateDatasetItemData({
+ input: DATA.invalidSimpleText,
+ expectedOutput: DATA.invalidNumber,
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.inputErrors).toBeDefined();
+ expect(result.expectedOutputErrors).toBeDefined();
+ }
+ });
+
+ it("should treat undefined as null when normalizeUndefinedToNull=true", () => {
+ const result = validateDatasetItemData({
+ input: undefined,
+ expectedOutput: undefined,
+ inputSchema: TEST_SCHEMAS.requiresObject,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ normalizeUndefinedToNull: true,
+ });
+ expect(result.isValid).toBe(false);
+ });
+
+ it("should reject null when schema doesn't allow null", () => {
+ const result = validateDatasetItemData({
+ input: null,
+ expectedOutput: null,
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ normalizeUndefinedToNull: true,
+ });
+ expect(result.isValid).toBe(false);
+ if (!result.isValid) {
+ expect(result.inputErrors).toBeDefined();
+ expect(result.expectedOutputErrors).toBeDefined();
+ }
+ });
+
+ it("should pass when null is allowed in schema", () => {
+ const result = validateDatasetItemData({
+ input: null,
+ expectedOutput: null,
+ inputSchema: TEST_SCHEMAS.allowsNull,
+ expectedOutputSchema: TEST_SCHEMAS.allowsNull,
+ normalizeUndefinedToNull: true,
+ });
+ expect(result.isValid).toBe(true);
+ });
+});
+
+// ============================================================================
+// INTEGRATION TESTS - Public API
+// ============================================================================
+
+describe("Public API - Dataset Schema Enforcement", () => {
+ let auth: string;
+ let projectId: string;
+
+ beforeEach(async () => {
+ const { auth: newAuth, projectId: newProjectId } =
+ await createOrgProjectAndApiKey();
+ auth = newAuth;
+ projectId = newProjectId;
+ });
+
+ describe("POST /api/public/v2/datasets - Schema Creation", () => {
+ it("should create dataset with input schema", async () => {
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "test-dataset",
+ description: "Test dataset",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.name).toBe("test-dataset");
+ expect(res.body.inputSchema).toEqual(TEST_SCHEMAS.simpleText);
+ expect(res.body.expectedOutputSchema).toBeNull();
+ });
+
+ it("should create dataset with expectedOutput schema", async () => {
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "test-dataset-2",
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.expectedOutputSchema).toEqual(
+ TEST_SCHEMAS.requiresObject,
+ );
+ expect(res.body.inputSchema).toBeNull();
+ });
+
+ it("should create dataset with both schemas", async () => {
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "test-dataset-3",
+ inputSchema: TEST_SCHEMAS.chatMessages,
+ expectedOutputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.inputSchema).toEqual(TEST_SCHEMAS.chatMessages);
+ expect(res.body.expectedOutputSchema).toEqual(TEST_SCHEMAS.simpleText);
+ });
+
+ it("should create dataset without schemas", async () => {
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "test-dataset-4",
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.inputSchema).toBeNull();
+ expect(res.body.expectedOutputSchema).toBeNull();
+ });
+
+ it("should reject invalid JSON schema format", async () => {
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "test-dataset-invalid",
+ inputSchema: { type: "invalid-type" },
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("POST /api/public/v2/datasets - UPSERT with Validation", () => {
+ it("should add schema to existing dataset via UPSERT", async () => {
+ // Create dataset without schema
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "upsert-dataset" },
+ auth,
+ );
+
+ // UPSERT with schema (should validate existing items)
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "upsert-dataset",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.inputSchema).toEqual(TEST_SCHEMAS.simpleText);
+ });
+
+ it("should block UPSERT if existing items fail validation", async () => {
+ // Create dataset without schema
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "upsert-fail" },
+ auth,
+ );
+
+ // Create item with invalid data (no schema yet)
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "upsert-fail",
+ input: { text: 123 }, // Invalid for simpleText schema
+ },
+ auth,
+ );
+
+ // Try to add schema via UPSERT - should fail
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "upsert-fail",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ expect(res.body.message).toContain("validation failed");
+ });
+ });
+
+ describe("GET /api/public/v2/datasets - Schema Fields", () => {
+ it("should return schemas in dataset list", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "get-test",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v2/datasets?page=1&limit=10",
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.data[0].inputSchema).toEqual(TEST_SCHEMAS.simpleText);
+ });
+
+ it("should return null schemas when not set", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "no-schema-test" },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v2/datasets?page=1&limit=10",
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ const dataset = res.body.data.find(
+ (d: any) => d.name === "no-schema-test",
+ );
+ expect(dataset.inputSchema).toBeNull();
+ expect(dataset.expectedOutputSchema).toBeNull();
+ });
+ });
+
+ describe("POST /api/public/dataset-items - Schema Validation", () => {
+ it("should create item with valid input (schema enforced)", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "valid-input-test",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "valid-input-test",
+ input: { text: "hello" },
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.input).toEqual({ text: "hello" });
+ });
+
+ it("should create item with valid expectedOutput (schema enforced)", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "valid-output-test",
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ },
+ auth,
+ );
+
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "valid-output-test",
+ expectedOutput: { value: 42 },
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.expectedOutput).toEqual({ value: 42 });
+ });
+
+ it("should create item without schemas set", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "no-validation" },
+ auth,
+ );
+
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "no-validation",
+ input: "anything goes",
+ expectedOutput: 123,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ });
+
+ it("should create item with null when schema allows null", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "allows-null",
+ inputSchema: TEST_SCHEMAS.allowsNull,
+ },
+ auth,
+ );
+
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "allows-null",
+ input: null,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ });
+
+ it("should reject item with invalid input", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "reject-invalid",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "reject-invalid",
+ input: { text: 123 }, // Invalid type
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ expect(res.body.message).toContain("validation failed");
+ });
+
+ it("should reject item with invalid expectedOutput", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "reject-output",
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "reject-output",
+ expectedOutput: "not an object",
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should reject item with null when schema doesn't allow null", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "no-null",
+ inputSchema: TEST_SCHEMAS.simpleText, // Requires object
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "no-null",
+ input: null,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ expect(res.body.message).toContain("validation failed");
+ });
+
+ it("should reject item with missing required fields", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "missing-fields",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "missing-fields",
+ input: {}, // Missing required 'text' field
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should validate complex nested structures", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "nested-test",
+ inputSchema: TEST_SCHEMAS.chatMessages,
+ },
+ auth,
+ );
+
+ const validRes = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "nested-test",
+ input: {
+ messages: [
+ { role: "user", content: "hello" },
+ { role: "assistant", content: "hi" },
+ ],
+ },
+ },
+ auth,
+ );
+
+ expect(validRes.status).toBe(200);
+
+ // Invalid nested data
+ const invalidRes = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "nested-test",
+ input: {
+ messages: [{ role: "invalid-role", content: "test" }],
+ },
+ },
+ auth,
+ );
+
+ expect(invalidRes.status).toBe(400);
+ });
+ });
+
+ describe("POST /api/public/dataset-items - UPSERT Validation", () => {
+ it("should validate on UPSERT create", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "upsert-create",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "upsert-create",
+ id: "custom-id-1",
+ input: { text: 123 }, // Invalid
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should validate on UPSERT update", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "upsert-update",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ // Create valid item
+ await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "upsert-update",
+ id: "update-id",
+ input: { text: "valid" },
+ },
+ auth,
+ );
+
+ // Update with invalid data
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "upsert-update",
+ id: "update-id",
+ input: { text: 999 }, // Invalid
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("Dataset Schema Addition - Existing Items Validation", () => {
+ it("should block schema addition if existing items are invalid", async () => {
+ // Create dataset without schema
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "existing-invalid" },
+ auth,
+ );
+
+ // Create items with data that won't match future schema
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "existing-invalid",
+ input: { text: 123 }, // Will be invalid for simpleText schema
+ },
+ auth,
+ );
+
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "existing-invalid",
+ input: { text: 456 },
+ },
+ auth,
+ );
+
+ // Try to add schema - should fail because items are invalid
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "existing-invalid",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ expect(res.body.message).toContain("validation failed");
+ expect(res.body.message).toContain("2 item(s)"); // Both items failed
+ });
+
+ it("should allow schema addition if all existing items are valid", async () => {
+ // Create dataset
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "existing-valid" },
+ auth,
+ );
+
+ // Create valid items
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "existing-valid",
+ input: { text: "hello" },
+ },
+ auth,
+ );
+
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "existing-valid",
+ input: { text: "world" },
+ },
+ auth,
+ );
+
+ // Add schema - should succeed
+ const res = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "existing-valid",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.inputSchema).toEqual(TEST_SCHEMAS.simpleText);
+ });
+
+ it("should fail when existing items have null and schema doesn't allow null", async () => {
+ // Create dataset
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ { name: "null-items" },
+ auth,
+ );
+
+ // Create item with null input
+ await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "null-items",
+ input: null,
+ },
+ auth,
+ );
+
+ // Try to add schema that doesn't allow null
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "null-items",
+ inputSchema: TEST_SCHEMAS.simpleText, // Requires object
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("End-to-End Workflow", () => {
+ it("should enforce schema across full workflow", async () => {
+ // 1. Create dataset with schema
+ const datasetRes = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "e2e-workflow",
+ inputSchema: TEST_SCHEMAS.simpleText,
+ expectedOutputSchema: TEST_SCHEMAS.requiresObject,
+ },
+ auth,
+ );
+ expect(datasetRes.status).toBe(200);
+
+ // 2. Create valid item (should succeed)
+ const validItemRes = await makeZodVerifiedAPICall(
+ PostDatasetItemsV1Response,
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "e2e-workflow",
+ input: { text: "valid input" },
+ expectedOutput: { value: 100 },
+ },
+ auth,
+ );
+ expect(validItemRes.status).toBe(200);
+
+ // 3. Try to create invalid item (should fail)
+ const invalidItemRes = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "e2e-workflow",
+ input: { text: 123 }, // Invalid
+ expectedOutput: { value: 50 },
+ },
+ auth,
+ );
+ expect(invalidItemRes.status).toBe(400);
+
+ // 4. Verify only valid item was created
+ const dataset = await prisma.dataset.findFirst({
+ where: { name: "e2e-workflow", projectId },
+ include: { datasetItems: true },
+ });
+ expect(dataset?.datasetItems.length).toBe(1);
+
+ // 5. Update schema (should validate existing items)
+ const updateSchemaRes = await makeAPICall(
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "e2e-workflow",
+ inputSchema: TEST_SCHEMAS.chatMessages, // Change schema
+ },
+ auth,
+ );
+ // Should fail because existing item doesn't match new schema
+ expect(updateSchemaRes.status).toBe(400);
+
+ // 6. Remove schema (should succeed)
+ const removeSchemaRes = await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "e2e-workflow",
+ inputSchema: null,
+ expectedOutputSchema: null,
+ },
+ auth,
+ );
+ expect(removeSchemaRes.status).toBe(200);
+ expect(removeSchemaRes.body.inputSchema).toBeNull();
+ });
+ });
+
+ describe("Error Response Format", () => {
+ it("should return detailed validation errors", async () => {
+ await makeZodVerifiedAPICall(
+ PostDatasetsV2Response,
+ "POST",
+ "/api/public/v2/datasets",
+ {
+ name: "error-format",
+ inputSchema: TEST_SCHEMAS.chatMessages,
+ },
+ auth,
+ );
+
+ const res = await makeAPICall(
+ "POST",
+ "/api/public/dataset-items",
+ {
+ datasetName: "error-format",
+ input: {
+ messages: [{ role: "bad-role", content: "test" }],
+ },
+ },
+ auth,
+ );
+
+ expect(res.status).toBe(400);
+ expect(res.body.message).toBeDefined();
+ // Check that error details are included
+ const errorMessage = res.body.message;
+ expect(typeof errorMessage).toBe("string");
+ });
+ });
+});
diff --git a/web/src/components/JSONSchemaEditor.tsx b/web/src/components/JSONSchemaEditor.tsx
new file mode 100644
index 0000000000..a1de2321e1
--- /dev/null
+++ b/web/src/components/JSONSchemaEditor.tsx
@@ -0,0 +1,110 @@
+import React from "react";
+import { ArrowUpRight } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { CodeMirrorEditor } from "@/src/components/editor";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+
+type JSONSchemaEditorMode = "json"; // Future: "json" | "builder"
+
+type JSONSchemaEditorProps = {
+ /**
+ * The JSON Schema as a string
+ */
+ value: string;
+ /**
+ * Callback when schema changes
+ */
+ onChange: (value: string) => void;
+ /**
+ * Editor mode - currently only "json", future: visual "builder"
+ */
+ mode?: JSONSchemaEditorMode;
+ /**
+ * Maximum height CSS class
+ */
+ className?: string;
+ /**
+ * Whether the editor is disabled
+ */
+ disabled?: boolean;
+ /**
+ * Show help text with link to JSON Schema docs
+ */
+ showHelp?: boolean;
+};
+
+/**
+ * Reusable JSON Schema editor component
+ * Currently supports JSON text editing mode
+ * Designed to be extended with visual schema builder in the future
+ */
+export const JSONSchemaEditor: React.FC<JSONSchemaEditorProps> = ({
+ value,
+ onChange,
+ mode = "json",
+ className = "max-h-[25vh]",
+ disabled = false,
+ showHelp = true,
+}) => {
+ const prettifyJson = () => {
+ try {
+ const parsedJson = JSON.parse(value);
+ const prettified = JSON.stringify(parsedJson, null, 2);
+ onChange(prettified);
+ } catch (error) {
+ showErrorToast(
+ "Failed to prettify JSON",
+ "Please verify your input is valid JSON",
+ "WARNING",
+ );
+ }
+ };
+
+ // Future: Add builder mode UI here
+ if (mode === "json") {
+ return (
+ <div className="flex flex-col gap-2">
+ {showHelp && (
+ <p className="text-sm text-muted-foreground">
+ Define the structure using JSON Schema format.{" "}
+ <a
+ href="https://json-schema.org/learn/miscellaneous-examples"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center underline hover:text-foreground"
+ >
+ See JSON Schema examples
+ <ArrowUpRight className="ml-0.5 h-3 w-3" />
+ </a>
+ </p>
+ )}
+ <div className="relative flex flex-col gap-1">
+ <CodeMirrorEditor
+ value={value}
+ onChange={onChange}
+ mode="json"
+ minHeight={100}
+ className={className}
+ editable={!disabled}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={prettifyJson}
+ disabled={disabled}
+ className="absolute right-3 top-3 text-xs"
+ >
+ Prettify
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Must be a valid JSON Schema object
+ </p>
+ </div>
+ );
+ }
+
+ // Future mode implementations go here
+ return null;
+};
diff --git a/web/src/features/datasets/components/CsvImportValidationError.tsx b/web/src/features/datasets/components/CsvImportValidationError.tsx
new file mode 100644
index 0000000000..edbf921472
--- /dev/null
+++ b/web/src/features/datasets/components/CsvImportValidationError.tsx
@@ -0,0 +1,93 @@
+import { useState } from "react";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import { Button } from "@/src/components/ui/button";
+import { type BulkDatasetItemValidationError } from "@langfuse/shared";
+
+type CsvImportValidationErrorProps = {
+ errors: BulkDatasetItemValidationError[];
+};
+
+export const CsvImportValidationError: React.FC<
+ CsvImportValidationErrorProps
+> = ({ errors }) => {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ const errorCount = errors.length;
+ const hasMoreThan10 = errorCount >= 10; // Backend might limit errors
+
+ return (
+ <Alert variant="destructive" className="mt-4">
+ <AlertTitle className="text-base font-semibold">
+ Schema Validation Failed
+ </AlertTitle>
+ <AlertDescription className="mt-2 space-y-3">
+ <p className="text-sm">
+ {hasMoreThan10
+ ? `${errorCount}+ items failed validation. Showing first ${errorCount} errors.`
+ : `${errorCount} item${errorCount === 1 ? "" : "s"} failed validation.`}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ The CSV data does not match the required schema for this dataset. Fix
+ the errors in your CSV file and try importing again.
+ </p>
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setIsExpanded(!isExpanded)}
+ className="h-auto p-0 text-sm font-medium hover:bg-transparent"
+ >
+ {isExpanded ? (
+ <ChevronDown className="mr-1 h-4 w-4" />
+ ) : (
+ <ChevronRight className="mr-1 h-4 w-4" />
+ )}
+ {isExpanded ? "Hide" : "Show"} error details
+ </Button>
+
+ {isExpanded && (
+ <div className="mt-3 max-h-[400px] space-y-3 overflow-y-auto rounded-md border border-destructive/20 bg-destructive/5 p-3">
+ {errors.map((error, idx) => (
+ <div
+ key={`${error.itemIndex}-${error.field}`}
+ className="space-y-1 border-b border-destructive/10 pb-3 last:border-0 last:pb-0"
+ >
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-xs text-muted-foreground">
+ #{idx + 1}
+ </span>
+ <span className="text-sm font-medium">
+ CSV Row {error.itemIndex + 2}:{" "}
+ {error.field === "input" ? "Input" : "Expected Output"}
+ </span>
+ </div>
+
+ <ul className="ml-6 space-y-1 text-sm">
+ {error.errors.map((err, errIdx) => (
+ <li key={errIdx} className="text-destructive">
+ {err.path !== "/" && (
+ <span className="font-mono text-xs text-muted-foreground">
+ {err.path}:{" "}
+ </span>
+ )}
+ {err.message}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+
+ {hasMoreThan10 && (
+ <p className="pt-2 text-xs text-muted-foreground">
+ Fix these errors to see if there are additional validation
+ issues.
+ </p>
+ )}
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetActionButton.tsx b/web/src/features/datasets/components/DatasetActionButton.tsx
index ac3866ad0c..b906a6bbd4 100644
--- a/web/src/features/datasets/components/DatasetActionButton.tsx
+++ b/web/src/features/datasets/components/DatasetActionButton.tsx
@@ -39,6 +39,8 @@ interface UpdateDatasetButtonProps extends BaseDatasetButtonProps {
datasetName: string;
datasetDescription?: string;
datasetMetadata?: Prisma.JsonValue;
+ datasetInputSchema?: Prisma.JsonValue;
+ datasetExpectedOutputSchema?: Prisma.JsonValue;
icon?: boolean;
}
@@ -138,7 +140,7 @@ export const DatasetActionButton = forwardRef<
</Button>
)}
</DialogTrigger>
- <DialogContent className="sm:max-w-xl">
+ <DialogContent className="max-h-[90vh] sm:max-w-2xl md:max-w-3xl">
<DialogHeader>
<DialogTitle className="mb-4">
{props.mode === "create"
@@ -179,6 +181,8 @@ export const DatasetActionButton = forwardRef<
datasetName={props.datasetName}
datasetDescription={props.datasetDescription}
datasetMetadata={props.datasetMetadata}
+ datasetInputSchema={props.datasetInputSchema}
+ datasetExpectedOutputSchema={props.datasetExpectedOutputSchema}
/>
)}
</DialogContent>
diff --git a/web/src/features/datasets/components/DatasetForm.tsx b/web/src/features/datasets/components/DatasetForm.tsx
index c500991df5..953d6b8fbf 100644
--- a/web/src/features/datasets/components/DatasetForm.tsx
+++ b/web/src/features/datasets/components/DatasetForm.tsx
@@ -15,12 +15,28 @@ import { api } from "@/src/utils/api";
import { useMemo, useState } from "react";
import { Input } from "@/src/components/ui/input";
import { CodeMirrorEditor } from "@/src/components/editor";
-import { DatasetNameSchema, type Prisma } from "@langfuse/shared";
+import {
+ DatasetNameSchema,
+ isValidJSONSchema,
+ type Prisma,
+} from "@langfuse/shared";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { Label } from "@/src/components/ui/label";
import { useRouter } from "next/router";
import { useUniqueNameValidation } from "@/src/hooks/useUniqueNameValidation";
import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";
+import { DatasetSchemaInput } from "./DatasetSchemaInput";
+import { DatasetSchemaValidationError } from "./DatasetSchemaValidationError";
+
+type ServerSideSchemaValidationErrors = {
+ datasetItemId: string;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ keyword?: string;
+ }>;
+}[];
interface BaseDatasetFormProps {
mode: "create" | "update" | "delete";
@@ -46,6 +62,8 @@ interface UpdateDatasetFormProps extends BaseDatasetFormProps {
datasetName: string;
datasetDescription?: string;
datasetMetadata?: Prisma.JsonValue;
+ datasetInputSchema?: Prisma.JsonValue;
+ datasetExpectedOutputSchema?: Prisma.JsonValue;
}
type DatasetFormProps =
@@ -53,6 +71,24 @@ type DatasetFormProps =
| UpdateDatasetFormProps
| DeleteDatasetFormProps;
+// Validation schema for JSON Schema strings
+export const jsonSchemaStringValidator = z.string().refine(
+ (value) => {
+ if (value === "") return true; // Empty is valid (means no schema)
+
+ try {
+ const parsed = JSON.parse(value);
+
+ return isValidJSONSchema(parsed);
+ } catch (error) {
+ return false;
+ }
+ },
+ {
+ message: "Must be a valid JSON Schema",
+ },
+);
+
const formSchema = z.object({
name: DatasetNameSchema,
description: z.string(),
@@ -61,6 +97,7 @@ const formSchema = z.object({
if (value === "") return true;
try {
JSON.parse(value);
+
return true;
} catch (error) {
return false;
@@ -71,12 +108,28 @@ const formSchema = z.object({
"Invalid input. Please provide a JSON object or double-quoted string.",
},
),
+ inputSchema: jsonSchemaStringValidator,
+ expectedOutputSchema: jsonSchemaStringValidator,
});
export const DatasetForm = (props: DatasetFormProps) => {
const [formError, setFormError] = useState<string | null>(null);
+ const [
+ serverSideSchemaValidationErrors,
+ setServerSideSchemaValidationErrors,
+ ] = useState<ServerSideSchemaValidationErrors | null>(null);
const capture = usePostHogClientCapture();
const [deleteConfirmationInput, setDeleteConfirmationInput] = useState("");
+
+ const inputSchemaString =
+ props.mode === "update" && props.datasetInputSchema
+ ? JSON.stringify(props.datasetInputSchema, null, 2)
+ : "";
+ const expectedOutputSchemaString =
+ props.mode === "update" && props.datasetExpectedOutputSchema
+ ? JSON.stringify(props.datasetExpectedOutputSchema, null, 2)
+ : "";
+
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues:
@@ -87,6 +140,8 @@ export const DatasetForm = (props: DatasetFormProps) => {
metadata: props.datasetMetadata
? JSON.stringify(props.datasetMetadata, null, 2)
: "",
+ inputSchema: inputSchemaString,
+ expectedOutputSchema: expectedOutputSchemaString,
}
: {
name:
@@ -95,13 +150,15 @@ export const DatasetForm = (props: DatasetFormProps) => {
: "",
description: "",
metadata: "",
+ inputSchema: "",
+ expectedOutputSchema: "",
},
});
const utils = api.useUtils();
const router = useRouter();
const createMutation = api.datasets.createDataset.useMutation();
- const renameMutation = api.datasets.updateDataset.useMutation();
+ const updateMutation = api.datasets.updateDataset.useMutation();
const deleteMutation = api.datasets.deleteDataset.useMutation();
const allDatasets = api.datasets.allDatasetMeta.useQuery(
@@ -124,11 +181,23 @@ export const DatasetForm = (props: DatasetFormProps) => {
});
function onSubmit(values: z.infer<typeof formSchema>) {
+ // Parse schemas if they're not empty (tRPC expects objects for DatasetJSONSchema)
+ const inputSchema =
+ values.inputSchema === "" ? null : JSON.parse(values.inputSchema);
+ const expectedOutputSchema =
+ values.expectedOutputSchema === ""
+ ? null
+ : JSON.parse(values.expectedOutputSchema);
+
const trimmedValues = {
- ...values,
name: values.name.trim(),
description: values.description !== "" ? values.description.trim() : null,
+ // Keep metadata as string - resolveMetadata in tRPC will parse it
+ metadata: values.metadata !== "" ? values.metadata : null,
+ inputSchema,
+ expectedOutputSchema,
};
+
if (props.mode === "create") {
capture("datasets:new_form_submit");
createMutation
@@ -136,33 +205,51 @@ export const DatasetForm = (props: DatasetFormProps) => {
...trimmedValues,
projectId: props.projectId,
})
- .then((dataset) => {
- void utils.datasets.invalidate();
- props.onFormSuccess?.();
- form.reset();
- router.push(
- `/project/${props.projectId}/datasets/${dataset.id}/items`,
- );
+ .then((result) => {
+ if (result.success) {
+ // Success - navigate to dataset items
+ void utils.datasets.invalidate();
+ props.onFormSuccess?.();
+ form.reset();
+ router.push(
+ `/project/${props.projectId}/datasets/${result.dataset.id}/items`,
+ );
+ } else {
+ // Validation failed - show errors
+ setServerSideSchemaValidationErrors(result.validationErrors);
+ setFormError(null);
+ }
})
.catch((error: Error) => {
+ // System error (not validation)
setFormError(error.message);
+ setServerSideSchemaValidationErrors(null);
console.error(error);
});
} else if (props.mode === "update") {
capture("datasets:update_form_submit");
- renameMutation
+ updateMutation
.mutateAsync({
...trimmedValues,
projectId: props.projectId,
datasetId: props.datasetId,
})
- .then(() => {
- void utils.datasets.invalidate();
- props.onFormSuccess?.();
- form.reset();
+ .then((result) => {
+ if (result.success) {
+ // Success - close dialog
+ void utils.datasets.invalidate();
+ props.onFormSuccess?.();
+ form.reset();
+ } else {
+ // Validation failed - show errors
+ setServerSideSchemaValidationErrors(result.validationErrors);
+ setFormError(null);
+ }
})
.catch((error: Error) => {
+ // System error (not validation)
setFormError(error.message);
+ setServerSideSchemaValidationErrors(null);
console.error(error);
});
}
@@ -197,107 +284,144 @@ export const DatasetForm = (props: DatasetFormProps) => {
};
return (
- <div>
- <Form {...form}>
- <form
- onSubmit={
- props.mode === "delete" ? handleDelete : form.handleSubmit(onSubmit)
- }
- >
- <DialogBody>
- {props.mode === "delete" ? (
- <div className="mb-8 grid w-full gap-1.5">
- <Label htmlFor="delete-confirmation">
- Type &quot;{props.datasetName}&quot; to confirm deletion
- </Label>
- <Input
- id="delete-confirmation"
- value={deleteConfirmationInput}
- onChange={(e) => setDeleteConfirmationInput(e.target.value)}
- />
- </div>
- ) : (
- <div className="mb-8 space-y-6">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormDescription>
- Use slashes &apos;/&apos; in dataset names to organize
- them into <em>folders</em>.
- </FormDescription>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description (optional)</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="metadata"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Metadata (optional)</FormLabel>
- <FormControl>
- <CodeMirrorEditor
- mode="json"
- value={field.value}
- onChange={(v) => {
- field.onChange(v);
- }}
- minHeight="none"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ <Form {...form}>
+ <form
+ onSubmit={
+ props.mode === "delete" ? handleDelete : form.handleSubmit(onSubmit)
+ }
+ className="flex h-full min-h-0 flex-col"
+ >
+ <DialogBody>
+ {props.mode === "delete" ? (
+ <div className="mb-8 grid w-full gap-1.5">
+ <Label htmlFor="delete-confirmation">
+ Type &quot;{props.datasetName}&quot; to confirm deletion
+ </Label>
+ <Input
+ id="delete-confirmation"
+ value={deleteConfirmationInput}
+ onChange={(e) => setDeleteConfirmationInput(e.target.value)}
+ />
+ </div>
+ ) : (
+ <div className="mb-8 space-y-6">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormDescription>
+ Use slashes &apos;/&apos; in dataset names to organize
+ them into <em>folders</em>.
+ </FormDescription>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Description (optional)</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="metadata"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Metadata (optional)</FormLabel>
+ <FormControl>
+ <CodeMirrorEditor
+ mode="json"
+ value={field.value}
+ onChange={(v) => {
+ field.onChange(v);
+ }}
+ minHeight="none"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="inputSchema"
+ render={({ field }) => (
+ <DatasetSchemaInput
+ label="Input schema"
+ description="Validate dataset item inputs against a JSON Schema. All new and existing items must conform to this schema."
+ value={field.value}
+ onChange={field.onChange}
+ initialValue={inputSchemaString}
+ />
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="expectedOutputSchema"
+ render={({ field }) => (
+ <DatasetSchemaInput
+ label="Expected output schema"
+ description="Validate dataset item expected outputs against a JSON Schema. All new and existing items must conform to this schema."
+ value={field.value}
+ onChange={field.onChange}
+ initialValue={expectedOutputSchemaString}
+ />
+ )}
+ />
+
+ {/* Show validation errors inline with form */}
+ {serverSideSchemaValidationErrors && (
+ <DatasetSchemaValidationError
+ projectId={props.projectId}
+ datasetId={
+ props.mode === "update" ? props.datasetId : "unknown"
+ }
+ errors={serverSideSchemaValidationErrors}
/>
- </div>
- )}
- </DialogBody>
- <DialogFooter>
- <div className="flex flex-col gap-4">
- <Button
- type="submit"
- variant={props.mode === "delete" ? "destructive" : "default"}
- disabled={!!form.formState.errors.name}
- loading={
- (props.mode === "create" && createMutation.isPending) ||
- (props.mode === "delete" && deleteMutation.isPending)
- }
- className="w-full"
- >
- {props.mode === "create"
- ? "Create dataset"
- : props.mode === "delete"
- ? "Delete Dataset"
- : "Update dataset"}
- </Button>
- {formError && (
- <p className="mt-4 text-center text-sm text-red-500">
- <span className="font-bold">Error:</span> {formError}
- </p>
)}
</div>
- </DialogFooter>
- </form>
- </Form>
- </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <div className="flex w-full flex-col gap-4">
+ <Button
+ type="submit"
+ variant={props.mode === "delete" ? "destructive" : "default"}
+ disabled={!!form.formState.errors.name}
+ loading={
+ (props.mode === "create" && createMutation.isPending) ||
+ (props.mode === "update" && updateMutation.isPending) ||
+ (props.mode === "delete" && deleteMutation.isPending)
+ }
+ className="w-full"
+ >
+ {props.mode === "create"
+ ? "Create dataset"
+ : props.mode === "delete"
+ ? "Delete Dataset"
+ : "Update dataset"}
+ </Button>
+ {formError && (
+ <p className="mt-4 text-center text-sm text-red-500">
+ <span className="font-bold">Error:</span> {formError}
+ </p>
+ )}
+ </div>
+ </DialogFooter>
+ </form>
+ </Form>
);
};
diff --git a/web/src/features/datasets/components/DatasetItemFieldSchemaErrors.tsx b/web/src/features/datasets/components/DatasetItemFieldSchemaErrors.tsx
new file mode 100644
index 0000000000..12240fb8b9
--- /dev/null
+++ b/web/src/features/datasets/components/DatasetItemFieldSchemaErrors.tsx
@@ -0,0 +1,60 @@
+import { AlertCircle } from "lucide-react";
+
+type DatasetError = {
+ datasetId: string;
+ datasetName: string;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ }>;
+};
+
+type DatasetItemFieldSchemaErrorsProps = {
+ errors: DatasetError[];
+ showDatasetName?: boolean;
+};
+
+export const DatasetItemFieldSchemaErrors: React.FC<
+ DatasetItemFieldSchemaErrorsProps
+> = ({ errors, showDatasetName = false }) => {
+ if (errors.length === 0) return null;
+
+ return (
+ <div className="rounded-md border border-destructive/50 bg-destructive/10 p-3">
+ <div className="flex items-start gap-2">
+ <AlertCircle className="mt-0.5 h-4 w-4 text-destructive" />
+ <div className="flex-1 space-y-2">
+ <p className="text-sm font-medium text-destructive">
+ Schema validation failed
+ </p>
+ {errors.map((error, idx) => (
+ <div key={`${error.datasetId}-${idx}`} className="space-y-1">
+ {showDatasetName && (
+ <p className="text-xs font-medium text-muted-foreground">
+ {error.datasetName}
+ </p>
+ )}
+ <ul className="space-y-1 text-sm text-destructive">
+ {error.errors.map((err, errIdx) => (
+ <li key={errIdx}>
+ {err.path === "/" ? (
+ <span>{err.message}</span>
+ ) : (
+ <span>
+ <span className="font-mono text-xs">
+ {err.path.replace(/^\//, "")}
+ </span>
+ : {err.message}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx b/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx
new file mode 100644
index 0000000000..a710b962cc
--- /dev/null
+++ b/web/src/features/datasets/components/DatasetItemSchemaErrors.tsx
@@ -0,0 +1,84 @@
+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import { AlertCircle } from "lucide-react";
+
+type DatasetError = {
+ datasetId: string;
+ datasetName: string;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ }>;
+};
+
+type DatasetItemSchemaErrorsProps = {
+ errors: DatasetError[];
+};
+
+export const DatasetItemSchemaErrors: React.FC<
+ DatasetItemSchemaErrorsProps
+> = ({ errors }) => {
+ if (errors.length === 0) return null;
+
+ // Group errors by dataset
+ const errorsByDataset = errors.reduce(
+ (acc, error) => {
+ const key = error.datasetId;
+ if (!acc[key]) {
+ acc[key] = {
+ datasetName: error.datasetName,
+ errors: [],
+ };
+ }
+ acc[key].errors.push(error);
+ return acc;
+ },
+ {} as Record<string, { datasetName: string; errors: DatasetError[] }>,
+ );
+
+ return (
+ <Alert variant="destructive" className="mt-4">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle className="text-base font-semibold">
+ Schema Validation Failed
+ </AlertTitle>
+ <AlertDescription className="mt-2 space-y-4">
+ <p className="text-sm">
+ The data does not match the required schema for this dataset.
+ </p>
+ {Object.entries(errorsByDataset).map(([datasetId, datasetErrors]) => (
+ <div key={datasetId} className="space-y-3">
+ {Object.keys(errorsByDataset).length > 1 && (
+ <div className="text-sm font-semibold">
+ {datasetErrors.datasetName}
+ </div>
+ )}
+ {datasetErrors.errors.map((error, idx) => (
+ <div key={idx} className="space-y-2">
+ <div className="text-sm font-semibold">
+ {error.field === "input" ? "Input" : "Expected Output"}
+ </div>
+ <ul className="ml-4 space-y-1.5 text-sm">
+ {error.errors.map((err, errIdx) => (
+ <li key={errIdx} className="list-disc">
+ {err.path === "/" ? (
+ <span>{err.message}</span>
+ ) : (
+ <span>
+ <span className="font-mono text-xs">
+ {err.path.replace(/^\//, "")}
+ </span>
+ : {err.message}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ ))}
+ </AlertDescription>
+ </Alert>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetSchemaHoverCard.tsx b/web/src/features/datasets/components/DatasetSchemaHoverCard.tsx
new file mode 100644
index 0000000000..e01dccddb3
--- /dev/null
+++ b/web/src/features/datasets/components/DatasetSchemaHoverCard.tsx
@@ -0,0 +1,116 @@
+import { ArrowUpRight, LockIcon, Copy, Check } from "lucide-react";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@/src/components/ui/hover-card";
+import { CodeMirrorEditor } from "@/src/components/editor";
+import type { Prisma } from "@langfuse/shared";
+import { Button } from "@/src/components/ui/button";
+import { Separator } from "@/src/components/ui/separator";
+import { useMemo, useState } from "react";
+import { generateSchemaExample } from "../lib/generateSchemaExample";
+import { copyTextToClipboard } from "@/src/utils/clipboard";
+
+type DatasetSchemaHoverCardProps = {
+ schema: Prisma.JsonValue;
+ schemaType: "input" | "expectedOutput";
+ showLabel?: boolean;
+};
+
+export const DatasetSchemaHoverCard: React.FC<DatasetSchemaHoverCardProps> = ({
+ schema,
+ schemaType,
+ showLabel = false,
+}) => {
+ const title =
+ schemaType === "input" ? "Input Schema" : "Expected Output Schema";
+
+ const schemaString = JSON.stringify(schema, null, 2);
+
+ // Generate example object from schema
+ const exampleObject = useMemo(() => generateSchemaExample(schema), [schema]);
+
+ // State for copy button feedback
+ const [copied, setCopied] = useState(false);
+
+ const handleCopyExample = async () => {
+ if (!exampleObject) return;
+
+ await copyTextToClipboard(exampleObject);
+
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <HoverCard openDelay={200} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <Button
+ variant="ghost"
+ className="inline-flex items-center gap-1.5 rounded p-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
+ aria-label={`View ${title}`}
+ size="sm"
+ >
+ <LockIcon className={showLabel ? "h-3 w-3" : "h-4 w-4"} />
+ {showLabel && <span>Schema enforced</span>}
+ </Button>
+ </HoverCardTrigger>
+ <HoverCardContent className="max-h-[600px] w-[400px] overflow-auto">
+ <p className="text-sm font-medium">{title}</p>
+ <p className="pt-2 text-sm text-muted-foreground">
+ Learn more about{" "}
+ <a
+ href="https://json-schema.org/learn/miscellaneous-examples"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center underline hover:text-foreground"
+ >
+ JSON Schema
+ <ArrowUpRight className="ml-0.5 h-3 w-3" />
+ </a>
+ </p>
+ <div className="mt-2">
+ <CodeMirrorEditor
+ mode="json"
+ value={schemaString}
+ onChange={() => {}} // Read-only
+ minHeight="none"
+ className="max-h-[250px] overflow-y-auto"
+ editable={false}
+ />
+ </div>
+
+ {exampleObject && (
+ <>
+ <Separator className="my-4" />
+ <div className="flex items-center justify-between">
+ <p className="text-sm font-medium">Example Object</p>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={handleCopyExample}
+ className="h-7 px-2"
+ >
+ {copied ? (
+ <Check className="h-3 w-3" />
+ ) : (
+ <Copy className="h-3 w-3" />
+ )}
+ </Button>
+ </div>
+ <div className="mt-2">
+ <CodeMirrorEditor
+ mode="json"
+ value={exampleObject}
+ minHeight="none"
+ className="max-h-[250px] overflow-y-auto"
+ editable={false}
+ />
+ </div>
+ </>
+ )}
+ </HoverCardContent>
+ </HoverCard>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetSchemaInput.tsx b/web/src/features/datasets/components/DatasetSchemaInput.tsx
new file mode 100644
index 0000000000..6c59436000
--- /dev/null
+++ b/web/src/features/datasets/components/DatasetSchemaInput.tsx
@@ -0,0 +1,87 @@
+import React, { useState } from "react";
+import {
+ FormControl,
+ FormDescription,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Switch } from "@/src/components/ui/switch";
+import { JSONSchemaEditor } from "@/src/components/JSONSchemaEditor";
+
+type DatasetSchemaInputProps = {
+ label: string;
+ description?: string;
+ value: string;
+ initialValue?: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+};
+
+export const DatasetSchemaInput: React.FC<DatasetSchemaInputProps> = ({
+ label,
+ description,
+ value,
+ initialValue,
+ onChange,
+ disabled = false,
+}) => {
+ // Track if schema enforcement is enabled based on whether value is empty
+ const [isEnabled, setIsEnabled] = useState(value !== "");
+
+ const handleToggle = (checked: boolean) => {
+ setIsEnabled(checked);
+ if (!checked) {
+ // Clear schema when disabling
+ onChange("");
+ } else if (value === "") {
+ // Set default empty schema when enabling
+ onChange(
+ initialValue ||
+ JSON.stringify(
+ {
+ type: "object",
+ properties: {},
+ required: [],
+ additionalProperties: false,
+ },
+ null,
+ 2,
+ ),
+ );
+ }
+ };
+
+ return (
+ <FormItem>
+ <div className="flex items-center justify-between">
+ <FormLabel>{label}</FormLabel>
+ <div className="flex items-center gap-2">
+ <span className="text-sm text-muted-foreground">
+ {isEnabled ? "Enabled" : "Disabled"}
+ </span>
+ <Switch
+ checked={isEnabled}
+ onCheckedChange={handleToggle}
+ disabled={disabled}
+ />
+ </div>
+ </div>
+
+ {description && <FormDescription>{description}</FormDescription>}
+
+ {isEnabled && (
+ <FormControl>
+ <JSONSchemaEditor
+ value={value}
+ onChange={onChange}
+ disabled={disabled}
+ className="max-h-[25vh]"
+ />
+ </FormControl>
+ )}
+
+ <FormMessage />
+ </FormItem>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetSchemaValidationError.tsx b/web/src/features/datasets/components/DatasetSchemaValidationError.tsx
new file mode 100644
index 0000000000..13a7e6f302
--- /dev/null
+++ b/web/src/features/datasets/components/DatasetSchemaValidationError.tsx
@@ -0,0 +1,109 @@
+import { useState } from "react";
+import { ChevronDown, ChevronRight, ExternalLink } from "lucide-react";
+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import { Button } from "@/src/components/ui/button";
+import Link from "next/link";
+
+type ValidationError = {
+ datasetItemId: string;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ keyword?: string;
+ }>;
+};
+
+type DatasetSchemaValidationErrorProps = {
+ projectId: string;
+ datasetId: string;
+ errors: ValidationError[];
+};
+
+export const DatasetSchemaValidationError: React.FC<
+ DatasetSchemaValidationErrorProps
+> = ({ projectId, datasetId, errors }) => {
+ const [isExpanded, setIsExpanded] = useState(false);
+
+ const errorCount = errors.length;
+ const hasMoreThan10 = errorCount === 10; // Backend limits to 10 errors
+
+ return (
+ <Alert variant="destructive" className="mt-4">
+ <AlertTitle className="text-base font-semibold">
+ Schema Validation Failed
+ </AlertTitle>
+ <AlertDescription className="mt-2 space-y-3">
+ <p className="text-sm">
+ {hasMoreThan10
+ ? `More than 10 items failed validation. Showing first 10 errors.`
+ : `${errorCount} item${errorCount === 1 ? "" : "s"} failed validation.`}
+ </p>
+
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setIsExpanded(!isExpanded)}
+ className="h-auto p-0 text-sm font-medium hover:bg-transparent"
+ >
+ {isExpanded ? (
+ <ChevronDown className="mr-1 h-4 w-4" />
+ ) : (
+ <ChevronRight className="mr-1 h-4 w-4" />
+ )}
+ {isExpanded ? "Hide" : "Show"} error details
+ </Button>
+
+ {isExpanded && (
+ <div className="mt-3 space-y-3 rounded-md border border-destructive/20 bg-destructive/5 p-3">
+ {errors.map((error, idx) => (
+ <div
+ key={`${error.datasetItemId}-${error.field}`}
+ className="space-y-1 border-b border-destructive/10 pb-3 last:border-0 last:pb-0"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-xs text-muted-foreground">
+ #{idx + 1}
+ </span>
+ <Link
+ href={`/project/${projectId}/datasets/${datasetId}/items/${error.datasetItemId}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-1 text-sm font-medium hover:underline"
+ >
+ Item: {error.datasetItemId}
+ <ExternalLink className="h-3 w-3" />
+ </Link>
+ </div>
+ <span className="rounded bg-destructive/20 px-2 py-0.5 text-xs font-medium">
+ {error.field === "input" ? "Input" : "Expected Output"}
+ </span>
+ </div>
+
+ <ul className="ml-6 space-y-1 text-sm">
+ {error.errors.map((err, errIdx) => (
+ <li key={errIdx} className="text-destructive">
+ <span className="font-mono text-xs text-muted-foreground">
+ Path {err.path}
+ </span>
+ : {err.message}
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+
+ {hasMoreThan10 && (
+ <p className="pt-2 text-xs text-muted-foreground">
+ Fix these errors to see if there are additional validation
+ issues.
+ </p>
+ )}
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ );
+};
diff --git a/web/src/features/datasets/components/DatasetsTable.tsx b/web/src/features/datasets/components/DatasetsTable.tsx
index 5e9405d81d..26ba9099ef 100644
--- a/web/src/features/datasets/components/DatasetsTable.tsx
+++ b/web/src/features/datasets/components/DatasetsTable.tsx
@@ -10,6 +10,7 @@ import {
DropdownMenuTrigger,
} from "@/src/components/ui/dropdown-menu";
import { DatasetActionButton } from "@/src/features/datasets/components/DatasetActionButton";
+import { DatasetSchemaHoverCard } from "@/src/features/datasets/components/DatasetSchemaHoverCard";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { api } from "@/src/utils/api";
import { withDefault, useQueryParam, StringParam } from "use-query-params";
@@ -43,6 +44,8 @@ type DatasetTableRow = {
countItems: number | null;
countRuns: number | null;
metadata: Prisma.JsonValue | null;
+ inputSchema?: Prisma.JsonValue | null;
+ expectedOutputSchema?: Prisma.JsonValue | null;
};
function createRow(
@@ -62,6 +65,8 @@ function createRow(
countItems: null,
countRuns: null,
metadata: null,
+ inputSchema: null,
+ expectedOutputSchema: null,
...data,
};
}
@@ -197,6 +202,43 @@ export function DatasetsTable(props: { projectId: string }) {
return value ? <LocalIsoDate date={value} /> : undefined;
},
},
+ {
+ accessorKey: "inputSchema",
+ header: "Input Schema",
+ id: "inputSchema",
+ enableHiding: true,
+ size: 80,
+ cell: ({ row }) => {
+ const inputSchema: DatasetTableRow["inputSchema"] =
+ row.getValue("inputSchema");
+
+ if (!inputSchema) return null;
+
+ return (
+ <DatasetSchemaHoverCard schema={inputSchema} schemaType="input" />
+ );
+ },
+ },
+ {
+ accessorKey: "expectedOutputSchema",
+ header: "Expected Output Schema",
+ id: "expectedOutputSchema",
+ enableHiding: true,
+ size: 90,
+ cell: ({ row }) => {
+ const expectedOutputSchema: DatasetTableRow["expectedOutputSchema"] =
+ row.getValue("expectedOutputSchema");
+
+ if (!expectedOutputSchema) return null;
+
+ return (
+ <DatasetSchemaHoverCard
+ schema={expectedOutputSchema}
+ schemaType="expectedOutput"
+ />
+ );
+ },
+ },
{
accessorKey: "metadata",
header: "Metadata",
@@ -243,6 +285,10 @@ export function DatasetsTable(props: { projectId: string }) {
datasetName={row.original.folderPath}
datasetDescription={row.getValue("description") ?? undefined}
datasetMetadata={row.getValue("metadata") ?? undefined}
+ datasetInputSchema={row.original.inputSchema ?? undefined}
+ datasetExpectedOutputSchema={
+ row.original.expectedOutputSchema ?? undefined
+ }
/>
</DropdownMenuItem>
<DropdownMenuItem asChild>
@@ -319,6 +365,8 @@ export function DatasetsTable(props: { projectId: string }) {
countItems: dataset.countDatasetItems,
countRuns: dataset.countDatasetRuns,
metadata: dataset.metadata,
+ inputSchema: dataset.inputSchema,
+ expectedOutputSchema: dataset.expectedOutputSchema,
}),
}),
);
diff --git a/web/src/features/datasets/components/EditDatasetItem.tsx b/web/src/features/datasets/components/EditDatasetItem.tsx
index 9cfa7268ee..84a7c70c09 100644
--- a/web/src/features/datasets/components/EditDatasetItem.tsx
+++ b/web/src/features/datasets/components/EditDatasetItem.tsx
@@ -2,7 +2,7 @@ import { api } from "@/src/utils/api";
import * as z from "zod/v4";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
-import { useEffect, useState } from "react";
+import { useEffect, useState, useMemo } from "react";
import {
Form,
FormControl,
@@ -15,6 +15,10 @@ import { Button } from "@/src/components/ui/button";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { CodeMirrorEditor } from "@/src/components/editor";
import { type RouterOutput } from "@/src/utils/types";
+import { DatasetSchemaHoverCard } from "./DatasetSchemaHoverCard";
+import { useDatasetItemValidation } from "../hooks/useDatasetItemValidation";
+import type { Prisma } from "@langfuse/shared";
+import { DatasetItemFieldSchemaErrors } from "./DatasetItemFieldSchemaErrors";
const formSchema = z.object({
input: z.string().refine(
@@ -64,12 +68,21 @@ const formSchema = z.object({
),
});
+type Dataset = {
+ id: string;
+ name: string;
+ inputSchema: Prisma.JsonValue | null;
+ expectedOutputSchema: Prisma.JsonValue | null;
+};
+
export const EditDatasetItem = ({
projectId,
datasetItem,
+ dataset,
}: {
projectId: string;
datasetItem: RouterOutput["datasets"]["itemById"];
+ dataset: Dataset | null;
}) => {
const [formError, setFormError] = useState<string | null>(null);
const [hasChanges, setHasChanges] = useState(false);
@@ -105,6 +118,34 @@ export const EditDatasetItem = ({
},
});
+ const inputValue = form.watch("input");
+ const expectedOutputValue = form.watch("expectedOutput");
+
+ // Track if fields have been touched or modified
+ const { touchedFields, dirtyFields } = form.formState;
+ const hasInteractedWithInput = touchedFields.input || dirtyFields.input;
+ const hasInteractedWithExpectedOutput =
+ touchedFields.expectedOutput || dirtyFields.expectedOutput;
+
+ // Create dataset array for validation hook
+ const datasets = useMemo(() => {
+ if (!dataset) return [];
+ return [dataset];
+ }, [dataset]);
+
+ // Validate against dataset schemas
+ const validation = useDatasetItemValidation(
+ inputValue,
+ expectedOutputValue,
+ datasets,
+ );
+
+ // Filter validation errors by field
+ const inputErrors = validation.errors.filter((e) => e.field === "input");
+ const expectedOutputErrors = validation.errors.filter(
+ (e) => e.field === "expectedOutput",
+ );
+
const updateDatasetItemMutation = api.datasets.updateDatasetItem.useMutation({
onSuccess: () => utils.datasets.invalidate(),
onError: (error) => setFormError(error.message),
@@ -141,13 +182,17 @@ export const EditDatasetItem = ({
<Button
type="submit"
loading={updateDatasetItemMutation.isPending}
- disabled={!hasChanges || !hasAccess}
+ disabled={
+ !hasChanges ||
+ !hasAccess ||
+ (validation.hasSchemas && !validation.isValid)
+ }
variant={hasChanges ? "default" : "ghost"}
>
{hasChanges ? "Save changes" : "Saved"}
</Button>
</div>
- <div className="flex-1 overflow-auto">
+ <div className="mt-4 flex-1 overflow-auto">
<div className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<FormField
@@ -155,7 +200,16 @@ export const EditDatasetItem = ({
name="input"
render={({ field }) => (
<FormItem>
- <FormLabel>Input</FormLabel>
+ <div className="flex items-center gap-2">
+ <FormLabel>Input</FormLabel>
+ {dataset?.inputSchema && (
+ <DatasetSchemaHoverCard
+ schema={dataset.inputSchema}
+ schemaType="input"
+ showLabel
+ />
+ )}
+ </div>
<FormControl>
<CodeMirrorEditor
mode="json"
@@ -169,6 +223,14 @@ export const EditDatasetItem = ({
/>
</FormControl>
<FormMessage />
+ {validation.hasSchemas &&
+ inputErrors.length > 0 &&
+ hasInteractedWithInput && (
+ <DatasetItemFieldSchemaErrors
+ errors={inputErrors}
+ showDatasetName={false}
+ />
+ )}
</FormItem>
)}
/>
@@ -177,7 +239,16 @@ export const EditDatasetItem = ({
name="expectedOutput"
render={({ field }) => (
<FormItem>
- <FormLabel>Expected output</FormLabel>
+ <div className="flex items-center gap-2">
+ <FormLabel>Expected output</FormLabel>
+ {dataset?.expectedOutputSchema && (
+ <DatasetSchemaHoverCard
+ schema={dataset.expectedOutputSchema}
+ schemaType="expectedOutput"
+ showLabel
+ />
+ )}
+ </div>
<FormControl>
<CodeMirrorEditor
mode="json"
@@ -191,10 +262,19 @@ export const EditDatasetItem = ({
/>
</FormControl>
<FormMessage />
+ {validation.hasSchemas &&
+ expectedOutputErrors.length > 0 &&
+ hasInteractedWithExpectedOutput && (
+ <DatasetItemFieldSchemaErrors
+ errors={expectedOutputErrors}
+ showDatasetName={false}
+ />
+ )}
</FormItem>
)}
/>
</div>
+
<FormField
control={form.control}
name="metadata"
diff --git a/web/src/features/datasets/components/NewDatasetItemForm.tsx b/web/src/features/datasets/components/NewDatasetItemForm.tsx
index 0653f25772..f9b726f18d 100644
--- a/web/src/features/datasets/components/NewDatasetItemForm.tsx
+++ b/web/src/features/datasets/components/NewDatasetItemForm.tsx
@@ -11,11 +11,15 @@ import {
FormMessage,
} from "@/src/components/ui/form";
import { api } from "@/src/utils/api";
-import { useState } from "react";
+import { useState, useMemo, useEffect } from "react";
import { CodeMirrorEditor } from "@/src/components/editor";
import { type Prisma } from "@langfuse/shared";
import { cn } from "@/src/utils/tailwind";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { DatasetSchemaHoverCard } from "./DatasetSchemaHoverCard";
+import { useDatasetItemValidation } from "../hooks/useDatasetItemValidation";
+import { DatasetItemFieldSchemaErrors } from "./DatasetItemFieldSchemaErrors";
+import { generateSchemaExample } from "../lib/generateSchemaExample";
import {
InputCommand,
InputCommandEmpty,
@@ -122,12 +126,90 @@ export const NewDatasetItemForm = (props: {
},
});
- const selectedDatasetCount = form.watch("datasetIds").length;
+ const selectedDatasetIds = form.watch("datasetIds");
+ const selectedDatasetCount = selectedDatasetIds.length;
+ const inputValue = form.watch("input");
+ const expectedOutputValue = form.watch("expectedOutput");
+
+ const hasInitialValues = Boolean(
+ props.input || props.output || props.metadata,
+ );
+
+ // Track if fields have been touched or modified
+ const { touchedFields, dirtyFields } = form.formState;
+ const hasInteractedWithInput = touchedFields.input || dirtyFields.input;
+ const hasInteractedWithExpectedOutput =
+ touchedFields.expectedOutput || dirtyFields.expectedOutput;
const datasets = api.datasets.allDatasetMeta.useQuery({
projectId: props.projectId,
});
+ // Get selected datasets with their schemas
+ const selectedDatasets = useMemo(() => {
+ if (!datasets.data) return [];
+ return datasets.data.filter((d) => selectedDatasetIds.includes(d.id));
+ }, [datasets.data, selectedDatasetIds]);
+
+ // Validate against all selected dataset schemas
+ const validation = useDatasetItemValidation(
+ inputValue,
+ expectedOutputValue,
+ selectedDatasets,
+ );
+
+ // Check if any selected dataset has schemas
+ const hasInputSchema = selectedDatasets.some((d) => d.inputSchema);
+ const hasOutputSchema = selectedDatasets.some((d) => d.expectedOutputSchema);
+
+ // Filter validation errors by field
+ const inputErrors = validation.errors.filter((e) => e.field === "input");
+ const expectedOutputErrors = validation.errors.filter(
+ (e) => e.field === "expectedOutput",
+ );
+
+ // Generate placeholders from schema when dataset is selected
+ useEffect(() => {
+ // Only generate if form has no initial values
+ if (hasInitialValues) return;
+
+ // Only generate if single dataset selected
+ if (selectedDatasets.length !== 1) return;
+
+ const dataset = selectedDatasets[0];
+ if (!dataset) return;
+
+ // Generate input placeholder if schema exists and field is empty
+ if (dataset.inputSchema && !inputValue) {
+ const placeholder = generateSchemaExample(dataset.inputSchema);
+ if (placeholder) {
+ form.setValue("input", placeholder, {
+ shouldValidate: false,
+ shouldDirty: false,
+ shouldTouch: false,
+ });
+ }
+ }
+
+ // Generate expectedOutput placeholder if schema exists and field is empty
+ if (dataset.expectedOutputSchema && !expectedOutputValue) {
+ const placeholder = generateSchemaExample(dataset.expectedOutputSchema);
+ if (placeholder) {
+ form.setValue("expectedOutput", placeholder, {
+ shouldValidate: false,
+ shouldDirty: false,
+ shouldTouch: false,
+ });
+ }
+ }
+ }, [
+ selectedDatasets,
+ hasInitialValues,
+ inputValue,
+ expectedOutputValue,
+ form,
+ ]);
+
const utils = api.useUtils();
const createManyDatasetItemsMutation =
api.datasets.createManyDatasetItems.useMutation({
@@ -156,9 +238,18 @@ export const NewDatasetItemForm = (props: {
sourceObservationId: props.observationId,
})),
})
- .then(() => {
- props.onFormSuccess?.();
- form.reset();
+ .then((result) => {
+ if (result.success) {
+ props.onFormSuccess?.();
+ form.reset();
+
+ return;
+ }
+
+ setFormError(
+ `Item does not match dataset schema. Errors: ${JSON.stringify(result.validationErrors, null, 2)}`,
+ );
+ console.error(result.validationErrors);
})
.catch((error) => {
console.error(error);
@@ -272,7 +363,20 @@ export const NewDatasetItemForm = (props: {
name="input"
render={({ field }) => (
<FormItem className="flex flex-col gap-2">
- <FormLabel>Input</FormLabel>
+ <div className="flex items-center gap-2">
+ <FormLabel>Input</FormLabel>
+ {hasInputSchema &&
+ selectedDatasets
+ .filter((d) => d.inputSchema)
+ .map((dataset) => (
+ <DatasetSchemaHoverCard
+ key={dataset.id}
+ schema={dataset.inputSchema!}
+ schemaType="input"
+ showLabel
+ />
+ ))[0]}
+ </div>
<FormControl>
<CodeMirrorEditor
mode="json"
@@ -285,6 +389,14 @@ export const NewDatasetItemForm = (props: {
/>
</FormControl>
<FormMessage />
+ {validation.hasSchemas &&
+ inputErrors.length > 0 &&
+ (hasInitialValues || hasInteractedWithInput) && (
+ <DatasetItemFieldSchemaErrors
+ errors={inputErrors}
+ showDatasetName={selectedDatasets.length > 1}
+ />
+ )}
</FormItem>
)}
/>
@@ -293,7 +405,20 @@ export const NewDatasetItemForm = (props: {
name="expectedOutput"
render={({ field }) => (
<FormItem className="flex flex-col gap-2">
- <FormLabel>Expected output</FormLabel>
+ <div className="flex items-center gap-2">
+ <FormLabel>Expected output</FormLabel>
+ {hasOutputSchema &&
+ selectedDatasets
+ .filter((d) => d.expectedOutputSchema)
+ .map((dataset) => (
+ <DatasetSchemaHoverCard
+ key={dataset.id}
+ schema={dataset.expectedOutputSchema!}
+ schemaType="expectedOutput"
+ showLabel
+ />
+ ))[0]}
+ </div>
<FormControl>
<CodeMirrorEditor
mode="json"
@@ -306,10 +431,19 @@ export const NewDatasetItemForm = (props: {
/>
</FormControl>
<FormMessage />
+ {validation.hasSchemas &&
+ expectedOutputErrors.length > 0 &&
+ (hasInitialValues || hasInteractedWithExpectedOutput) && (
+ <DatasetItemFieldSchemaErrors
+ errors={expectedOutputErrors}
+ showDatasetName={selectedDatasets.length > 1}
+ />
+ )}
</FormItem>
)}
/>
</div>
+
<FormField
control={form.control}
name="metadata"
@@ -336,7 +470,10 @@ export const NewDatasetItemForm = (props: {
type="submit"
loading={createManyDatasetItemsMutation.isPending}
className="w-full"
- disabled={selectedDatasetCount === 0}
+ disabled={
+ selectedDatasetCount === 0 ||
+ (validation.hasSchemas && !validation.isValid)
+ }
>
Add
{selectedDatasetCount > 1
diff --git a/web/src/features/datasets/components/PreviewCsvImport.tsx b/web/src/features/datasets/components/PreviewCsvImport.tsx
index 5c6688c5f9..8777adbd60 100644
--- a/web/src/features/datasets/components/PreviewCsvImport.tsx
+++ b/web/src/features/datasets/components/PreviewCsvImport.tsx
@@ -23,6 +23,8 @@ import { MAX_FILE_SIZE_BYTES } from "@/src/features/datasets/components/UploadDa
import { Progress } from "@/src/components/ui/progress";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";
+import { CsvImportValidationError } from "./CsvImportValidationError";
+import { type BulkDatasetItemValidationError } from "@langfuse/shared";
import { chunk } from "lodash";
const MIN_CHUNK_SIZE = 1;
@@ -132,6 +134,9 @@ export function PreviewCsvImport({
processedItems: 0,
status: "not-started",
});
+ const [validationErrors, setValidationErrors] = useState<
+ BulkDatasetItemValidationError[]
+ >([]);
const utils = api.useUtils();
const mutCreateManyDatasetItems =
@@ -226,6 +231,9 @@ export function PreviewCsvImport({
return;
}
+ // Clear any previous validation errors
+ setValidationErrors([]);
+
let processedCount = 0;
let headerMap: Map<string, number>;
@@ -278,11 +286,28 @@ export function PreviewCsvImport({
const chunks = chunk(items, optimalChunkSize);
for (const [index, chunk] of chunks.entries()) {
- await mutCreateManyDatasetItems.mutateAsync({
+ const result = await mutCreateManyDatasetItems.mutateAsync({
projectId,
items: chunk,
});
+ // Check if validation failed
+ if (!result.success) {
+ // Adjust itemIndex to account for already processed chunks
+ const adjustedErrors = result.validationErrors.map((error) => ({
+ ...error,
+ itemIndex: error.itemIndex + processedCount,
+ }));
+
+ setValidationErrors(adjustedErrors);
+ setProgress?.({
+ totalItems: 0,
+ processedItems: 0,
+ status: "not-started",
+ });
+ return;
+ }
+
processedCount += chunk.length;
setProgress?.({
totalItems: items.length,
@@ -434,6 +459,9 @@ export function PreviewCsvImport({
</div>
</CardContent>
</Card>
+ {validationErrors.length > 0 && (
+ <CsvImportValidationError errors={validationErrors} />
+ )}
</DialogBody>
<DialogFooter>
<Button
@@ -445,6 +473,7 @@ export function PreviewCsvImport({
setSelectedMetadataColumn(new Set());
setExcludedColumns(new Set());
setCsvFile(null);
+ setValidationErrors([]);
}}
>
Cancel
diff --git a/web/src/features/datasets/hooks/useDatasetItemValidation.ts b/web/src/features/datasets/hooks/useDatasetItemValidation.ts
new file mode 100644
index 0000000000..3b8268b04f
--- /dev/null
+++ b/web/src/features/datasets/hooks/useDatasetItemValidation.ts
@@ -0,0 +1,116 @@
+import { useMemo } from "react";
+import { validateFieldAgainstSchema } from "@langfuse/shared";
+import type { Prisma } from "@langfuse/shared";
+
+type Dataset = {
+ id: string;
+ name: string;
+ inputSchema: Prisma.JsonValue | null;
+ expectedOutputSchema: Prisma.JsonValue | null;
+};
+
+type DatasetError = {
+ datasetId: string;
+ datasetName: string;
+ field: "input" | "expectedOutput";
+ errors: Array<{
+ path: string;
+ message: string;
+ }>;
+};
+
+type ValidationResult = {
+ isValid: boolean;
+ errors: DatasetError[];
+ hasSchemas: boolean; // Indicates if any dataset has schemas
+};
+
+/**
+ * Validates dataset item input and expectedOutput against multiple dataset schemas
+ * @param inputString - JSON string of input data
+ * @param expectedOutputString - JSON string of expected output data
+ * @param datasets - Array of datasets with their schemas
+ * @returns Validation result with errors grouped by dataset
+ */
+export const useDatasetItemValidation = (
+ inputString: string,
+ expectedOutputString: string,
+ datasets: Dataset[],
+): ValidationResult => {
+ return useMemo(() => {
+ const errors: DatasetError[] = [];
+ let hasInputSchema = false;
+ let hasOutputSchema = false;
+
+ // Parse JSON strings once
+ let inputData: unknown = null;
+ let outputData: unknown = null;
+
+ try {
+ inputData = inputString ? JSON.parse(inputString) : null;
+ } catch (e) {
+ // Invalid JSON - skip validation (Zod will catch this)
+ return { isValid: true, errors: [], hasSchemas: false };
+ }
+
+ try {
+ outputData = expectedOutputString
+ ? JSON.parse(expectedOutputString)
+ : null;
+ } catch (e) {
+ // Invalid JSON - skip validation (Zod will catch this)
+ return { isValid: true, errors: [], hasSchemas: false };
+ }
+
+ // Validate against each dataset's schemas
+ for (const dataset of datasets) {
+ // Validate input schema
+ if (dataset.inputSchema) {
+ hasInputSchema = true;
+ const result = validateFieldAgainstSchema({
+ data: inputData,
+ schema: dataset.inputSchema as Record<string, unknown>,
+ });
+
+ if (!result.isValid) {
+ errors.push({
+ datasetId: dataset.id,
+ datasetName: dataset.name,
+ field: "input",
+ errors: result.errors.map((err) => ({
+ path: err.path,
+ message: err.message,
+ })),
+ });
+ }
+ }
+
+ // Validate expectedOutput schema
+ if (dataset.expectedOutputSchema) {
+ hasOutputSchema = true;
+ const result = validateFieldAgainstSchema({
+ data: outputData,
+ schema: dataset.expectedOutputSchema as Record<string, unknown>,
+ });
+
+ if (!result.isValid) {
+ errors.push({
+ datasetId: dataset.id,
+ datasetName: dataset.name,
+ field: "expectedOutput",
+ errors: result.errors.map((err) => ({
+ path: err.path,
+ message: err.message,
+ })),
+ });
+ }
+ }
+ }
+
+ return {
+ isValid: errors.length === 0,
+ errors,
+ hasSchemas: hasInputSchema || hasOutputSchema,
+ };
+ }, [inputString, expectedOutputString, datasets]);
+};
diff --git a/web/src/features/datasets/lib/generateSchemaExample.ts b/web/src/features/datasets/lib/generateSchemaExample.ts
new file mode 100644
index 0000000000..f329a97f88
--- /dev/null
+++ b/web/src/features/datasets/lib/generateSchemaExample.ts
@@ -0,0 +1,30 @@
+import jsf from "json-schema-faker";
+import type { Prisma } from "@langfuse/shared";
+
+/**
+ * Generate an example object from a JSON Schema using json-schema-faker
+ * @param schema - JSON Schema to generate example from
+ * @returns Formatted JSON string of the generated example, or empty string on error
+ */
+export function generateSchemaExample(schema: Prisma.JsonValue): string {
+ try {
+ if (!schema || typeof schema !== "object") {
+ console.error("Invalid schema: must be an object", schema);
+
+ return "";
+ }
+ jsf.option({
+ alwaysFakeOptionals: true,
+ useDefaultValue: true,
+ useExamplesValue: true,
+ });
+
+ const generated = jsf.generate(schema);
+
+ return JSON.stringify(generated, null, 2);
+ } catch (error) {
+ console.error("Failed to generate schema example:", error);
+
+ return "";
+ }
+}
diff --git a/web/src/features/datasets/server/actions/createDataset.ts b/web/src/features/datasets/server/actions/createDataset.ts
index f8b6eba66f..c84baafa5d 100644
--- a/web/src/features/datasets/server/actions/createDataset.ts
+++ b/web/src/features/datasets/server/actions/createDataset.ts
@@ -1,9 +1,10 @@
import {
DatasetNameSchema,
InvalidRequestError,
- type Prisma,
+ Prisma,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
+import { validateAllDatasetItems } from "@langfuse/shared/src/server";
type DatasetJson =
| Prisma.InputJsonObject
@@ -14,6 +15,8 @@ type UpsertDatasetInput = {
name: string;
description?: string;
metadata?: DatasetJson;
+ inputSchema?: DatasetJson;
+ expectedOutputSchema?: DatasetJson;
};
type UpdateDatasetInput = {
@@ -23,6 +26,8 @@ type UpdateDatasetInput = {
metadata?: DatasetJson;
remoteExperimentUrl?: string | null;
remoteExperimentPayload?: DatasetJson;
+ inputSchema?: DatasetJson;
+ expectedOutputSchema?: DatasetJson;
};
export const upsertDataset = async ({
@@ -39,6 +44,58 @@ export const upsertDataset = async ({
);
}
+ // Check if dataset exists (for UPDATE path)
+ const existingDataset = await prisma.dataset.findUnique({
+ where: {
+ projectId_name: {
+ projectId,
+ name: input.name,
+ },
+ },
+ select: {
+ id: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ },
+ });
+
+ // If updating and schemas are being set, validate all existing items
+ if (existingDataset) {
+ const isSettingInputSchema = input.inputSchema !== undefined;
+ const isSettingExpectedOutputSchema =
+ input.expectedOutputSchema !== undefined;
+
+ if (isSettingInputSchema || isSettingExpectedOutputSchema) {
+ // Determine final schemas after update
+ const finalInputSchema = isSettingInputSchema
+ ? input.inputSchema
+ : existingDataset.inputSchema;
+ const finalExpectedOutputSchema = isSettingExpectedOutputSchema
+ ? input.expectedOutputSchema
+ : existingDataset.expectedOutputSchema;
+
+ // Validate if any schema is being set (not null)
+ if (finalInputSchema !== null || finalExpectedOutputSchema !== null) {
+ const validationResult = await validateAllDatasetItems({
+ datasetId: existingDataset.id,
+ projectId,
+ inputSchema: finalInputSchema as Record<string, unknown> | null,
+ expectedOutputSchema: finalExpectedOutputSchema as Record<
+ string,
+ unknown
+ > | null,
+ prisma,
+ });
+
+ if (!validationResult.isValid) {
+ throw new InvalidRequestError(
+ `Schema validation failed for ${validationResult.errors.length === 10 ? "more than 10" : validationResult.errors.length} item(s). Details: ${JSON.stringify(validationResult.errors)}`,
+ );
+ }
+ }
+ }
+ }
+
return await prisma.dataset.upsert({
where: {
projectId_name: {
@@ -50,11 +107,35 @@ export const upsertDataset = async ({
name: input.name,
description: input.description ?? undefined,
metadata: input.metadata ?? undefined,
+ inputSchema:
+ input.inputSchema === undefined
+ ? undefined
+ : input.inputSchema === null
+ ? Prisma.DbNull
+ : input.inputSchema,
+ expectedOutputSchema:
+ input.expectedOutputSchema === undefined
+ ? undefined
+ : input.expectedOutputSchema === null
+ ? Prisma.DbNull
+ : input.expectedOutputSchema,
projectId,
},
update: {
description: input.description ?? undefined,
metadata: input.metadata ?? undefined,
+ inputSchema:
+ input.inputSchema === undefined
+ ? undefined
+ : input.inputSchema === null
+ ? Prisma.DbNull
+ : input.inputSchema,
+ expectedOutputSchema:
+ input.expectedOutputSchema === undefined
+ ? undefined
+ : input.expectedOutputSchema === null
+ ? Prisma.DbNull
+ : input.expectedOutputSchema,
},
});
};
@@ -88,6 +169,18 @@ export const updateDataset = async ({
metadata: input.metadata ?? undefined,
remoteExperimentUrl: input.remoteExperimentUrl,
remoteExperimentPayload: input.remoteExperimentPayload ?? undefined,
+ inputSchema:
+ input.inputSchema === undefined
+ ? undefined
+ : input.inputSchema === null
+ ? Prisma.DbNull
+ : input.inputSchema,
+ expectedOutputSchema:
+ input.expectedOutputSchema === undefined
+ ? undefined
+ : input.expectedOutputSchema === null
+ ? Prisma.DbNull
+ : input.expectedOutputSchema,
},
});
};
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 7a0f01eaf6..873649c1da 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -52,9 +52,18 @@ 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";
const formatDatasetItemData = (data: string | null | undefined) => {
if (data === "") return Prisma.DbNull;
+
try {
return !!data ? (JSON.parse(data) as Prisma.InputJsonObject) : undefined;
} catch (e) {
@@ -62,6 +71,7 @@ const formatDatasetItemData = (data: string | null | undefined) => {
"[trpc.datasets.formatDatasetItemData] failed to parse dataset item data",
e,
);
+
return undefined;
}
};
@@ -109,6 +119,131 @@ 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;
@@ -161,6 +296,8 @@ const generateDatasetQuery = ({
d.project_id,
d.updated_at,
d.created_at,
+ d.input_schema,
+ d.expected_output_schema,
2 as sort_priority, -- Individual datasets second
'dataset'::text as row_type -- Mark as individual dataset
FROM filtered_datasets d
@@ -178,6 +315,8 @@ const generateDatasetQuery = ({
d.project_id,
d.updated_at,
d.created_at,
+ d.input_schema,
+ d.expected_output_schema,
1 as sort_priority, -- Folders first
'folder'::text as row_type, -- Mark as folder representative
ROW_NUMBER() OVER (
@@ -189,11 +328,11 @@ const generateDatasetQuery = ({
),
combined AS (
SELECT
- id, name, description, metadata, project_id, updated_at, created_at, sort_priority, row_type
+ id, name, description, metadata, project_id, updated_at, created_at, sort_priority, row_type, input_schema, expected_output_schema
FROM individual_datasets_in_folder
UNION ALL
SELECT
- id, name, description, metadata, project_id, updated_at, created_at, sort_priority, row_type
+ id, name, description, metadata, project_id, updated_at, created_at, sort_priority, row_type, input_schema, expected_output_schema
FROM subfolder_representatives WHERE rn = 1
)
SELECT
@@ -202,7 +341,7 @@ const generateDatasetQuery = ({
${orderAndLimit}
`;
} else {
- const baseColumns = Prisma.sql`id, name, description, metadata, project_id, updated_at, created_at`;
+ const baseColumns = Prisma.sql`id, name, description, metadata, project_id, updated_at, created_at, input_schema, expected_output_schema`;
// When we're at the root level, show all individual datasets that don't have folders
// and one representative per folder for datasets that do have folders
@@ -210,7 +349,7 @@ const generateDatasetQuery = ({
WITH ${datasetsCTE},
individual_datasets AS (
/* Individual datasets without folders */
- SELECT d.id, d.name, d.description, d.metadata, d.project_id, d.updated_at, d.created_at, 'dataset'::text as row_type
+ SELECT d.id, d.name, d.description, d.metadata, d.project_id, d.updated_at, d.created_at, d.input_schema, d.expected_output_schema, 'dataset'::text as row_type
FROM filtered_datasets d
WHERE d.name NOT LIKE '%/%'
),
@@ -224,6 +363,8 @@ const generateDatasetQuery = ({
d.project_id,
d.updated_at,
d.created_at,
+ d.input_schema,
+ d.expected_output_schema,
'folder'::text as row_type, -- Mark as folder representative
ROW_NUMBER() OVER (PARTITION BY SPLIT_PART(d.name, '/', 1) ORDER BY LENGTH(d.name) ASC, d.updated_at DESC) AS rn
FROM filtered_datasets d
@@ -272,6 +413,8 @@ export const datasetRouter = createTRPCRouter({
select: {
id: true,
name: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
},
});
}),
@@ -314,6 +457,8 @@ export const datasetRouter = createTRPCRouter({
d.created_at as "createdAt",
d.updated_at as "updatedAt",
d.metadata,
+ d.input_schema as "inputSchema",
+ d.expected_output_schema as "expectedOutputSchema",
d.row_type`,
projectId: input.projectId,
limit: input.limit,
@@ -662,6 +807,7 @@ export const datasetRouter = createTRPCRouter({
searchType: input.searchType,
});
}),
+
updateDatasetItem: protectedProjectProcedure
.input(
z.object({
@@ -682,6 +828,49 @@ export const datasetRouter = createTRPCRouter({
projectId: input.projectId,
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 },
+ });
+
+ if (!dataset) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Dataset not found",
+ });
+ }
+
+ // 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: {
@@ -691,18 +880,8 @@ export const datasetRouter = createTRPCRouter({
datasetId: input.datasetId,
},
data: {
- input:
- input.input === ""
- ? Prisma.DbNull
- : input.input !== undefined
- ? (JSON.parse(input.input) as Prisma.InputJsonObject)
- : undefined,
- expectedOutput:
- input.expectedOutput === ""
- ? Prisma.DbNull
- : input.expectedOutput !== undefined
- ? (JSON.parse(input.expectedOutput) as Prisma.InputJsonObject)
- : undefined,
+ input: normalizeForUpdate(parsedInput),
+ expectedOutput: normalizeForUpdate(parsedExpectedOutput),
metadata:
input.metadata === ""
? Prisma.DbNull
@@ -714,6 +893,7 @@ export const datasetRouter = createTRPCRouter({
status: input.status,
},
});
+
await auditLog({
session: ctx.session,
resourceType: "datasetItem",
@@ -721,6 +901,7 @@ export const datasetRouter = createTRPCRouter({
action: "update",
after: datasetItem,
});
+
return datasetItem;
}),
createDataset: protectedProjectProcedure
@@ -730,33 +911,59 @@ export const datasetRouter = createTRPCRouter({
name: StringNoHTMLNonEmpty,
description: StringNoHTML.nullish(),
metadata: z.string().nullish(),
+ inputSchema: DatasetJSONSchema.nullish(),
+ expectedOutputSchema: DatasetJSONSchema.nullish(),
}),
)
- .mutation(async ({ input, ctx }) => {
+ .mutation(async ({ input, ctx }): Promise<DatasetMutationResult> => {
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
scope: "datasets:CUD",
});
- const dataset = await upsertDataset({
- input: {
- name: input.name,
- description: input.description ?? undefined,
- metadata: resolveMetadata(input.metadata),
- },
- projectId: input.projectId,
- });
+ try {
+ const dataset = await upsertDataset({
+ input: {
+ name: input.name,
+ description: input.description ?? undefined,
+ metadata: resolveMetadata(input.metadata),
+ inputSchema: input.inputSchema,
+ expectedOutputSchema: input.expectedOutputSchema,
+ },
+ projectId: input.projectId,
+ });
- await auditLog({
- session: ctx.session,
- resourceType: "dataset",
- resourceId: dataset.id,
- action: "create",
- after: dataset,
- });
+ await auditLog({
+ session: ctx.session,
+ resourceType: "dataset",
+ resourceId: dataset.id,
+ action: "create",
+ after: dataset,
+ });
- return dataset;
+ return { success: true, dataset };
+ } catch (error) {
+ // Check if this is a validation error from upsertDataset
+ if (
+ error instanceof Error &&
+ error.message.includes("Schema validation failed")
+ ) {
+ // Parse validation errors from message
+ const match = error.message.match(/Details: (\[.*\])$/);
+ if (match) {
+ try {
+ const validationErrors = JSON.parse(match[1]);
+ return { success: false, validationErrors };
+ } catch (e) {
+ // Failed to parse, rethrow original error
+ throw error;
+ }
+ }
+ }
+ // Re-throw non-validation errors
+ throw error;
+ }
}),
updateDataset: protectedProjectProcedure
.input(
@@ -766,21 +973,76 @@ export const datasetRouter = createTRPCRouter({
name: StringNoHTMLNonEmpty.nullish(),
description: StringNoHTML.nullish(),
metadata: z.string().nullish(),
+ inputSchema: DatasetJSONSchema.nullish(),
+ expectedOutputSchema: DatasetJSONSchema.nullish(),
}),
)
- .mutation(async ({ input, ctx }) => {
+ .mutation(async ({ input, ctx }): Promise<DatasetMutationResult> => {
throwIfNoProjectAccess({
session: ctx.session,
projectId: input.projectId,
scope: "datasets:CUD",
});
+ // If schemas are being updated, validate all existing items
+ // Fast validation (10K items in <1s) means we can always validate
+ if (
+ input.inputSchema !== undefined ||
+ input.expectedOutputSchema !== undefined
+ ) {
+ const existingDataset = await ctx.prisma.dataset.findUnique({
+ where: {
+ id_projectId: {
+ id: input.datasetId,
+ projectId: input.projectId,
+ },
+ },
+ select: { inputSchema: true, expectedOutputSchema: true },
+ });
+
+ if (existingDataset) {
+ // Determine the final schemas after update
+ const finalInputSchema =
+ input.inputSchema !== undefined
+ ? input.inputSchema
+ : existingDataset.inputSchema;
+ const finalExpectedOutputSchema =
+ input.expectedOutputSchema !== undefined
+ ? input.expectedOutputSchema
+ : existingDataset.expectedOutputSchema;
+
+ // Validate all items if at least one schema is being set (not null)
+ if (finalInputSchema !== null || finalExpectedOutputSchema !== null) {
+ const validationResult = await validateAllDatasetItems({
+ datasetId: input.datasetId,
+ projectId: input.projectId,
+ inputSchema: finalInputSchema as Record<string, unknown> | null,
+ expectedOutputSchema: finalExpectedOutputSchema as Record<
+ string,
+ unknown
+ > | null,
+ prisma: ctx.prisma,
+ });
+
+ if (!validationResult.isValid) {
+ // Return validation errors instead of throwing
+ return {
+ success: false,
+ validationErrors: validationResult.errors,
+ };
+ }
+ }
+ }
+ }
+
const dataset = await updateDataset({
input: {
id: input.datasetId,
name: input.name ?? undefined,
description: input.description ?? undefined,
metadata: resolveMetadata(input.metadata),
+ inputSchema: input.inputSchema,
+ expectedOutputSchema: input.expectedOutputSchema,
},
projectId: input.projectId,
});
@@ -793,7 +1055,7 @@ export const datasetRouter = createTRPCRouter({
after: dataset,
});
- return dataset;
+ return { success: true, dataset };
}),
deleteDataset: protectedProjectProcedure
.input(z.object({ projectId: z.string(), datasetId: z.string() }))
@@ -952,6 +1214,8 @@ export const datasetRouter = createTRPCRouter({
name: duplicateDatasetName(counter),
description: dataset.description ?? undefined,
metadata: dataset.metadata ?? undefined,
+ inputSchema: dataset.inputSchema,
+ expectedOutputSchema: dataset.expectedOutputSchema,
},
projectId: input.projectId,
});
@@ -1006,6 +1270,11 @@ export const datasetRouter = createTRPCRouter({
projectId: input.projectId,
},
},
+ select: {
+ id: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ },
});
if (!dataset) {
throw new TRPCError({
@@ -1014,10 +1283,25 @@ export const datasetRouter = createTRPCRouter({
});
}
+ 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: formatDatasetItemData(input.input),
- expectedOutput: formatDatasetItemData(input.expectedOutput),
+ input: parsedInput,
+ expectedOutput: parsedExpectedOutput,
metadata: formatDatasetItemData(input.metadata),
datasetId: input.datasetId,
sourceTraceId: input.sourceTraceId,
@@ -1025,6 +1309,7 @@ export const datasetRouter = createTRPCRouter({
projectId: input.projectId,
},
});
+
await auditLog({
session: ctx.session,
resourceType: "datasetItem",
@@ -1032,6 +1317,7 @@ export const datasetRouter = createTRPCRouter({
action: "create",
after: datasetItem,
});
+
return datasetItem;
}),
@@ -1051,61 +1337,103 @@ export const datasetRouter = createTRPCRouter({
),
}),
)
- .mutation(async ({ input, ctx }) => {
- throwIfNoProjectAccess({
- session: ctx.session,
- projectId: input.projectId,
- scope: "datasets:CUD",
- });
+ .mutation(
+ async ({
+ input,
+ ctx,
+ }): Promise<
+ | { success: true }
+ | {
+ success: false;
+ validationErrors: BulkDatasetItemValidationError[];
+ }
+ > => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ 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 },
+ // 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,
projectId: input.projectId,
- },
- });
+ status: DatasetStatus.ACTIVE,
+ }));
- if (datasets.length !== datasetIds.length) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "One or more datasets not found",
+ // Validate all items - all-or-nothing
+ const validationErrors = validateBulkDatasetItems({
+ items: itemsWithIds,
+ datasetSchemas: datasetSchemaMap,
});
- }
- 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,
- projectId: input.projectId,
- status: DatasetStatus.ACTIVE,
- }));
+ // If any validation errors, return them instead of throwing
+ if (validationErrors.length > 0) {
+ return {
+ success: false,
+ validationErrors,
+ };
+ }
- await ctx.prisma.datasetItem.createMany({
- data: itemsWithIds,
- });
+ // All items valid - create all
+ await ctx.prisma.datasetItem.createMany({
+ data: itemsWithIds,
+ });
- await Promise.all(
- itemsWithIds.map(async (item) =>
- auditLog({
- session: ctx.session,
- resourceType: "datasetItem",
- resourceId: item.id,
- action: "create",
- after: item,
- }),
- ),
- );
+ await Promise.all(
+ itemsWithIds.map(async (item) =>
+ auditLog({
+ session: ctx.session,
+ resourceType: "datasetItem",
+ resourceId: item.id,
+ action: "create",
+ after: item,
+ }),
+ ),
+ );
- return;
- }),
+ return { success: true };
+ },
+ ),
runItemsByItemId: protectedProjectProcedure
.input(
z.object({
@@ -1672,6 +2000,131 @@ export const datasetRouter = createTRPCRouter({
after: updatedDataset,
});
+ return updatedDataset;
+ }),
+
+ validateDatasetSchema: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ datasetId: z.string(),
+ inputSchema: DatasetJSONSchema.nullable(),
+ expectedOutputSchema: DatasetJSONSchema.nullable(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "datasets:CUD",
+ });
+
+ const dataset = await ctx.prisma.dataset.findUnique({
+ where: {
+ id_projectId: {
+ id: input.datasetId,
+ projectId: input.projectId,
+ },
+ },
+ });
+
+ if (!dataset) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Dataset not found",
+ });
+ }
+
+ const validationResult = await validateAllDatasetItems({
+ datasetId: input.datasetId,
+ projectId: input.projectId,
+ inputSchema: input.inputSchema,
+ expectedOutputSchema: input.expectedOutputSchema,
+ prisma: ctx.prisma,
+ });
+
+ return validationResult;
+ }),
+
+ setDatasetSchema: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ datasetId: z.string(),
+ inputSchema: DatasetJSONSchema.nullable(),
+ expectedOutputSchema: DatasetJSONSchema.nullable(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "datasets:CUD",
+ });
+
+ const dataset = await ctx.prisma.dataset.findUnique({
+ where: {
+ id_projectId: {
+ id: input.datasetId,
+ projectId: input.projectId,
+ },
+ },
+ });
+
+ if (!dataset) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Dataset not found",
+ });
+ }
+
+ // Validate all existing items before applying schema
+ const validationResult = await validateAllDatasetItems({
+ datasetId: input.datasetId,
+ projectId: input.projectId,
+ inputSchema: input.inputSchema,
+ expectedOutputSchema: input.expectedOutputSchema,
+ prisma: ctx.prisma,
+ });
+
+ if (!validationResult.isValid) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Schema validation failed for ${validationResult.errors.length} item(s)`,
+ cause: validationResult.errors,
+ });
+ }
+
+ // Update dataset with new schemas
+ const updatedDataset = await ctx.prisma.dataset.update({
+ where: {
+ id_projectId: {
+ id: input.datasetId,
+ projectId: input.projectId,
+ },
+ },
+ data: {
+ inputSchema: input.inputSchema ?? Prisma.DbNull,
+ expectedOutputSchema: input.expectedOutputSchema ?? Prisma.DbNull,
+ },
+ });
+
+ // Audit log
+ await auditLog({
+ session: ctx.session,
+ resourceType: "dataset",
+ resourceId: input.datasetId,
+ action: "updateSchema",
+ before: {
+ inputSchema: dataset.inputSchema,
+ expectedOutputSchema: dataset.expectedOutputSchema,
+ },
+ after: {
+ inputSchema: updatedDataset.inputSchema,
+ expectedOutputSchema: updatedDataset.expectedOutputSchema,
+ },
+ });
+
return updatedDataset;
}),
});
diff --git a/web/src/features/public-api/types/datasets.ts b/web/src/features/public-api/types/datasets.ts
index 2c3078368f..8c157efeb0 100644
--- a/web/src/features/public-api/types/datasets.ts
+++ b/web/src/features/public-api/types/datasets.ts
@@ -10,6 +10,7 @@ import {
removeObjectKeys,
type DatasetRunItemDomain,
} from "@langfuse/shared";
+import { DatasetJSONSchema } from "@langfuse/shared/src/server";
import { z } from "zod/v4";
/**
@@ -23,6 +24,8 @@ const APIDataset = z
name: z.string(),
description: z.string().nullable(),
metadata: z.any(),
+ inputSchema: z.any().nullable(),
+ expectedOutputSchema: z.any().nullable(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
})
@@ -115,6 +118,8 @@ export const PostDatasetsV2Body = z.object({
name: z.string(),
description: z.string().nullish(),
metadata: jsonSchema.nullish(),
+ inputSchema: DatasetJSONSchema.nullish(),
+ expectedOutputSchema: DatasetJSONSchema.nullish(),
});
export const PostDatasetsV2Response = APIDataset.strict();
@@ -238,6 +243,8 @@ export const PostDatasetsV1Body = z.object({
name: z.string(),
description: z.string().nullish(),
metadata: jsonSchema.nullish(),
+ inputSchema: DatasetJSONSchema.nullish(),
+ expectedOutputSchema: DatasetJSONSchema.nullish(),
});
export const PostDatasetsV1Response = APIDataset.extend({
items: z.array(APIDatasetItem),
diff --git a/web/src/pages/api/public/dataset-items/index.ts b/web/src/pages/api/public/dataset-items/index.ts
index 1d90b09d32..7e9c3180c2 100644
--- a/web/src/pages/api/public/dataset-items/index.ts
+++ b/web/src/pages/api/public/dataset-items/index.ts
@@ -12,9 +12,10 @@ import {
import {
type DatasetItem,
LangfuseNotFoundError,
+ InvalidRequestError,
Prisma,
} from "@langfuse/shared";
-import { logger } from "@langfuse/shared/src/server";
+import { logger, validateDatasetItemData } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/auditLog";
export const config = {
@@ -48,6 +49,12 @@ export default withMiddlewares({
projectId: auth.scope.projectId,
name: datasetName,
},
+ select: {
+ id: true,
+ name: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
+ },
});
if (!dataset) {
throw new LangfuseNotFoundError("Dataset not found");
@@ -55,6 +62,30 @@ export default withMiddlewares({
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
+ });
+
+ if (!validationResult.isValid) {
+ const errorDetails = {
+ inputErrors: validationResult.inputErrors,
+ expectedOutputErrors: validationResult.expectedOutputErrors,
+ };
+ throw new InvalidRequestError(
+ `Dataset item validation failed: ${JSON.stringify(errorDetails)}`,
+ );
+ }
+
let item: DatasetItem;
try {
item = await prisma.datasetItem.upsert({
diff --git a/web/src/pages/api/public/datasets.ts b/web/src/pages/api/public/datasets.ts
index 14204e0627..c95669f131 100644
--- a/web/src/pages/api/public/datasets.ts
+++ b/web/src/pages/api/public/datasets.ts
@@ -18,13 +18,16 @@ export default withMiddlewares({
responseSchema: PostDatasetsV1Response,
rateLimitResource: "datasets",
fn: async ({ body, auth }) => {
- const { name, description, metadata } = body;
+ const { name, description, metadata, inputSchema, expectedOutputSchema } =
+ body;
const dataset = await upsertDataset({
input: {
name,
description: description ?? undefined,
metadata: metadata ?? undefined,
+ inputSchema,
+ expectedOutputSchema,
},
projectId: auth.scope.projectId,
});
@@ -59,6 +62,8 @@ export default withMiddlewares({
name: true,
description: true,
metadata: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
projectId: true,
createdAt: true,
updatedAt: true,
diff --git a/web/src/pages/api/public/v2/datasets/index.ts b/web/src/pages/api/public/v2/datasets/index.ts
index 6f954cc5f0..a67b778164 100644
--- a/web/src/pages/api/public/v2/datasets/index.ts
+++ b/web/src/pages/api/public/v2/datasets/index.ts
@@ -18,13 +18,16 @@ export default withMiddlewares({
responseSchema: PostDatasetsV2Response,
rateLimitResource: "datasets",
fn: async ({ body, auth }) => {
- const { name, description, metadata } = body;
+ const { name, description, metadata, inputSchema, expectedOutputSchema } =
+ body;
const dataset = await upsertDataset({
input: {
name,
description: description ?? undefined,
metadata: metadata ?? undefined,
+ inputSchema,
+ expectedOutputSchema,
},
projectId: auth.scope.projectId,
});
@@ -53,6 +56,8 @@ export default withMiddlewares({
name: true,
description: true,
metadata: true,
+ inputSchema: true,
+ expectedOutputSchema: true,
projectId: true,
createdAt: true,
updatedAt: true,
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
index 5293f47485..03292b5ba0 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
@@ -238,6 +238,10 @@ export default function Dataset() {
datasetName={dataset.data?.name ?? ""}
datasetDescription={dataset.data?.description ?? undefined}
datasetMetadata={dataset.data?.metadata}
+ datasetInputSchema={dataset.data?.inputSchema ?? undefined}
+ datasetExpectedOutputSchema={
+ dataset.data?.expectedOutputSchema ?? undefined
+ }
/>
</DropdownMenuItem>
<DropdownMenuItem asChild>
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
index 0ec6b0ba33..c47095387d 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/items.tsx
@@ -93,6 +93,10 @@ export default function DatasetItems() {
datasetName={dataset.data?.name ?? ""}
datasetDescription={dataset.data?.description ?? undefined}
datasetMetadata={dataset.data?.metadata}
+ datasetInputSchema={dataset.data?.inputSchema ?? undefined}
+ datasetExpectedOutputSchema={
+ dataset.data?.expectedOutputSchema ?? undefined
+ }
/>
</DropdownMenuItem>
<DropdownMenuItem asChild>
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
index 07942c3bc0..a332578d9a 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/items/[itemId]/index.tsx
@@ -21,12 +21,27 @@ export default function Dataset() {
},
);
+ const dataset = api.datasets.byId.useQuery({
+ datasetId,
+ projectId,
+ });
+
return (
<DatasetItemDetailPage activeTab={DATASET_ITEM_TABS.ITEM}>
<EditDatasetItem
key={itemId}
projectId={projectId}
datasetItem={item.data ?? null}
+ dataset={
+ dataset.data
+ ? {
+ id: dataset.data.id,
+ name: dataset.data.name,
+ inputSchema: dataset.data.inputSchema ?? null,
+ expectedOutputSchema: dataset.data.expectedOutputSchema ?? null,
+ }
+ : null
+ }
/>
</DatasetItemDetailPage>
);