{"record":{"id":"523cf696ff45f520","repo":"mastra-ai/mastra","slug":"schema-validation-failed-due-to-an-invalid-schema","errorCode":null,"errorMessage":"Schema validation failed due to an invalid schema definition. This often happens when a union schema (z.union or z.or) has undefined options. Please check that all schema options are properly defined. Original error: ${err.message}","messagePattern":"Schema validation failed due to an invalid schema definition\\. This often happens when a union schema \\(z\\.union or z\\.or\\) has undefined options\\. Please check that all schema options are properly defined\\. Original error: (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/core/src/tools/validation.ts","lineNumber":33,"sourceCode":"function safeValidate<T>(\n  schema: StandardSchemaWithJSON<T>,\n  data: unknown,\n): { value: T } | { issues: readonly StandardSchemaIssue[] } {\n  try {\n    const result = schema['~standard'].validate(data);\n    if (result instanceof Promise) {\n      throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n    }\n    // Prioritise issues over value: Valibot returns both on failure (typed: false).\n    if ('issues' in result && Array.isArray(result.issues) && result.issues.length > 0) {\n      return { issues: result.issues as readonly StandardSchemaIssue[] };\n    }\n    return result as { value: T } | { issues: readonly StandardSchemaIssue[] };\n  } catch (err) {\n    // Catch Zod internal errors like \"Cannot read properties of undefined (reading 'run')\"\n    // This happens when a union schema has undefined options\n    if (err instanceof TypeError && err.message.includes('Cannot read properties of undefined')) {\n      throw new Error(\n        `Schema validation failed due to an invalid schema definition. ` +\n          `This often happens when a union schema (z.union or z.or) has undefined options. ` +\n          `Please check that all schema options are properly defined. Original error: ${err.message}`,\n      );\n    }\n    throw err;\n  }\n}\n\n/**\n * Formatted validation errors structure.\n * Contains `errors` array for messages at this level, and `fields` for nested field errors.\n */\nexport type FormattedValidationErrors<T = unknown> = {\n  errors: string[];\n  fields: T extends object ? { [K in keyof T]?: FormattedValidationErrors<T[K]> } : unknown;\n};\n","sourceCodeStart":15,"sourceCodeEnd":51,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/tools/validation.ts#L15-L51","documentation":"When schema validation throws internally (rather than returning issues), Mastra detects the common Zod crash `Cannot read properties of undefined (reading 'run')` and rethrows this explanatory error. This crash almost always means a union schema (`z.union([...])` or `.or()`) contains an `undefined` option — typically from an import/circular-dependency problem where a schema constant is `undefined` at validation time.","triggerScenarios":"A tool or workflow schema built with `z.union([schemaA, schemaB])` or `schemaA.or(schemaB)` where one operand is `undefined` at runtime (failed/hoisted import, circular dependency, conditional schema construction that skipped an option).","commonSituations":"Barrel-file circular imports in ESM where schema modules reference each other; conditional code like `z.union([...(useA ? [schemaA] : [])])` producing an empty/undefined entry; typos in imported schema names silently becoming undefined under TS-loose configs.","solutions":["Inspect the union schema in the failing validator and log each option — find the `undefined` one.","Fix the import (avoid circular dependencies between schema modules; import directly instead of via barrels).","Guard conditional unions: filter/fallback, e.g. `z.union(opts.filter(Boolean))`, and add a dev-time assertion that every option is defined.","Enable TypeScript `verbatimModuleSyntax`/strict import checks to catch undefined schema imports at build time."],"exampleFix":"// before\nimport { schemaB } from './schemas'; // circular -> undefined at module init\nexport const input = z.union([schemaA, schemaB]);\n// after\nimport { schemaB } from './schema-b'; // direct import breaks the cycle\nexport const input = z.union([schemaA, schemaB]);","handlingStrategy":"validation","validationCode":"function assertUnionOptionsDefined(...options: unknown[]) {\n  const bad = options.map((o, i) => [i, o]).filter(([, o]) => o === undefined);\n  if (bad.length) throw new Error(`Union schema options undefined at indexes: ${bad.map(([i]) => i).join(',')}`);\n}\n// assertUnionOptionsDefined(schemaA, schemaB) before z.union([schemaA, schemaB])","typeGuard":"function isDefinedSchema(v: unknown): v is NonNullable<unknown> {\n  return v !== undefined && v !== null && typeof v === 'object';\n}","tryCatchPattern":"try {\n  validateInput(data, schema);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('invalid schema definition')) {\n    console.error('Check union schema options for undefined values (likely circular/failed import).');\n  }\n  throw e;\n}","preventionTips":["Avoid circular imports between schema modules; import schemas directly, not via barrels.","Never build unions with conditional spreads that can emit undefined: use `.filter(Boolean)` and assert non-empty.","Enable strict TS import checking so typos in schema imports fail at compile time."],"tags":["schema","validation","zod","union","circular-import"],"backgroundTag":"invalid-union-schema-definition","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}