Skip to content

fix(schema-compat): keep null valid for nullable enums and literals - #25086

Merged
abhiaiyer91 merged 1 commit into
mastra-ai:mainfrom
breken-ai:fix/schema-compat-nullable-enum
Sep 25, 2026
Merged

abhiaiyer91 merged 1 commit into
mastra-ai:mainfrom
breken-ai:fix/schema-compat-nullable-enum

Conversation

@breken-ai

@breken-ai breken-ai commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #24516.

zodToJsonSchema rewrites a nullable schema from anyOf: [{ type: X, ... }, { type: "null" }] to { type: [X, "null"], ... } (fixAnyOfNullable in packages/schema-compat/src/zod-to-json.ts). When the non-null branch has an enum or const, those keys were copied over unchanged. JSON Schema requires type and enum/const to both hold, so the exported schema rejected null, which the Zod schema accepts:

z.enum(['red', 'blue']).nullable()  ->  {"type":["string","null"],"enum":["red","blue"]}   // null rejected
z.literal('fast').nullable()        ->  {"type":["string","null"],"const":"fast"}          // null rejected

This fix adds null to enum and turns const into enum: [const, null] when the two branches are merged. This is the approach proposed in the triage comment on the issue. Other schemas are unchanged.

Tests. I added two regression tests to zod-to-json.test.ts. They compile the exported schema with Ajv, then check that null and the listed values are accepted and that other values are still rejected.

  • On main (c58c88b8), both tests fail in the v4 project with expected false to be true on the null check. The v3 project already passed, because the v3 path keeps anyOf.
  • With this fix, the full @mastra/schema-compat suite passes: 36 files, 959 tests, 9 skipped, for both v3 and v4.
  • tsc --noEmit, oxlint, eslint and oxfmt --check are clean on the changed files.

I added a patch changeset for @mastra/schema-compat.

Related issue(s)

Fixes #24516

Type of change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Code refactoring
  • Performance improvement
  • Test update

Checklist

  • I have linked the related issue(s) in the description above
  • I have made corresponding changes to the documentation (if applicable)
  • I have added tests that prove my fix is effective or that my feature works
  • I have addressed all Coderabbit comments on this PR

An AI coding agent (Breken) found this fix, wrote it and tested it. It is submitted from the breken-ai account.

ELI5

A nullable field should accept either one of its listed values or null. This change fixes exported JSON Schemas so nullable enums and literals accept null, as their Zod schemas do.

Changes

  • Updated fixAnyOfNullable to add null to an enum when it merges nullable branches.
  • Converted a merged const into an enum containing the constant and null.
  • Added Ajv regression tests for nullable enums and literals. The tests check that null and allowed values pass, and other values fail.
  • Added a patch changeset for @mastra/schema-compat.

zodToJsonSchema folds a zod v4 nullable enum/literal from
anyOf [{type: X, enum|const}, {type: null}] into type: [X, null], but
kept enum/const unchanged. type and enum/const both have to hold, so
the exported schema rejected null. Add null to enum, and turn const
into enum [const, null], when folding.

Fixes mastra-ai#24516
@changeset-bot

changeset-bot Bot commented Sep 25, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: fc31087

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 33 packages
Name Type
@mastra/schema-compat Patch
@mastra/code-sdk Patch
mastracode Patch
@mastra/agent-builder Patch
@mastra/core Patch
@mastra/editor Patch
@mastra/memory Patch
@internal/playground Patch
@mastra/server Patch
@mastra/voice-google-gemini-live Patch
@mastra/voice-openai-realtime Patch
@mastra/voice-xai-realtime Patch
@mastra/client-js Patch
@mastra/factory Patch
@mastra/mcp-docs-server Patch
@mastra/opencode Patch
@mastra/longmemeval Patch
@mastra/elysia Patch
@mastra/express Patch
@mastra/fastify Patch
@mastra/hono Patch
@mastra/koa Patch
@mastra/nestjs Patch
mastra Patch
@mastra/deployer-cloud Patch
@mastra/react Patch
@mastra/playground-ui Patch
@mastra/deployer Patch
create-mastra Patch
@mastra/next Patch
@mastra/tanstack-start Patch
create-factory Patch
@mastra/temporal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@dane-ai-mastra dane-ai-mastra Bot added the needs-issue PR is missing a linked issue label Sep 25, 2026
@vercel

vercel Bot commented Sep 25, 2026

Copy link
Copy Markdown

@breken-ai is attempting to deploy a commit to the Mastra Team on Vercel.

A member of the Team first needs to authorize it.

@dane-ai-mastra

dane-ai-mastra Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

PR triage

Linked issue check passed (#24516).

Mastra uses CodeRabbit for automated code reviews. Please address all feedback from CodeRabbit by either making changes to your PR or leaving a comment explaining why you disagree with the feedback. Since CodeRabbit is an AI, it may occasionally provide incorrect feedback.


Changed test gate

Changed Test Gate is pending. The Changed Test Gate / changed-tests check will update the test label when it completes.

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: mastra-ai/mastra/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 7c3b3860-fb6a-41d6-8ced-522642435fc5

📥 Commits

Reviewing files that changed from the base of the PR and between 56fef1c and fc31087.

📒 Files selected for processing (3)
  • .changeset/nullable-enum-keeps-null.md
  • packages/schema-compat/src/zod-to-json.test.ts
  • packages/schema-compat/src/zod-to-json.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


Walkthrough

fixAnyOfNullable now includes null in the allowed values when converting nullable Zod v4 enums and literals. New tests validate the generated schemas with Ajv.

Changes

Nullable schema conversion

Layer / File(s) Summary
Merge nullable branches and validate schemas
packages/schema-compat/src/zod-to-json.ts, packages/schema-compat/src/zod-to-json.test.ts, .changeset/nullable-enum-keeps-null.md
fixAnyOfNullable adds null to an existing enum or converts a const to an enum containing the const value and null. Ajv tests check that null and the allowed value validate, while an unlisted value does not. A patch changeset records the fix.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to fc310

The changeset explains the fix clearly, and no issue requiring correction before merge remains.

Security Architecture Review

Security architecture risk: 🔵 Low · up to fc310

The change makes generated schemas accept null where the originating nullable Zod schemas already do, while the new tests still reject other values. No new access path or security-control bypass was established, but downstream behavior has not been verified end to end.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Consumers that validate newly generated Zod v4 nullable enum or literal schemas may now admit null where their previous generated schemas rejected it. Existing dataset paths can persist those generated schemas; the extent of external or attacker-controlled exposure is not established.

Trust Boundaries and Controls

  • observed — The flagged test helper does not create a production entrypoint. In the examined dataset paths, schema conversion precedes storage, and updates retain the existing dataset scope filter.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation addresses [#24516] in fixAnyOfNullable. It removes the non-null branch const before merging, converts that value to enum: [constValue, null], and appends null to an existing…
Out of Scope Changes check ✅ Passed The changed source code, regression tests, and @mastra/schema-compat patch changeset directly support [#24516]. The changes do not introduce an unrelated behavior or unrelated file change.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the nullable enum and literal fix. It uses conventional commit syntax and is specific to the changeset. It exceeds the ideal 50-character length and uses lowercase, but the…
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Create a new PR

Comment @coderabbitai help to get the list of available commands.

@dane-ai-mastra dane-ai-mastra Bot removed the needs-issue PR is missing a linked issue label Sep 25, 2026

@mastra-platform mastra-platform Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve

Findings

  • Mechanism: fixAnyOfNullable (packages/schema-compat/src/zod-to-json.ts:113) collapses anyOf: [X, {type:null}] into type: [X, "null"] but carried enum/const over unchanged. JSON Schema ANDs type with enum/const, so null was rejected. The PR appends null to enum and rewrites const as enum: [const, null]. That is the minimal correct repair at the one place the merge happens.
  • Correctness: const is removed from the spread, so no stale const is left behind. Duplicate null is guarded. A falsy const (0, false, '') is handled correctly because the check is !== undefined.
  • Tests: the two Ajv-based regressions check that null, an allowed value, and a rejected value each behave as expected. Non-blocking nit: they only cover string enums and literals. Numeric literals take the same path.
  • Scope: one focused change plus a changeset. No scope creep.

Approach
My design before opening the diff was the same: add null to the allowed values at the anyOf→type-array merge. I agree with this approach.

Issue and intent

  • Closes #24516, an open bug with labels status: auto-triaged and p: high. It has no needs approval label.
  • Classification: bug fix. The implemented behavior matches the issue's proposed fix.

Verification

  • pnpm install --frozen-lockfile --ignore-scripts and pnpm turbo build --filter @mastra/schema-compat... passed (6/6 tasks). All commands ran with env -u GH_TOKEN -u GITHUB_TOKEN.
  • Full pnpm vitest run in packages/schema-compat: exit 0, 36/36 files, 959 passed, 9 skipped (v3 + v4).
  • tsc --noEmit -p .: exit 0 (the tsc exit code itself, captured directly).
  • Base vs head: with origin/main's zod-to-json.ts, both new tests fail in the v4 project (null rejected). On the head they pass. The v3 path keeps anyOf and already accepted null.
  • Pre-execution inspection: the diff changes no scripts, dependencies (ajv is already a dependency), test config or CI.
  • CI: CodeRabbit, Socket and Superagent passed. The Vercel deploys need authorization for an external contributor (advisory).
  • History: the merge logic in fixAnyOfNullable dates from 6833c69 (Jan 2026) and has always carried enum/const over unchanged. So this is a long-standing bug, not a regression.

Existing review disposition

  • Inline review threads: 0 (GraphQL, no further pages).
  • CodeRabbit posted only a summary with no substantive inline findings. changeset-bot, dane-ai-mastra and vercel comments are informational.

Adversarial check

  • Strongest case: a downstream provider compat, such as Gemini's string-only enum, could choke on null in enum. It fails because the Zod-v4 path previously produced a schema that contradicted the Zod contract. Also, the v3 path already emits null via anyOf, so consumers already handle nullable enums.

Requested changes
None.

Assumptions

  • Only string enums and literals are covered by tests. Numeric and boolean literals take the same code path, so the missing tests are not blocking.

Open questions
None.

Review runtime: anthropic/claude-opus-5-5, reasoning setting: low.

@mastra-platform mastra-platform Bot added the status:auto-approved Factory review auto-approved label Sep 25, 2026

@mastra-platform mastra-platform Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve

Prior pass disposition

  • Prior verdict: approve at fc31087, with no requested changes. Nothing was pushed after it: the head is still fc310878730846b59d68a757b10e9d1e5d3c643d and the PR has one commit. So there is nothing to address, refute or invalidate. The prior assumption (numeric and boolean literals go through the same const→enum code path as the tested string literal) still holds.

Findings

  • [fresh] No new defects. fixAnyOfNullable (packages/schema-compat/src/zod-to-json.ts) is where the nullable branch is merged into a type: [X, "null"] array. The fix adds null to enum, or rewrites const as enum: [const, null], at that point. That is where the value becomes wrong, so this is not a symptom patch.

Approach
The required outcome is that the exported schema accepts null wherever Zod accepts it. The simplest design is to add null to the allowed values during the merge, and that is exactly what the PR does, with no extra scope.

Issue and intent
The PR closes issue 24516, a bug labelled p:high. It is classified as a bug fix. Its behavior and scope match the issue, and nothing has changed since the prior pass.

Verification (current head fc31087)

  • env -u GH_TOKEN -u GITHUB_TOKEN pnpm vitest run in packages/schema-compat: exit 0. 36/36 files passed (959 tests passed, 9 skipped).
  • env -u GH_TOKEN -u GITHUB_TOKEN pnpm tsc --noEmit -p .: exit 0.
  • Base vs head: I compared them on this same head earlier today, and the head SHA hasn't changed. The new tests fail on main's zod-to-json.ts in the v4 project and pass on the head.
  • Pre-execution check: the diff contains only the changeset, the test file and zod-to-json.ts. It changes no scripts, dependencies or config.
  • CI (advisory): Build, Lint, changed-tests and the security scans passed. The unit test shards, the kitchen-sink E2E runs, Memory Tests and some store tests are still pending. The Vercel deploys need authorization for an external contributor.

Other-reviewer disposition

  • No new reviews or inline threads since the prior pass. CodeRabbit posted only a summary; its check shows the review as completed, so no bot is pending on this head.

Adversarial check
The strongest objection is that a provider-specific conversion might reject null inside enum. It fails because the v3 path already emits a nullable anyOf that accepts null, and the old v4 output contradicted the Zod schema.

Assumptions

  • Numeric and boolean literals are not tested separately because they take the same code path as the tested string literal.

Open questions
None.

Review runtime: anthropic/claude-opus-5-5, reasoning setting: low.

@abhiaiyer91
abhiaiyer91 merged commit 3913a33 into mastra-ai:main Sep 25, 2026
94 of 97 checks passed
leoisadev1 added a commit that referenced this pull request Nov 10, 2026
…empty-string literals (#29416)

## Summary

A tool whose input schema has a numeric, boolean or empty-string literal
(`z.literal(1)`, `z.literal(true)`, `z.union([z.string(),
z.literal('')])`) makes every Gemini request from that agent fail with
HTTP 400. `GoogleSchemaCompatLayer.postProcessJSONNode` rewrites each
`const` into `enum: [const]` and passes other enums through, but Gemini
only accepts `enum` as non-empty strings on a string node. This PR
normalizes enums in `@mastra/schema-compat`'s Google layer right after
that rewrite. Both the `processToCompatSchema` / `applyCompatLayer` path
that tools use and the `processToAISDKSchema` path go through it.

```diff
 postProcessJSONNode (packages/schema-compat/src/provider-compats/google.ts)
   const: v  ->  enum: [v]
+  toGeminiEnum(node)
+    string enum on a string (or untyped) node -> keep it, type: 'string'; a null value -> nullable: true
+    anything else -> drop enum, keep or infer type (boolean / string / integer / number,
+                     anyOf when mixed), append "Must be 1." / "Must be one of: 1, 2." to description
   nullable anyOf collapse
+    when either side carries that note, keep the parent description in front of it
```

Tool-call arguments are still validated against the original schema, so
this changes only what is sent to Gemini, not which inputs are accepted.

## Evidence

The issue's reproduction snippet, run against the package source:

- **Before** (main):
  ```json

{"type":"object","properties":{"v":{"type":"number","enum":[1]}},"required":["v"]}

{"type":"object","properties":{"flag":{"type":"boolean","enum":[true]}},"required":["flag"]}

{"type":"object","properties":{"x":{"anyOf":[{"type":"string"},{"type":"string","enum":[""]}]}},"required":["x"]}
  ```
  **After:**
  ```json
{"type":"object","properties":{"v":{"type":"number","description":"Must
be 1."}},"required":["v"]}

{"type":"object","properties":{"flag":{"type":"boolean","description":"Must
be true."}},"required":["flag"]}

{"type":"object","properties":{"x":{"anyOf":[{"type":"string"},{"type":"string","description":"Must
be \"\"."}]}},"required":["x"]}
  ```

The new test file
`packages/schema-compat/src/provider-compats/google-literal-enums.test.ts`
runs the real layer through `applyCompatLayer`, `processToAISDKSchema`
and `processToCompatSchema`, with no mocks. Every case walks the output
and fails on any `const`, any enum value that isn't a non-empty string,
or any enum on a node that isn't `type: 'string'`. It covers the three
cases from the issue; a nullable mixed union of `z.enum` and a numeric
literal; `z.literal(['a', 'b', null])`; `z.literal(null)`; mixed
`z.literal([1, 'a'])`; external JSON Schema with typeless or integer
enums; descriptions on literals, nullable and doubly nullable wrappers;
zod v3; and validation of the original literal values.

- **Before** (main's `google.ts` swapped in): `Tests 15 failed | 3
passed (18)`. The 3 that pass check behaviour that must not change:
valid string enums are untouched, ordinary nullable descriptions are
untouched, and arguments are still validated.
  **After:** `Tests  18 passed (18)`.

Other checks: the rest of the package's unit suites, including
`google.test.ts` and the #25086 / #17179 nullable-enum tests, pass
(`1044 passed | 9 skipped`); `tsc --noEmit`, `oxlint --type-aware
--deny-warnings`, `oxfmt` and prettier are clean.

Not checked: a live Gemini request (no API key here). Also not run
locally: the CommonJS `dist` tests, which need a package build that this
machine's Node can't run (tsdown can't load its `.ts` config); CI builds
and runs them. `z.literal(null)` alone still emits `type: 'null'`, as
main does: the node keeps that type so a parent `anyOf` can recognise
and drop it.

## Merge Danger

**Door:** two-way. Only the JSON Schema sent to Google models changes;
nothing is stored or published, and a revert restores the old output.

**Blast radius:** tools and structured output sent to Gemini through
`GoogleSchemaCompatLayer`. Schemas without non-string or empty enums
produce the same output as before, except that an external JSON Schema
enum with no `type` now gets `type: "string"`. If the new shape were
wrong, Gemini requests that fail today with HTTP 400 would keep failing.

Closes #29167

## Follow-ups

- On the `processToAISDKSchema` path, `fixAISDKNullableUnionTypes` still
drops `nullable` from `anyOf` nodes. An existing test in
`google.test.ts` (from #16129) asserts that behaviour, so this PR leaves
it alone.
- A live Gemini check that it accepts a standalone `{ "type": "null",
"nullable": true }` property.

## Council review

Rounds: 6

| Seat | Round 1 | Round 2 | Round 3 | Round 4 | Round 5 | Round 6 |
| --- | --- | --- | --- | --- | --- | --- |
| GPT-6.1 Sol | 7 / 8 / 10 / 9 | 9 / 9 / 10 / 10 | 9 / 10 / 10 / 10 | 8
/ 9 / 10 / 8 | 8 / 9 / 10 / 9 | 9.5 / 10 / 10 / 9.5 |
| Claude Opus 5.5 | not run | not run | 8 / 9 / 8 / 9 | 9 / 9 / 10 / 8 |
9 / 9 / 10 / 9 | 9 / 9 / 10 / 9 |
| Grok 4.7 | empty seat | empty seat | empty seat | empty seat | empty
seat | empty seat |

Scores are Correctness / Tests / Scope / Code quality.

Created with Claude Opus 5.5 in T3 Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## ELI5

Gemini only accepts certain kinds of allowed-value lists. This change
converts other literal values into descriptions so Gemini can read the
tool schemas, while Mastra still checks tool arguments against the
original schema.

## Changes

- Keep enums only when all values are non-empty strings and the schema
node is string-typed. Represent `null` with `nullable: true` where
applicable.
- For other enum values, remove the enum, preserve or infer the schema
type, and add the allowed values to the description.
- Preserve parent descriptions when nullable `anyOf` schemas collapse.
- Add tests for Zod v3 and v4, external JSON Schema, the compatibility
and AI SDK paths, and validation against original schemas.
- Add a changeset for `@mastra/schema-compat`.

## Verification

The PR description reports 18 new tests passing, 1044 package tests
passing, and 9 skipped. It also reports clean TypeScript, Oxlint,
formatting, and Prettier checks. A live Gemini request was not checked.
Local CommonJS `dist` tests were not run; the PR description says CI
builds and runs them.

The change does not address `fixAISDKNullableUnionTypes` dropping
`nullable` from `anyOf` on the `processToAISDKSchema` path. Testing a
standalone `{ "type": "null", "nullable": true }` schema remains a
follow-up.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status:auto-approved Factory review auto-approved

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] schema-compat/zodToJsonSchema: nullable zod v4 enum/literal widens to type:[X,"null"] but keeps enum/const, so exported schema rejects null

2 participants