{"record":{"id":"b31853c540eec874","repo":"mastra-ai/mastra","slug":"schemavalidationerror-field-this-formaterrors-res","errorCode":null,"errorMessage":"SchemaValidationError(field, this.formatErrors(result.error))","messagePattern":"SchemaValidationError\\(field, this\\.formatErrors\\(result\\.error\\)\\)","errorType":"validation","errorClass":"SchemaValidationError","httpStatus":null,"severity":"error","filePath":"packages/core/src/datasets/validation/validator.ts","lineNumber":41,"sourceCode":"    if (!zodSchema) {\n      const zodString = jsonSchemaToZod(schema);\n      zodSchema = resolveZodSchema(zodString);\n      this.cache.set(cacheKey, zodSchema);\n    }\n    return zodSchema;\n  }\n\n  /** Clear cached validator (call when schema changes) */\n  clearCache(cacheKey: string): void {\n    this.cache.delete(cacheKey);\n  }\n\n  /** Validate data against schema */\n  validate(data: unknown, schema: JSONSchema7, field: 'input' | 'groundTruth', cacheKey: string): void {\n    const zodSchema = this.getValidator(schema, cacheKey);\n    const result = zodSchema.safeParse(data);\n    if (!result.success) {\n      throw new SchemaValidationError(field, this.formatErrors(result.error));\n    }\n  }\n\n  /** Validate multiple items, returning valid/invalid split */\n  validateBatch(\n    items: Array<{ input: unknown; groundTruth?: unknown }>,\n    inputSchema: JSONSchema7 | null | undefined,\n    outputSchema: JSONSchema7 | null | undefined,\n    cacheKeyPrefix: string,\n    maxErrors = 10,\n  ): BatchValidationResult {\n    const result: BatchValidationResult = { valid: [], invalid: [] };\n\n    // Pre-compile schemas for performance\n    const inputValidator = inputSchema ? this.getValidator(inputSchema, `${cacheKeyPrefix}:input`) : null;\n    const outputValidator = outputSchema ? this.getValidator(outputSchema, `${cacheKeyPrefix}:output`) : null;\n\n    for (const [i, item] of items.entries()) {","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/datasets/validation/validator.ts#L23-L59","documentation":"The dataset validator converts a JSON Schema (JSONSchema7) to a Zod schema and safeParses the data. When parsing fails, it throws SchemaValidationError carrying the field name ('input' or 'groundTruth') and the formatted Zod error list. This means a dataset item does not conform to the declared schema for the given field.","triggerScenarios":"Calling validator.validate(data, schema, field, cacheKey) directly, or any library path that validates dataset items (saving/adding records, creating experiments, running evaluation) with data that violates the JSON schema for input or groundTruth.","commonSituations":"Missing required properties, wrong types (e.g. string instead of number), extra strictness from the schema, or a dataset row pasted in from another source with a different shape; also happens when the schema was changed after records were created with an older shape.","solutions":["Read the formatted error list in the SchemaValidationError and correct the offending item(s) to match the schema.","Run the validation locally first (e.g. with ajv) before submitting records so failures are caught client-side.","If the schema changed intentionally, migrate existing records to the new shape instead of editing the schema to fit old data.","Confirm the correct JSONSchema7 draft is used; unsupported or malformed schemas can compile to an unexpectedly strict Zod schema."],"exampleFix":"// before\nawait dataset.addRecord({ input: { q: 'hello' } }); // schema requires 'question'\n// after\nawait dataset.addRecord({ input: { question: 'hello' } });","handlingStrategy":"validation","validationCode":"import Ajv from 'ajv';\nconst ajv = new Ajv();\nconst validate = ajv.compile(schema);\nif (!validate(item.input)) throw new Error(`Invalid input: ${ajv.errorsText(validate.errors)}`);","typeGuard":"function conformsToSchema(data: unknown, schema: object): boolean {\n  try {\n    const ajv = new Ajv();\n    return Boolean(ajv.compile(schema as object)(data));\n  } catch { return false; }\n}","tryCatchPattern":"try {\n  dataset.validate(data, schema, 'input', cacheKey);\n} catch (e) {\n  if (e.name === 'SchemaValidationError') {\n    console.error(`Field '${e.field}' failed:`, e.message);\n    return; // or fix/reject the record\n  }\n  throw e;\n}","preventionTips":["Validate records with ajv (or a Zod equivalent) before submitting to the library.","Keep schemas in one place and version them; migrate old records when schemas change.","Log the full SchemaValidationError message — it lists every offending path and reason."],"tags":["validation","schema","zod","datasets"],"backgroundTag":"schema-validation-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}