Skip to content

fix(zod): reject non-object Zod v3 strict schema roots - #2358

Merged
HAYDEN-OAI merged 11 commits into
mainfrom
agent/fix-zod-v3-strict-root-schemas-carwfbif
Aug 15, 2026
Merged

HAYDEN-OAI merged 11 commits into
mainfrom
agent/fix-zod-v3-strict-root-schemas-carwfbif

Conversation

@HAYDEN-OAI

Copy link
Copy Markdown
Contributor

Summary

  • Reject Zod v3 Structured Outputs schemas whose parsed root is not type: "object", using the same synchronous error as the existing Zod v4 path across zodResponseFormat, zodTextFormat, zodFunction, and zodResponsesFunction.
  • Gate validation exclusively on openaiStrictMode and perform it before root naming, schema-definition expansion, or $ref wrapping, preserving valid named, lazy, recursive, refined, transformed, and defaulted object roots.
  • Add a focused 77-case regression matrix covering primitive/array/object-union/discriminated-union/nullable/optional/intersection/any roots, Zod v3/v4 behavior, nested unions and arrays, escaped schema definitions, every generic converter target, and unchanged Realtime behavior.

Why

The vendored Zod v3 converter previously returned invalid strict root schemas unchecked. The four strict public helpers therefore emitted schemas that Structured Outputs cannot accept, while the equivalent Zod v4 conversion already failed synchronously. Valid Zod v4 optional object roots remain accepted because v4 normalizes them to an actual root object; the unsupported Zod v3 representation is correctly rejected.

Validation

  • Regression-first: the new focused suite produced 36 failures against unchanged main before the fix.
  • pnpm test -- tests/helpers/zod-root-schema-validation.test.ts — 77 passing tests.
  • pnpm test:unit — 2,167 passing tests across 71 files.
  • pnpm format and pnpm lint.
  • pnpm exec tsc.
  • pnpm build, including CommonJS/ESM SDK and Bedrock import checks.
  • ./node_modules/typescript-4-9/bin/tsc --project dist/src/tsconfig.json --noEmit.
  • ./node_modules/typescript/bin/tsc --project dist/src/tsconfig.json --noEmit.
  • pnpm exec publint dist.
  • CI-equivalent ATTW package analysis and node scripts/utils/attw-report.cjs — Types ok!.
  • node --experimental-strip-types scripts/test-packed-package.ts — offline CommonJS/ESM consumer and both compiler versions; 263/300 source checks across 1,200 source maps.
  • Built-package smoke check confirms all four strict helpers reject primitive roots while zodRealtimeFunction remains non-strict.
  • Both changed files are handwritten, have no generated marker, and are outside the generated/legacy allowlist.

@openai-sdks

openai-sdks Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

OkTest Summary

✅ 237/237 SDK tests passed in 10.566s for Node SDK PR #2358.

Test results — 42 files
Test Result Time
tests/chat-completions-complex-body.test.ts ✅ Passed 198ms
tests/chat-completions-create.test.ts ✅ Passed 222ms
tests/chat-completions-stream.test.ts ✅ Passed 213ms
tests/files-content-binary.test.ts ✅ Passed 156ms
tests/files-create-multipart.test.ts ✅ Passed 152ms
tests/files-list-pagination.test.ts ✅ Passed 173ms
tests/initialize-config.test.ts ✅ Passed 178ms
tests/instance-isolation.test.ts ✅ Passed 106ms
tests/models-list.test.ts ✅ Passed 145ms
tests/responses-background-lifecycle.test.ts ✅ Passed 210ms
tests/responses-body-method-errors.test.ts ✅ Passed 305ms
tests/responses-cancel-timeout.test.ts ✅ Passed 237ms
tests/responses-cancel.test.ts ✅ Passed 214ms
tests/responses-compact-retries.test.ts ✅ Passed 274ms
tests/responses-compact.test.ts ✅ Passed 230ms
tests/responses-create-advanced-stream.test.ts ✅ Passed 136ms
tests/responses-create-advanced.test.ts ✅ Passed 155ms
tests/responses-create-disconnect.test.ts ✅ Passed 1.187s
tests/responses-create-errors.test.ts ✅ Passed 215ms
tests/responses-create-malformed-api-responses.test.ts ✅ Passed 200ms
tests/responses-create-retries.test.ts ✅ Passed 259ms
tests/responses-create-stream-failures.test.ts ✅ Passed 219ms
tests/responses-create-stream-timeout.test.ts ✅ Passed 2.168s
tests/responses-create-stream-wire.test.ts ✅ Passed 2.513s
tests/responses-create-stream.test.ts ✅ Passed 92ms
tests/responses-create-terminal-states.test.ts ✅ Passed 210ms
tests/responses-create-timeout.test.ts ✅ Passed 275ms
tests/responses-create.test.ts ✅ Passed 146ms
tests/responses-delete.test.ts ✅ Passed 138ms
tests/responses-input-items-errors.test.ts ✅ Passed 165ms
tests/responses-input-items-list.test.ts ✅ Passed 183ms
tests/responses-input-items-options.test.ts ✅ Passed 109ms
tests/responses-input-tokens-count-timeout.test.ts ✅ Passed 236ms
tests/responses-input-tokens-count.test.ts ✅ Passed 316ms
tests/responses-malformed-inputs.test.ts ✅ Passed 2.181s
tests/responses-not-found-errors.test.ts ✅ Passed 316ms
tests/responses-parse.test.ts ✅ Passed 225ms
tests/responses-retrieve-retries.test.ts ✅ Passed 274ms
tests/responses-retrieve.test.ts ✅ Passed 229ms
tests/responses-stored-method-errors.test.ts ✅ Passed 628ms
tests/retry-behavior.test.ts ✅ Passed 3.093s
tests/sdk-error-shape.test.ts ✅ Passed 270ms

View OkTest run #31905576584

SDK merge (c79f697a97e6) · head (ef52f1330839) · base (a3deafb5f91d) · OkTest (7e7850017529)

@jbeckwith-oai jbeckwith-oai 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.

Reviewed exact head e1f2b1d97c6da364550aba75c8c6c76658c235ba. The documented strict helpers are correct, but two Low internal strict-mode consistency gaps remain:

  1. Validate the effective returned root after name wrapping. validateStrictRootSchema(main) accepts an object, after which the default named nameStrategy: 'ref' path returns a root $ref, which strict Structured Outputs forbids. Public helpers use duplicate-ref, so this is limited to the package-importable _vendor converter and its internal openaiStrictMode option. Validate the final structural root or reject this strict name strategy; add direct strict named-object coverage.

  2. Reject nullable OpenAPI roots in the strict predicate. The new type-only check accepts the OpenAPI3 nullable parser's { type: 'object', nullable: true }, even though the root admits null. Public strict helpers do not select OpenAPI3, so this has the same narrow direct-converter scope. Make the predicate semantic enough to reject nullable: true and add a direct strict OpenAPI nullable-object regression.

No supported-helper/API issue was found; the focused matrix and strict thermo are clean, and exact CI is fully green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d2d73fe2ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@jbeckwith-oai jbeckwith-oai 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.

Re-reviewed the full merge-base diff at exact head d2d73fe. No findings. The strict-root guard now validates both the parsed and final wrapped schema, rejects OpenAPI nullable object roots, preserves supported strict-helper and non-strict behavior, and has focused parity coverage. Strict thermo and exact CI are clean.

@jbeckwith-oai jbeckwith-oai 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.

Found one Medium reference-semantics bug and one Medium strict-thermo/architecture blocker in the exact-head diff. The earlier named-ref and nullable-root issues remain fixed; exact CI is green.

@jbeckwith-oai jbeckwith-oai 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.

Found one Medium strict-root serialization correctness issue in the exact-head diff. The prior reference-materialization problems are fixed and strict thermo passes; the sole live ecosystem failure is an unrelated external service-auth 500.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2e73208685

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@jbeckwith-oai jbeckwith-oai 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.

The boxed-BigInt gap is fixed on exact 2e732086851e88730d9cee70a879695bfde6f905, but this needs one structural correction before another carrier-specific patch.

[Medium, strict thermo] Define one ordinary JSON-schema record boundary. zodToJsonSchema.ts has grown 128→211 lines and the focused test to 449 lines by approximating JSON serialization piecemeal: prototype walking, arrays, toJSON, and four primitive unboxers. Two remaining holes show the catalog is still open-ended:

  • [Low] A callable root such as Object.assign(() => {}, { type: "object" }) passes both checks, but JSON.stringify returns undefined.
  • [Low] An extensible Proxy whose getPrototypeOf trap returns itself serializes as a valid object, but the prototype walk never terminates.

Please stop adding isolated coercion cases and establish one explicit accepted carrier invariant—preferably a plain/ordinary JSON-schema record at the strict typed converter/helper boundary—then reject exotic carriers uniformly. This should remove the unboxer matrix and arbitrary prototype traversal while preserving the focused public-helper/reference regressions. If the callable fix is made locally during that reframing, reject typeof schema === "function"; if any prototype walk remains, detect repeats.

All exact-head CI is green and no file crosses 1k, but the repeated special-case growth is the blocker under the repository architecture guidance.

Anchors:

function validateStrictRootSerializationHook(schema: object): void {
for (let target: object | null = schema; target !== null; target = Object.getPrototypeOf(target)) {
const serializationHook = Object.getOwnPropertyDescriptor(target, 'toJSON');
if (!serializationHook) {
continue;
}
if (!('value' in serializationHook) || typeof serializationHook.value === 'function') {
throw new Error("Root schema cannot contain a callable or accessor-backed 'toJSON' property");
}
break;
}
}
function validateStrictRootShape(schema: object): void {
if (Array.isArray(schema)) {
throw new TypeError('Root schema must serialize to a JSON object');
}
const primitiveUnboxers = [
String.prototype.valueOf,
Number.prototype.valueOf,
Boolean.prototype.valueOf,
...(typeof BigInt === 'function' ? [BigInt.prototype.valueOf] : []),
];
for (const unbox of primitiveUnboxers) {
try {
Reflect.apply(unbox, schema, []);
} catch {
// Primitive intrinsics reject objects without their matching internal slot.
continue;
}
throw new TypeError('Root schema must serialize to a JSON object');
}
}
function validateStrictRootSchema(schema: object, openaiStrictMode: boolean | undefined): void {
if (!openaiStrictMode) {
return;
}
validateStrictRootShape(schema);
const descriptors = Object.getOwnPropertyDescriptors(schema);
for (const keyword of ['type', 'nullable', '$ref'] as const) {
const descriptor = descriptors[keyword];
if (descriptor?.enumerable && !('value' in descriptor)) {
throw new Error(`Root schema validation keyword '${keyword}' must be a data property`);
}
}
validateStrictRootSerializationHook(schema);
const type = descriptors['type']?.enumerable ? descriptors['type'].value : undefined;
const nullable = descriptors['nullable']?.enumerable && descriptors['nullable'].value === true;
if (type !== 'object' || nullable) {
const actualType = nullable && type ? `${type},null` : type;
throw new Error(
`Root schema must have type: 'object' but got type: ${actualType ? `'${actualType}'` : 'undefined'}`,
);
}
const reference = descriptors['$ref'];
if (
reference?.enumerable &&
reference.value !== undefined &&
typeof reference.value !== 'function' &&
typeof reference.value !== 'symbol'
) {
throw new Error("Root schema must be a concrete object and cannot contain '$ref'");
}
}
function cloneStrictRootSchemaDefinitions(refs: ReturnType<typeof getRefs>): void {
if (refs.openaiStrictMode) {
refs.definitions = { ...refs.definitions };
}
}

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62b93b2a4a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@jbeckwith-oai jbeckwith-oai 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.

The latest Proxy keyword reads help, but exact 8a545a1b9ed6f5f3a5331a90b57e0c6bc16b2cde still needs the same Medium boundary redesign rather than more serialization cases.

zodToJsonSchema.ts has grown 128→212 lines and the focused suite to 512 lines around a prototype walker, cycle state, array/function cases, four primitive-brand probes, descriptors/accessors, toJSON, omitted values, and Proxy reads. This remains an open-ended approximation of ECMAScript serialization rather than one typed root invariant. Concrete holes remain: boxed nullable: Object(true) passes but serializes as true; a Proxy can synthesize callable toJSON from get while descriptors show none; and a fresh Proxy at every getPrototypeOf hop never repeats in the WeakSet.

Please define one supported canonical/owned JSON-schema record boundary at the strict converter/helper edge, snapshot/own the root once, validate and return that same stable record, reject unsupported carriers uniformly, and delete the prototype/unboxer catalog. Preserve the canonical parseDef(..., forceResolution) path and focused public-helper/registered/lazy/recursive/naming/non-strict regressions. The three examples above are evidence for this single structural fix, not requests for three more local patches.

No file crosses 1k and no suppression/mock issue was found. All changed focused tests pass; the sole Node 22 failure is the unrelated generated Skills Versions APIConnectionError (Node 24/26 and every other applicable check pass).

Anchor:

function validateStrictRootSerializationHook(schema: object): void {
const visitedPrototypes = new WeakSet<object>();
for (let target: object | null = schema; target !== null; target = Object.getPrototypeOf(target)) {
if (visitedPrototypes.has(target)) {
throw new TypeError('Root schema cannot contain a cyclic prototype chain');
}
visitedPrototypes.add(target);
const serializationHook = Object.getOwnPropertyDescriptor(target, 'toJSON');
if (!serializationHook) {
continue;
}
if (!('value' in serializationHook) || typeof serializationHook.value === 'function') {
throw new Error("Root schema cannot contain a callable or accessor-backed 'toJSON' property");
}
break;
}
}
function validateStrictRootShape(schema: object): void {
if (typeof schema === 'function' || Array.isArray(schema)) {
throw new TypeError('Root schema must serialize to a JSON object');
}
const primitiveUnboxers = [
String.prototype.valueOf,
Number.prototype.valueOf,
Boolean.prototype.valueOf,
...(typeof BigInt === 'function' ? [BigInt.prototype.valueOf] : []),
];
for (const unbox of primitiveUnboxers) {
try {
Reflect.apply(unbox, schema, []);
} catch {
// Primitive intrinsics reject objects without their matching internal slot.
continue;
}
throw new TypeError('Root schema must serialize to a JSON object');
}
}
function validateStrictRootSchema(schema: object, openaiStrictMode: boolean | undefined): void {
if (!openaiStrictMode) {
return;
}
validateStrictRootShape(schema);
const descriptors = Object.getOwnPropertyDescriptors(schema);
for (const keyword of ['type', 'nullable', '$ref'] as const) {
const descriptor = descriptors[keyword];
if (descriptor?.enumerable && !('value' in descriptor)) {
throw new Error(`Root schema validation keyword '${keyword}' must be a data property`);
}
}
validateStrictRootSerializationHook(schema);
const type = descriptors['type']?.enumerable ? Reflect.get(schema, 'type') : undefined;
const nullable = descriptors['nullable']?.enumerable && Reflect.get(schema, 'nullable') === true;
if (type !== 'object' || nullable) {
const actualType = nullable && type ? `${type},null` : type;
throw new Error(
`Root schema must have type: 'object' but got type: ${actualType ? `'${actualType}'` : 'undefined'}`,
);
}
const reference = descriptors['$ref']?.enumerable ? Reflect.get(schema, '$ref') : undefined;
if (reference !== undefined && typeof reference !== 'function' && typeof reference !== 'symbol') {
throw new Error("Root schema must be a concrete object and cannot contain '$ref'");
}
}
function cloneStrictRootSchemaDefinitions(refs: ReturnType<typeof getRefs>): void {
if (refs.openaiStrictMode) {
refs.definitions = { ...refs.definitions };
}
}

@jbeckwith-oai jbeckwith-oai 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.

Re-reviewed exact head ef52f13308394db93d8f64fd6af40e9a5705f494 and approved. The prior architecture blocker is resolved: strict conversion now owns one stable plain-record snapshot, validates and returns that same record, and removes the open-ended prototype/unboxer/serialization catalog. Canonical forced parsing, registered/lazy/recursive roots, frozen definitions, naming, public helpers, and non-strict behavior remain sound. Strict thermo is clean at 194 production lines plus a focused 331-line suite, with no suppressions or problematic mocks. The sole Node 22 generated Skills/Versions connection failure is the unrelated mock-server early-404 flake; changed tests, Node 24/26, build, lint, ecosystem, performance, detect-breaking, and CodeQL are green.

@HAYDEN-OAI
HAYDEN-OAI added this pull request to the merge queue Aug 15, 2026
Merged via the queue into main with commit cc7dbfa Aug 15, 2026
35 of 37 checks passed
@HAYDEN-OAI
HAYDEN-OAI deleted the agent/fix-zod-v3-strict-root-schemas-carwfbif branch August 15, 2026 21:48
@openai-sdks openai-sdks Bot mentioned this pull request Aug 15, 2026

This branch was previously deployed

1 inactive deployment
ci — ef52f133 Deployed Aug 15, 2026 by HAYDEN-OAI via examples #8099
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants