perf(v4): eliminate dictionary-mode overhead via shadow-proto (no breaking changes)#5870
perf(v4): eliminate dictionary-mode overhead via shadow-proto (no breaking changes)#5870gsoldevila wants to merge 1 commit intocolinhacks:mainfrom
Conversation
…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
…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
…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
…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
…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>
…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>
…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>
…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
35f768e to
37e0839
Compare
|
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 Key changes
Summary | 4 files | 1 commit | base: Shadow-proto architecture in
|
|
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 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 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. |
|
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 I'm doing some tests locally, but I believe it should preserve the behaviour when doing: Happy to submit a new PR if you think the trade-off is acceptable. |
|
Thanks, Gerard. Seems like you posted this before seeing #5897, which is substantially identical to what you suggested. (Good idea!) |
|
Hi! yes, I saw your PR after posting. FYI we cherry-picked your commit and applied it to Thanks a lot for the fix! |

Summary
Fixes #5760
Own-property count before/after this PR:
z.string()z.string().min(1).max(10).email()z.number()z.object({})Problem
Two sources contributed to the ~91 own properties per schema instance:
$constructorcopies every method from_.prototypeto each new instance, adding ~60 own properties.ZodType.initassigns ~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
_.prototypeand the parent prototype. Library methods are placed oninternalProto; the copy-loop continues to target the empty_.prototype.core.ts
$internalProto(a unique Symbol) soschemas.tscan locate each constructor's internal prototype.$constructor, createinternalProto = Object.create(Parent.prototype), wire_.prototype → internalProtoviaObject.setPrototypeOf, and expose it as_[$internalProto].Object.keys(_.prototype)now returns[]by default, making it a no-op unless a user explicitly adds methods to_.prototype.classic/schemas.ts
_protoInitMap(WeakMap) and_initProtohelper that targetsinst._zod.constr[$internalProto]._initProtocalls.parse,safeParse,parseAsync,safeParseAsync, encode/decode variants) remain per-instance — they captureinstand must work when detached.mini/schemas.ts
_initProtoinfrastructure added.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:
Because
_.prototypeis 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.tssuites (classic and mini) pass without modification.New test:
fast-properties.test.tsAsserts for common schemas that:
optional,nullable, etc.) are NOT own propertiesconst { parse } = schema; parse("x"))All tests passed ✅
