Skip to content

fix(v4): let z.intersection merge cyclic outputs instead of overflowing - #6764

Merged
colinhacks merged 1 commit into
mainfrom
intersection-cyclic-merge
Nov 20, 2026
Merged

colinhacks merged 1 commit into
mainfrom
intersection-cyclic-merge

Conversation

@colinhacks

Copy link
Copy Markdown
Owner

z.intersection(A, B).safeParse(x) threw RangeError: Maximum call stack size exceeded when x is cyclic and A and B are different recursive schemas. Each side parses the cycle into its own output graph, and merging them recursed around the cycle forever. The same schema on both sides was safe only because both sides hand back the same objects.

The merge now keeps the left/right pairs it has open, and a pair reached again closes the cycle with the merged object already in progress, so the result is cyclic like the input. Tracking starts only once a shared key holds objects on both sides, so a flat intersection allocates nothing new.

Cost: flat intersections are unchanged, a nested intersection with two shared object keys measured about 4% slower, and a zod/mini bundle that uses z.intersection grows by 64 B gzipped.

When both sides of an intersection parsed a cyclic input into different output graphs, the merge recursed around the cycle until the stack overflowed, so `safeParse` threw a `RangeError`. The merge now tracks the pairs it has open once a shared key holds objects on both sides, and a pair reached again closes the cycle with the output already in progress.
Copilot AI balanced review requested due to automatic review settings November 16, 2026 02:02

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@colinhacks
colinhacks merged commit 2a343ed into main Nov 20, 2026
8 checks passed
@colinhacks
colinhacks deleted the intersection-cyclic-merge branch November 20, 2026 17:35

This branch was successfully deployed

1 active deployment
Preview – zod-v4 — 0d2cc1bd Deployed Nov 16, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants