Skip to content

feat(v4): parse input containing reference cycles - #6387

Merged
colinhacks merged 1 commit into
mainfrom
feat/cyclic-data
Aug 16, 2026
Merged

colinhacks merged 1 commit into
mainfrom
feat/cyclic-data

Conversation

@colinhacks

@colinhacks colinhacks commented Aug 12, 2026 •

Copy link
Copy Markdown
Owner

Parses input that contains reference cycles. Today this is a RangeError — safeParse included, so it isn't even catchable through the result. Fixes #5346.

const Node = z.object({
  id: z.number(),
  get self() { return Node; },
});

const input: any = { id: 1 };
input.self = input;

const out = Node.parse(input);
out.self === out; // true

zod/mini doesn't get this, and pays 34 gzipped bytes for not getting it.

Shape

Core gains one seam:

export interface $ZodMemoizer {
  alloc<T extends object>(inst: $ZodType, payload: ParsePayload, empty: T, ctx: ParseContextInternal): T;
}

A container hands the memoizer the object it is about to build into. That is core's entire share of the mechanism: the interface, one _zod.memoizer field, and one changed line per container —

payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};

memo is read once, at construction, into a closure constant, so a schema that was never given one runs exactly the code it runs today. In the JIT the same constant decides which of two strings gets emitted, so non-injected schemas produce byte-identical generated code.

The memoizer itself is core/memoizer.ts. Nothing outside that module references it unless a layer asks for it, so it shakes out completely: zod/mini links none of it and the string isRecursive doesn't appear in its bundle. Classic opts a container in with one line before its init:

core.attachMemoizer(inst);
core.$ZodObjectJIT.init(inst, def);

The one other core line is in runChecks, so a repeat visit doesn't re-run the node's checks against a value that is still being built.

What the memoizer does

It registers the real output object before any child is parsed, so a reference back to the same input resolves to the object the caller will actually receive — nothing is copied afterwards. The lookup is keyed on (schema, input), not on the input alone, and that is what makes mutual recursion sound: one node validated against two schemas needs an output per schema.

const A = z.object({ x: z.string(), get b() { return B; } });
const B = z.object({ y: z.number(), get a() { return A; } });

const n: any = { x: "s", y: 1 };
n.b = n; n.a = n;

const out = A.parse(n);
Object.keys(out);      // ["x", "b"]   — the A view
Object.keys(out.b);    // ["y", "a"]   — the B view, separately validated
out.b.a === out;       // true

A repeat visit returns without ever reaching core, which is also what stops the node's checks running a second time against a half-built value. A cycle that closes through a .transform() throws ZodCyclicError — the transform's output can't exist at the moment the back-edge needs to bind, so the alternatives are a clear error or a silently wrong graph. Transforms that aren't on the cycle are unaffected.

A schema that can't re-enter itself disarms both halves on its first parse: the wrapper puts the original run back and alloc becomes a single field read.

Cost

Bundle, esbuild --minify / gzip -9:

bundle main this PR delta
zod-mini-object 3928 3962 +34 (+0.9%)
zod-mini-full 3925 3959 +34 (+0.9%)
zod-object (classic) 21205 21978 +773 (+3.6%)
zod-full (classic) 21201 21974 +773 (+3.6%)

Neither mini bundle contains any of the memoizer — isRecursive, backEdges and the error message are all absent.

Runtime, best-of-3 processes per side, both pinned to the same base:

workload main this PR
flat object 23.9 ns −10.0%
nested object 122.1 ns +8.4%
refined object 243.5 ns +0.5%
array of 20 objects 749.5 ns +3.7%
record, 5 keys 435.2 ns +0.8%
flat object, jitless 152.2 ns +3.9%
build + first parse, wide schema 1.67 ms +0.6%
recursive schema, 364-node tree 27.0 µs +171%

Non-recursive parsing is unchanged — those rows are run-to-run noise.

The last row is the price: a recursive schema over ordinary acyclic data pays ~2.7×, for the memo lookup and insert on every node. That is not a consequence of skipping the JIT — the fastpass is still generated and used, and the jitless path carries the same absolute per-node overhead, which it wouldn't if the JIT were being bypassed. Putting the same logic inside core's containers instead measured ~2.6×, so this shape costs essentially nothing over that while keeping zod/mini at 34 bytes.

Behavior change

Under a recursive schema, two positions holding the same input object now produce the same output object:

const shared = { v: 1, kids: [] };
const out = Node.parse({ v: 0, kids: [shared, shared] });
out.kids[0] === out.kids[1]; // true — previously two independent copies

The output graph mirrors the input graph, which is also what arktype does. Non-recursive schemas are untouched and still copy.

The alternative — scoping entries to the parse stack so acyclic input is bit-for-bit unchanged — diverges between sync and async. Under parseAsync sibling subtrees are in flight together, so the second occurrence of a shared node finds the first one's in-progress entry and binds to it, while parse walks siblings sequentially and doesn't. "Currently being parsed" only equals "is my ancestor" when parsing is sequential. Keeping entries for the whole parse makes the two agree.

What does not change: memoization skips the container's parse, not the checks and transforms layered on top of it. A .refine() or .transform() on a shared node still runs once per reference, exactly as it does on a non-recursive schema, so side effects keep their existing counts.

Limits

Measured, and worth knowing before merging:

  • Maximum recursion depth drops from ~3400 to ~1100 levels. The interceptor adds a stack frame per container, so a deeply nested chain that parses today can overflow. Binary-searched, with zod/mini (which has no memoizer) as the control.
  • z.intersection on a cycle produces a truncated graph. mergeValues builds a fresh object after both sides are parsed, so it can never be the object a back-edge already resolved to. Values validate correctly and invalid input is still rejected, but the cycle is replaced by a copy. Same class as transform-on-a-cycle, which throws; this one doesn't yet.
  • Identity is keyed on (schema, input), not on input alone. That is what keeps mutual recursion sound, but it means Node.partial().parse(cyclic) gives a root that is not the node its own cycle points back to — the root is keyed on the partial clone, the cycled node on the original.
  • .readonly() on a cycled node doesn't freeze it. Freezing a node that is still being built would make its remaining keys fail to assign, silently.

Supersedes #5347 and #5664.

Copilot AI lite review requested due to automatic review settings August 12, 2026 21:09

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 reached their quota limit.

@dosubot

dosubot Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

📄 Knowledge review

🆕 New pages

1 new page was drafted from this PR.

Page Library
Parsing Cyclical Data Zod OSS

Leave Feedback Ask Dosu about zod

@pullfrog pullfrog 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.

Caution

Two reproducible correctness bugs in the memo layer. One corrupts issue paths whenever an invalid node is reached more than once; the other lets a tuple hand back an empty placeholder, producing a successful parse whose output violates the schema.

Reviewed changes — full read of the single commit 73c5f915 against main, plus local repros against the branch for every claim below.

  • Per-parse (schema, input) memo — ParseContextInternal.memo holds Map<$ZodType, Map<object, MemoEntry>>, allocated lazily and living for the whole parse. ctx is freshly spread per _parse/_safeParse/_parseAsync, so nothing leaks between calls (verified with a reused params object).
  • memoEnter / memoExit — containers register their freshly-allocated output container by reference before descending; MemoEntry.issues === null is the "still on the parse stack" sentinel that distinguishes a back-edge from a finished node reached again.
  • payload.memo back-edge flag — gates runChecks so a .refine() never sees a half-built object; propagated through handlePipeResult, and implicitly through $ZodUnion since it returns the winning option's payload directly.
  • isRecursive gate — subtree walk cached in a module-level WeakMap, resolved at codegen time in the JIT so non-recursive schemas emit byte-identical fastpass code.
  • Containers wired — $ZodObject, $ZodObjectJIT's generated fastpass, $ZodArray, $ZodTuple, $ZodRecord (both key branches), $ZodMap, $ZodSet.
  • $ZodCyclicError — new error thrown by $ZodTransform when a cycle closes through it, in both the core and classic transform implementations.
  • Backward direction — the canary gets memo: undefined so it can't hand the real pass its throwaway output. Encoding through a cycle works.

⚠️ The docs still tell users that cyclical data causes an infinite loop

packages/docs/content/api.mdx:1468 reads "Though recursive schemas are supported, passing cyclical data into Zod will cause an infinite loop." That becomes wrong the moment this lands, and it's the one place a user would look. The deliberate behavior change — shared references producing shared output nodes under a recursive schema — also has no home in the docs today, and it's the kind of thing people hit without knowing why.

Technical details
# Docs are stale for cyclic input and shared-reference output

## Affected sites
- `packages/docs/content/api.mdx:1468` — Callout asserting cyclical data causes an infinite loop. Contradicted by this PR.
- `packages/docs/content/api.mdx:1451` — "Recursive objects" section; the natural home for the new semantics.

## Required outcome
- The infinite-loop callout is replaced with an accurate description of cycle support.
- Readers can find out that (a) under a recursive schema the output graph mirrors the input graph, so the same input object at two positions yields one output object, and a transform on a shared node runs once rather than once per occurrence; (b) a cycle that closes through a `.transform()` is an error rather than a parse result.

## Open questions for the human
- Does this ship with the parse-level opt-in flag from the PR's "Open question" section? If so the docs need to describe the flag instead, and this section changes shape.

⚠️ Nothing tests an invalid node reached more than once

Every failure case in cyclic-data.test.ts reaches its bad value exactly once. That is the shape of input that breaks both memo bugs flagged inline, and it's a shape users hit constantly — a tree of records where the same malformed child is referenced from two parents. The valid-shared-node case has a test (a recursive schema shares one output node per input node); its invalid twin is what's missing.

Technical details
# Coverage gap: invalid values reached through more than one path

## Affected sites
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts` — no test asserts issue paths for an input object that appears at two or more positions.

## Required outcome
- A test pins the exact `issue.path` for each occurrence of a shared invalid node, so a memoized issue replayed at a second position cannot silently acquire the first position's prefix. Reference point: the identical non-recursive schema reports `[["kids", 0, "v"], ["kids", 1, "v"]]`.
- A test covers a shared node two levels deep (a diamond), where the corruption compounds.
- A test asserts that `parse` and `parseAsync` produce the same issue list, not just the same value identity, for a shared invalid node.
- A test covers a container that fails its own structural check (e.g. a too-short tuple) and is then reached a second time in the same parse.

ℹ️ Nitpicks

  • $ZodCyclicError escapes safeParse as a thrown exception rather than surfacing as an issue — confirmed locally. The PR opens by noting that today's RangeError "isn't even catchable through the result"; the replacement has the same property. Deliberate is fine, but worth a sentence in the PR body either way.
  • isRecursive walking def fresh on every container means an object graph shared by many schemas is re-walked once per container rather than once per parse. Only paid on first parse, so probably not worth changing — noting it since the PR attributes the +10% build-and-first-parse row to this walk.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/core/schemas.ts Outdated
// A back-edge into a node still on the stack reports nothing here — the node
// in progress reports them at its own path — and skips checks, because its
// output is not populated yet.
if (hit.issues) payload.issues.push(...hit.issues);

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.

Memoized issues are replayed by reference, and util.prefixIssues (core/util.ts:839) mutates iss.path in place with unshift. So every replay prepends another segment onto the same path array, and both positions end up reporting the same corrupted path.

Reproduced against this branch — Node = z.object({ v: z.number(), get kids() { return z.array(Node) } }) with shared = { v: "bad", kids: [] } parsed as { v: 0, kids: [shared, shared] } gives [["kids",1,0,"v"], ["kids",1,0,"v"]]. The identical non-recursive schema gives [["kids",0,"v"], ["kids",1,"v"]].

Technical details
# Memo replay mutates shared issue paths

## Affected sites
- `packages/zod/src/v4/core/schemas.ts:122` — `payload.issues.push(...hit.issues)` pushes the same `$ZodRawIssue` objects into a second payload.
- `packages/zod/src/v4/core/schemas.ts:134` — `memoExit` stores `payload.issues.slice()`, a shallow copy that shares every issue object with the live payload.
- `packages/zod/src/v4/core/util.ts:839` — `prefixIssues` does `iss.path.unshift(path)` in place and returns the same objects.

## Observed
All against this branch, `z.object({ v: z.number(), get kids() { return z.array(Node) } })`:

```
input { v: 0, kids: [shared, shared] }, shared = { v: "bad", kids: [] }
  non-recursive baseline  [["kids",0,"v"], ["kids",1,"v"]]     <- correct
  this branch, jit        [["kids",1,0,"v"], ["kids",1,0,"v"]]
  this branch, jitless    [["kids","kids",1,0,"v"], ["kids","kids",1,0,"v"]]

three occurrences         [["kids",2,1,0,"v"]] x3

two-level diamond
  leaf = { v: "x", kids: [] }; mid = { v: 1, kids: [leaf, leaf] }
  input { v: 0, kids: [mid, mid] }
                          [["kids",1,0,"kids",1,0,"v"]] x4
```

The jitless path is worse because `$ZodObject` also routes through `prefixIssues`, while `$ZodObjectJIT`'s generated fastpass already spreads issues (`{ ...iss, path: [...] }`) and so only picks up the array's mutation.

## Required outcome
- An issue replayed from the memo at a second position carries the path it would have had if that position had been parsed independently.
- Replaying at position N does not observably alter the issue reported at position N-1, no matter how many positions share the node or how deeply they nest.

## Suggested approach
Clone both the issue and its `path` array at the boundary — either when snapshotting in `memoExit` or when replaying in `memoEnter`. `memoEnter` is the cheaper of the two, since it only pays on a hit.

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.

Still present after 9a16a4e — the code moved verbatim to classic/cycles.ts:141/:163, so this anchor is dangling; re-raised there.

Pullfrog  | View workflow run | via Pullfrog | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/core/schemas.ts Resolved
Comment thread packages/zod/src/v4/core/schemas.ts Outdated
// in progress reports them at its own path — and skips checks, because its
// output is not populated yet.
if (hit.issues) payload.issues.push(...hit.issues);
else payload.memo = true;

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 PR body argues that keeping entries for the whole parse is what makes sync and async agree, since "currently being parsed" only equals "is my ancestor" when parsing is sequential. But issues === null is a "currently being parsed" scope, and it gates this branch — so the divergence comes back for issue reporting even though values now agree.

Same schema, same input: parse reports two issues, parseAsync reports one, because under async the sibling subtrees are in flight together and the second occurrence finds issues: null.

Technical details
# The in-flight sentinel reintroduces sync/async divergence for issues

## Affected sites
- `packages/zod/src/v4/core/schemas.ts:57-59` — `MemoEntry.issues` doubles as the value cache and as the on-stack flag.
- `packages/zod/src/v4/core/schemas.ts:122-123` — the branch: replay issues if settled, otherwise mark as a back-edge and report nothing.
- `packages/zod/src/v4/core/schemas.ts:134` — `memoExit` only settles the entry after all child promises resolve, so under async a node stays `null` for as long as its subtree is outstanding.

## Observed
```ts
const mk = (isAsync: boolean) => {
  const Node: any = z.object({
    v: isAsync ? z.number().refine(async (n) => n >= 0) : z.number().refine((n) => n >= 0),
    get kids() { return z.array(Node); },
  });
  return Node;
};
const shared = { v: -5, kids: [] };
const input  = { v: 0, kids: [shared, shared] };

mk(false).safeParse(input)       // 2 issues
await mk(true).safeParseAsync(input)  // 1 issue: ["kids", 0, "v"]
```

Overall `success` still agrees, because the first occurrence always settles before the parse ends. What diverges is the issue list, and it diverges as a function of promise scheduling rather than of the input.

## Required outcome
- For the same schema and input, `parse` and `parseAsync` produce the same issue list, not merely the same `success` and the same value identities.

## Open questions for the human
- Is the async under-report actually the preferred semantics, with sync's duplicate report the thing to change? Reporting a shared node's issues once at its first position is defensible; if so the fix is on the sync side and this becomes a decision rather than a bug. Either way the two should be made to agree deliberately rather than by scheduling.

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.

Still present after 9a16a4e — the sentinel moved to classic/cycles.ts:140-145; sync reports 2 issues, async 1, on the same input.

Pullfrog  | View workflow run | via Pullfrog | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/core/schemas.ts Outdated
// `def.shape` is redefined as a non-enumerable accessor, so `for...in` misses it.
const shape = def.shape;
if (shape) for (const key in shape) check(shape[key]);
for (const key in def) {

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 walk only reaches schemas held in def, never ones held in inst._zod.checks. z.property(key, schema) stores a real schema in $ZodCheckProperty's def.schema and parses through it, so a cycle closing that way is invisible to the gate and still blows the stack.

Not a regression — it's the status quo — but it does bound what "parses input containing reference cycles" covers, and it's cheap to state in the PR body if you'd rather not chase it.

Technical details
# isRecursive does not see schemas reachable through checks

## Affected sites
- `packages/zod/src/v4/core/schemas.ts:80-93` — child discovery reads `def.shape` and then `for...in def`; `inst._zod.checks` is never consulted.
- `packages/zod/src/v4/core/checks.ts` — `$ZodCheckProperty` holds `def.schema` and runs it during `check`.

## Observed
```ts
const Node: any = z.object({ id: z.number() })
  .passthrough()
  .check(z.property("self", z.lazy(() => Node)));

const input: any = { id: 1 };
input.self = input;
Node.parse(input); // RangeError: Maximum call stack size exceeded
```

`isRecursive(Node)` walks only `def.shape = { id }`, caches `false`, and no memo machinery is installed.

## Required outcome
Either cycles through `z.property()` are detected and handled like every other container, or the limitation is stated so users aren't surprised.

## Suggested approach (optional)
Detection alone is not sufficient here. `$ZodCheckProperty.check` calls `def.schema._zod.run(payload, {})` with a hardcoded empty ctx, which drops `ctx.memo` at the check boundary — every re-entry would allocate a fresh memo and never register a hit. That ctx-forwarding gap is pre-existing and outside this diff, but it has to be closed for the path to work.

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.

Still present after 9a16a4e — isRecursive moved unchanged to classic/cycles.ts:37-68 and still never consults inst._zod.checks.

Pullfrog  | View workflow run | via Pullfrog | Using Claude Opus | 𝕏

for (const [name, build] of cases) {
for (const jitless of [false, true]) {
const { schema, input } = build();
expect(() => schema.parse(input, { jitless }), `${name} (jitless: ${jitless})`).not.toThrow();

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.

.not.toThrow() is the whole assertion for all nine containers, so this passes as long as parsing terminates — it would still pass if a container handed back an empty placeholder instead of the real output. It does not, in fact, catch the tuple bug flagged in core/schemas.ts. Each case already returns its input, so asserting the back-edge's identity (and one scalar off the node) would make these cases able to fail.

Comment thread packages/zod/src/v4/classic/schemas.ts Resolved
@colinhacks colinhacks changed the title feat(v4): parse input containing reference cycles feat(v4): parse input containing reference cycles (classic only) Aug 13, 2026

@pullfrog pullfrog 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.

Caution

This PR introduces two critical correctness bugs: encoding silently skips every check below the top-level node, and replayed memo issues have their paths corrupted in place.

Reviewed changes

  • Re-reviewed 9a16a4ee against the previously reviewed 73c5f915, which is a full architectural rewrite — every core/ change was reverted and the feature now lives entirely in the new classic/cycles.ts.

  • Confirmed two findings from the prior review are fixed: tuple too_small no longer strands its memo entry, and the duplicated $ZodCyclicError in core is gone. Both threads resolved.

  • Reproduced four defects locally against the branch, three of them new in this commit, plus a prototype-corruption bug in fillObject.

  • Verified the full v4 suite is green (224 files / 2848 tests) and that the four remaining prior threads still apply, with pointer replies added at their new locations.

🚨 The rewrite lost the canary guard

The most important regression in this commit is structural, so it's worth stating outside the inline comment. The pre-refactor version passed memo: undefined when $ZodType.run builds its backward canary context. That guard is what kept the throwaway skipChecks: true pass from seeding the real pass's memo.

Moving the state onto ctx under a string key silently dropped it, because { ...ctx, skipChecks: true } at core/schemas.ts:285 copies "~cycles" by reference. The canary now settles a memo entry for every nested container, and the real pass returns those entries without ever descending. Net effect: z.encode accepts data that violates any .refine() below the root.

This is the general hazard with hanging per-parse state off ctx — every existing { ...ctx, ... } spread in core is now a place where the memo can leak into a context it wasn't meant for, and none of them are annotated. Worth grepping for the rest of them before settling on this design.

⚠️ Cycle support is now classic-only, and the PR body describes the reverted design

zod/mini still throws RangeError on cyclic input — verified on this branch. Nothing in core/ references cycles.ts anymore, so @zod/core consumers get nothing either.

That makes most of the PR body stale: the bundle-cost table, the runtime table, the claim about isRecursive in JIT codegen, and the open question about mini's +10% all describe the architecture that 9a16a4ee reverted. Worth rewriting the description before merge so the discussion isn't anchored to numbers that no longer correspond to any code.

packages/docs/content/api.mdx:1468 also still says "passing cyclical data into Zod will cause an infinite loop", which this PR makes untrue for classic.

⚠️ No numbers on any of the three axes

Per CLAUDE.md, a change to packages/zod/src needs runtime, memory, and bundle figures together. I want to flag explicitly that I did not measure any — I dispatched this and the agent couldn't execute benchmarks, so treat the following as a hypothesis to test, not a finding.

The memory axis is the one I'd check first. installCycleGuard is called unconditionally from all six classic container constructors, and each call allocates a make arrow plus a deferred closure. core/core.ts:61-64 runs inst._zod.deferred but never clears the array, so both closures are retained for the instance's lifetime even after the guard has removed itself from _zod.run. That is a fixed per-container-instance cost landing directly on top of 3063993 ("cut per-schema memory ~90%").

Bundle should now be roughly neutral for mini, since nothing in core pulls in cycles.ts.

ℹ️ Nitpicks

cyclic-data.test.ts:201 still asserts only .not.toThrow() across all nine containers. Given that three of the four bugs above are wrong-output rather than infinite-loop bugs, that assertion shape is what let them through — a case with an invalid node reached more than once would have caught both the path corruption and the encode regression.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
let state = (ctx as WithState)[STATE];
if (!state) {
state = { bySchema: new Map(), pending: undefined };
(ctx as WithState)[STATE] = state;

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.

Critical: encoding skips every check below the top-level node.

$ZodType.run's backward canary at core/schemas.ts:285 does { ...ctx, skipChecks: true }. Object spread copies the string-keyed "~cycles" state by reference, so the canary and the real pass share one memo. The canary settles an entry for every nested container while skipChecks is on; the real pass then hits those entries at line 134 and returns the canary's output without ever calling base, so no nested .refine() / .check() ever runs.

The pre-refactor version guarded exactly this by passing memo: undefined on the canary. That guard was dropped when the state moved onto ctx.

Technical details
const codec = z.codec(z.number(), z.number(), { decode: (n) => n, encode: (n) => n });
const Node: any = z.object({
  n: codec,
  get kids() { return z.array(Node); },
}).refine((o) => o.n !== 1);

z.safeEncode(Node, { n: 500, kids: [{ n: 1, kids: [] }] });
// => { success: true }   refine ran 1 time

The non-recursive control (no get kids, so no guard) gives success: false with an issue at ["kids", 0]. Decode on the same recursive schema is correct — success: false, refine runs twice. Only the encode direction is affected, and all four entry points share it: encode, safeEncode, encodeAsync, safeEncodeAsync.

Type errors still surface (a child with n: "bad" reports at ["kids",0,"n"]); it is specifically checks that are lost.

Mechanism confirmed by patching core/schemas.ts:285 to { ...ctx, skipChecks: true, ["~cycles"]: undefined } — that flips the repro to success: false with refine running twice.

Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
// A back-edge into a node still on the stack reports nothing here, and
// never reaches `base`, so its checks don't run against a half-built value.
if (hit.issues) {
payload.issues.push(...hit.issues);

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.

Critical: replaying memo issues corrupts their paths. (Re-anchoring #6387 (comment) — the old anchor in core/ no longer exists.)

This pushes the same $ZodRawIssue objects into a second payload, and util.prefixIssues (core/util.ts:839) does iss.path.unshift(...) in place. Every replay prepends onto the one shared array, so paths accumulate across occurrences instead of being independent. The result.issues.slice() at line 163 is a shallow copy — it clones the array but shares the issue objects.

Technical details
const Node: any = z.object({
  v: z.number(),
  get kids() { return z.array(Node); },
});
const shared = { v: "bad", kids: [] };
Node.safeParse({ v: 0, kids: [shared, shared] });
variant paths produced expected (non-recursive baseline)
jit ["kids",1,0,"v"] ×2 ["kids",0,"v"], ["kids",1,"v"]
jitless / async ["kids","kids",1,0,"v"] ×2 same as above
three occurrences ["kids",2,1,0,"v"] ×3 three distinct paths
two-level diamond ["kids",1,0,"kids",1,0,"v"] ×4 four distinct paths

jit and non-jit diverge because $ZodObjectJIT spreads issues ({...iss, path: [...]}) while the non-JIT $ZodObject uses prefixIssues.

Container-level check issues are corrupted the same way: a .refine() on the node reports ["kids",1,0] ×2.

A deep copy of each issue's path at line 163 (or on replay here) is the minimum fix.

Comment thread packages/zod/src/v4/classic/cycles.ts Resolved
Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
Comment on lines +111 to +117
if (recursive === undefined) {
recursive = isRecursive(inst, new Set());
if (!recursive) {
inst._zod.run = base;
return base(payload, ctx);
}
}

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.

A non-recursive schema starts memoizing after its first parse if anything captured _zod.run.

The if (!recursive) early-out is nested inside if (recursive === undefined), so it only fires on the very first call. It restores inst._zod.run = base, but any reference to the wrapper captured before that keeps pointing at the wrapper — and on every subsequent call recursive is already false, so the guard falls straight through to the memo path.

core/schemas.ts:2241 and :2320 do exactly this: they capture def.options[0]._zod.run at construction time for single-option unions.

Technical details
const Leaf = z.object({ v: z.number() });
const U = z.union([Leaf]);          // single option -> captures Leaf._zod.run
const T = z.object({ a: U, b: U, c: U });

const shared = { v: 1 };
const o = T.parse({ a: shared, b: shared, c: shared });

o.a === o.b;  // false  (the first call installed `base`)
o.b === o.c;  // true   <- memoized, despite nothing here being recursive

Same with a single-option z.discriminatedUnion. This contradicts the PR's stated invariant that non-recursive schemas are untouched and still copy — and the divergence between a and b/c makes it order-dependent, which is worse than being uniformly wrong.

Hoisting the early-out so it runs whenever recursive === false, not just on the resolving call, fixes it.

Comment thread packages/zod/src/v4/classic/cycles.ts Resolved
@colinhacks colinhacks changed the title feat(v4): parse input containing reference cycles (classic only) feat(v4): parse input containing reference cycles Aug 13, 2026

@pullfrog pullfrog 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.

Caution

9734abac is a full rewrite of the mechanism, and it lands with zero test changes (cyclic-data.test.ts is byte-identical to 9a16a4ee). It fixes one prior finding and introduces a new critical one. The runtime and bundle numbers in the PR body now describe an architecture that no longer exists — remeasured below, the recursive-parse regression is 24×, not the 8.7× advertised.

Reviewed changes

  • classic/cycles.ts — the Filler family (fillObject/fillArray/fillMap/fillSet) and installCycleGuard are gone; provide()/arm()/bucket()/Memoizer replace them. No more placeholder, no more copy: core now registers its real output object directly.
  • core/schemas.ts — core is touched again, contrary to the title's "classic only" and the body's "core is untouched". New $ZodMemoizer interface, new _$ZodTypeInternals.memoizer?, and seven allocation sites become payload.value = memo ? memo.alloc(...) : <empty>, plus two $ZodObjectJIT codegen branches.
  • classic/schemas.ts — six container constructors sandwich core init with cycles.provide(inst) / cycles.arm(inst).
  • classic/tests/cyclic-data.test.ts — unchanged.

Confirmed fixed: the fillObject [[Prototype]] corruption, which went away with the placeholder design. That thread is resolved.

Still reproducing against 9734abac, so I've left those threads open rather than restating them here: encode skipping every check below the root, issue-path corruption via shared $ZodRawIssue objects, a non-recursive schema memoizing after something captures _zod.run, sync/async divergence, isRecursive ignoring _zod.checks, and ZodCyclicError being unexported.

🚨 New: z.encode of cyclic data returns a detached graph when the schema has checks

const Node: any = z.object({
  n: z.number(),
  get self() { return z.optional(Node); },
}).refine(() => true);
const input: any = { n: 1 };
input.self = input;

const out = z.encode(Node, input);
out.self === out; // false — the cycle closes on a throwaway object

The backward path runs the canary pass first (core/schemas.ts:296), which consumes m.bucket and registers { input → canaryOutput }. The real pass's alloc then sees m.bucket === undefined, returns empty unregistered, and the real back-edge binds to the canary's object. Drop the .refine() and there is no canary and it returns true — which is exactly why the existing "encodes through a cycle" test (cyclic-data.test.ts:290) can't see it: that schema has no checks.

Worth flagging that this is not the same bug as the ctx leak on the open thread, and fixing that one does not fix this one. I patched line 296 to { ...ctx, skipChecks: true, ["~cycles"]: undefined } and it flipped the check-skipping case to correct (success=false, refine ran 2×) while leaving self === out still false. ~cycles lives on ctx but m.bucket is instance state, so both the ctx sharing and the bucket handoff need separate fixes.

📉 Runtime: 24× on recursive schemas, not 8.7×

Min-of-9, fixed iteration counts with gc() between samples, interleaved PR → baseline → PR → baseline (per-side spread ≤1%), load average 0.02–0.18, importing source directly rather than through the package export map:

workload main 9734abac delta
recursive schema, 364-node acyclic tree 15255 ns 365703 ns 24.0× slower
recursive schema, flat 4-node 167 ns 3885 ns 23.2× slower
non-recursive control, flat 4-node 296 ns 307 ns +3.6%
z.string() leaf 6.1 ns 6.2 ns ~0%

The body's table says +775% / "~8.7× slower" on the 364-node row. That measured v2's copy, which no longer exists — v3 is about 2.8× worse than what's being advertised, on ordinary acyclic input through a schema whose only sin is being recursive.

I have a hypothesis but haven't proven it: (ctx as WithState)[STATE] = state adds a property to the ctx object mid-parse, changing its hidden class and demoting every downstream ctx.async / ctx.direction / ctx.skipChecks read. Cheap to test with %HaveSameMap before committing to a fix.

📦 Bundle: zod/mini is no longer free

esbuild --bundle --minify --conditions=@zod/source, gzip -9, baseline = merge-base e25b68e1:

fixture main 9734abac delta
zod-mini-object 3576 3602 +26 (+0.73%)
zod-mini-simple-object 3919 3951 +32 (+0.82%)
zod-mini-full 3573 3599 +26 (+0.73%)
zod-object 19379 20092 +713 (+3.7%)
zod-full 19374 20087 +713 (+3.7%)

The body's table has zod-mini-object at 3576 → 3575, "−1 (nil)", and the prose says "core is untouched, and mini links none of it". Both described v2. It's still well under the +359 B the body attributes to the original in-core design, so the argument for this shape survives — the table just needs redoing.

On memory: _zod goes 10 → 11 own properties for z.object({ a: z.string() }), so V8's 12→13 step isn't crossed and there's no 128 B → 848 B cliff. But every classic container now allocates a Memoizer (3 fields including a closure) plus an arm() deferred closure, which lands directly on top of 3063993's per-schema memory work. I wasn't able to get trustworthy byte figures — packages/bench/memory/, which CLAUDE.md points at for exactly this, doesn't exist in the tree.

🧪 No test moved across a full rewrite

The mechanism changed completely and cyclic-data.test.ts didn't change at all, which is the main reason three of the bugs above are invisible to CI. Concretely: cyclic-data.test.ts:201 still asserts only .not.toThrow() for all nine containers, no test parses an invalid node reached more than once (that's the issue-path corruption), "encodes through a cycle" uses a check-free schema (that's this review's new finding and the check-skipping one), and "sync and async agree on a shared reference" asserts identity only and never compares issue lists.

ℹ️ Nitpicks

  • packages/docs/content/api.mdx:1468 still says cyclical data causes an infinite loop. No docs change in the diff.
  • The PR title says "classic only" and the body says core is untouched. Neither is true of 9734abac — worth updating both before merge so the changelog doesn't mislead.

I did want to note two things I chased and found clean, so they don't get re-litigated: the JIT fastpass writes memo.alloc(...) before the per-key parse loop (core/schemas.ts:2049 vs 2050-2126), so registration correctly precedes descent; and a thrown ZodCyclicError doesn't poison the memoizer, since the wrapper re-sets m.bucket before every delegation.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/classic/cycles.ts Resolved
Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
return empty;
},
};
inst._zod.memoizer = m;

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.

provide() runs unconditionally in all six classic container constructors, so inst._zod.memoizer is permanently truthy under classic — there's no counterpart to the run wrapper's self-removal on line 141.

That means the memo ? memo.alloc(inst, payload, <empty>, ctx) : <empty> branch at all seven core sites, plus the extra inst/memo Doc params in the JIT fastpass, are baked into every classic container parse forever, recursive or not. The body's "non-recursive schemas are free" holds for the wrapper but not for the core hook; the +3.6% on my non-recursive control is that residue.

If the intent is for alloc to decay to "a single field read" as the doc comment on line 96 says, the disarm on line 139-142 needs to clear inst._zod.memoizer too — though note the JIT fastpass reads memo at codegen time, so clearing it post-construction won't undo the generated source.

Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
let state = (ctx as WithState)[STATE];
if (!state) {
state = { bySchema: new Map(), pending: undefined };
(ctx as WithState)[STATE] = state;

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.

Adding a property to the ctx object mid-parse changes its hidden class, and ctx is read on essentially every parse frame below this point (ctx.async, ctx.direction, ctx.skipChecks).

This is my leading suspect for the 24× regression measured on recursive schemas — worth checking with %HaveSameMap on the ctx before and after this assignment. If it's confirmed, initializing the slot on the ctx at creation (or threading the state somewhere other than the shared ctx object) would keep the shape stable.

@pullfrog pullfrog 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.

Caution

1e136526 is a clean, behavior-neutral perf commit, and it is a big win — the recursive-parse regression drops from 24.0× to 5.05×. But all four critical correctness findings from the last review still reproduce verbatim on this head, so nothing that blocked merge has moved.

Reviewed changes — 1e136526 is the only new commit since the previously reviewed 9734abac, and it touches ~20 lines of one file.

  • Inlined the settle closure into both branches of the run wrapper. classic/cycles.ts:174-187 writes the memo-entry settle logic out twice rather than allocating one closure per node. The sync and async paths are otherwise identical to what they replaced — same instanceof Promise discrimination, same byInput.get(input) re-lookup, same EMPTY_ISSUES sentinel. I found no behavioral difference, and cyclic-data.test.ts is green (14 tests, plus typecheck).
  • Nothing else changed. No test, doc, or PR-body updates; core/schemas.ts and classic/schemas.ts are untouched since 9734abac.

🚨 All four critical findings still reproduce on this head

I re-ran each one against 1e136526 rather than assuming, since the perf commit did touch the wrapper. All four are unchanged, and their threads stay open:

finding result on 1e136526
z.encode of cyclic data through a schema with checks returns a detached graph out.self === out → false
z.encode skips every check below the top node recursive: success=true, refine ran 1× · non-recursive control: success=false
memo replay corrupts issue paths in place [["kids",1,0,"v"],["kids",1,0,"v"]] vs the correct [["kids",0,"v"],["kids",1,"v"]]
a non-recursive schema starts memoizing after its first parse a===b:false b===c:true where all three should be false

The second row is the one I'd rank first: z.encode accepting data that violates a .refine() one level down is silent data corruption on the encode path, and it only needs a recursive schema — no cyclic input required.

Technical details
# Four reproducing critical defects, unchanged by `1e136526`

## Affected sites
- `packages/zod/src/v4/classic/cycles.ts:170` — `m.bucket` handoff is single-use and the backward direction's canary pass consumes it before the real pass. Thread open.
- `packages/zod/src/v4/core/schemas.ts:296` — `{ ...ctx, skipChecks: true }` copies the `"~cycles"` state by reference into the canary context, so the canary settles entries the real pass then reuses without descending. This is the only `{ ...ctx` spread in all of `packages/zod/src/v4`. Thread open.
- `packages/zod/src/v4/classic/cycles.ts:161` — `payload.issues.push(...hit.issues)` shares `$ZodRawIssue` objects; `util.prefixIssues` unshifts `iss.path` in place and the `.slice()` at line 186 is shallow. Thread open.
- `packages/zod/src/v4/classic/cycles.ts:137-143` — the `!m.armed` early-out is nested inside `if (m.armed === undefined)`, so an instance whose `_zod.run` was captured elsewhere (single-option unions capture `def.options[0]._zod.run` at construction) keeps memoizing. Thread open.

## Required outcome
- The four inline threads are addressed, and each acquires a test that fails without the fix.

⚠️ Recursive parsing is 5.05× slower than main, not the 3.0× the body advertises

The closure removal is the real thing — this is the largest single perf move in the PR so far. Remeasured with the same harness as last time (min-of-9, fixed iteration counts with gc() between samples, three revisions interleaved across two rounds, per-side spread ≤1.2%, load average 0.32, importing source by relative path rather than through the export map):

workload main 9734abac 1e136526
recursive schema, 364-node acyclic tree 15.8 µs 379 µs (24.0×) 79.8 µs (5.05×)
recursive schema, flat 4-node 175 ns 4044 ns (23.1×) 682 ns (3.90×)
non-recursive control, flat 4-node 346 ns 352 ns 343 ns (~0%)
z.string() leaf 7.7 ns 7.7 ns 7.7 ns

Two things follow. The 4.7× win is far larger than one closure allocation per node should buy on its own (~820 ns/node saved on the tree row), which suggests the closure was forcing context allocation or blocking inlining of the whole wrapper — worth knowing, because whatever that mechanism is may still have headroom left in it. And the residual is still 5× on ordinary acyclic input through a schema whose only property is being recursive, which is not an exotic shape.

The PR body's table now says +200% on the 364-node row against a 25.1 µs baseline; I measure 5.05× against a 15.8 µs baseline. The ratio is what's comparable, and it's still understated by ~1.7×. Bundle is also unmoved by this commit and the body's table still describes v2 — remeasured this run against merge-base e25b68e1: zod-mini-object 3576 → 3599 (+23, and the body claims −1), zod-object 19379 → 20100 (+721).

Technical details
# PR body's three-axes numbers still describe a superseded architecture

## Affected sites
- PR description, "Cost" section — runtime table and bundle table both predate `9734abac`'s rewrite and `1e136526`'s perf fix.

## Required outcome
- The runtime row for a recursive schema reflects a remeasurement of the current head, and the bundle table reflects that `zod/mini` now pays ~+23 B rather than nothing.
- The `~5×` residual on recursive-but-acyclic parsing is either reduced further or stated in the body as the accepted cost, so reviewers aren't reading a number that is 1.7× optimistic.

## Suggested approach (optional)
- The `(ctx as WithState)[STATE] = state` assignment at `cycles.ts:148-152` is still the untested hypothesis for part of the residual — it adds a property to `ctx` mid-parse, and `ctx.async` / `ctx.direction` / `ctx.skipChecks` are read on nearly every frame below. `%HaveSameMap` on `ctx` across that assignment settles it cheaply.

ℹ️ Nitpicks

  • Three consecutive rewrites of this mechanism — 9a16a4ee, 9734abac, 1e136526 — have now landed with cyclic-data.test.ts byte-identical throughout. The perf commit specifically has no guard: nothing in the suite would notice if the closure crept back in, and nothing would notice the 5× either.
  • packages/docs/content/api.mdx:1468 still says cyclical data causes an infinite loop.
  • The PR title still says nothing about core being touched, and the body still says "Core's whole diff is one file, +30/−9" alongside a bundle table asserting mini is free. The first is true, the second isn't.

Pullfrog  | Fix it ➔ | View workflow run | Using Claude Opus | 𝕏

@pullfrog pullfrog 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.

Caution

fa5f57a2 is a perf commit that I cannot measure any perf win from, and it pays for that with two new memory regressions: the schema now permanently retains the last graph it parsed, and a throwing parse leaks an entry per node forever. All prior critical findings still reproduce unchanged.

Reviewed changes — fa5f57a2 is the only new commit since the previously reviewed 1e136526. It touches ~20 lines of classic/cycles.ts and nothing else; no test, doc, or PR-body update, and core/schemas.ts / classic/schemas.ts are untouched since 9734abac.

  • Added a ctx-keyed bucket cache — m.ctx / m.ownBucket (cycles.ts:168-175) replace the per-node state.bySchema.get(inst) lookup with an identity check.
  • Added an allocation stack — alloc pushes a MemoEntry onto m.stack; the wrapper captures depth before base and pops after (cycles.ts:192-196), replacing the per-node byInput.get(input) re-lookup.

I re-ran the four prior criticals against this head rather than assuming, since the commit touches the wrapper again. Risks 1, 3 and 4 reproduce verbatim (out.self === out → false; [["kids",1,0,"v"],["kids",1,0,"v"]] vs the correct [["kids",0,"v"],["kids",1,"v"]]; b === c → true). Their threads stay open. cyclic-data.test.ts is byte-identical for the third rewrite running.

📉 The commit does not measurably improve the workload it targets

Two worktrees at fa5f57a2 and 1e136526 so the main tree was never mutated, bench importing each worktree's source by absolute path, min-of-9 fixed-iteration samples with gc() between, 5 interleaved rounds, load average 0.17:

364-node acyclic tree r1 r2 r3 r4 r5 min
fa5f57a2 78168 80591 77567 79448 78344 77567 ns
1e136526 77756 77276 77389 77229 77242 77229 ns

1e136526 is faster in 5 of 5 rounds, median gap +1.4% against the new commit. Same direction on the other two rows: flat 4-node 713 ns vs 672 ns, non-recursive control 318 ns vs 297 ns. Bundle moves the wrong way too — zod-object 20100 → 20161 (+61 B gzipped); zod-mini-object holds at 3599.

I also built a third variant — fa5f57a2 with only the ctx cache reverted — expecting it to land between the two. It measured 82010 ns, slower than both, which is incoherent with a lookup-count model. My read is that per-node map lookups are simply not where the residual ~5× lives, and the two changes are landing as V8 layout noise rather than as the win the commit message claims.

That leaves a scope question only you can answer: is this commit worth keeping? As measured it costs memory (below), bundle, and three extra Memoizer fields for no runtime gain, and reverting it would retire both inline findings at once. If you believe the win is real and my harness is missing it, the counter-measurement is the thing to post — but I'd rather not have it merged on the strength of the commit subject alone.

Technical details
# `fa5f57a2` regresses two axes for no measured gain on the third

## Affected sites
- `packages/zod/src/v4/classic/cycles.ts:168-175` — ctx-keyed bucket cache. Costs permanent retention (see inline thread), buys nothing measurable.
- `packages/zod/src/v4/classic/cycles.ts:192-196` — allocation stack. Costs an unbounded leak on throw (see inline thread), buys nothing measurable.
- Bundle: `zod-object` 20100 → 20161 gzipped bytes.

## Required outcome
- Either a remeasurement showing a real runtime win that justifies the memory and bundle cost, or the commit is dropped and `1e136526` stands as the head of the perf work.
- If it is kept, both inline findings are fixed and each acquires a test that fails without the fix.

## Suggested approach (optional)
- Reverting `fa5f57a2` is the cheapest path: it restores `byInput.get(input)` and `bucket(state, inst)`, which have no retention and no leak, at a cost my harness cannot distinguish from zero.
- If the residual ~5× is still the target, the untested hypothesis from the last review is the better lead: `(ctx as WithState)[STATE] = state` at `cycles.ts:162-166` adds a property to `ctx` mid-parse, and `ctx.async` / `ctx.direction` / `ctx.skipChecks` are read on nearly every frame below it. `%HaveSameMap` on `ctx` across that assignment settles it cheaply.

## Open questions for the human
- Five commits in, the mechanism has been rewritten three times and `cyclic-data.test.ts` is still byte-identical throughout. Nothing in the suite would notice if a perf change regressed rather than improved — which is exactly what I measure here. Is a perf guard in scope for this PR?

ℹ️ Nitpicks

  • The comment at cycles.ts:98-100 asserts the ctx cache "replaces a map lookup per node with an identity check" as a stated benefit. Accurate as a description of the code, but not of the outcome — worth not leaving a performance claim in a comment the numbers don't support.
  • packages/docs/content/api.mdx:1468 still says cyclical data causes an infinite loop.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
} else {
byInput = bucket(state, inst);
m.ctx = ctx;
m.ownBucket = byInput;

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.

m.ctx and m.ownBucket are never cleared — there is no finally and no post-parse hook anywhere in cycles.ts — so when a parse returns, the schema instance is still holding that parse's ctx, and through ctx["~cycles"] the bySchema map for every schema that participated. One recursive container therefore pins the entire last-parsed graph, inputs and outputs both.

Verified: after Node.parse(input) on a 51-node graph, m.ctx !== undefined, m.ownBucket.size === 51 with the input objects as keys, and m.ctx["~cycles"] still populated. Schemas are module-level singletons in normal use, so the largest document a schema ever sees stays reachable for the life of the process.

Technical details
# The ctx-keyed bucket cache retains the last parsed graph forever

## Affected sites
- `packages/zod/src/v4/classic/cycles.ts:173-174` — `m.ctx = ctx; m.ownBucket = byInput;` are strong references written on every cache miss and cleared nowhere.
- `packages/zod/src/v4/classic/cycles.ts:101-102` — the field declarations; neither is documented as outliving the parse.

## Required outcome
- After a top-level parse completes, no schema instance retains that parse's `ctx`, its `MemoState`, or any input or output object from it.
- A test asserts this — e.g. parse through a recursive schema, drop the input reference, and assert the graph is collectable (or, more cheaply, assert `m.ctx === undefined` once the outermost frame has returned).

## Suggested approach (optional)
- The outermost wrapper frame for an instance is identifiable as `depth === 0`. Clearing `m.ctx` / `m.ownBucket` there costs one cache miss at the root of the next parse and nothing per node, so it should preserve whatever the cache is worth. This pairs naturally with the `m.stack` leak on the other thread — one `try`/`finally` at `depth === 0` can reset all three fields.
- Simpler still: revert the cache. I could not measure a win from it (see the review body), and `bucket(state, inst)` has no retention.

## Open questions for the human
- Is there a reason the cache has to survive the parse? If a repeat-parse hit was intended, it does not happen — `ctx` is a fresh object literal in all four of `_parse` / `_parseAsync` / `_safeParse` / `_safeParseAsync` (`core/parse.ts:17/40/60/82`), so `m.ctx === ctx` can never match across calls.

Comment thread packages/zod/src/v4/classic/cycles.ts Outdated
const result = base(payload, ctx);
m.bucket = undefined;
// Nothing was allocated when the container rejected its input outright.
const entry = m.stack.length > depth ? m.stack.pop()! : undefined;

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 pop only runs if base returns normally. When it throws, the entry stays on m.stack permanently, and m.stack is instance state that nothing ever resets.

Verified: three throwing parses grow m.stack to 2, then 4, then 6, and a later successful parse leaves it at 6 — each stranded entry still retaining its output object. ZodCyclicError, which this PR introduces at classic/schemas.ts:2097 and which the suite's own "rejects a cycle that closes through a transform" test triggers, reaches this path, as does any throwing .transform() or .refine(). A service that rejects cyclic payloads would leak on every rejection.

Technical details
# A throwing parse strands memo entries on `m.stack` permanently

## Affected sites
- `packages/zod/src/v4/classic/cycles.ts:192-196` — `depth` is captured and the pop performed around `base(payload, ctx)` with no `try`/`finally`, so any exception skips the pop.
- `packages/zod/src/v4/classic/cycles.ts:127` — `m.stack.push(entry)` in `alloc`, the matching push.
- `packages/zod/src/v4/classic/schemas.ts:2097` — `throw new cycles.ZodCyclicError()` is one reachable thrower; user code in `.transform()` / `.refine()` is another.

## Required outcome
- `m.stack` returns to its pre-parse length whether the parse returns or throws, so repeated failing parses of one schema do not grow memory without bound.
- A test parses a recursive schema through a thrower several times and asserts the state does not accumulate.

## Suggested approach (optional)
- A `try` / `finally` around `base(payload, ctx)` that restores `m.stack.length = depth` covers both the normal and exceptional exits, and subsumes the current `m.stack.length > depth` check.
- Correctness is not affected today, which is why nothing catches this: `depth` is re-read on every call, so a stale prefix still lets the next frame pop its own entry. I confirmed a successful parse after three throws still returns `success: true`. It is purely a leak — but an unbounded one.

@pullfrog pullfrog 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.

Caution

be590a4d is a clean pure move — classic/cycles.ts → core/memoizer.ts plus a rename pass — and it fixes the unexported-error thread. But it is the fourth revision of this mechanism to land with cyclic-data.test.ts byte-identical, and I re-executed every outstanding finding against this commit: all six correctness defects still reproduce verbatim.

Reviewed changes

  • classic/cycles.ts deleted, core/memoizer.ts created (189 lines). Same machinery, new names: provide→attachMemoizer, arm→armMemoizer, isPending→isBackEdge, ZodCyclicError→$ZodCyclicError, "~cycles"→"~memo", m.bucket→m.handoff, m.ownBucket→m.bucket, m.armed→m.recursive, m.stack→m.open.
  • core/index.ts:5 — export * from "./memoizer.js".
  • core/schemas.ts, classic/schemas.ts — call-site renames only.
  • classic/tests/cyclic-data.test.ts — unchanged.

Confirmed fixed: $ZodCyclicError is now reachable as z.core.$ZodCyclicError (typeof === "function"), matching the $ZodEncodeError precedent. Thread resolved.

🚨 Every carried finding still reproduces on be590a4

I ran each one rather than assuming, since the rename churn could plausibly have shifted behavior. Nothing did.

risk1  encode-detached:      self===out is false                     (expected true)
risk2  encode-skips-checks:  recursive ENCODE success=true  refineCalls=1   ← bug
                             recursive DECODE success=false refineCalls=2   ← correct
risk3  issue-paths jit:      [["kids",1,0,"v"],["kids",1,0,"v"]]
       issue-paths jitless:  [["kids","kids",1,0,"v"]] x2
       correct control:      [["kids",0,"v"],["kids",1,"v"]]
risk4  nonrec-memoizes:      a===b:false b===c:true a===c:false      (expected all false)
risk5  sync vs async:        sync ["kids",1,0,"v"]  async ["kids","kids",1,0,"v"]
risk10 retention:            m.ctx set, m.bucket.size=63, root input pinned
risk11 m.open leak:          [1,2,3,3] across 3 throwing parses + 1 successful

The encode one is the sharpest demonstration: same schema, same input, safeDecode correctly runs the nested refine twice and fails, safeEncode runs it once and returns success. That is the canary pass consuming m.handoff before the real pass gets it.

All ten open threads are anchored on a file that no longer exists, so GitHub is showing them OUTDATED. They are all still live.

Current line mapping in core/memoizer.ts
finding v3 anchor v4 anchor
encode detached graph / handoff consumed by canary cycles.ts:170 memoizer.ts:164
encode skips nested checks ({ ...ctx } at core/schemas.ts:296 copies "~memo") — memoizer.ts:137
issue-path corruption (push(...hit.issues), shallow .slice()) cycles.ts:161 memoizer.ts:156, :171
non-recursive schema memoizes (early-out nested inside === undefined) cycles.ts:139 memoizer.ts:125-131
ctx hidden-class change cycles.ts:151 memoizer.ts:137
permanent graph retention via m.ctx/m.bucket cycles.ts:174 memoizer.ts:144-149
m.open never drains on throw cycles.ts:196 memoizer.ts:169

ℹ️ The bundle table is now accurate, and the tree-shaking claim checks out

esbuild --bundle --minify --conditions=@zod/source, gzip -9, baseline = merge-base e25b68e1:

fixture main fa5f57a2 be590a4d
zod-mini-object 3552 3580 3580 (+28, +0.79%)
zod-mini-full 3551 3579 3579
zod-object 19360 20147 20098 (+738, +3.8%)

The body says +26 mini / +741 classic, which is within noise of measured. First time in this PR the table describes the architecture actually in the tree. Moving into core/ also saved 49 B on classic.

And the "mini doesn't pay for it" claim is verifiably true rather than merely plausible: grepping the minified mini bundle, isRecursive, attachMemoizer, armMemoizer, isBackEdge, ~memo, ZodCyclicError, reference cycle and backEdges all appear 0 times (each appears once in classic). Only the field-name read memoizer survives, once.

The runtime row is the one still off. Min-of-9, fixed iteration counts, gc() between samples, three interleaved rounds (per-side spread ≤1%), load average 0.05:

workload main be590a4d
recursive schema, 364-node acyclic tree 16.3 µs 80.3 µs (4.92×)
recursive schema, flat 4-node 176 ns 730 ns (4.14×)
non-recursive control, flat 4-node 307 ns 300 ns (~0%)

The body claims +171% (2.71×) against a 27.0 µs baseline. I measure the baseline at 16.3 µs, which puts the real ratio ~1.8× worse than advertised — on ordinary acyclic input through a schema whose only sin is being recursive.

🧪 Four rewrites, zero test movement

The mechanism has now been rewritten three times and relocated once, and cyclic-data.test.ts has not changed a byte since 9a16a4ee. That is the direct reason six defects survive CI: line 201 still asserts only .not.toThrow() for all nine containers, no test parses an invalid node reached more than once, "encodes through a cycle" (:290) uses a check-free schema so it cannot construct a canary, and "sync and async agree on a shared reference" (:378) compares identity but never issue lists. There is also no perf guard, which is how a 4.9× regression on recursive schemas stays invisible.

ℹ️ Nitpicks

  • The $ZodCyclicError message text changed in this commit (long explanatory sentence → "Cannot parse a reference cycle that closes through a transform"). Fine change, but it is a behavior change inside a commit billed as a move, and the test's /reference cycle/ regex matches both so nothing flags it.
  • packages/docs/content/api.mdx:1468 still says cyclical data causes an infinite loop.

Two things I chased and found clean, so they don't get re-litigated: the JIT fastpass still writes memo.alloc(...) before the per-key parse loop (core/schemas.ts:2047 vs 2050+), so registration precedes descent; and the ctx-identity cache cannot serve a stale bucket across parses, since all four entry points in core/parse.ts build ctx as a fresh object literal.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

ctx: undefined,
bucket: undefined,
open: [],
alloc(_inst, payload, empty) {

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.

inst and ctx are dead. The only implementation of alloc is this one, and it discards both — _inst is unused and ctx isn't even in the parameter list.

They're still declared on the interface (core/schemas.ts:37) and passed at all eight call sites, and the JIT fastpass carries an extra inst Doc parameter (core/schemas.ts:2022-2024, :2129) solely to feed one of them. Dropping them to alloc(payload, empty) is a strict win on all three axes: two fewer arguments pushed per container node on the hot path, one fewer codegen parameter, and a few bytes off both bundles.

If they're placeholders for a future implementation, worth a comment saying so — otherwise this reads as leftover shape from the v1 in-core design.

export * from "./parse.js";
export * from "./errors.js";
export * from "./schemas.js";
export * from "./memoizer.js";

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.

This is the flat public form, so attachMemoizer, armMemoizer, isBackEdge and $ZodCyclicError all become z.core.* API. Three lines down, util and regexes are deliberately namespaced (export * as util) precisely to keep implementation detail out of the flat surface.

$ZodCyclicError being public is right — that's the fix for the unexported-error thread, and it matches $ZodEncodeError. The other three are the injection protocol, and this same commit marks $ZodMemoizer and _zod.memoizer @internal while leaving these three untagged. Either namespace the module or tag the three functions, otherwise this locks in three accidental public functions that no export-surface test would catch.

@pullfrog pullfrog 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.

Caution

714d706 introduces a validation bypass. The new payload.memo flag is never cleared, so a .refine() on any wrapper around a recursive schema is silently skipped for cyclic input — safeParse returns success: true for data that violates the refinement. Details inline on core/memoizer.ts:157.

Reviewed changes

  • Re-executed all eight carried findings from the be590a4 review against this commit — one is fixed (cyclic z.encode now round-trips identity; that thread is replied to and resolved), seven still reproduce verbatim.
  • Traced the new payload.memo flag from its single write (core/memoizer.ts:157) to its single read (core/schemas.ts:235) and enumerated every schema type that forwards the same ParsePayload object across a schema boundary.
  • Verified the armMemoizer → attachMemoizer collapse is wiring-equivalent: the deferred is pushed before core .init, so it wraps the final _zod.parse in both the checks branch (where run reads parse dynamically) and the no-checks branch (where core's run = parse deferred is queued behind it, making the run === wrapped self-removal guard at :127 correct).
  • Confirmed $ZodObjectJIT's superParse capture at core/schemas.ts:2021 is not a bypass — it is only reachable from inside jitParse, which is itself the wrapper's base.
  • Confirmed payload.memo does not escape into user-visible output; core/parse.ts reads only .value and .issues, and the standard-schema adapter goes through safeParse.
  • Re-measured all three axes against merge-base e25b68e1 and ran the full v4 suite (224 files / 2848 tests, green, no type errors).

🧪 Still no test movement

classic/tests/cyclic-data.test.ts is byte-identical for the fifth consecutive revision — three mechanism rewrites, two perf passes, one file move, and now a wrap-point change, with zero test changes. The suite stays green while a four-line schema silently skips its own refinement, which is the concrete cost of that.

The two closest existing cases both miss it for the same structural reason: "checks run once per node" (:206) and "reports a failing check inside a cycle" (:227) put the .refine() on the recursive node itself, and the outermost call is never a memo hit, so the flag is set on a child payload the object never reads back. It takes a .refine() on a wrapper around the node to see the leak. Similarly, "encodes through a cycle" (:290) uses a checkless z.codec, which is why the backward-direction hole stays uncovered.

📉 The runtime number in the body

Re-measured this run, min-of-9 fixed-iteration samples with gc() between, three interleaved rounds, load average 0.00, per-side spread ≤4%:

workload e25b68e1 714d706
recursive schema, 511-node acyclic tree 21.7 µs 99.7 µs (4.6×)
recursive schema, flat 4-node 135 ns 573 ns (4.2×)
non-recursive control, flat 4-node 232 ns 240 ns (~flat)

The body still claims +171% (2.71×). The control row confirms the cost is confined to recursive schemas, but it lands on ordinary acyclic input through them, not only on input that actually contains a cycle — worth stating explicitly in the body, since that is what most users of a recursive schema will hit. Bundle is unchanged from the last review and the body's table there is accurate; the zod/mini tree-shaking claim still verifies (none of isRecursive, attachMemoizer, isBackEdge, ~memo, backEdges survive in the minified mini bundle).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

payload.issues.push(...hit.issues);
} else {
// Still being parsed: its own checks cover it, so skip them here.
payload.memo = true;

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.

This is a validation bypass. payload.memo is set here and never cleared, and runChecks early-returns on it (core/schemas.ts:235). Wrapper schemas forward the same payload object across the schema boundary, so the flag propagates upward and silently suppresses every enclosing wrapper's checks up to the nearest container.

A/B on identical schemas, with a .refine() that always returns false and cyclic input:

                              be590a4         714d706
z.optional(N).refine(F)     → success=false   success=true  (refine called 0x)
z.lazy(()=>N).refine(F)     → success=false   success=true  (refine called 0x)
z.union([N,null]).refine(F) → success=false   success=true  (refine called 0x)

Acyclic input through the same schema still reports success=false with the refine called, so the refinement demonstrably works — it is skipped only when a cycle is present. safeParse now returns success: true for data that violates a refinement.

The comment above is right about the intent — the memoized node's own checks do cover it — but the flag doesn't stop at that node. Everything that forwards the payload object rather than building a fresh one is affected: $ZodOptional, $ZodExactOptional (core/schemas.ts:3603), $ZodNullable (:3653), $ZodDefault (:3709), $ZodPrefault (:3763, :3770), $ZodNonOptional (:3811), $ZodSuccess (:3905), $ZodCatch (:3958, :3962), $ZodReadonly (:4255), plus $ZodLazy and $ZodUnion, and $ZodPipe/$ZodCodec on their abort branch. $ZodCatch is the worst of them — it resets payload.issues = [] without clearing memo.

state.backEdges on the next two lines already records hit.value in ctx-scoped state. Deciding the check-skip from that set, keyed on the value, would avoid hanging a sticky boolean on an object the parent reuses.

checks: checks.$ZodCheck<never>[],
ctx?: ParseContextInternal | undefined
): util.MaybeAsync<ParsePayload> => {
if (payload.memo) return payload;

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.

Worth flagging that the obvious fix — clearing payload.memo here after the early return — does not work. A memoized schema with no checks has run === parse === wrapped, because the no-checks deferred at :227 copies the wrapper straight into run. runChecks is then never invoked on that payload at all, so the flag is never cleared and travels up untouched. That is exactly the shape of the repro on core/memoizer.ts:157.

The flag has to be cleared by whoever set it, or not live on the shared payload in the first place.

@pullfrog pullfrog 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.

Caution

9bf5e604 fixes the .readonly() freeze for the direct case, but the guard it adds is defeated by any schema that rebuilds the payload in between. Through z.pipe, z.codec or z.xor a cyclic parse now returns success: true with an empty frozen object — every key silently dropped.

Reviewed changes — 9bf5e604 is the only new commit since the previously reviewed 714d7067. It touches handleReadonlyResult and adds the first tests this PR has gained in six revisions.

  • Guarded Object.freeze behind payload.memo (core/schemas.ts:4267). Freezing a node a back-edge is still building made its remaining keys fail to assign silently, since the JIT fastpass is not strict mode. Confirmed fixed for the direct case: with the self getter declared before id, Node.parse on a .readonly() back-edge now returns ["self","id"] where 714d706 returned [].
  • Added two tests — a .readonly() cycle and a z.intersection cycle. cyclic-data.test.ts goes 14 → 16 tests and is green, with no type errors. The file had been byte-identical across the previous five revisions.
  • Re-executed three of the carried criticals against this head rather than assuming, since the commit touches the parse path. All three reproduce verbatim: the payload.memo validation bypass (success=true, refine called 0×, against an acyclic control of success=false, called 1×), the issue-path corruption ([["kids",1,0,"v"],["kids",1,0,"v"]] for the correct [["kids",0,"v"],["kids",1,"v"]]), and a non-recursive schema memoizing on its second parse. The remaining open threads anchor on code this commit does not touch, so they stay open.
  • Bundle re-measured (esbuild --bundle --minify --conditions=@zod/source, gzip -9): zod-mini-object 3592 → 3590, zod-object 20117 → 20120. Neutral, as expected for three lines outside the container path. Runtime and memory are structurally unmoved — no new allocation, and the added read is one property on the .readonly() path only.

🚨 The guard is per-visit, but the hazard is per-value

payload.memo is a flag on the payload object, so it survives only as far as the next schema that forwards that exact object. $ZodPipe / $ZodCodec build a fresh payload in handlePipeResult (core/schemas.ts:4092-4099) and $ZodXor copies successes[0].value into its own (:2304-2306). Both keep the half-built value and drop the flag, and one wrapper later the new guard reads false and freezes it.

This is now the third instance of one class, each found and patched individually: ZodTransform got isBackEdge, handleReadonlyResult got payload.memo, and z.intersection is still unguarded. The question worth settling before a fourth site turns up is whether the predicate belongs on the payload at all. state.backEdges already records the value on the two lines below the flag's only write, and isBackEdge(ctx, payload.value) already answers "is this object still being built" precisely — keyed on the value rather than on which payload happens to be carrying it. It is what ZodTransform uses, and neither pipe nor xor would have defeated it. It also decouples this fix from the open thread on memoizer.ts:157, where the same flag is being asked a different question ("have this node's checks already run") that a value-keyed set answers just as well.

Technical details
# `payload.memo` is not a durable signal for "this value is still being built"

## Affected sites
- `packages/zod/src/v4/core/schemas.ts:4267` — `handleReadonlyResult` gates the freeze on `payload.memo`.
- `packages/zod/src/v4/core/schemas.ts:4092-4099` — `handlePipeResult` constructs `{ value, issues, fallback }` for `def.out`, dropping `memo`.
- `packages/zod/src/v4/core/schemas.ts:2304-2306` — `handleExclusiveUnionResults` assigns `final.value = successes[0].value` from a per-option payload, dropping `memo`.
- `packages/zod/src/v4/core/schemas.ts` `$ZodIntersection` — merges a snapshot of the left side; unguarded (see inline thread on the new test).
- `packages/zod/src/v4/core/memoizer.ts:157` — the flag's only write, adjacent to `state.backEdges.add(hit.value)`.

## Required outcome
- A value that is still under construction cannot be frozen, snapshotted, or merged, regardless of how many payload-rebuilding schemas sit between the memo hit and the consumer.
- The predicate used by `handleReadonlyResult` gives the same answer as the one used by `ZodTransform` for the same value.
- Each affected shape acquires a test that fails without the fix.

## Suggested approach (optional)
- Replace the `payload.memo` read in `handleReadonlyResult` with `isBackEdge(ctx, payload.value)`. `$ZodReadonly.parse` already has `ctx` in scope at `core/schemas.ts:4251`; only `handleReadonlyResult` would need it threaded through, and the `.then()` branch at :4257 would become a closure over `ctx`.
- If that closure allocation is unwelcome on the parse path, the sync branch at :4259 can pass `ctx` directly and only the promise branch pays it.

## Open questions for the human
- `z.intersection` and `z.xor` currently produce a wrong-but-successful graph under a cycle rather than throwing. Is `$ZodCyclicError` the intended answer for every construct that cannot bind a back-edge, the way `ZodTransform` already does it, or is the intersection behavior meant to be a documented limitation?

ℹ️ Nitpicks

  • packages/docs/content/api.mdx:1468 still says passing cyclical data into Zod causes an infinite loop.
  • The PR body's runtime row still claims +171% (2.71×) on the recursive-tree workload; the last two runs measured ~4.6× against merge-base e25b68e1, and it lands on ordinary acyclic input through any recursive schema. Unchanged by this commit, but still the number a reader sees first.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

payload.value = Object.freeze(payload.value);
// A repeat visit hands back a node that is still being built; freezing it here
// would make the rest of its keys fail to assign.
if (!payload.memo) payload.value = Object.freeze(payload.value);

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.

payload.memo only survives as far as the next schema that forwards this exact payload object. $ZodPipe/$ZodCodec build a fresh payload in handlePipeResult (:4092-4099) and $ZodXor copies successes[0].value into its own (:2304-2306) — both keep the half-built value and drop the flag, so this line freezes a node that is still being filled in. Put either between the memo hit and the .readonly() and the parse returns success: true with {}.

baseline readonly (self first):  success=true keys=["self","id"] frozen=false   ← this fix, working
pipe+readonly (self first):     success=true keys=[]             frozen=true
xor+readonly  (self first):     success=true keys=[]             frozen=true
pipe+readonly acyclic control:  success=true innerKeys=["self","id"]
Technical details
# The freeze guard is bypassed by any payload-rebuilding schema

## Affected sites
- `packages/zod/src/v4/core/schemas.ts:4267` — reads `payload.memo`, which the immediate caller may not be the one that set.
- `packages/zod/src/v4/core/schemas.ts:4092-4099` — `handlePipeResult` builds `{ value: left.value, issues: left.issues, fallback: left.fallback }` for `def.out`; `memo` is not copied.
- `packages/zod/src/v4/core/schemas.ts:2304-2306` — `handleExclusiveUnionResults` does `final.value = successes[0].value`; `successes[0]` is a per-option payload that carries the flag, `final` does not.

## Repro
```ts
const N: any = z.object({
  get self() { return z.optional(z.pipe(N, z.unknown()).readonly()); },
  id: z.number(),
});
const input: any = { id: 1 };
input.self = input;

N.safeParse(input); // { success: true, data: {} }  — frozen, both keys lost
```
The root output object is registered by the memoizer, the back-edge resolves to it while it is still empty, `handlePipeResult` hands it on without the flag, `Object.freeze` lands on it, and the JIT fastpass's subsequent `setProp` calls for `self` and `id` fail silently because generated code is not strict mode. Swapping the key order so `id` is declared first only changes which keys survive. `z.xor([N, z.string()]).readonly()` behaves identically. The same schema on acyclic input yields `["self","id"]`, so the freeze itself is working — it is the guard that is not reached.

## Required outcome
- A node under construction is not frozen no matter how many payload-rebuilding schemas sit between the memo hit and `$ZodReadonly`.
- Tests cover `.readonly()` reached through `z.pipe` and through `z.xor` on a back-edge, and fail without the fix.

## Suggested approach (optional)
- `isBackEdge(ctx, payload.value)` answers this keyed on the value rather than the payload, is already exported, and is already what `ZodTransform` uses for the same question. `$ZodReadonly.parse` has `ctx` in scope at `:4251`.

expect(result.id).toBe(7);
expect(result.self.id).toBe(7);
expect(result.self).not.toBe(result);
expect(result.self.self).toBeUndefined();

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.

"Values are right, the graph is not" holds only because id is declared before self in this schema. $ZodIntersection merges a snapshot of the left side, so hoisting the self getter above the other keys takes that snapshot before they are assigned, and the parse succeeds with an output missing a required key. As written the test blesses z.intersection under a cycle as merely lossy in graph shape, when it is also unsound in value.

Technical details
# `z.intersection` under a cycle can produce a successful parse whose output violates the schema

## Affected sites
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts:417-439` — the new test, and the comment at :428-429 characterising the limitation as graph-shape-only.
- `packages/zod/src/v4/core/schemas.ts` `$ZodIntersection` — parses both sides, then merges into a new object. The left side is a back-edge hit, so the merge reads a node that is still being filled in. Unlike `ZodTransform` (`classic/schemas.ts:2090`) it has no `isBackEdge` guard.

## Repro
```ts
const N: any = z.object({
  get self() { return z.intersection(N, z.object({ tag: z.string() })); },
  id: z.number(),
  tag: z.string(),
});
const input: any = { id: 7, tag: "t" };
input.self = input;

const r = N.safeParse(input);
r.success;      // true
r.data.self;    // { tag: "t" } — `id` is required and absent
```
Re-validating `r.data.self` against `z.object({ id: z.number(), tag: z.string() })` fails, so a successful parse emitted output that its own schema rejects.

## Required outcome
- Either `z.intersection` throws `$ZodCyclicError` when a side resolves to a back-edge, matching what `ZodTransform` already does when it cannot bind one — or the ordering hazard is pinned by a test and stated as a documented limitation rather than implied to be graph-shape-only.
- If the current behavior is kept, a test covers the key order that loses required keys, not only the order that happens to survive.

// fail to assign, silently, because generated code is not strict mode.
const result = Node.parse(input);
expect(Object.keys(result).sort()).toEqual(["id", "self"]);
expect(result.self).toBe(result);

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.

Neither assertion pins the trade this fix makes. result.self is declared .readonly() but comes back with Object.isFrozen(result.self) === false, while the identical position on acyclic input is frozen. Skipping the freeze is the right call — the node cannot be frozen mid-build — but it is a silent contract deviation, so it is worth an explicit expect(Object.isFrozen(result.self)).toBe(false) here rather than leaving it implied by two assertions that pass either way.

@pullfrog pullfrog 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.

ℹ️ Tests only — no source line moved, so the four open criticals from the previous review are all still live and their threads stay open on their own terms. The new coverage itself has two soft spots, inline.

Reviewed changes — c1d8645b is the only new commit since the previously reviewed 9bf5e604. git diff --stat 9bf5e604..c1d8645b is one file, +127/-0: six new tests in cyclic-data.test.ts, taking it 16 → 22.

  • Added identity assertions for shapes that previously had only .not.toThrow() — an array back-edge alongside a duplicated node (:441), and cycles closing through a z.map key and a z.set member (:458). The map-key position is genuinely new coverage: the existing container sweep at :51-204 puts the cyclic node in the map's value slot only, and dropping the memo-resolved key in handleMapResult is caught by this test and by nothing else in the file.
  • Pinned three documented limits as tests — a frozen input parses without mutation (:482), Node.partial() yields a root that is not the node its own cycle points back to (:500), and checks run per reference on a completed memo hit (:547).
  • Added a concurrent-parseAsync test (:522). It passes, but it cannot fail — inline.
  • Verified locally: all 22 tests green with no type errors (pnpm vitest run packages/zod/src/v4/classic/tests/cyclic-data.test.ts). Bundle, runtime and memory are unmoved by construction — the diff against the previously reviewed head contains no src line.

⚠️ Every shape the new tests cover is one that already works

The previous review's required outcome was that each affected shape acquire a test that fails without the fix, with copy-pasteable repros for .readonly() through z.pipe, .readonly() through z.xor, and the z.intersection key order that drops a required key. None of the six new tests lands on any of them. The suite grows 16 → 22 while the known-broken shapes stay uncovered, so a fix for any of them would land with no regression guard, and the z.intersection test committed in 9bf5e604 still passes only because of the key order it happens to use.

Technical details
# The added coverage does not intersect the shapes that are currently broken

## Affected sites
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts:441-566` — the six added tests.

## Uncovered, each already reduced to a repro in an open thread on this PR
- `.readonly()` reached through `z.pipe` / `z.codec` on a back-edge — `handlePipeResult` rebuilds the payload and drops `memo`, so `Object.freeze` lands on a half-built node.
- `.readonly()` reached through `z.xor` — same failure via `handleExclusiveUnionResults`.
- `z.intersection` on a back-edge with the cycling key declared *first* — the committed test at `:417` survives only because `id` precedes `self`.
- A check on a *wrapper* around the recursive node, where `payload.memo` suppresses `runChecks`.

## Required outcome
- Each shape a reviewer has reduced to a repro has a test in this file, and that test fails on `c1d8645b` and passes after the corresponding fix.

## Open questions for the human
- Is the intent to land the mechanism now and close the four open criticals in follow-ups, or to close them in this PR? That decides whether these belong here as red-then-green tests or as entries in the PR body's **Limits** section — which today lists the `z.intersection` graph truncation but not that the same construct can drop a required key and still report `success: true`.

ℹ️ Nitpicks

  • :441 — the test is named "keeps two cycles and a shared node distinct in one input", but the input holds one cycle (root → kids → root) plus one duplicated acyclic node (shared, whose kids is empty).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

expect([a.id, b.id, c.id]).toEqual([1, 2, 3]);
expect(a.self).toBe(a);
expect(b.self).toBe(b);
expect(c.self).toBe(c);

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.

This test cannot fail on the property its name claims. Promise.all([f(), g(), h()]) evaluates the three calls sequentially before any microtask runs, and the memoizer unwinds m.handoff and m.open synchronously before parseAsync returns its pending promise (memoizer.ts:164-180) — no await boundary falls inside the wrapper. I mutated the memoizer two ways to check, and this test passed both.

Technical details
# The concurrent-`parseAsync` test passes under mutations that break exactly the independence it names

## Affected sites
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts:522-545`

## What I measured
Two mutations of `packages/zod/src/v4/core/memoizer.ts`, each run against this test verbatim plus three pre-existing tests as controls:

| mutation | this test | controls |
|---|---|---|
| `m.open.pop()` moved into the `.then()` continuation (`:169` → post-await), so concurrent calls can pop each other's entries | **PASS** | none caught it either |
| `if (m.ctx === ctx)` → `if (m.bucket)` (`:142`), so a single bucket is shared across every parse context | **PASS** | pre-existing `"keeps separate parses independent"` (`:310`) FAILS |

The second mutation is literally "parses of one schema are not independent", and this test does not notice it.

## Why
The wrapper's entire mutable-state section — state lookup, bucket cache, hit check, `m.handoff = bucket`, `base(...)` (which calls `alloc` synchronously at the top of the container's parse), `m.handoff = undefined`, pop — completes before `base` returns its promise. For this schema the only `await` is inside a leaf `z.number().refine(async …)`, below every memoizer touch, so interleaving inside the wrapper is structurally impossible. What is left are value and identity assertions, and those are satisfied by `bucket.get` / `bucket.set` keying alone.

## Required outcome
- Either the test observes something the shared per-instance state actually carries across the await — issue attribution is the natural candidate, e.g. concurrent parses where some inputs are invalid and each result must carry only its own issues at its own paths — or the concurrency framing comes off the name and it is described as what it does cover.

Node.parse({ id: 0, kids: [shared, shared] });

// Memoization skips the container's parse, not the checks layered on it.
expect(calls).toBe(3);

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 comment generalizes past what the test covers. .refine() runs per reference here only because the second shared is a completed memo hit — when the repeat reference is a back-edge instead, payload.memo makes runChecks early-return, and this same schema with kids cycling back to the root gives calls === 1, not 2. Worth adding that arm so both regimes are pinned explicitly, rather than the cyclic one being left to :206 to imply.

@pullfrog pullfrog 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.

ℹ️ Tests only, and both of them can fail — I mutation-tested them. One nit inline. No source line moved, so the open threads from the previous reviews stand on their own terms.

Reviewed changes — c1d8645b..1105c720, +61/-0 in one file, appended after the old end of cyclic-data.test.ts (line 566). File goes 22 → 24 tests; full file green, no type errors.

  • Pinned the bound on root-wrapped recursive schemas — :568 walks self from the root and asserts a wrapper (.partial(), .partial().partial(), .extend()) adds exactly one node and does not compound, documenting PR-body Limit #3.
  • Guarded the schema-identity caching the memoizer's termination depends on — :598 gives both a shape getter and a z.lazy() callback a body that returns a freshly derived schema (.partial() of itself), then asserts each resolves exactly once.

I ran four mutations against a copied src tree to check these are real coverage rather than restatement:

mutation :568 :598 controls (:4, :500)
bucketFor collapsed to one shared bucket fail pass fail
m.ctx === ctx bucket cache hoisted module-level fail pass fail
$ZodObject shape cache (core/schemas.ts:1943-1948) made non-caching pass fail pass
$ZodLazy._cachedInner (core/schemas.ts:4638-4642) removed pass fail pass

:598 is the stronger of the two and is unique coverage — it is the only test in the file that dies when either caching site breaks, and it dies with a stack overflow, which is exactly the failure mode the memoizer would otherwise inherit. Worth keeping as-is.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using Claude Opus | 𝕏

Comment on lines +592 to +595
expect(count(Node.parse(input))).toBe(1);
expect(count(Node.partial().parse(input))).toBe(2);
expect(count(Node.partial().partial().parse(input))).toBe(2);
expect(count(Node.extend({ extra: z.string().optional() }).parse(input))).toBe(2);

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.

count returns cardinality, so 2 is satisfied both by root → nodeA, nodeA.self === nodeA (what the comment above claims) and by root → nodeA, nodeA.self === root — a materially different graph. The first two assertions are also a weaker restatement of :500, which already runs Node.partial().parse(input) on this exact schema and asserts result.self !== result and result.self.self === result.self. The new ground here is the stacked/extended arms, so pin those by shape rather than by count.

Technical details
# `count === 2` does not pin the graph shape the comment describes

## Affected sites
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts:593-595` — `count(...) === 2` cannot distinguish a back-edge that closes one level down from one that closes at the root.
- `packages/zod/src/v4/classic/tests/cyclic-data.test.ts:592-593` — duplicates `:490-497` and `:500-520`, which use a byte-identical `Node` and already assert the identity relation directly.

## Required outcome
- The `.partial().partial()` and `.extend()` arms — the only arms without a pre-existing equivalent — assert *where* the cycle closes, not just how many nodes it spans.

## Suggested approach
- Measured on this head: `Node.parse` gives `self === root`, while all three wrapped arms give `self !== root` and `self.self === self`. Asserting `out.self.self === out.self` alongside the count captures that.
Suggested change
expect(count(Node.parse(input))).toBe(1);
expect(count(Node.partial().parse(input))).toBe(2);
expect(count(Node.partial().partial().parse(input))).toBe(2);
expect(count(Node.extend({ extra: z.string().optional() }).parse(input))).toBe(2);
expect(count(Node.parse(input))).toBe(1);
for (const wrapped of [Node.partial(), Node.partial().partial(), Node.extend({ extra: z.string().optional() })]) {
const out = wrapped.parse(input);
expect(count(out)).toBe(2);
// Closes one level down, not back at the root.
expect(out.self.self).toBe(out.self);
}

Today a cyclic input is a RangeError, safeParse included, so it isn't
even catchable through the result.

Core gains a $ZodMemoizer seam: a container asks the injected memoizer
for the object it is about to build into. Classic injects one per
container instance; zod/mini injects nothing and links none of this.
Core's whole share is one interface, one `_zod` field, one changed
allocation line per container, and one line in runChecks -- the memoizer
is read once at construction, so a schema without one runs exactly the
code it runs today, and the JIT emits byte-identical output for it.

Everything else lives in core/memoizer.ts, which nothing references
unless a layer asks for it. It registers the real output object before
any child is parsed, so a reference back to the same input resolves to
it with nothing to copy. The lookup is keyed on (schema, input), which
is what makes mutual recursion sound: a node validated against two
schemas gets an output per schema. A repeat visit returns without
reaching core, which also stops the node's checks running against a
half-built value. A cycle closing through a transform throws
ZodCyclicError. A schema that cannot re-enter itself removes the
interceptor on its first parse.

Fixes #5346

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@colinhacks
colinhacks merged commit 942bf8c into main Aug 16, 2026
7 checks passed
@colinhacks
colinhacks deleted the feat/cyclic-data branch August 16, 2026 21:27
colinhacks added a commit that referenced this pull request Aug 29, 2026
The per-type switch can only enumerate kinds Zod ships. A third-party
container built on `$constructor` holds its children under a key only its
author knows, so an unknown `def.type` falls back to scanning the def —
still skipping accessors, so it cannot fire a getter.

Without this a cycle through such a type throws RangeError, which is the
crash #6387 removed.
colinhacks added a commit that referenced this pull request Aug 29, 2026
* fix(v4): stop the cycle walk from firing a default factory

isRecursive() walks a schema's def looking for child schemas, and
`.default(fn)` exposes `defaultValue` as a getter that calls `fn`. The
walk's `for...in` therefore ran the user's factory: an extra call on the
first parse of a container, a call even when the key was present and no
default was needed, and a call at z.compile() time before any parse.

Skip accessor properties in the walk. `merge()` was the one place a def
held a child schema behind an enumerable getter, so `catchall` becomes a
plain data property there — b is fully constructed by then, so the
laziness bought nothing.

Regressed in #6387, released in v4.5.0. Fixes #6495

* test(v4): cover safeExtend in the def-accessor invariant

The tripwire listed six of the seven `mergeDefs` call sites. `safeExtend`
is the closest sibling to `extend`, so a future getter is as likely to
appear there. The merge-derived case fails without the `merge()` fix,
alongside the other three.

* refactor(v4): enumerate child schemas per type in the cycle walk

Replaces the generic def scan with an explicit switch over `def.type`,
so the walk reads only slots that actually hold schemas and never touches
`defaultValue`. The accessor skip and the `merge()` catchall change it
depended on both come back out.

`kind satisfies never` in the default branch makes a new built-in type a
compile error rather than a silent fallthrough, matching `visit.ts`.
Unknown user-defined kinds are treated as leaves.

* fix(v4): keep discovering children of user-defined schema types

The per-type switch can only enumerate kinds Zod ships. A third-party
container built on `$constructor` holds its children under a key only its
author knows, so an unknown `def.type` falls back to scanning the def —
still skipping accessors, so it cannot fire a getter.

Without this a cycle through such a type throws RangeError, which is the
crash #6387 removed.

This branch was successfully deployed

1 active deployment
Preview – zod-v4 — 44b36336 Deployed Aug 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.

Support circular object validation

2 participants