mastra-ai/mastra · error · HTTPException
error.message (schema validation error, cause: field/errors)
Error message
error.message (schema validation error, cause: field/errors)
What it means
The BATCH_INSERT_ITEMS route (POST /datasets/:datasetId/items/batch) validates each item's input/groundTruth/etc. against the dataset's configured Zod schemas. When ds.addItems rejects with a schema validation error, the handler converts it to HTTP 400 with cause: { field, errors } detailing which field failed and why.
Source
Thrown at packages/server/src/server/handlers/datasets.ts:1216
externalId?: string | null;
input: unknown;
groundTruth?: unknown;
expectedTrajectory?: unknown;
toolMocks?: DatasetItemToolMock[];
unmockedToolPolicy?: 'allow' | 'deny';
scorerIds?: string[];
metadata?: Record<string, unknown>;
source?: DatasetItemSource;
}>;
};
const ds = await mastra.datasets.get({ id: datasetId });
const addedItems = await ds.addItems({
items: items.map(item => ({ ...item, externalId: item.externalId ?? undefined })),
});
return { items: addedItems, count: addedItems.length };
} catch (error) {
if (isSchemaValidationError(error)) {
throw new HTTPException(400, {
message: error.message,
cause: { field: error.field, errors: error.errors },
});
}
if (error instanceof MastraError) {
if (error.id === 'DATASET_ITEM_IDENTITY_CONFLICT') {
throw new HTTPException(409, {
message: error.message,
cause: { conflicts: 'conflicts' in error ? error.conflicts : [] },
});
}
if (error.id === 'DATASET_ITEM_EXTERNAL_ID_INVALID') {
throw new HTTPException(400, { message: error.message, cause: { field: 'externalId' } });
}
throw new HTTPException(getHttpStatusForMastraError(error.id) as StatusCode, { message: error.message });
}
return handleError(error, 'Error batch inserting items');
}View on GitHub (pinned to 75dd419e61)
Solutions
- Read cause.field and cause.errors in the 400 response to see exactly which item field failed validation.
- Fetch the dataset details (GET /datasets/:datasetId) to inspect its input/groundTruth schemas and conform your items.
- Validate items client-side with the same Zod schemas before calling the batch endpoint.
- If the schema intentionally changed, update the producing code or regenerate the items.
Example fix
// before
await client.batchInsertItems(dsId, [{ input: '{"query":"hi"}' }]); // 400 schema validation
// after
const parsed = datasetInputSchema.parse(JSON.parse('{"query":"hi"}'));
await client.batchInsertItems(dsId, [{ input: parsed }]); Defensive patterns
Strategy: validation
Validate before calling
import { z } from 'zod';
const inputSchema = dataset.inputSchema; // same Zod schema the dataset was created with
const validated = items.map(item => ({
...item,
input: inputSchema.parse(item.input),
...(item.groundTruth && groundTruthSchema ? { groundTruth: groundTruthSchema.parse(item.groundTruth) } : {}),
})); // throws ZodError with field details before the HTTP call Type guard
function isSchemaValidationErrorBody(
body: unknown
): body is { message: string; cause?: { field?: string; errors?: unknown } } {
return typeof body === 'object' && body !== null && 'message' in body;
} Try / catch
try {
const res = await fetch(`/api/datasets/${datasetId}/items/batch`, { method: 'POST', body: JSON.stringify({ items }) });
if (res.status === 400) {
const body = await res.json();
console.error(`Schema validation failed on field '${body.cause?.field}':`, body.cause?.errors);
return null;
}
if (!res.ok) throw new Error(await res.text());
return await res.json();
} catch (err) {
console.error(err);
throw err;
} Prevention
- Reuse the exact Zod schemas the dataset was created with for client-side validation before posting.
- Parse JSON strings into objects before assigning to input/groundTruth.
- Re-validate items after any dataset schema change (new required fields, changed types).
- Surface cause.field and cause.errors from the 400 response in your tooling.
When it happens
Trigger: POST /datasets/:datasetId/items/batch where one or more items' payload fields (input, groundTruth, expectedTrajectory, metadata) fail the dataset's schema — wrong types, missing required properties, or extra constraints violated.
Common situations: Client sends stringified JSON instead of a parsed object for input; dataset schema changed (new required field) while the client still posts the old shape; AI-generated items not conforming to schema; groundTruth provided when the dataset defines no groundTruth schema.
Understand the failure class
Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.
Related errors
- DATASET_ITEM_EXTERNAL_ID_INVALID
- error.message (workflow schema validation error)
- OBSERVABILITY_INVALID_CONFIG
- OBSERVABILITY_INVALID_INSTANCE_CONFIG
- SchemaValidationError(field, this.formatErrors(result.error)
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/5b92d0f873265c55.
Report an issue: GitHub.