Repository navigation
fix(schema-compat): keep null valid for nullable enums and literals - #25086
Conversation
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 detectedLatest commit: fc31087 The changes in this PR will be included in the next version bump. This PR includes changesets to release 33 packages
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 |
|
@breken-ai is attempting to deploy a commit to the Mastra Team on Vercel. A member of the Team first needs to authorize it. |
PR triageLinked 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 gateChanged Test Gate is pending. The |
|
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 configurationConfiguration used: Repository: mastra-ai/mastra/.coderabbit.yaml Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. Walkthrough
ChangesNullable schema conversion
Priority: ➖ Normal Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix · Severity of issue fixed: Medium Merge Risk: ⚪ Minimal · up to The changeset explains the fix clearly, and no issue requiring correction before merge remains. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Verdict: approve
Findings
- Mechanism:
fixAnyOfNullable(packages/schema-compat/src/zod-to-json.ts:113) collapsesanyOf: [X, {type:null}]intotype: [X, "null"]but carriedenum/constover unchanged. JSON Schema ANDstypewithenum/const, so null was rejected. The PR appendsnulltoenumand rewritesconstasenum: [const, null]. That is the minimal correct repair at the one place the merge happens. - Correctness:
constis removed from the spread, so no staleconstis left behind. Duplicatenullis guarded. A falsyconst(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-triagedandp: high. It has noneeds approvallabel. - Classification: bug fix. The implemented behavior matches the issue's proposed fix.
Verification
pnpm install --frozen-lockfile --ignore-scriptsandpnpm turbo build --filter @mastra/schema-compat...passed (6/6 tasks). All commands ran withenv -u GH_TOKEN -u GITHUB_TOKEN.- Full
pnpm vitest runinpackages/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'szod-to-json.ts, both new tests fail in the v4 project (nullrejected). On the head they pass. The v3 path keepsanyOfand already acceptednull. - Pre-execution inspection: the diff changes no scripts, dependencies (
ajvis 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
fixAnyOfNullabledates from 6833c69 (Jan 2026) and has always carriedenum/constover 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
nullinenum. It fails because the Zod-v4 path previously produced a schema that contradicted the Zod contract. Also, the v3 path already emits null viaanyOf, 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.
There was a problem hiding this comment.
Verdict: approve
Prior pass disposition
- Prior verdict: approve at
fc31087, with no requested changes. Nothing was pushed after it: the head is stillfc310878730846b59d68a757b10e9d1e5d3c643dand the PR has one commit. So there is nothing to address, refute or invalidate. The prior assumption (numeric and boolean literals go through the sameconst→enumcode 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 atype: [X, "null"]array. The fix addsnulltoenum, or rewritesconstasenum: [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 runinpackages/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'szod-to-json.tsin 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.
…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>
Description
Fixes #24516.
zodToJsonSchemarewrites a nullable schema fromanyOf: [{ type: X, ... }, { type: "null" }]to{ type: [X, "null"], ... }(fixAnyOfNullableinpackages/schema-compat/src/zod-to-json.ts). When the non-null branch has anenumorconst, those keys were copied over unchanged. JSON Schema requirestypeandenum/constto both hold, so the exported schema rejectednull, which the Zod schema accepts:This fix adds
nulltoenumand turnsconstintoenum: [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 thatnulland the listed values are accepted and that other values are still rejected.main(c58c88b8), both tests fail in the v4 project withexpected false to be trueon thenullcheck. The v3 project already passed, because the v3 path keepsanyOf.@mastra/schema-compatsuite passes: 36 files, 959 tests, 9 skipped, for both v3 and v4.tsc --noEmit,oxlint,eslintandoxfmt --checkare clean on the changed files.I added a patch changeset for
@mastra/schema-compat.Related issue(s)
Fixes #24516
Type of change
Checklist
An AI coding agent (Breken) found this fix, wrote it and tested it. It is submitted from the
breken-aiaccount.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 acceptnull, as their Zod schemas do.Changes
fixAnyOfNullableto addnullto an enum when it merges nullable branches.constinto an enum containing the constant andnull.nulland allowed values pass, and other values fail.@mastra/schema-compat.