Skip to content

perf(v4): eliminate dictionary-mode overhead via shadow-proto (no breaking changes)#5870

Closed
gsoldevila wants to merge 1 commit intocolinhacks:mainfrom
gsoldevila:zod-memory-optimization-v2
Closed

perf(v4): eliminate dictionary-mode overhead via shadow-proto (no breaking changes)#5870
gsoldevila wants to merge 1 commit intocolinhacks:mainfrom
gsoldevila:zod-memory-optimization-v2

Conversation

@gsoldevila
Copy link
Copy Markdown

Summary

Fixes #5760

Own-property count before/after this PR:

Schema Before After
z.string() ~91 ~18
z.string().min(1).max(10).email() ~91 ~18
z.number() ~91 ~17
z.object({}) ~91 ~18

Problem

Two sources contributed to the ~91 own properties per schema instance:

  1. The copy-loop in $constructor copies every method from _.prototype to each new instance, adding ~60 own properties.
  2. Classic ZodType.init assigns ~30 builder methods as per-instance own properties.

V8 switches from fast-property (inline-cache) to dictionary mode at ~20–30 own properties, degrading all property access by up to 24×.

Solution: shadow-proto

Introduce a hidden internal prototype layer between the user-visible _.prototype and the parent prototype. Library methods are placed on internalProto; the copy-loop continues to target the empty _.prototype.

inst
 └── _.prototype           ← user-visible (empty by default; copy-loop targets this)
      └── internalProto    ← library space (_initProto writes here)
           └── Parent / Object.prototype

core.ts

  • Export $internalProto (a unique Symbol) so schemas.ts can locate each constructor's internal prototype.
  • Inside $constructor, create internalProto = Object.create(Parent.prototype), wire _.prototype → internalProto via Object.setPrototypeOf, and expose it as _[$internalProto].
  • The copy-loop is unchangedObject.keys(_.prototype) now returns [] by default, making it a no-op unless a user explicitly adds methods to _.prototype.

classic/schemas.ts

  • Add _protoInitMap (WeakMap) and _initProto helper that targets inst._zod.constr[$internalProto].
  • All 133 per-instance builder method assignments replaced with _initProto calls.
  • Parse-family closures (parse, safeParse, parseAsync, safeParseAsync, encode/decode variants) remain per-instance — they capture inst and must work when detached.

mini/schemas.ts

  • Same _initProto infrastructure added.
  • The 6 builder methods in ZodMiniType (check, with, clone, brand, register, apply) moved to the internal prototype.

Key advantage: no breaking changes

The original prototype-extension contract is fully preserved:

// Still works exactly as before
z.ZodType.prototype.myHelper = function() { return "custom"; };
z.string().myHelper(); // ✓  "custom"

Because _.prototype is now empty by default, the copy-loop activates only when users add methods there — propagating them to new instances exactly as the original code did.

Both prototypes.test.ts suites (classic and mini) pass without modification.

New test: fast-properties.test.ts

Asserts for common schemas that:

  • Own-property count is < 25
  • Builder methods (optional, nullable, etc.) are NOT own properties
  • Parse methods ARE own properties (detached usage must work: const { parse } = schema; parse("x"))

All tests passed ✅
image

gsoldevila added a commit to gsoldevila/kibana that referenced this pull request Apr 21, 2026
…el savings)

Replaces the shared-method-references patch with the more complete
shadow-proto strategy:

- Introduces a hidden `internalProto` layer between `_.prototype` (user
  space) and the parent prototype. All library methods are placed on
  `internalProto` via `_initProto`, making them prototype-inherited rather
  than own properties.
- Own-property count per schema instance drops from ~91 → ~22, keeping
  all instances firmly in V8's fast-property mode (threshold: ~27).
- Methods are shared across instances (prototype-inherited), eliminating
  the ~50-closure per-instance allocation from the original design.
- Backward-compatible: user-added prototype extensions continue to work
  because `_.prototype` (user space) shadows `internalProto`.
- Covers classic and mini Zod API (6 files: schemas.cjs/js + core.cjs/js
  + mini/schemas.cjs/js).

Upstream PR: colinhacks/zod#5870

Made-with: Cursor
gsoldevila added a commit to gsoldevila/kibana that referenced this pull request Apr 21, 2026
…el savings)

Replaces the shared-method-references patch with the more complete
shadow-proto strategy:

- Introduces a hidden `internalProto` layer between `_.prototype` (user
  space) and the parent prototype. All library methods are placed on
  `internalProto` via `_initProto`, making them prototype-inherited rather
  than own properties.
- Own-property count per schema instance drops from ~91 → ~22, keeping
  all instances firmly in V8's fast-property mode (threshold: ~27).
- Methods are shared across instances (prototype-inherited), eliminating
  the ~50-closure per-instance allocation from the original design.
- Backward-compatible: user-added prototype extensions continue to work
  because `_.prototype` (user space) shadows `internalProto`.
- Covers classic and mini Zod API (6 files: schemas.cjs/js + core.cjs/js
  + mini/schemas.cjs/js).

Upstream PR: colinhacks/zod#5870

Made-with: Cursor
gsoldevila added a commit to gsoldevila/kibana that referenced this pull request Apr 21, 2026
…el savings)

Replaces the shared-method-references patch with the more complete
shadow-proto strategy:

- Introduces a hidden `internalProto` layer between `_.prototype` (user
  space) and the parent prototype. All library methods are placed on
  `internalProto` via `_initProto`, making them prototype-inherited rather
  than own properties.
- Own-property count per schema instance drops from ~91 → ~22, keeping
  all instances firmly in V8's fast-property mode (threshold: ~27).
- Methods are shared across instances (prototype-inherited), eliminating
  the ~50-closure per-instance allocation from the original design.
- Backward-compatible: user-added prototype extensions continue to work
  because `_.prototype` (user space) shadows `internalProto`.
- Covers classic and mini Zod API (6 files: schemas.cjs/js + core.cjs/js
  + mini/schemas.cjs/js).

Upstream PR: colinhacks/zod#5870

Made-with: Cursor
gsoldevila added a commit to gsoldevila/kibana that referenced this pull request Apr 22, 2026
…el savings)

Replaces the shared-method-references patch with the more complete
shadow-proto strategy:

- Introduces a hidden `internalProto` layer between `_.prototype` (user
  space) and the parent prototype. All library methods are placed on
  `internalProto` via `_initProto`, making them prototype-inherited rather
  than own properties.
- Own-property count per schema instance drops from ~91 → ~22, keeping
  all instances firmly in V8's fast-property mode (threshold: ~27).
- Methods are shared across instances (prototype-inherited), eliminating
  the ~50-closure per-instance allocation from the original design.
- Backward-compatible: user-added prototype extensions continue to work
  because `_.prototype` (user space) shadows `internalProto`.
- Covers classic and mini Zod API (6 files: schemas.cjs/js + core.cjs/js
  + mini/schemas.cjs/js).

Upstream PR: colinhacks/zod#5870

Made-with: Cursor
gsoldevila added a commit to elastic/kibana that referenced this pull request Apr 22, 2026
…263121)

## Summary

Applies a memory optimization patch to Zod v4 to address significant
heap cost regression introduced with the upgrade to Zod 4.x (see
upstream issue [#5760](colinhacks/zod#5760)).

### Problem

Zod v4 assigns every method (`parse`, `check`, `optional`, `email`,
etc.) as an **own-property arrow function** on each schema instance.
Because each arrow function closes over `inst`, each instance allocates
~91 unique function objects. V8 switches from fast-property mode to slow
"dictionary mode" when an object accumulates more than ~27 own
properties, causing an extra heap tax on top of the closure overhead. In
practice this costs **~12.8 KB of heap per schema** (vs ~1.5 KB with Zod
3).

### Fix — Shadow-Proto Architecture

Introduces a hidden intermediate prototype layer (`internalProto`)
between `_.prototype` (the user-visible class prototype) and the parent.
Library methods are placed on `internalProto` via `_initProto` (once per
concrete type, lazily), so they become **inherited** rather than own
properties.

```
instance → _.prototype (user space, empty by default)
         → internalProto (library space: 69 shared methods)
         → Parent
```

Key properties:
- **Own-property count**: ~91 → **~22** (well below V8's dictionary-mode
threshold of ~27)
- **Shared methods**: all 69 builder/parse methods are
prototype-inherited; instances share the same function objects
(`s1.optional === s2.optional`)
- **Backward-compatible**: user-added prototype extensions on
`_.prototype` still shadow `internalProto` transparently
- **Covers both variants**: classic and mini Zod APIs (6 files patched)

Six Zod files are patched (both CJS and ESM variants):

- `zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper +
moves all builder methods to `internalProto`
- `zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini API
surface
- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype →
internalProto`, exposes `$internalProto` symbol; copy-loop left as no-op
for library methods

The patch is managed by `patch-package` and lives in
`patches/zod+4.3.6.patch`. An upstream PR is being prepared:
[colinhacks/zod#5870](colinhacks/zod#5870).

### Result

| Metric | Before (Zod v4, unpatched) | After (shadow-proto patch) |
| ------------------------------- | -------------------------- |
-------------------------- |
| Own properties per instance | ~91 | **~22** |
| V8 property storage mode | Dictionary (slow) | **Fast** |
| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |
| Shared method references | ✗ (per-instance closures) | **✓**
(prototype-inherited)|
| **Memory reduction** | — | **~80%** |
| `z.iso.datetime().optional()` | ✅ | ✅ |
| Prototype augmentation | ✅ | ✅ |
| All parse/validate/chain APIs | ✅ | ✅ |

> Validated by full Kibana heap snapshot comparison: ~113 MB reduction
at startup.

### Patch persistence

The patch is applied automatically during `yarn kbn bootstrap` (after
`yarn install`) via `patch-package --error-on-fail`. The `patches/`
directory is committed and version-controlled.

**Removal criteria**: remove `patches/zod+4.3.6.patch` (and the
`patch-package` devDependency) once the upstream Zod issue is resolved
and Kibana upgrades to the patched version.

### New dependency: `patch-package`

| | |
|---|---|
| **Purpose** | Applies and maintains the shadow-proto patch to
`node_modules/zod` across `yarn install` runs. Invoked as `patch-package
--error-on-fail` in the bootstrap step. |
| **Justification** | The optimization requires modifying Zod's compiled
JavaScript internals (`$constructor` wiring, `_initProto` helper,
builder method placement). These changes cannot be applied at the
TypeScript/import level, so a post-install patch is the correct
mechanism. `patch-package` is the industry-standard tool for this
pattern, with a simple invocation model and deterministic patch
application. |
| **Alternatives explored** | (1) **Custom patching script** — Kibana
used a bespoke `src/dev/node_modules_patches/` mechanism in an earlier
iteration of this PR; `patch-package` is strictly simpler and more
maintainable. (2) **`@kbn/zod` wrapper** — the wrapper re-exports
`zod/v4` but cannot intercept the compiled `$constructor` and prototype
wiring needed for this optimization. (3) **Private Elastic
fork/registry** — viable but significantly heavier: requires maintaining
a fork, publishing to a registry, and updating consumers;
disproportionate effort for a temporary vendor patch. |
| **Existing dependencies** | Kibana has no existing dependency
providing `patch-package`-equivalent functionality. `yarn patch` (a
built-in Yarn Berry feature) is not available since Kibana uses Yarn
Classic. |

### Test plan

- `npx patch-package --error-on-fail` applies cleanly from scratch
- `z.iso.datetime().optional()` works
- `z.string().email().optional()`, `obj.pick()`, `enum.extract()` all
work
- `z.httpUrl()` correctly rejects `ftp://`, `file:///` URLs (only
`http`/`https` accepted)
- Shared references confirmed: `z.string().optional ===
z.string().optional` → `true`
- Own-property count confirmed:
`Object.getOwnPropertyNames(z.string()).length` → `22`
- Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)
- `node scripts/check_changes.ts` passes
- Heap snapshot comparison: ~113 MB reduction at Kibana startup

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
kibanamachine added a commit to elastic/kibana that referenced this pull request Apr 22, 2026
…ces (#263121) (#265044)

# Backport

This will backport the following commits from `main` to `9.4`:
- [fix(zod): reduce per-schema heap cost via shared method references
(#263121)](#263121)

<!--- Backport version: 9.6.6 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

<!--BACKPORT [{"author":{"name":"Gerard
Soldevila","email":"gerard.soldevila@elastic.co"},"sourceCommit":{"committedDate":"2026-04-22T13:19:07Z","message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa","branchLabelMapping":{"^v9.5.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Team:Core","release_note:skip","ci:build-cloud-image","backport:version","v9.4.0","v9.5.0"],"title":"fix(zod):
reduce per-schema heap cost via shared method
references","number":263121,"url":"https://github.com/elastic/kibana/pull/263121","mergeCommit":{"message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa"}},"sourceBranch":"main","suggestedTargetBranches":["9.4"],"targetPullRequestStates":[{"branch":"9.4","label":"v9.4.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.5.0","branchLabelMappingKey":"^v9.5.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/263121","number":263121,"mergeCommit":{"message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa"}}]}]
BACKPORT-->

Co-authored-by: Gerard Soldevila <gerard.soldevila@elastic.co>
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
tiansivive pushed a commit to tiansivive/kibana that referenced this pull request Apr 23, 2026
…lastic#263121)

## Summary

Applies a memory optimization patch to Zod v4 to address significant
heap cost regression introduced with the upgrade to Zod 4.x (see
upstream issue [elastic#5760](colinhacks/zod#5760)).

### Problem

Zod v4 assigns every method (`parse`, `check`, `optional`, `email`,
etc.) as an **own-property arrow function** on each schema instance.
Because each arrow function closes over `inst`, each instance allocates
~91 unique function objects. V8 switches from fast-property mode to slow
"dictionary mode" when an object accumulates more than ~27 own
properties, causing an extra heap tax on top of the closure overhead. In
practice this costs **~12.8 KB of heap per schema** (vs ~1.5 KB with Zod
3).

### Fix — Shadow-Proto Architecture

Introduces a hidden intermediate prototype layer (`internalProto`)
between `_.prototype` (the user-visible class prototype) and the parent.
Library methods are placed on `internalProto` via `_initProto` (once per
concrete type, lazily), so they become **inherited** rather than own
properties.

```
instance → _.prototype (user space, empty by default)
         → internalProto (library space: 69 shared methods)
         → Parent
```

Key properties:
- **Own-property count**: ~91 → **~22** (well below V8's dictionary-mode
threshold of ~27)
- **Shared methods**: all 69 builder/parse methods are
prototype-inherited; instances share the same function objects
(`s1.optional === s2.optional`)
- **Backward-compatible**: user-added prototype extensions on
`_.prototype` still shadow `internalProto` transparently
- **Covers both variants**: classic and mini Zod APIs (6 files patched)

Six Zod files are patched (both CJS and ESM variants):

- `zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper +
moves all builder methods to `internalProto`
- `zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini API
surface
- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype →
internalProto`, exposes `$internalProto` symbol; copy-loop left as no-op
for library methods

The patch is managed by `patch-package` and lives in
`patches/zod+4.3.6.patch`. An upstream PR is being prepared:
[colinhacks/zod#5870](colinhacks/zod#5870).

### Result

| Metric | Before (Zod v4, unpatched) | After (shadow-proto patch) |
| ------------------------------- | -------------------------- |
-------------------------- |
| Own properties per instance | ~91 | **~22** |
| V8 property storage mode | Dictionary (slow) | **Fast** |
| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |
| Shared method references | ✗ (per-instance closures) | **✓**
(prototype-inherited)|
| **Memory reduction** | — | **~80%** |
| `z.iso.datetime().optional()` | ✅ | ✅ |
| Prototype augmentation | ✅ | ✅ |
| All parse/validate/chain APIs | ✅ | ✅ |

> Validated by full Kibana heap snapshot comparison: ~113 MB reduction
at startup.

### Patch persistence

The patch is applied automatically during `yarn kbn bootstrap` (after
`yarn install`) via `patch-package --error-on-fail`. The `patches/`
directory is committed and version-controlled.

**Removal criteria**: remove `patches/zod+4.3.6.patch` (and the
`patch-package` devDependency) once the upstream Zod issue is resolved
and Kibana upgrades to the patched version.

### New dependency: `patch-package`

| | |
|---|---|
| **Purpose** | Applies and maintains the shadow-proto patch to
`node_modules/zod` across `yarn install` runs. Invoked as `patch-package
--error-on-fail` in the bootstrap step. |
| **Justification** | The optimization requires modifying Zod's compiled
JavaScript internals (`$constructor` wiring, `_initProto` helper,
builder method placement). These changes cannot be applied at the
TypeScript/import level, so a post-install patch is the correct
mechanism. `patch-package` is the industry-standard tool for this
pattern, with a simple invocation model and deterministic patch
application. |
| **Alternatives explored** | (1) **Custom patching script** — Kibana
used a bespoke `src/dev/node_modules_patches/` mechanism in an earlier
iteration of this PR; `patch-package` is strictly simpler and more
maintainable. (2) **`@kbn/zod` wrapper** — the wrapper re-exports
`zod/v4` but cannot intercept the compiled `$constructor` and prototype
wiring needed for this optimization. (3) **Private Elastic
fork/registry** — viable but significantly heavier: requires maintaining
a fork, publishing to a registry, and updating consumers;
disproportionate effort for a temporary vendor patch. |
| **Existing dependencies** | Kibana has no existing dependency
providing `patch-package`-equivalent functionality. `yarn patch` (a
built-in Yarn Berry feature) is not available since Kibana uses Yarn
Classic. |

### Test plan

- `npx patch-package --error-on-fail` applies cleanly from scratch
- `z.iso.datetime().optional()` works
- `z.string().email().optional()`, `obj.pick()`, `enum.extract()` all
work
- `z.httpUrl()` correctly rejects `ftp://`, `file:///` URLs (only
`http`/`https` accepted)
- Shared references confirmed: `z.string().optional ===
z.string().optional` → `true`
- Own-property count confirmed:
`Object.getOwnPropertyNames(z.string()).length` → `22`
- Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)
- `node scripts/check_changes.ts` passes
- Heap snapshot comparison: ~113 MB reduction at Kibana startup

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
SoniaSanzV pushed a commit to SoniaSanzV/kibana that referenced this pull request Apr 27, 2026
…lastic#263121)

## Summary

Applies a memory optimization patch to Zod v4 to address significant
heap cost regression introduced with the upgrade to Zod 4.x (see
upstream issue [elastic#5760](colinhacks/zod#5760)).

### Problem

Zod v4 assigns every method (`parse`, `check`, `optional`, `email`,
etc.) as an **own-property arrow function** on each schema instance.
Because each arrow function closes over `inst`, each instance allocates
~91 unique function objects. V8 switches from fast-property mode to slow
"dictionary mode" when an object accumulates more than ~27 own
properties, causing an extra heap tax on top of the closure overhead. In
practice this costs **~12.8 KB of heap per schema** (vs ~1.5 KB with Zod
3).

### Fix — Shadow-Proto Architecture

Introduces a hidden intermediate prototype layer (`internalProto`)
between `_.prototype` (the user-visible class prototype) and the parent.
Library methods are placed on `internalProto` via `_initProto` (once per
concrete type, lazily), so they become **inherited** rather than own
properties.

```
instance → _.prototype (user space, empty by default)
         → internalProto (library space: 69 shared methods)
         → Parent
```

Key properties:
- **Own-property count**: ~91 → **~22** (well below V8's dictionary-mode
threshold of ~27)
- **Shared methods**: all 69 builder/parse methods are
prototype-inherited; instances share the same function objects
(`s1.optional === s2.optional`)
- **Backward-compatible**: user-added prototype extensions on
`_.prototype` still shadow `internalProto` transparently
- **Covers both variants**: classic and mini Zod APIs (6 files patched)

Six Zod files are patched (both CJS and ESM variants):

- `zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper +
moves all builder methods to `internalProto`
- `zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini API
surface
- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype →
internalProto`, exposes `$internalProto` symbol; copy-loop left as no-op
for library methods

The patch is managed by `patch-package` and lives in
`patches/zod+4.3.6.patch`. An upstream PR is being prepared:
[colinhacks/zod#5870](colinhacks/zod#5870).

### Result

| Metric | Before (Zod v4, unpatched) | After (shadow-proto patch) |
| ------------------------------- | -------------------------- |
-------------------------- |
| Own properties per instance | ~91 | **~22** |
| V8 property storage mode | Dictionary (slow) | **Fast** |
| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |
| Shared method references | ✗ (per-instance closures) | **✓**
(prototype-inherited)|
| **Memory reduction** | — | **~80%** |
| `z.iso.datetime().optional()` | ✅ | ✅ |
| Prototype augmentation | ✅ | ✅ |
| All parse/validate/chain APIs | ✅ | ✅ |

> Validated by full Kibana heap snapshot comparison: ~113 MB reduction
at startup.

### Patch persistence

The patch is applied automatically during `yarn kbn bootstrap` (after
`yarn install`) via `patch-package --error-on-fail`. The `patches/`
directory is committed and version-controlled.

**Removal criteria**: remove `patches/zod+4.3.6.patch` (and the
`patch-package` devDependency) once the upstream Zod issue is resolved
and Kibana upgrades to the patched version.

### New dependency: `patch-package`

| | |
|---|---|
| **Purpose** | Applies and maintains the shadow-proto patch to
`node_modules/zod` across `yarn install` runs. Invoked as `patch-package
--error-on-fail` in the bootstrap step. |
| **Justification** | The optimization requires modifying Zod's compiled
JavaScript internals (`$constructor` wiring, `_initProto` helper,
builder method placement). These changes cannot be applied at the
TypeScript/import level, so a post-install patch is the correct
mechanism. `patch-package` is the industry-standard tool for this
pattern, with a simple invocation model and deterministic patch
application. |
| **Alternatives explored** | (1) **Custom patching script** — Kibana
used a bespoke `src/dev/node_modules_patches/` mechanism in an earlier
iteration of this PR; `patch-package` is strictly simpler and more
maintainable. (2) **`@kbn/zod` wrapper** — the wrapper re-exports
`zod/v4` but cannot intercept the compiled `$constructor` and prototype
wiring needed for this optimization. (3) **Private Elastic
fork/registry** — viable but significantly heavier: requires maintaining
a fork, publishing to a registry, and updating consumers;
disproportionate effort for a temporary vendor patch. |
| **Existing dependencies** | Kibana has no existing dependency
providing `patch-package`-equivalent functionality. `yarn patch` (a
built-in Yarn Berry feature) is not available since Kibana uses Yarn
Classic. |

### Test plan

- `npx patch-package --error-on-fail` applies cleanly from scratch
- `z.iso.datetime().optional()` works
- `z.string().email().optional()`, `obj.pick()`, `enum.extract()` all
work
- `z.httpUrl()` correctly rejects `ftp://`, `file:///` URLs (only
`http`/`https` accepted)
- Shared references confirmed: `z.string().optional ===
z.string().optional` → `true`
- Own-property count confirmed:
`Object.getOwnPropertyNames(z.string()).length` → `22`
- Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)
- `node scripts/check_changes.ts` passes
- Heap snapshot comparison: ~113 MB reduction at Kibana startup

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
…aking changes)

Zod v4 schema instances accumulate too many own properties, pushing them past
V8's fast-property threshold (~20–30) and into dictionary mode. Dictionary mode
degrades property access by up to 24× (see issue colinhacks#5760).

Two sources contribute:
1. The `// support prototype modifications` copy-loop in `$constructor` copies
   every method from `_.prototype` to each new instance — adding ~60 own props.
2. Classic `ZodType` init assigns ~30 builder methods as per-instance own props.

Introduce a hidden *internal* prototype layer between the user-visible `_.prototype`
and the parent prototype chain. Library methods are placed there; the copy-loop
continues to target only the user-visible `_.prototype`.

```
inst
 └── _.prototype           ← user space (empty by default; copy-loop targets this)
      └── internalProto    ← library space (_initProto writes here)
           └── Parent / Object.prototype
```

- Export `$internalProto` (a unique symbol) to identify each constructor's
  internal prototype from `schemas.ts`.
- In `$constructor`, create `internalProto` for each constructor, wire
  `_.prototype → internalProto`, and expose it as `_[$internalProto]`.
- The copy-loop is **unchanged** — but since `_.prototype` is now empty by
  default, it is a no-op unless a user explicitly adds methods there.

- Add `_protoInitMap` (WeakMap) and `_initProto` helper.
- `_initProto` targets `inst._zod.constr[$internalProto]` (the internal proto),
  not `Object.getPrototypeOf(inst)` (the user-visible proto).
- All 133 per-instance builder method assignments replaced with `_initProto`
  calls; parse-family closures stay per-instance for detached-usage safety.

- Same `_initProto` infrastructure added.
- The 6 builder methods in `ZodMiniType` (`check`, `with`, `clone`, `brand`,
  `register`, `apply`) moved to the internal prototype.

Unlike removing the copy-loop entirely (which breaks prototype augmentation),
this design preserves the original contract:

```js
// Still works — copy-loop propagates user extensions from _.prototype to instances
z.ZodType.prototype.myHelper = function() { ... };
z.string().myHelper(); // ✓
```

The copy-loop is only a no-op for *library* methods (they live on internalProto,
which `Object.keys(_.prototype)` never enumerates).

- `z.string()` own-property count: ~91 → ~18 (well below V8's threshold)
- No breaking changes; all 3,589 tests pass including both `prototypes.test.ts`
  suites without modification
- `z.ZodType.prototype` augmentation works exactly as before

`fast-properties.test.ts` asserts:
- Own-property count < 25 for common schemas
- Builder methods are NOT own properties
- Parse methods ARE own properties (detached usage must work)

Closes: colinhacks#5760
Made-with: Cursor
@pullfrog
Copy link
Copy Markdown
Contributor

pullfrog Bot commented Apr 28, 2026

TL;DR — Reduces per-schema own-property count from ~91 to ~17–18 by introducing a hidden internal prototype layer ("shadow-proto") between instances and the user-visible _.prototype. This keeps V8 in fast-property / inline-cache mode instead of falling into dictionary mode, which was causing up to ~24× slower property access. No breaking changes — the existing prototype-extension contract is fully preserved.

Key changes

  • Add $internalProto layer in $constructor — A hidden prototype is inserted between _.prototype (user space) and the parent prototype; library methods are installed there so Object.keys(_.prototype) stays empty by default and the copy-loop becomes a no-op.
  • Replace ~133 per-instance closures with shared _initProto calls in classic schemas.ts — Builder methods (check, optional, nullable, describe, string/number/bigint/date/array/object/enum/file validators, wrapper unwrap, etc.) are now this-based functions installed once per concrete type on the internal prototype, eliminating ~50 function object allocations per schema.
  • Apply same _initProto pattern to mini schemas.ts — The 6 ZodMiniType builder methods (check, with, clone, brand, register, apply) are moved to the internal prototype.
  • Add fast-properties.test.ts regression suite — Asserts own-property counts stay below 25, builder methods are not own properties, and parse-family methods are own properties (so detached usage like const { parse } = schema keeps working).

Summary | 4 files | 1 commit | base: mainzod-memory-optimization-v2


Shadow-proto architecture in core.ts

Before: $constructor created a flat prototype chain (inst → _.prototype → Parent.prototype); all library methods were copied to every instance as own properties, pushing V8 into dictionary mode at ~91 own props.
After: A new internalProto layer sits between _.prototype and the parent. Library methods live on internalProto; _.prototype stays empty by default, so the copy-loop is a no-op for stock schemas.

The prototype chain is now: inst → _.prototype (user space, empty) → internalProto (library methods) → Parent.prototype. The $internalProto symbol is exported so schemas.ts can locate the internal proto for each constructor.

User prototype extensions continue to work — adding methods to z.ZodType.prototype causes the existing copy-loop to activate, propagating them to new instances exactly as before.

core.ts


Shared this-based methods in classic schemas.ts

Before: Every schema instance received ~30+ builder methods as per-instance arrow closures capturing inst, plus ~60 methods copied from the prototype — totaling ~91 own properties.
After: Builder methods are defined once as named this-based functions and installed on the internal prototype via _initProto. Own-property count drops to ~17–18 per instance.

The _initProto helper uses a WeakMap<object, Set<string>> to track which method groups have already been installed on each internal prototype, ensuring one-time setup per concrete type per key. Parse-family methods (parse, safeParse, parseAsync, etc.) intentionally remain per-instance closures — they capture inst for detached usage patterns like arr.map(schema.parse).

Why keep parse methods as own properties?

Parse methods are commonly used in a detached manner (e.g. const { parse } = schema; parse(value) or arr.map(schema.parse)). Prototype-based this binding would break in these cases. The ~8 parse/encode/decode closures are the only per-instance functions that remain.

schemas.ts · fast-properties.test.ts


Mini schemas get the same treatment

Before: ZodMiniType assigned 6 builder methods (check, with, clone, brand, register, apply) as per-instance closures.
After: These are shared this-based functions installed once via _initProto.

The mini _initProto is a slightly simpler copy of the classic version (no defineProps parameter needed).

mini/schemas.ts

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

@colinhacks
Copy link
Copy Markdown
Owner

colinhacks commented Apr 29, 2026

Thanks, Gerard. Unfortunately, despite the efforts here to avoid breaking changes, there are still breaking changes for any users who pull out references to schema methods. Today this works:

const opt = schema.optional;
opt(); // ZodOptional<typeof schema>

After this PR it silently returns a corrupt schema that fails the next time anything tries to parse with it. Parse-family methods are kept as per-instance closures so const { parse } = schema still works; nothing else does.

Zod is now widely used enough that there's a Murphy's law effect with breaking changes like this. Somebody, probably hundreds of somebodies, rely on the ability to pull out methods like this and use them as standalone functions. In fact, I specifically like the fact that there are no gotchas around this-binding with Zod's current approach.

The memory overhead is unfortunate. I'm receptive to anything that could be done to reduce it. I'd even be open to introducing some minor breakage if it meant a significant runtime parsing performance boost. But at this point I'm not convinced that this is a good trade-off.

Closing for now because I'm going through a backlog here. Perhaps DM me if you'd like to float other approaches or continue this discussion.

@gsoldevila
Copy link
Copy Markdown
Author

Thanks for the thorough review, @colinhacks. I totally missed the extracted references scenario.

For us in Kibana, upgrading to 4.x has a huge memory impact (> 100 Mb), so we're exploring non-breaking alternatives.

There is a backward-compatible variant worth considering: auto-bind getters on the prototype. Instead of placing a plain shared function on internalProto, each builder method could be a getter that returns _sharedFn.bind(this):

Object.defineProperty(internalProto, 'optional', {
  get() { return _sharedOptional.bind(this); },
  configurable: true,
});

I'm doing some tests locally, but I believe it should preserve the behaviour when doing:

const opt = schema.optional;
opt(); // ✓ works — `this` is permanently bound to schema at access time
schema.optional(); // ✓ works as before

Happy to submit a new PR if you think the trade-off is acceptable.

@colinhacks
Copy link
Copy Markdown
Owner

colinhacks commented Apr 30, 2026

Thanks, Gerard. Seems like you posted this before seeing #5897, which is substantially identical to what you suggested. (Good idea!)

@gsoldevila
Copy link
Copy Markdown
Author

Hi! yes, I saw your PR after posting.
Both are similar, but your approach is even better as you only pay the allocation overhead once.

FYI we cherry-picked your commit and applied it to 4.3.6.
We did some memory tests and there are substantial memory savings, so I confirm #5760 is correctly addressed.

Thanks a lot for the fix!

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.

Schema instances have ~91 own properties → dictionary mode → ~24x slower property access vs Zod 3

2 participants